db/sqlite3/src/sqlite3.c

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/db/sqlite3/src/sqlite3.c	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,146388 @@
     1.4 +/******************************************************************************
     1.5 +** This file is an amalgamation of many separate C source files from SQLite
     1.6 +** version 3.8.4.2.  By combining all the individual C code files into this 
     1.7 +** single large file, the entire code can be compiled as a single translation
     1.8 +** unit.  This allows many compilers to do optimizations that would not be
     1.9 +** possible if the files were compiled separately.  Performance improvements
    1.10 +** of 5% or more are commonly seen when SQLite is compiled as a single
    1.11 +** translation unit.
    1.12 +**
    1.13 +** This file is all you need to compile SQLite.  To use SQLite in other
    1.14 +** programs, you need this file and the "sqlite3.h" header file that defines
    1.15 +** the programming interface to the SQLite library.  (If you do not have 
    1.16 +** the "sqlite3.h" header file at hand, you will find a copy embedded within
    1.17 +** the text of this file.  Search for "Begin file sqlite3.h" to find the start
    1.18 +** of the embedded sqlite3.h header file.) Additional code files may be needed
    1.19 +** if you want a wrapper to interface SQLite with your choice of programming
    1.20 +** language. The code for the "sqlite3" command-line shell is also in a
    1.21 +** separate file. This file contains only code for the core SQLite library.
    1.22 +*/
    1.23 +#define SQLITE_CORE 1
    1.24 +#define SQLITE_AMALGAMATION 1
    1.25 +#ifndef SQLITE_PRIVATE
    1.26 +# define SQLITE_PRIVATE static
    1.27 +#endif
    1.28 +#ifndef SQLITE_API
    1.29 +# define SQLITE_API
    1.30 +#endif
    1.31 +/************** Begin file sqliteInt.h ***************************************/
    1.32 +/*
    1.33 +** 2001 September 15
    1.34 +**
    1.35 +** The author disclaims copyright to this source code.  In place of
    1.36 +** a legal notice, here is a blessing:
    1.37 +**
    1.38 +**    May you do good and not evil.
    1.39 +**    May you find forgiveness for yourself and forgive others.
    1.40 +**    May you share freely, never taking more than you give.
    1.41 +**
    1.42 +*************************************************************************
    1.43 +** Internal interface definitions for SQLite.
    1.44 +**
    1.45 +*/
    1.46 +#ifndef _SQLITEINT_H_
    1.47 +#define _SQLITEINT_H_
    1.48 +
    1.49 +/*
    1.50 +** These #defines should enable >2GB file support on POSIX if the
    1.51 +** underlying operating system supports it.  If the OS lacks
    1.52 +** large file support, or if the OS is windows, these should be no-ops.
    1.53 +**
    1.54 +** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
    1.55 +** system #includes.  Hence, this block of code must be the very first
    1.56 +** code in all source files.
    1.57 +**
    1.58 +** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
    1.59 +** on the compiler command line.  This is necessary if you are compiling
    1.60 +** on a recent machine (ex: Red Hat 7.2) but you want your code to work
    1.61 +** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
    1.62 +** without this option, LFS is enable.  But LFS does not exist in the kernel
    1.63 +** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
    1.64 +** portability you should omit LFS.
    1.65 +**
    1.66 +** The previous paragraph was written in 2005.  (This paragraph is written
    1.67 +** on 2008-11-28.) These days, all Linux kernels support large files, so
    1.68 +** you should probably leave LFS enabled.  But some embedded platforms might
    1.69 +** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
    1.70 +**
    1.71 +** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
    1.72 +*/
    1.73 +#ifndef SQLITE_DISABLE_LFS
    1.74 +# define _LARGE_FILE       1
    1.75 +# ifndef _FILE_OFFSET_BITS
    1.76 +#   define _FILE_OFFSET_BITS 64
    1.77 +# endif
    1.78 +# define _LARGEFILE_SOURCE 1
    1.79 +#endif
    1.80 +
    1.81 +/*
    1.82 +** For MinGW, check to see if we can include the header file containing its
    1.83 +** version information, among other things.  Normally, this internal MinGW
    1.84 +** header file would [only] be included automatically by other MinGW header
    1.85 +** files; however, the contained version information is now required by this
    1.86 +** header file to work around binary compatibility issues (see below) and
    1.87 +** this is the only known way to reliably obtain it.  This entire #if block
    1.88 +** would be completely unnecessary if there was any other way of detecting
    1.89 +** MinGW via their preprocessor (e.g. if they customized their GCC to define
    1.90 +** some MinGW-specific macros).  When compiling for MinGW, either the
    1.91 +** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
    1.92 +** defined; otherwise, detection of conditions specific to MinGW will be
    1.93 +** disabled.
    1.94 +*/
    1.95 +#if defined(_HAVE_MINGW_H)
    1.96 +# include "mingw.h"
    1.97 +#elif defined(_HAVE__MINGW_H)
    1.98 +# include "_mingw.h"
    1.99 +#endif
   1.100 +
   1.101 +/*
   1.102 +** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
   1.103 +** define is required to maintain binary compatibility with the MSVC runtime
   1.104 +** library in use (e.g. for Windows XP).
   1.105 +*/
   1.106 +#if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
   1.107 +    defined(_WIN32) && !defined(_WIN64) && \
   1.108 +    defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
   1.109 +    defined(__MSVCRT__)
   1.110 +# define _USE_32BIT_TIME_T
   1.111 +#endif
   1.112 +
   1.113 +/* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear
   1.114 +** first in QNX.  Also, the _USE_32BIT_TIME_T macro must appear first for
   1.115 +** MinGW.
   1.116 +*/
   1.117 +/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
   1.118 +/************** Begin file sqlite3.h *****************************************/
   1.119 +/*
   1.120 +** 2001 September 15
   1.121 +**
   1.122 +** The author disclaims copyright to this source code.  In place of
   1.123 +** a legal notice, here is a blessing:
   1.124 +**
   1.125 +**    May you do good and not evil.
   1.126 +**    May you find forgiveness for yourself and forgive others.
   1.127 +**    May you share freely, never taking more than you give.
   1.128 +**
   1.129 +*************************************************************************
   1.130 +** This header file defines the interface that the SQLite library
   1.131 +** presents to client programs.  If a C-function, structure, datatype,
   1.132 +** or constant definition does not appear in this file, then it is
   1.133 +** not a published API of SQLite, is subject to change without
   1.134 +** notice, and should not be referenced by programs that use SQLite.
   1.135 +**
   1.136 +** Some of the definitions that are in this file are marked as
   1.137 +** "experimental".  Experimental interfaces are normally new
   1.138 +** features recently added to SQLite.  We do not anticipate changes
   1.139 +** to experimental interfaces but reserve the right to make minor changes
   1.140 +** if experience from use "in the wild" suggest such changes are prudent.
   1.141 +**
   1.142 +** The official C-language API documentation for SQLite is derived
   1.143 +** from comments in this file.  This file is the authoritative source
   1.144 +** on how SQLite interfaces are suppose to operate.
   1.145 +**
   1.146 +** The name of this file under configuration management is "sqlite.h.in".
   1.147 +** The makefile makes some minor changes to this file (such as inserting
   1.148 +** the version number) and changes its name to "sqlite3.h" as
   1.149 +** part of the build process.
   1.150 +*/
   1.151 +#ifndef _SQLITE3_H_
   1.152 +#define _SQLITE3_H_
   1.153 +#include <stdarg.h>     /* Needed for the definition of va_list */
   1.154 +
   1.155 +/*
   1.156 +** Make sure we can call this stuff from C++.
   1.157 +*/
   1.158 +#if 0
   1.159 +extern "C" {
   1.160 +#endif
   1.161 +
   1.162 +
   1.163 +/*
   1.164 +** Add the ability to override 'extern'
   1.165 +*/
   1.166 +#ifndef SQLITE_EXTERN
   1.167 +# define SQLITE_EXTERN extern
   1.168 +#endif
   1.169 +
   1.170 +#ifndef SQLITE_API
   1.171 +# define SQLITE_API
   1.172 +#endif
   1.173 +
   1.174 +
   1.175 +/*
   1.176 +** These no-op macros are used in front of interfaces to mark those
   1.177 +** interfaces as either deprecated or experimental.  New applications
   1.178 +** should not use deprecated interfaces - they are support for backwards
   1.179 +** compatibility only.  Application writers should be aware that
   1.180 +** experimental interfaces are subject to change in point releases.
   1.181 +**
   1.182 +** These macros used to resolve to various kinds of compiler magic that
   1.183 +** would generate warning messages when they were used.  But that
   1.184 +** compiler magic ended up generating such a flurry of bug reports
   1.185 +** that we have taken it all out and gone back to using simple
   1.186 +** noop macros.
   1.187 +*/
   1.188 +#define SQLITE_DEPRECATED
   1.189 +#define SQLITE_EXPERIMENTAL
   1.190 +
   1.191 +/*
   1.192 +** Ensure these symbols were not defined by some previous header file.
   1.193 +*/
   1.194 +#ifdef SQLITE_VERSION
   1.195 +# undef SQLITE_VERSION
   1.196 +#endif
   1.197 +#ifdef SQLITE_VERSION_NUMBER
   1.198 +# undef SQLITE_VERSION_NUMBER
   1.199 +#endif
   1.200 +
   1.201 +/*
   1.202 +** CAPI3REF: Compile-Time Library Version Numbers
   1.203 +**
   1.204 +** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
   1.205 +** evaluates to a string literal that is the SQLite version in the
   1.206 +** format "X.Y.Z" where X is the major version number (always 3 for
   1.207 +** SQLite3) and Y is the minor version number and Z is the release number.)^
   1.208 +** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
   1.209 +** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
   1.210 +** numbers used in [SQLITE_VERSION].)^
   1.211 +** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
   1.212 +** be larger than the release from which it is derived.  Either Y will
   1.213 +** be held constant and Z will be incremented or else Y will be incremented
   1.214 +** and Z will be reset to zero.
   1.215 +**
   1.216 +** Since version 3.6.18, SQLite source code has been stored in the
   1.217 +** <a href="http://www.fossil-scm.org/">Fossil configuration management
   1.218 +** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
   1.219 +** a string which identifies a particular check-in of SQLite
   1.220 +** within its configuration management system.  ^The SQLITE_SOURCE_ID
   1.221 +** string contains the date and time of the check-in (UTC) and an SHA1
   1.222 +** hash of the entire source tree.
   1.223 +**
   1.224 +** See also: [sqlite3_libversion()],
   1.225 +** [sqlite3_libversion_number()], [sqlite3_sourceid()],
   1.226 +** [sqlite_version()] and [sqlite_source_id()].
   1.227 +*/
   1.228 +#define SQLITE_VERSION        "3.8.4.2"
   1.229 +#define SQLITE_VERSION_NUMBER 3008004
   1.230 +#define SQLITE_SOURCE_ID      "2014-03-26 18:51:19 02ea166372bdb2ef9d8dfbb05e78a97609673a8e"
   1.231 +
   1.232 +/*
   1.233 +** CAPI3REF: Run-Time Library Version Numbers
   1.234 +** KEYWORDS: sqlite3_version, sqlite3_sourceid
   1.235 +**
   1.236 +** These interfaces provide the same information as the [SQLITE_VERSION],
   1.237 +** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
   1.238 +** but are associated with the library instead of the header file.  ^(Cautious
   1.239 +** programmers might include assert() statements in their application to
   1.240 +** verify that values returned by these interfaces match the macros in
   1.241 +** the header, and thus insure that the application is
   1.242 +** compiled with matching library and header files.
   1.243 +**
   1.244 +** <blockquote><pre>
   1.245 +** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
   1.246 +** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
   1.247 +** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
   1.248 +** </pre></blockquote>)^
   1.249 +**
   1.250 +** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
   1.251 +** macro.  ^The sqlite3_libversion() function returns a pointer to the
   1.252 +** to the sqlite3_version[] string constant.  The sqlite3_libversion()
   1.253 +** function is provided for use in DLLs since DLL users usually do not have
   1.254 +** direct access to string constants within the DLL.  ^The
   1.255 +** sqlite3_libversion_number() function returns an integer equal to
   1.256 +** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns 
   1.257 +** a pointer to a string constant whose value is the same as the 
   1.258 +** [SQLITE_SOURCE_ID] C preprocessor macro.
   1.259 +**
   1.260 +** See also: [sqlite_version()] and [sqlite_source_id()].
   1.261 +*/
   1.262 +SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
   1.263 +SQLITE_API const char *sqlite3_libversion(void);
   1.264 +SQLITE_API const char *sqlite3_sourceid(void);
   1.265 +SQLITE_API int sqlite3_libversion_number(void);
   1.266 +
   1.267 +/*
   1.268 +** CAPI3REF: Run-Time Library Compilation Options Diagnostics
   1.269 +**
   1.270 +** ^The sqlite3_compileoption_used() function returns 0 or 1 
   1.271 +** indicating whether the specified option was defined at 
   1.272 +** compile time.  ^The SQLITE_ prefix may be omitted from the 
   1.273 +** option name passed to sqlite3_compileoption_used().  
   1.274 +**
   1.275 +** ^The sqlite3_compileoption_get() function allows iterating
   1.276 +** over the list of options that were defined at compile time by
   1.277 +** returning the N-th compile time option string.  ^If N is out of range,
   1.278 +** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
   1.279 +** prefix is omitted from any strings returned by 
   1.280 +** sqlite3_compileoption_get().
   1.281 +**
   1.282 +** ^Support for the diagnostic functions sqlite3_compileoption_used()
   1.283 +** and sqlite3_compileoption_get() may be omitted by specifying the 
   1.284 +** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
   1.285 +**
   1.286 +** See also: SQL functions [sqlite_compileoption_used()] and
   1.287 +** [sqlite_compileoption_get()] and the [compile_options pragma].
   1.288 +*/
   1.289 +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   1.290 +SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
   1.291 +SQLITE_API const char *sqlite3_compileoption_get(int N);
   1.292 +#endif
   1.293 +
   1.294 +/*
   1.295 +** CAPI3REF: Test To See If The Library Is Threadsafe
   1.296 +**
   1.297 +** ^The sqlite3_threadsafe() function returns zero if and only if
   1.298 +** SQLite was compiled with mutexing code omitted due to the
   1.299 +** [SQLITE_THREADSAFE] compile-time option being set to 0.
   1.300 +**
   1.301 +** SQLite can be compiled with or without mutexes.  When
   1.302 +** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
   1.303 +** are enabled and SQLite is threadsafe.  When the
   1.304 +** [SQLITE_THREADSAFE] macro is 0, 
   1.305 +** the mutexes are omitted.  Without the mutexes, it is not safe
   1.306 +** to use SQLite concurrently from more than one thread.
   1.307 +**
   1.308 +** Enabling mutexes incurs a measurable performance penalty.
   1.309 +** So if speed is of utmost importance, it makes sense to disable
   1.310 +** the mutexes.  But for maximum safety, mutexes should be enabled.
   1.311 +** ^The default behavior is for mutexes to be enabled.
   1.312 +**
   1.313 +** This interface can be used by an application to make sure that the
   1.314 +** version of SQLite that it is linking against was compiled with
   1.315 +** the desired setting of the [SQLITE_THREADSAFE] macro.
   1.316 +**
   1.317 +** This interface only reports on the compile-time mutex setting
   1.318 +** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
   1.319 +** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
   1.320 +** can be fully or partially disabled using a call to [sqlite3_config()]
   1.321 +** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
   1.322 +** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
   1.323 +** sqlite3_threadsafe() function shows only the compile-time setting of
   1.324 +** thread safety, not any run-time changes to that setting made by
   1.325 +** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
   1.326 +** is unchanged by calls to sqlite3_config().)^
   1.327 +**
   1.328 +** See the [threading mode] documentation for additional information.
   1.329 +*/
   1.330 +SQLITE_API int sqlite3_threadsafe(void);
   1.331 +
   1.332 +/*
   1.333 +** CAPI3REF: Database Connection Handle
   1.334 +** KEYWORDS: {database connection} {database connections}
   1.335 +**
   1.336 +** Each open SQLite database is represented by a pointer to an instance of
   1.337 +** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
   1.338 +** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
   1.339 +** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
   1.340 +** and [sqlite3_close_v2()] are its destructors.  There are many other
   1.341 +** interfaces (such as
   1.342 +** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
   1.343 +** [sqlite3_busy_timeout()] to name but three) that are methods on an
   1.344 +** sqlite3 object.
   1.345 +*/
   1.346 +typedef struct sqlite3 sqlite3;
   1.347 +
   1.348 +/*
   1.349 +** CAPI3REF: 64-Bit Integer Types
   1.350 +** KEYWORDS: sqlite_int64 sqlite_uint64
   1.351 +**
   1.352 +** Because there is no cross-platform way to specify 64-bit integer types
   1.353 +** SQLite includes typedefs for 64-bit signed and unsigned integers.
   1.354 +**
   1.355 +** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
   1.356 +** The sqlite_int64 and sqlite_uint64 types are supported for backwards
   1.357 +** compatibility only.
   1.358 +**
   1.359 +** ^The sqlite3_int64 and sqlite_int64 types can store integer values
   1.360 +** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
   1.361 +** sqlite3_uint64 and sqlite_uint64 types can store integer values 
   1.362 +** between 0 and +18446744073709551615 inclusive.
   1.363 +*/
   1.364 +#ifdef SQLITE_INT64_TYPE
   1.365 +  typedef SQLITE_INT64_TYPE sqlite_int64;
   1.366 +  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
   1.367 +#elif defined(_MSC_VER) || defined(__BORLANDC__)
   1.368 +  typedef __int64 sqlite_int64;
   1.369 +  typedef unsigned __int64 sqlite_uint64;
   1.370 +#else
   1.371 +  typedef long long int sqlite_int64;
   1.372 +  typedef unsigned long long int sqlite_uint64;
   1.373 +#endif
   1.374 +typedef sqlite_int64 sqlite3_int64;
   1.375 +typedef sqlite_uint64 sqlite3_uint64;
   1.376 +
   1.377 +/*
   1.378 +** If compiling for a processor that lacks floating point support,
   1.379 +** substitute integer for floating-point.
   1.380 +*/
   1.381 +#ifdef SQLITE_OMIT_FLOATING_POINT
   1.382 +# define double sqlite3_int64
   1.383 +#endif
   1.384 +
   1.385 +/*
   1.386 +** CAPI3REF: Closing A Database Connection
   1.387 +**
   1.388 +** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
   1.389 +** for the [sqlite3] object.
   1.390 +** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if
   1.391 +** the [sqlite3] object is successfully destroyed and all associated
   1.392 +** resources are deallocated.
   1.393 +**
   1.394 +** ^If the database connection is associated with unfinalized prepared
   1.395 +** statements or unfinished sqlite3_backup objects then sqlite3_close()
   1.396 +** will leave the database connection open and return [SQLITE_BUSY].
   1.397 +** ^If sqlite3_close_v2() is called with unfinalized prepared statements
   1.398 +** and unfinished sqlite3_backups, then the database connection becomes
   1.399 +** an unusable "zombie" which will automatically be deallocated when the
   1.400 +** last prepared statement is finalized or the last sqlite3_backup is
   1.401 +** finished.  The sqlite3_close_v2() interface is intended for use with
   1.402 +** host languages that are garbage collected, and where the order in which
   1.403 +** destructors are called is arbitrary.
   1.404 +**
   1.405 +** Applications should [sqlite3_finalize | finalize] all [prepared statements],
   1.406 +** [sqlite3_blob_close | close] all [BLOB handles], and 
   1.407 +** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
   1.408 +** with the [sqlite3] object prior to attempting to close the object.  ^If
   1.409 +** sqlite3_close_v2() is called on a [database connection] that still has
   1.410 +** outstanding [prepared statements], [BLOB handles], and/or
   1.411 +** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation
   1.412 +** of resources is deferred until all [prepared statements], [BLOB handles],
   1.413 +** and [sqlite3_backup] objects are also destroyed.
   1.414 +**
   1.415 +** ^If an [sqlite3] object is destroyed while a transaction is open,
   1.416 +** the transaction is automatically rolled back.
   1.417 +**
   1.418 +** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
   1.419 +** must be either a NULL
   1.420 +** pointer or an [sqlite3] object pointer obtained
   1.421 +** from [sqlite3_open()], [sqlite3_open16()], or
   1.422 +** [sqlite3_open_v2()], and not previously closed.
   1.423 +** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
   1.424 +** argument is a harmless no-op.
   1.425 +*/
   1.426 +SQLITE_API int sqlite3_close(sqlite3*);
   1.427 +SQLITE_API int sqlite3_close_v2(sqlite3*);
   1.428 +
   1.429 +/*
   1.430 +** The type for a callback function.
   1.431 +** This is legacy and deprecated.  It is included for historical
   1.432 +** compatibility and is not documented.
   1.433 +*/
   1.434 +typedef int (*sqlite3_callback)(void*,int,char**, char**);
   1.435 +
   1.436 +/*
   1.437 +** CAPI3REF: One-Step Query Execution Interface
   1.438 +**
   1.439 +** The sqlite3_exec() interface is a convenience wrapper around
   1.440 +** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
   1.441 +** that allows an application to run multiple statements of SQL
   1.442 +** without having to use a lot of C code. 
   1.443 +**
   1.444 +** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
   1.445 +** semicolon-separate SQL statements passed into its 2nd argument,
   1.446 +** in the context of the [database connection] passed in as its 1st
   1.447 +** argument.  ^If the callback function of the 3rd argument to
   1.448 +** sqlite3_exec() is not NULL, then it is invoked for each result row
   1.449 +** coming out of the evaluated SQL statements.  ^The 4th argument to
   1.450 +** sqlite3_exec() is relayed through to the 1st argument of each
   1.451 +** callback invocation.  ^If the callback pointer to sqlite3_exec()
   1.452 +** is NULL, then no callback is ever invoked and result rows are
   1.453 +** ignored.
   1.454 +**
   1.455 +** ^If an error occurs while evaluating the SQL statements passed into
   1.456 +** sqlite3_exec(), then execution of the current statement stops and
   1.457 +** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
   1.458 +** is not NULL then any error message is written into memory obtained
   1.459 +** from [sqlite3_malloc()] and passed back through the 5th parameter.
   1.460 +** To avoid memory leaks, the application should invoke [sqlite3_free()]
   1.461 +** on error message strings returned through the 5th parameter of
   1.462 +** of sqlite3_exec() after the error message string is no longer needed.
   1.463 +** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
   1.464 +** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
   1.465 +** NULL before returning.
   1.466 +**
   1.467 +** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
   1.468 +** routine returns SQLITE_ABORT without invoking the callback again and
   1.469 +** without running any subsequent SQL statements.
   1.470 +**
   1.471 +** ^The 2nd argument to the sqlite3_exec() callback function is the
   1.472 +** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
   1.473 +** callback is an array of pointers to strings obtained as if from
   1.474 +** [sqlite3_column_text()], one for each column.  ^If an element of a
   1.475 +** result row is NULL then the corresponding string pointer for the
   1.476 +** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
   1.477 +** sqlite3_exec() callback is an array of pointers to strings where each
   1.478 +** entry represents the name of corresponding result column as obtained
   1.479 +** from [sqlite3_column_name()].
   1.480 +**
   1.481 +** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
   1.482 +** to an empty string, or a pointer that contains only whitespace and/or 
   1.483 +** SQL comments, then no SQL statements are evaluated and the database
   1.484 +** is not changed.
   1.485 +**
   1.486 +** Restrictions:
   1.487 +**
   1.488 +** <ul>
   1.489 +** <li> The application must insure that the 1st parameter to sqlite3_exec()
   1.490 +**      is a valid and open [database connection].
   1.491 +** <li> The application must not close the [database connection] specified by
   1.492 +**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
   1.493 +** <li> The application must not modify the SQL statement text passed into
   1.494 +**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
   1.495 +** </ul>
   1.496 +*/
   1.497 +SQLITE_API int sqlite3_exec(
   1.498 +  sqlite3*,                                  /* An open database */
   1.499 +  const char *sql,                           /* SQL to be evaluated */
   1.500 +  int (*callback)(void*,int,char**,char**),  /* Callback function */
   1.501 +  void *,                                    /* 1st argument to callback */
   1.502 +  char **errmsg                              /* Error msg written here */
   1.503 +);
   1.504 +
   1.505 +/*
   1.506 +** CAPI3REF: Result Codes
   1.507 +** KEYWORDS: SQLITE_OK {error code} {error codes}
   1.508 +** KEYWORDS: {result code} {result codes}
   1.509 +**
   1.510 +** Many SQLite functions return an integer result code from the set shown
   1.511 +** here in order to indicate success or failure.
   1.512 +**
   1.513 +** New error codes may be added in future versions of SQLite.
   1.514 +**
   1.515 +** See also: [SQLITE_IOERR_READ | extended result codes],
   1.516 +** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
   1.517 +*/
   1.518 +#define SQLITE_OK           0   /* Successful result */
   1.519 +/* beginning-of-error-codes */
   1.520 +#define SQLITE_ERROR        1   /* SQL error or missing database */
   1.521 +#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
   1.522 +#define SQLITE_PERM         3   /* Access permission denied */
   1.523 +#define SQLITE_ABORT        4   /* Callback routine requested an abort */
   1.524 +#define SQLITE_BUSY         5   /* The database file is locked */
   1.525 +#define SQLITE_LOCKED       6   /* A table in the database is locked */
   1.526 +#define SQLITE_NOMEM        7   /* A malloc() failed */
   1.527 +#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
   1.528 +#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
   1.529 +#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
   1.530 +#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
   1.531 +#define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
   1.532 +#define SQLITE_FULL        13   /* Insertion failed because database is full */
   1.533 +#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
   1.534 +#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
   1.535 +#define SQLITE_EMPTY       16   /* Database is empty */
   1.536 +#define SQLITE_SCHEMA      17   /* The database schema changed */
   1.537 +#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
   1.538 +#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
   1.539 +#define SQLITE_MISMATCH    20   /* Data type mismatch */
   1.540 +#define SQLITE_MISUSE      21   /* Library used incorrectly */
   1.541 +#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
   1.542 +#define SQLITE_AUTH        23   /* Authorization denied */
   1.543 +#define SQLITE_FORMAT      24   /* Auxiliary database format error */
   1.544 +#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
   1.545 +#define SQLITE_NOTADB      26   /* File opened that is not a database file */
   1.546 +#define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */
   1.547 +#define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
   1.548 +#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
   1.549 +#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
   1.550 +/* end-of-error-codes */
   1.551 +
   1.552 +/*
   1.553 +** CAPI3REF: Extended Result Codes
   1.554 +** KEYWORDS: {extended error code} {extended error codes}
   1.555 +** KEYWORDS: {extended result code} {extended result codes}
   1.556 +**
   1.557 +** In its default configuration, SQLite API routines return one of 26 integer
   1.558 +** [SQLITE_OK | result codes].  However, experience has shown that many of
   1.559 +** these result codes are too coarse-grained.  They do not provide as
   1.560 +** much information about problems as programmers might like.  In an effort to
   1.561 +** address this, newer versions of SQLite (version 3.3.8 and later) include
   1.562 +** support for additional result codes that provide more detailed information
   1.563 +** about errors. The extended result codes are enabled or disabled
   1.564 +** on a per database connection basis using the
   1.565 +** [sqlite3_extended_result_codes()] API.
   1.566 +**
   1.567 +** Some of the available extended result codes are listed here.
   1.568 +** One may expect the number of extended result codes will increase
   1.569 +** over time.  Software that uses extended result codes should expect
   1.570 +** to see new result codes in future releases of SQLite.
   1.571 +**
   1.572 +** The SQLITE_OK result code will never be extended.  It will always
   1.573 +** be exactly zero.
   1.574 +*/
   1.575 +#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
   1.576 +#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
   1.577 +#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
   1.578 +#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
   1.579 +#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
   1.580 +#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
   1.581 +#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
   1.582 +#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
   1.583 +#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
   1.584 +#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
   1.585 +#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
   1.586 +#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
   1.587 +#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
   1.588 +#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
   1.589 +#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
   1.590 +#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
   1.591 +#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
   1.592 +#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
   1.593 +#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
   1.594 +#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
   1.595 +#define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
   1.596 +#define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
   1.597 +#define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
   1.598 +#define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))
   1.599 +#define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))
   1.600 +#define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))
   1.601 +#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
   1.602 +#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
   1.603 +#define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
   1.604 +#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
   1.605 +#define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
   1.606 +#define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
   1.607 +#define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
   1.608 +#define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
   1.609 +#define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
   1.610 +#define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
   1.611 +#define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
   1.612 +#define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))
   1.613 +#define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
   1.614 +#define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
   1.615 +#define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
   1.616 +#define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
   1.617 +#define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
   1.618 +#define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
   1.619 +#define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
   1.620 +#define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
   1.621 +#define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
   1.622 +#define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
   1.623 +#define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
   1.624 +#define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
   1.625 +#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
   1.626 +#define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
   1.627 +
   1.628 +/*
   1.629 +** CAPI3REF: Flags For File Open Operations
   1.630 +**
   1.631 +** These bit values are intended for use in the
   1.632 +** 3rd parameter to the [sqlite3_open_v2()] interface and
   1.633 +** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
   1.634 +*/
   1.635 +#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
   1.636 +#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
   1.637 +#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
   1.638 +#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
   1.639 +#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
   1.640 +#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
   1.641 +#define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
   1.642 +#define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
   1.643 +#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
   1.644 +#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
   1.645 +#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
   1.646 +#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
   1.647 +#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
   1.648 +#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
   1.649 +#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
   1.650 +#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
   1.651 +#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
   1.652 +#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
   1.653 +#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
   1.654 +#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
   1.655 +
   1.656 +/* Reserved:                         0x00F00000 */
   1.657 +
   1.658 +/*
   1.659 +** CAPI3REF: Device Characteristics
   1.660 +**
   1.661 +** The xDeviceCharacteristics method of the [sqlite3_io_methods]
   1.662 +** object returns an integer which is a vector of these
   1.663 +** bit values expressing I/O characteristics of the mass storage
   1.664 +** device that holds the file that the [sqlite3_io_methods]
   1.665 +** refers to.
   1.666 +**
   1.667 +** The SQLITE_IOCAP_ATOMIC property means that all writes of
   1.668 +** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
   1.669 +** mean that writes of blocks that are nnn bytes in size and
   1.670 +** are aligned to an address which is an integer multiple of
   1.671 +** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
   1.672 +** that when data is appended to a file, the data is appended
   1.673 +** first then the size of the file is extended, never the other
   1.674 +** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
   1.675 +** information is written to disk in the same order as calls
   1.676 +** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
   1.677 +** after reboot following a crash or power loss, the only bytes in a
   1.678 +** file that were written at the application level might have changed
   1.679 +** and that adjacent bytes, even bytes within the same sector are
   1.680 +** guaranteed to be unchanged.  The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
   1.681 +** flag indicate that a file cannot be deleted when open.
   1.682 +*/
   1.683 +#define SQLITE_IOCAP_ATOMIC                 0x00000001
   1.684 +#define SQLITE_IOCAP_ATOMIC512              0x00000002
   1.685 +#define SQLITE_IOCAP_ATOMIC1K               0x00000004
   1.686 +#define SQLITE_IOCAP_ATOMIC2K               0x00000008
   1.687 +#define SQLITE_IOCAP_ATOMIC4K               0x00000010
   1.688 +#define SQLITE_IOCAP_ATOMIC8K               0x00000020
   1.689 +#define SQLITE_IOCAP_ATOMIC16K              0x00000040
   1.690 +#define SQLITE_IOCAP_ATOMIC32K              0x00000080
   1.691 +#define SQLITE_IOCAP_ATOMIC64K              0x00000100
   1.692 +#define SQLITE_IOCAP_SAFE_APPEND            0x00000200
   1.693 +#define SQLITE_IOCAP_SEQUENTIAL             0x00000400
   1.694 +#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
   1.695 +#define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
   1.696 +
   1.697 +/*
   1.698 +** CAPI3REF: File Locking Levels
   1.699 +**
   1.700 +** SQLite uses one of these integer values as the second
   1.701 +** argument to calls it makes to the xLock() and xUnlock() methods
   1.702 +** of an [sqlite3_io_methods] object.
   1.703 +*/
   1.704 +#define SQLITE_LOCK_NONE          0
   1.705 +#define SQLITE_LOCK_SHARED        1
   1.706 +#define SQLITE_LOCK_RESERVED      2
   1.707 +#define SQLITE_LOCK_PENDING       3
   1.708 +#define SQLITE_LOCK_EXCLUSIVE     4
   1.709 +
   1.710 +/*
   1.711 +** CAPI3REF: Synchronization Type Flags
   1.712 +**
   1.713 +** When SQLite invokes the xSync() method of an
   1.714 +** [sqlite3_io_methods] object it uses a combination of
   1.715 +** these integer values as the second argument.
   1.716 +**
   1.717 +** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
   1.718 +** sync operation only needs to flush data to mass storage.  Inode
   1.719 +** information need not be flushed. If the lower four bits of the flag
   1.720 +** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
   1.721 +** If the lower four bits equal SQLITE_SYNC_FULL, that means
   1.722 +** to use Mac OS X style fullsync instead of fsync().
   1.723 +**
   1.724 +** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
   1.725 +** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
   1.726 +** settings.  The [synchronous pragma] determines when calls to the
   1.727 +** xSync VFS method occur and applies uniformly across all platforms.
   1.728 +** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
   1.729 +** energetic or rigorous or forceful the sync operations are and
   1.730 +** only make a difference on Mac OSX for the default SQLite code.
   1.731 +** (Third-party VFS implementations might also make the distinction
   1.732 +** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
   1.733 +** operating systems natively supported by SQLite, only Mac OSX
   1.734 +** cares about the difference.)
   1.735 +*/
   1.736 +#define SQLITE_SYNC_NORMAL        0x00002
   1.737 +#define SQLITE_SYNC_FULL          0x00003
   1.738 +#define SQLITE_SYNC_DATAONLY      0x00010
   1.739 +
   1.740 +/*
   1.741 +** CAPI3REF: OS Interface Open File Handle
   1.742 +**
   1.743 +** An [sqlite3_file] object represents an open file in the 
   1.744 +** [sqlite3_vfs | OS interface layer].  Individual OS interface
   1.745 +** implementations will
   1.746 +** want to subclass this object by appending additional fields
   1.747 +** for their own use.  The pMethods entry is a pointer to an
   1.748 +** [sqlite3_io_methods] object that defines methods for performing
   1.749 +** I/O operations on the open file.
   1.750 +*/
   1.751 +typedef struct sqlite3_file sqlite3_file;
   1.752 +struct sqlite3_file {
   1.753 +  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
   1.754 +};
   1.755 +
   1.756 +/*
   1.757 +** CAPI3REF: OS Interface File Virtual Methods Object
   1.758 +**
   1.759 +** Every file opened by the [sqlite3_vfs.xOpen] method populates an
   1.760 +** [sqlite3_file] object (or, more commonly, a subclass of the
   1.761 +** [sqlite3_file] object) with a pointer to an instance of this object.
   1.762 +** This object defines the methods used to perform various operations
   1.763 +** against the open file represented by the [sqlite3_file] object.
   1.764 +**
   1.765 +** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element 
   1.766 +** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
   1.767 +** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
   1.768 +** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
   1.769 +** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
   1.770 +** to NULL.
   1.771 +**
   1.772 +** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
   1.773 +** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
   1.774 +** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
   1.775 +** flag may be ORed in to indicate that only the data of the file
   1.776 +** and not its inode needs to be synced.
   1.777 +**
   1.778 +** The integer values to xLock() and xUnlock() are one of
   1.779 +** <ul>
   1.780 +** <li> [SQLITE_LOCK_NONE],
   1.781 +** <li> [SQLITE_LOCK_SHARED],
   1.782 +** <li> [SQLITE_LOCK_RESERVED],
   1.783 +** <li> [SQLITE_LOCK_PENDING], or
   1.784 +** <li> [SQLITE_LOCK_EXCLUSIVE].
   1.785 +** </ul>
   1.786 +** xLock() increases the lock. xUnlock() decreases the lock.
   1.787 +** The xCheckReservedLock() method checks whether any database connection,
   1.788 +** either in this process or in some other process, is holding a RESERVED,
   1.789 +** PENDING, or EXCLUSIVE lock on the file.  It returns true
   1.790 +** if such a lock exists and false otherwise.
   1.791 +**
   1.792 +** The xFileControl() method is a generic interface that allows custom
   1.793 +** VFS implementations to directly control an open file using the
   1.794 +** [sqlite3_file_control()] interface.  The second "op" argument is an
   1.795 +** integer opcode.  The third argument is a generic pointer intended to
   1.796 +** point to a structure that may contain arguments or space in which to
   1.797 +** write return values.  Potential uses for xFileControl() might be
   1.798 +** functions to enable blocking locks with timeouts, to change the
   1.799 +** locking strategy (for example to use dot-file locks), to inquire
   1.800 +** about the status of a lock, or to break stale locks.  The SQLite
   1.801 +** core reserves all opcodes less than 100 for its own use.
   1.802 +** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
   1.803 +** Applications that define a custom xFileControl method should use opcodes
   1.804 +** greater than 100 to avoid conflicts.  VFS implementations should
   1.805 +** return [SQLITE_NOTFOUND] for file control opcodes that they do not
   1.806 +** recognize.
   1.807 +**
   1.808 +** The xSectorSize() method returns the sector size of the
   1.809 +** device that underlies the file.  The sector size is the
   1.810 +** minimum write that can be performed without disturbing
   1.811 +** other bytes in the file.  The xDeviceCharacteristics()
   1.812 +** method returns a bit vector describing behaviors of the
   1.813 +** underlying device:
   1.814 +**
   1.815 +** <ul>
   1.816 +** <li> [SQLITE_IOCAP_ATOMIC]
   1.817 +** <li> [SQLITE_IOCAP_ATOMIC512]
   1.818 +** <li> [SQLITE_IOCAP_ATOMIC1K]
   1.819 +** <li> [SQLITE_IOCAP_ATOMIC2K]
   1.820 +** <li> [SQLITE_IOCAP_ATOMIC4K]
   1.821 +** <li> [SQLITE_IOCAP_ATOMIC8K]
   1.822 +** <li> [SQLITE_IOCAP_ATOMIC16K]
   1.823 +** <li> [SQLITE_IOCAP_ATOMIC32K]
   1.824 +** <li> [SQLITE_IOCAP_ATOMIC64K]
   1.825 +** <li> [SQLITE_IOCAP_SAFE_APPEND]
   1.826 +** <li> [SQLITE_IOCAP_SEQUENTIAL]
   1.827 +** </ul>
   1.828 +**
   1.829 +** The SQLITE_IOCAP_ATOMIC property means that all writes of
   1.830 +** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
   1.831 +** mean that writes of blocks that are nnn bytes in size and
   1.832 +** are aligned to an address which is an integer multiple of
   1.833 +** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
   1.834 +** that when data is appended to a file, the data is appended
   1.835 +** first then the size of the file is extended, never the other
   1.836 +** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
   1.837 +** information is written to disk in the same order as calls
   1.838 +** to xWrite().
   1.839 +**
   1.840 +** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
   1.841 +** in the unread portions of the buffer with zeros.  A VFS that
   1.842 +** fails to zero-fill short reads might seem to work.  However,
   1.843 +** failure to zero-fill short reads will eventually lead to
   1.844 +** database corruption.
   1.845 +*/
   1.846 +typedef struct sqlite3_io_methods sqlite3_io_methods;
   1.847 +struct sqlite3_io_methods {
   1.848 +  int iVersion;
   1.849 +  int (*xClose)(sqlite3_file*);
   1.850 +  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
   1.851 +  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
   1.852 +  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
   1.853 +  int (*xSync)(sqlite3_file*, int flags);
   1.854 +  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
   1.855 +  int (*xLock)(sqlite3_file*, int);
   1.856 +  int (*xUnlock)(sqlite3_file*, int);
   1.857 +  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
   1.858 +  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
   1.859 +  int (*xSectorSize)(sqlite3_file*);
   1.860 +  int (*xDeviceCharacteristics)(sqlite3_file*);
   1.861 +  /* Methods above are valid for version 1 */
   1.862 +  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
   1.863 +  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
   1.864 +  void (*xShmBarrier)(sqlite3_file*);
   1.865 +  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
   1.866 +  /* Methods above are valid for version 2 */
   1.867 +  int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
   1.868 +  int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
   1.869 +  /* Methods above are valid for version 3 */
   1.870 +  /* Additional methods may be added in future releases */
   1.871 +};
   1.872 +
   1.873 +/*
   1.874 +** CAPI3REF: Standard File Control Opcodes
   1.875 +**
   1.876 +** These integer constants are opcodes for the xFileControl method
   1.877 +** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
   1.878 +** interface.
   1.879 +**
   1.880 +** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
   1.881 +** opcode causes the xFileControl method to write the current state of
   1.882 +** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
   1.883 +** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
   1.884 +** into an integer that the pArg argument points to. This capability
   1.885 +** is used during testing and only needs to be supported when SQLITE_TEST
   1.886 +** is defined.
   1.887 +** <ul>
   1.888 +** <li>[[SQLITE_FCNTL_SIZE_HINT]]
   1.889 +** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
   1.890 +** layer a hint of how large the database file will grow to be during the
   1.891 +** current transaction.  This hint is not guaranteed to be accurate but it
   1.892 +** is often close.  The underlying VFS might choose to preallocate database
   1.893 +** file space based on this hint in order to help writes to the database
   1.894 +** file run faster.
   1.895 +**
   1.896 +** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
   1.897 +** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
   1.898 +** extends and truncates the database file in chunks of a size specified
   1.899 +** by the user. The fourth argument to [sqlite3_file_control()] should 
   1.900 +** point to an integer (type int) containing the new chunk-size to use
   1.901 +** for the nominated database. Allocating database file space in large
   1.902 +** chunks (say 1MB at a time), may reduce file-system fragmentation and
   1.903 +** improve performance on some systems.
   1.904 +**
   1.905 +** <li>[[SQLITE_FCNTL_FILE_POINTER]]
   1.906 +** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
   1.907 +** to the [sqlite3_file] object associated with a particular database
   1.908 +** connection.  See the [sqlite3_file_control()] documentation for
   1.909 +** additional information.
   1.910 +**
   1.911 +** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
   1.912 +** No longer in use.
   1.913 +**
   1.914 +** <li>[[SQLITE_FCNTL_SYNC]]
   1.915 +** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
   1.916 +** sent to the VFS immediately before the xSync method is invoked on a
   1.917 +** database file descriptor. Or, if the xSync method is not invoked 
   1.918 +** because the user has configured SQLite with 
   1.919 +** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place 
   1.920 +** of the xSync method. In most cases, the pointer argument passed with
   1.921 +** this file-control is NULL. However, if the database file is being synced
   1.922 +** as part of a multi-database commit, the argument points to a nul-terminated
   1.923 +** string containing the transactions master-journal file name. VFSes that 
   1.924 +** do not need this signal should silently ignore this opcode. Applications 
   1.925 +** should not call [sqlite3_file_control()] with this opcode as doing so may 
   1.926 +** disrupt the operation of the specialized VFSes that do require it.  
   1.927 +**
   1.928 +** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
   1.929 +** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
   1.930 +** and sent to the VFS after a transaction has been committed immediately
   1.931 +** but before the database is unlocked. VFSes that do not need this signal
   1.932 +** should silently ignore this opcode. Applications should not call
   1.933 +** [sqlite3_file_control()] with this opcode as doing so may disrupt the 
   1.934 +** operation of the specialized VFSes that do require it.  
   1.935 +**
   1.936 +** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
   1.937 +** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
   1.938 +** retry counts and intervals for certain disk I/O operations for the
   1.939 +** windows [VFS] in order to provide robustness in the presence of
   1.940 +** anti-virus programs.  By default, the windows VFS will retry file read,
   1.941 +** file write, and file delete operations up to 10 times, with a delay
   1.942 +** of 25 milliseconds before the first retry and with the delay increasing
   1.943 +** by an additional 25 milliseconds with each subsequent retry.  This
   1.944 +** opcode allows these two values (10 retries and 25 milliseconds of delay)
   1.945 +** to be adjusted.  The values are changed for all database connections
   1.946 +** within the same process.  The argument is a pointer to an array of two
   1.947 +** integers where the first integer i the new retry count and the second
   1.948 +** integer is the delay.  If either integer is negative, then the setting
   1.949 +** is not changed but instead the prior value of that setting is written
   1.950 +** into the array entry, allowing the current retry settings to be
   1.951 +** interrogated.  The zDbName parameter is ignored.
   1.952 +**
   1.953 +** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
   1.954 +** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
   1.955 +** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
   1.956 +** write ahead log and shared memory files used for transaction control
   1.957 +** are automatically deleted when the latest connection to the database
   1.958 +** closes.  Setting persistent WAL mode causes those files to persist after
   1.959 +** close.  Persisting the files is useful when other processes that do not
   1.960 +** have write permission on the directory containing the database file want
   1.961 +** to read the database file, as the WAL and shared memory files must exist
   1.962 +** in order for the database to be readable.  The fourth parameter to
   1.963 +** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
   1.964 +** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
   1.965 +** WAL mode.  If the integer is -1, then it is overwritten with the current
   1.966 +** WAL persistence setting.
   1.967 +**
   1.968 +** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
   1.969 +** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
   1.970 +** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
   1.971 +** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
   1.972 +** xDeviceCharacteristics methods. The fourth parameter to
   1.973 +** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
   1.974 +** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
   1.975 +** mode.  If the integer is -1, then it is overwritten with the current
   1.976 +** zero-damage mode setting.
   1.977 +**
   1.978 +** <li>[[SQLITE_FCNTL_OVERWRITE]]
   1.979 +** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
   1.980 +** a write transaction to indicate that, unless it is rolled back for some
   1.981 +** reason, the entire database file will be overwritten by the current 
   1.982 +** transaction. This is used by VACUUM operations.
   1.983 +**
   1.984 +** <li>[[SQLITE_FCNTL_VFSNAME]]
   1.985 +** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
   1.986 +** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
   1.987 +** final bottom-level VFS are written into memory obtained from 
   1.988 +** [sqlite3_malloc()] and the result is stored in the char* variable
   1.989 +** that the fourth parameter of [sqlite3_file_control()] points to.
   1.990 +** The caller is responsible for freeing the memory when done.  As with
   1.991 +** all file-control actions, there is no guarantee that this will actually
   1.992 +** do anything.  Callers should initialize the char* variable to a NULL
   1.993 +** pointer in case this file-control is not implemented.  This file-control
   1.994 +** is intended for diagnostic use only.
   1.995 +**
   1.996 +** <li>[[SQLITE_FCNTL_PRAGMA]]
   1.997 +** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] 
   1.998 +** file control is sent to the open [sqlite3_file] object corresponding
   1.999 +** to the database file to which the pragma statement refers. ^The argument
  1.1000 +** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  1.1001 +** pointers to strings (char**) in which the second element of the array
  1.1002 +** is the name of the pragma and the third element is the argument to the
  1.1003 +** pragma or NULL if the pragma has no argument.  ^The handler for an
  1.1004 +** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  1.1005 +** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  1.1006 +** or the equivalent and that string will become the result of the pragma or
  1.1007 +** the error message if the pragma fails. ^If the
  1.1008 +** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal 
  1.1009 +** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
  1.1010 +** file control returns [SQLITE_OK], then the parser assumes that the
  1.1011 +** VFS has handled the PRAGMA itself and the parser generates a no-op
  1.1012 +** prepared statement.  ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  1.1013 +** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  1.1014 +** that the VFS encountered an error while handling the [PRAGMA] and the
  1.1015 +** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
  1.1016 +** file control occurs at the beginning of pragma statement analysis and so
  1.1017 +** it is able to override built-in [PRAGMA] statements.
  1.1018 +**
  1.1019 +** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  1.1020 +** ^The [SQLITE_FCNTL_BUSYHANDLER]
  1.1021 +** file-control may be invoked by SQLite on the database file handle
  1.1022 +** shortly after it is opened in order to provide a custom VFS with access
  1.1023 +** to the connections busy-handler callback. The argument is of type (void **)
  1.1024 +** - an array of two (void *) values. The first (void *) actually points
  1.1025 +** to a function of type (int (*)(void *)). In order to invoke the connections
  1.1026 +** busy-handler, this function should be invoked with the second (void *) in
  1.1027 +** the array as the only argument. If it returns non-zero, then the operation
  1.1028 +** should be retried. If it returns zero, the custom VFS should abandon the
  1.1029 +** current operation.
  1.1030 +**
  1.1031 +** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  1.1032 +** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  1.1033 +** to have SQLite generate a
  1.1034 +** temporary filename using the same algorithm that is followed to generate
  1.1035 +** temporary filenames for TEMP tables and other internal uses.  The
  1.1036 +** argument should be a char** which will be filled with the filename
  1.1037 +** written into memory obtained from [sqlite3_malloc()].  The caller should
  1.1038 +** invoke [sqlite3_free()] on the result to avoid a memory leak.
  1.1039 +**
  1.1040 +** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  1.1041 +** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  1.1042 +** maximum number of bytes that will be used for memory-mapped I/O.
  1.1043 +** The argument is a pointer to a value of type sqlite3_int64 that
  1.1044 +** is an advisory maximum number of bytes in the file to memory map.  The
  1.1045 +** pointer is overwritten with the old value.  The limit is not changed if
  1.1046 +** the value originally pointed to is negative, and so the current limit 
  1.1047 +** can be queried by passing in a pointer to a negative number.  This
  1.1048 +** file-control is used internally to implement [PRAGMA mmap_size].
  1.1049 +**
  1.1050 +** <li>[[SQLITE_FCNTL_TRACE]]
  1.1051 +** The [SQLITE_FCNTL_TRACE] file control provides advisory information
  1.1052 +** to the VFS about what the higher layers of the SQLite stack are doing.
  1.1053 +** This file control is used by some VFS activity tracing [shims].
  1.1054 +** The argument is a zero-terminated string.  Higher layers in the
  1.1055 +** SQLite stack may generate instances of this file control if
  1.1056 +** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
  1.1057 +**
  1.1058 +** <li>[[SQLITE_FCNTL_HAS_MOVED]]
  1.1059 +** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
  1.1060 +** pointer to an integer and it writes a boolean into that integer depending
  1.1061 +** on whether or not the file has been renamed, moved, or deleted since it
  1.1062 +** was first opened.
  1.1063 +**
  1.1064 +** </ul>
  1.1065 +*/
  1.1066 +#define SQLITE_FCNTL_LOCKSTATE               1
  1.1067 +#define SQLITE_GET_LOCKPROXYFILE             2
  1.1068 +#define SQLITE_SET_LOCKPROXYFILE             3
  1.1069 +#define SQLITE_LAST_ERRNO                    4
  1.1070 +#define SQLITE_FCNTL_SIZE_HINT               5
  1.1071 +#define SQLITE_FCNTL_CHUNK_SIZE              6
  1.1072 +#define SQLITE_FCNTL_FILE_POINTER            7
  1.1073 +#define SQLITE_FCNTL_SYNC_OMITTED            8
  1.1074 +#define SQLITE_FCNTL_WIN32_AV_RETRY          9
  1.1075 +#define SQLITE_FCNTL_PERSIST_WAL            10
  1.1076 +#define SQLITE_FCNTL_OVERWRITE              11
  1.1077 +#define SQLITE_FCNTL_VFSNAME                12
  1.1078 +#define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
  1.1079 +#define SQLITE_FCNTL_PRAGMA                 14
  1.1080 +#define SQLITE_FCNTL_BUSYHANDLER            15
  1.1081 +#define SQLITE_FCNTL_TEMPFILENAME           16
  1.1082 +#define SQLITE_FCNTL_MMAP_SIZE              18
  1.1083 +#define SQLITE_FCNTL_TRACE                  19
  1.1084 +#define SQLITE_FCNTL_HAS_MOVED              20
  1.1085 +#define SQLITE_FCNTL_SYNC                   21
  1.1086 +#define SQLITE_FCNTL_COMMIT_PHASETWO        22
  1.1087 +
  1.1088 +/*
  1.1089 +** CAPI3REF: Mutex Handle
  1.1090 +**
  1.1091 +** The mutex module within SQLite defines [sqlite3_mutex] to be an
  1.1092 +** abstract type for a mutex object.  The SQLite core never looks
  1.1093 +** at the internal representation of an [sqlite3_mutex].  It only
  1.1094 +** deals with pointers to the [sqlite3_mutex] object.
  1.1095 +**
  1.1096 +** Mutexes are created using [sqlite3_mutex_alloc()].
  1.1097 +*/
  1.1098 +typedef struct sqlite3_mutex sqlite3_mutex;
  1.1099 +
  1.1100 +/*
  1.1101 +** CAPI3REF: OS Interface Object
  1.1102 +**
  1.1103 +** An instance of the sqlite3_vfs object defines the interface between
  1.1104 +** the SQLite core and the underlying operating system.  The "vfs"
  1.1105 +** in the name of the object stands for "virtual file system".  See
  1.1106 +** the [VFS | VFS documentation] for further information.
  1.1107 +**
  1.1108 +** The value of the iVersion field is initially 1 but may be larger in
  1.1109 +** future versions of SQLite.  Additional fields may be appended to this
  1.1110 +** object when the iVersion value is increased.  Note that the structure
  1.1111 +** of the sqlite3_vfs object changes in the transaction between
  1.1112 +** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  1.1113 +** modified.
  1.1114 +**
  1.1115 +** The szOsFile field is the size of the subclassed [sqlite3_file]
  1.1116 +** structure used by this VFS.  mxPathname is the maximum length of
  1.1117 +** a pathname in this VFS.
  1.1118 +**
  1.1119 +** Registered sqlite3_vfs objects are kept on a linked list formed by
  1.1120 +** the pNext pointer.  The [sqlite3_vfs_register()]
  1.1121 +** and [sqlite3_vfs_unregister()] interfaces manage this list
  1.1122 +** in a thread-safe way.  The [sqlite3_vfs_find()] interface
  1.1123 +** searches the list.  Neither the application code nor the VFS
  1.1124 +** implementation should use the pNext pointer.
  1.1125 +**
  1.1126 +** The pNext field is the only field in the sqlite3_vfs
  1.1127 +** structure that SQLite will ever modify.  SQLite will only access
  1.1128 +** or modify this field while holding a particular static mutex.
  1.1129 +** The application should never modify anything within the sqlite3_vfs
  1.1130 +** object once the object has been registered.
  1.1131 +**
  1.1132 +** The zName field holds the name of the VFS module.  The name must
  1.1133 +** be unique across all VFS modules.
  1.1134 +**
  1.1135 +** [[sqlite3_vfs.xOpen]]
  1.1136 +** ^SQLite guarantees that the zFilename parameter to xOpen
  1.1137 +** is either a NULL pointer or string obtained
  1.1138 +** from xFullPathname() with an optional suffix added.
  1.1139 +** ^If a suffix is added to the zFilename parameter, it will
  1.1140 +** consist of a single "-" character followed by no more than
  1.1141 +** 11 alphanumeric and/or "-" characters.
  1.1142 +** ^SQLite further guarantees that
  1.1143 +** the string will be valid and unchanged until xClose() is
  1.1144 +** called. Because of the previous sentence,
  1.1145 +** the [sqlite3_file] can safely store a pointer to the
  1.1146 +** filename if it needs to remember the filename for some reason.
  1.1147 +** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  1.1148 +** must invent its own temporary name for the file.  ^Whenever the 
  1.1149 +** xFilename parameter is NULL it will also be the case that the
  1.1150 +** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  1.1151 +**
  1.1152 +** The flags argument to xOpen() includes all bits set in
  1.1153 +** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
  1.1154 +** or [sqlite3_open16()] is used, then flags includes at least
  1.1155 +** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
  1.1156 +** If xOpen() opens a file read-only then it sets *pOutFlags to
  1.1157 +** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
  1.1158 +**
  1.1159 +** ^(SQLite will also add one of the following flags to the xOpen()
  1.1160 +** call, depending on the object being opened:
  1.1161 +**
  1.1162 +** <ul>
  1.1163 +** <li>  [SQLITE_OPEN_MAIN_DB]
  1.1164 +** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
  1.1165 +** <li>  [SQLITE_OPEN_TEMP_DB]
  1.1166 +** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
  1.1167 +** <li>  [SQLITE_OPEN_TRANSIENT_DB]
  1.1168 +** <li>  [SQLITE_OPEN_SUBJOURNAL]
  1.1169 +** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
  1.1170 +** <li>  [SQLITE_OPEN_WAL]
  1.1171 +** </ul>)^
  1.1172 +**
  1.1173 +** The file I/O implementation can use the object type flags to
  1.1174 +** change the way it deals with files.  For example, an application
  1.1175 +** that does not care about crash recovery or rollback might make
  1.1176 +** the open of a journal file a no-op.  Writes to this journal would
  1.1177 +** also be no-ops, and any attempt to read the journal would return
  1.1178 +** SQLITE_IOERR.  Or the implementation might recognize that a database
  1.1179 +** file will be doing page-aligned sector reads and writes in a random
  1.1180 +** order and set up its I/O subsystem accordingly.
  1.1181 +**
  1.1182 +** SQLite might also add one of the following flags to the xOpen method:
  1.1183 +**
  1.1184 +** <ul>
  1.1185 +** <li> [SQLITE_OPEN_DELETEONCLOSE]
  1.1186 +** <li> [SQLITE_OPEN_EXCLUSIVE]
  1.1187 +** </ul>
  1.1188 +**
  1.1189 +** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  1.1190 +** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
  1.1191 +** will be set for TEMP databases and their journals, transient
  1.1192 +** databases, and subjournals.
  1.1193 +**
  1.1194 +** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  1.1195 +** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  1.1196 +** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  1.1197 +** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
  1.1198 +** SQLITE_OPEN_CREATE, is used to indicate that file should always
  1.1199 +** be created, and that it is an error if it already exists.
  1.1200 +** It is <i>not</i> used to indicate the file should be opened 
  1.1201 +** for exclusive access.
  1.1202 +**
  1.1203 +** ^At least szOsFile bytes of memory are allocated by SQLite
  1.1204 +** to hold the  [sqlite3_file] structure passed as the third
  1.1205 +** argument to xOpen.  The xOpen method does not have to
  1.1206 +** allocate the structure; it should just fill it in.  Note that
  1.1207 +** the xOpen method must set the sqlite3_file.pMethods to either
  1.1208 +** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
  1.1209 +** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
  1.1210 +** element will be valid after xOpen returns regardless of the success
  1.1211 +** or failure of the xOpen call.
  1.1212 +**
  1.1213 +** [[sqlite3_vfs.xAccess]]
  1.1214 +** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  1.1215 +** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  1.1216 +** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  1.1217 +** to test whether a file is at least readable.   The file can be a
  1.1218 +** directory.
  1.1219 +**
  1.1220 +** ^SQLite will always allocate at least mxPathname+1 bytes for the
  1.1221 +** output buffer xFullPathname.  The exact size of the output buffer
  1.1222 +** is also passed as a parameter to both  methods. If the output buffer
  1.1223 +** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  1.1224 +** handled as a fatal error by SQLite, vfs implementations should endeavor
  1.1225 +** to prevent this by setting mxPathname to a sufficiently large value.
  1.1226 +**
  1.1227 +** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  1.1228 +** interfaces are not strictly a part of the filesystem, but they are
  1.1229 +** included in the VFS structure for completeness.
  1.1230 +** The xRandomness() function attempts to return nBytes bytes
  1.1231 +** of good-quality randomness into zOut.  The return value is
  1.1232 +** the actual number of bytes of randomness obtained.
  1.1233 +** The xSleep() method causes the calling thread to sleep for at
  1.1234 +** least the number of microseconds given.  ^The xCurrentTime()
  1.1235 +** method returns a Julian Day Number for the current date and time as
  1.1236 +** a floating point value.
  1.1237 +** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  1.1238 +** Day Number multiplied by 86400000 (the number of milliseconds in 
  1.1239 +** a 24-hour day).  
  1.1240 +** ^SQLite will use the xCurrentTimeInt64() method to get the current
  1.1241 +** date and time if that method is available (if iVersion is 2 or 
  1.1242 +** greater and the function pointer is not NULL) and will fall back
  1.1243 +** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  1.1244 +**
  1.1245 +** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  1.1246 +** are not used by the SQLite core.  These optional interfaces are provided
  1.1247 +** by some VFSes to facilitate testing of the VFS code. By overriding 
  1.1248 +** system calls with functions under its control, a test program can
  1.1249 +** simulate faults and error conditions that would otherwise be difficult
  1.1250 +** or impossible to induce.  The set of system calls that can be overridden
  1.1251 +** varies from one VFS to another, and from one version of the same VFS to the
  1.1252 +** next.  Applications that use these interfaces must be prepared for any
  1.1253 +** or all of these interfaces to be NULL or for their behavior to change
  1.1254 +** from one release to the next.  Applications must not attempt to access
  1.1255 +** any of these methods if the iVersion of the VFS is less than 3.
  1.1256 +*/
  1.1257 +typedef struct sqlite3_vfs sqlite3_vfs;
  1.1258 +typedef void (*sqlite3_syscall_ptr)(void);
  1.1259 +struct sqlite3_vfs {
  1.1260 +  int iVersion;            /* Structure version number (currently 3) */
  1.1261 +  int szOsFile;            /* Size of subclassed sqlite3_file */
  1.1262 +  int mxPathname;          /* Maximum file pathname length */
  1.1263 +  sqlite3_vfs *pNext;      /* Next registered VFS */
  1.1264 +  const char *zName;       /* Name of this virtual file system */
  1.1265 +  void *pAppData;          /* Pointer to application-specific data */
  1.1266 +  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  1.1267 +               int flags, int *pOutFlags);
  1.1268 +  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  1.1269 +  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  1.1270 +  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  1.1271 +  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  1.1272 +  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  1.1273 +  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  1.1274 +  void (*xDlClose)(sqlite3_vfs*, void*);
  1.1275 +  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  1.1276 +  int (*xSleep)(sqlite3_vfs*, int microseconds);
  1.1277 +  int (*xCurrentTime)(sqlite3_vfs*, double*);
  1.1278 +  int (*xGetLastError)(sqlite3_vfs*, int, char *);
  1.1279 +  /*
  1.1280 +  ** The methods above are in version 1 of the sqlite_vfs object
  1.1281 +  ** definition.  Those that follow are added in version 2 or later
  1.1282 +  */
  1.1283 +  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  1.1284 +  /*
  1.1285 +  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  1.1286 +  ** Those below are for version 3 and greater.
  1.1287 +  */
  1.1288 +  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  1.1289 +  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  1.1290 +  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  1.1291 +  /*
  1.1292 +  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  1.1293 +  ** New fields may be appended in figure versions.  The iVersion
  1.1294 +  ** value will increment whenever this happens. 
  1.1295 +  */
  1.1296 +};
  1.1297 +
  1.1298 +/*
  1.1299 +** CAPI3REF: Flags for the xAccess VFS method
  1.1300 +**
  1.1301 +** These integer constants can be used as the third parameter to
  1.1302 +** the xAccess method of an [sqlite3_vfs] object.  They determine
  1.1303 +** what kind of permissions the xAccess method is looking for.
  1.1304 +** With SQLITE_ACCESS_EXISTS, the xAccess method
  1.1305 +** simply checks whether the file exists.
  1.1306 +** With SQLITE_ACCESS_READWRITE, the xAccess method
  1.1307 +** checks whether the named directory is both readable and writable
  1.1308 +** (in other words, if files can be added, removed, and renamed within
  1.1309 +** the directory).
  1.1310 +** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  1.1311 +** [temp_store_directory pragma], though this could change in a future
  1.1312 +** release of SQLite.
  1.1313 +** With SQLITE_ACCESS_READ, the xAccess method
  1.1314 +** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
  1.1315 +** currently unused, though it might be used in a future release of
  1.1316 +** SQLite.
  1.1317 +*/
  1.1318 +#define SQLITE_ACCESS_EXISTS    0
  1.1319 +#define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
  1.1320 +#define SQLITE_ACCESS_READ      2   /* Unused */
  1.1321 +
  1.1322 +/*
  1.1323 +** CAPI3REF: Flags for the xShmLock VFS method
  1.1324 +**
  1.1325 +** These integer constants define the various locking operations
  1.1326 +** allowed by the xShmLock method of [sqlite3_io_methods].  The
  1.1327 +** following are the only legal combinations of flags to the
  1.1328 +** xShmLock method:
  1.1329 +**
  1.1330 +** <ul>
  1.1331 +** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  1.1332 +** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  1.1333 +** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  1.1334 +** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  1.1335 +** </ul>
  1.1336 +**
  1.1337 +** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  1.1338 +** was given no the corresponding lock.  
  1.1339 +**
  1.1340 +** The xShmLock method can transition between unlocked and SHARED or
  1.1341 +** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
  1.1342 +** and EXCLUSIVE.
  1.1343 +*/
  1.1344 +#define SQLITE_SHM_UNLOCK       1
  1.1345 +#define SQLITE_SHM_LOCK         2
  1.1346 +#define SQLITE_SHM_SHARED       4
  1.1347 +#define SQLITE_SHM_EXCLUSIVE    8
  1.1348 +
  1.1349 +/*
  1.1350 +** CAPI3REF: Maximum xShmLock index
  1.1351 +**
  1.1352 +** The xShmLock method on [sqlite3_io_methods] may use values
  1.1353 +** between 0 and this upper bound as its "offset" argument.
  1.1354 +** The SQLite core will never attempt to acquire or release a
  1.1355 +** lock outside of this range
  1.1356 +*/
  1.1357 +#define SQLITE_SHM_NLOCK        8
  1.1358 +
  1.1359 +
  1.1360 +/*
  1.1361 +** CAPI3REF: Initialize The SQLite Library
  1.1362 +**
  1.1363 +** ^The sqlite3_initialize() routine initializes the
  1.1364 +** SQLite library.  ^The sqlite3_shutdown() routine
  1.1365 +** deallocates any resources that were allocated by sqlite3_initialize().
  1.1366 +** These routines are designed to aid in process initialization and
  1.1367 +** shutdown on embedded systems.  Workstation applications using
  1.1368 +** SQLite normally do not need to invoke either of these routines.
  1.1369 +**
  1.1370 +** A call to sqlite3_initialize() is an "effective" call if it is
  1.1371 +** the first time sqlite3_initialize() is invoked during the lifetime of
  1.1372 +** the process, or if it is the first time sqlite3_initialize() is invoked
  1.1373 +** following a call to sqlite3_shutdown().  ^(Only an effective call
  1.1374 +** of sqlite3_initialize() does any initialization.  All other calls
  1.1375 +** are harmless no-ops.)^
  1.1376 +**
  1.1377 +** A call to sqlite3_shutdown() is an "effective" call if it is the first
  1.1378 +** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
  1.1379 +** an effective call to sqlite3_shutdown() does any deinitialization.
  1.1380 +** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  1.1381 +**
  1.1382 +** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  1.1383 +** is not.  The sqlite3_shutdown() interface must only be called from a
  1.1384 +** single thread.  All open [database connections] must be closed and all
  1.1385 +** other SQLite resources must be deallocated prior to invoking
  1.1386 +** sqlite3_shutdown().
  1.1387 +**
  1.1388 +** Among other things, ^sqlite3_initialize() will invoke
  1.1389 +** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
  1.1390 +** will invoke sqlite3_os_end().
  1.1391 +**
  1.1392 +** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  1.1393 +** ^If for some reason, sqlite3_initialize() is unable to initialize
  1.1394 +** the library (perhaps it is unable to allocate a needed resource such
  1.1395 +** as a mutex) it returns an [error code] other than [SQLITE_OK].
  1.1396 +**
  1.1397 +** ^The sqlite3_initialize() routine is called internally by many other
  1.1398 +** SQLite interfaces so that an application usually does not need to
  1.1399 +** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
  1.1400 +** calls sqlite3_initialize() so the SQLite library will be automatically
  1.1401 +** initialized when [sqlite3_open()] is called if it has not be initialized
  1.1402 +** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  1.1403 +** compile-time option, then the automatic calls to sqlite3_initialize()
  1.1404 +** are omitted and the application must call sqlite3_initialize() directly
  1.1405 +** prior to using any other SQLite interface.  For maximum portability,
  1.1406 +** it is recommended that applications always invoke sqlite3_initialize()
  1.1407 +** directly prior to using any other SQLite interface.  Future releases
  1.1408 +** of SQLite may require this.  In other words, the behavior exhibited
  1.1409 +** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  1.1410 +** default behavior in some future release of SQLite.
  1.1411 +**
  1.1412 +** The sqlite3_os_init() routine does operating-system specific
  1.1413 +** initialization of the SQLite library.  The sqlite3_os_end()
  1.1414 +** routine undoes the effect of sqlite3_os_init().  Typical tasks
  1.1415 +** performed by these routines include allocation or deallocation
  1.1416 +** of static resources, initialization of global variables,
  1.1417 +** setting up a default [sqlite3_vfs] module, or setting up
  1.1418 +** a default configuration using [sqlite3_config()].
  1.1419 +**
  1.1420 +** The application should never invoke either sqlite3_os_init()
  1.1421 +** or sqlite3_os_end() directly.  The application should only invoke
  1.1422 +** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
  1.1423 +** interface is called automatically by sqlite3_initialize() and
  1.1424 +** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
  1.1425 +** implementations for sqlite3_os_init() and sqlite3_os_end()
  1.1426 +** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  1.1427 +** When [custom builds | built for other platforms]
  1.1428 +** (using the [SQLITE_OS_OTHER=1] compile-time
  1.1429 +** option) the application must supply a suitable implementation for
  1.1430 +** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
  1.1431 +** implementation of sqlite3_os_init() or sqlite3_os_end()
  1.1432 +** must return [SQLITE_OK] on success and some other [error code] upon
  1.1433 +** failure.
  1.1434 +*/
  1.1435 +SQLITE_API int sqlite3_initialize(void);
  1.1436 +SQLITE_API int sqlite3_shutdown(void);
  1.1437 +SQLITE_API int sqlite3_os_init(void);
  1.1438 +SQLITE_API int sqlite3_os_end(void);
  1.1439 +
  1.1440 +/*
  1.1441 +** CAPI3REF: Configuring The SQLite Library
  1.1442 +**
  1.1443 +** The sqlite3_config() interface is used to make global configuration
  1.1444 +** changes to SQLite in order to tune SQLite to the specific needs of
  1.1445 +** the application.  The default configuration is recommended for most
  1.1446 +** applications and so this routine is usually not necessary.  It is
  1.1447 +** provided to support rare applications with unusual needs.
  1.1448 +**
  1.1449 +** The sqlite3_config() interface is not threadsafe.  The application
  1.1450 +** must insure that no other SQLite interfaces are invoked by other
  1.1451 +** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
  1.1452 +** may only be invoked prior to library initialization using
  1.1453 +** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  1.1454 +** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  1.1455 +** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  1.1456 +** Note, however, that ^sqlite3_config() can be called as part of the
  1.1457 +** implementation of an application-defined [sqlite3_os_init()].
  1.1458 +**
  1.1459 +** The first argument to sqlite3_config() is an integer
  1.1460 +** [configuration option] that determines
  1.1461 +** what property of SQLite is to be configured.  Subsequent arguments
  1.1462 +** vary depending on the [configuration option]
  1.1463 +** in the first argument.
  1.1464 +**
  1.1465 +** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  1.1466 +** ^If the option is unknown or SQLite is unable to set the option
  1.1467 +** then this routine returns a non-zero [error code].
  1.1468 +*/
  1.1469 +SQLITE_API int sqlite3_config(int, ...);
  1.1470 +
  1.1471 +/*
  1.1472 +** CAPI3REF: Configure database connections
  1.1473 +**
  1.1474 +** The sqlite3_db_config() interface is used to make configuration
  1.1475 +** changes to a [database connection].  The interface is similar to
  1.1476 +** [sqlite3_config()] except that the changes apply to a single
  1.1477 +** [database connection] (specified in the first argument).
  1.1478 +**
  1.1479 +** The second argument to sqlite3_db_config(D,V,...)  is the
  1.1480 +** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code 
  1.1481 +** that indicates what aspect of the [database connection] is being configured.
  1.1482 +** Subsequent arguments vary depending on the configuration verb.
  1.1483 +**
  1.1484 +** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  1.1485 +** the call is considered successful.
  1.1486 +*/
  1.1487 +SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  1.1488 +
  1.1489 +/*
  1.1490 +** CAPI3REF: Memory Allocation Routines
  1.1491 +**
  1.1492 +** An instance of this object defines the interface between SQLite
  1.1493 +** and low-level memory allocation routines.
  1.1494 +**
  1.1495 +** This object is used in only one place in the SQLite interface.
  1.1496 +** A pointer to an instance of this object is the argument to
  1.1497 +** [sqlite3_config()] when the configuration option is
  1.1498 +** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
  1.1499 +** By creating an instance of this object
  1.1500 +** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  1.1501 +** during configuration, an application can specify an alternative
  1.1502 +** memory allocation subsystem for SQLite to use for all of its
  1.1503 +** dynamic memory needs.
  1.1504 +**
  1.1505 +** Note that SQLite comes with several [built-in memory allocators]
  1.1506 +** that are perfectly adequate for the overwhelming majority of applications
  1.1507 +** and that this object is only useful to a tiny minority of applications
  1.1508 +** with specialized memory allocation requirements.  This object is
  1.1509 +** also used during testing of SQLite in order to specify an alternative
  1.1510 +** memory allocator that simulates memory out-of-memory conditions in
  1.1511 +** order to verify that SQLite recovers gracefully from such
  1.1512 +** conditions.
  1.1513 +**
  1.1514 +** The xMalloc, xRealloc, and xFree methods must work like the
  1.1515 +** malloc(), realloc() and free() functions from the standard C library.
  1.1516 +** ^SQLite guarantees that the second argument to
  1.1517 +** xRealloc is always a value returned by a prior call to xRoundup.
  1.1518 +**
  1.1519 +** xSize should return the allocated size of a memory allocation
  1.1520 +** previously obtained from xMalloc or xRealloc.  The allocated size
  1.1521 +** is always at least as big as the requested size but may be larger.
  1.1522 +**
  1.1523 +** The xRoundup method returns what would be the allocated size of
  1.1524 +** a memory allocation given a particular requested size.  Most memory
  1.1525 +** allocators round up memory allocations at least to the next multiple
  1.1526 +** of 8.  Some allocators round up to a larger multiple or to a power of 2.
  1.1527 +** Every memory allocation request coming in through [sqlite3_malloc()]
  1.1528 +** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
  1.1529 +** that causes the corresponding memory allocation to fail.
  1.1530 +**
  1.1531 +** The xInit method initializes the memory allocator.  For example,
  1.1532 +** it might allocate any require mutexes or initialize internal data
  1.1533 +** structures.  The xShutdown method is invoked (indirectly) by
  1.1534 +** [sqlite3_shutdown()] and should deallocate any resources acquired
  1.1535 +** by xInit.  The pAppData pointer is used as the only parameter to
  1.1536 +** xInit and xShutdown.
  1.1537 +**
  1.1538 +** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  1.1539 +** the xInit method, so the xInit method need not be threadsafe.  The
  1.1540 +** xShutdown method is only called from [sqlite3_shutdown()] so it does
  1.1541 +** not need to be threadsafe either.  For all other methods, SQLite
  1.1542 +** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  1.1543 +** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  1.1544 +** it is by default) and so the methods are automatically serialized.
  1.1545 +** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  1.1546 +** methods must be threadsafe or else make their own arrangements for
  1.1547 +** serialization.
  1.1548 +**
  1.1549 +** SQLite will never invoke xInit() more than once without an intervening
  1.1550 +** call to xShutdown().
  1.1551 +*/
  1.1552 +typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  1.1553 +struct sqlite3_mem_methods {
  1.1554 +  void *(*xMalloc)(int);         /* Memory allocation function */
  1.1555 +  void (*xFree)(void*);          /* Free a prior allocation */
  1.1556 +  void *(*xRealloc)(void*,int);  /* Resize an allocation */
  1.1557 +  int (*xSize)(void*);           /* Return the size of an allocation */
  1.1558 +  int (*xRoundup)(int);          /* Round up request size to allocation size */
  1.1559 +  int (*xInit)(void*);           /* Initialize the memory allocator */
  1.1560 +  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
  1.1561 +  void *pAppData;                /* Argument to xInit() and xShutdown() */
  1.1562 +};
  1.1563 +
  1.1564 +/*
  1.1565 +** CAPI3REF: Configuration Options
  1.1566 +** KEYWORDS: {configuration option}
  1.1567 +**
  1.1568 +** These constants are the available integer configuration options that
  1.1569 +** can be passed as the first argument to the [sqlite3_config()] interface.
  1.1570 +**
  1.1571 +** New configuration options may be added in future releases of SQLite.
  1.1572 +** Existing configuration options might be discontinued.  Applications
  1.1573 +** should check the return code from [sqlite3_config()] to make sure that
  1.1574 +** the call worked.  The [sqlite3_config()] interface will return a
  1.1575 +** non-zero [error code] if a discontinued or unsupported configuration option
  1.1576 +** is invoked.
  1.1577 +**
  1.1578 +** <dl>
  1.1579 +** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  1.1580 +** <dd>There are no arguments to this option.  ^This option sets the
  1.1581 +** [threading mode] to Single-thread.  In other words, it disables
  1.1582 +** all mutexing and puts SQLite into a mode where it can only be used
  1.1583 +** by a single thread.   ^If SQLite is compiled with
  1.1584 +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1.1585 +** it is not possible to change the [threading mode] from its default
  1.1586 +** value of Single-thread and so [sqlite3_config()] will return 
  1.1587 +** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  1.1588 +** configuration option.</dd>
  1.1589 +**
  1.1590 +** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  1.1591 +** <dd>There are no arguments to this option.  ^This option sets the
  1.1592 +** [threading mode] to Multi-thread.  In other words, it disables
  1.1593 +** mutexing on [database connection] and [prepared statement] objects.
  1.1594 +** The application is responsible for serializing access to
  1.1595 +** [database connections] and [prepared statements].  But other mutexes
  1.1596 +** are enabled so that SQLite will be safe to use in a multi-threaded
  1.1597 +** environment as long as no two threads attempt to use the same
  1.1598 +** [database connection] at the same time.  ^If SQLite is compiled with
  1.1599 +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1.1600 +** it is not possible to set the Multi-thread [threading mode] and
  1.1601 +** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1.1602 +** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  1.1603 +**
  1.1604 +** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  1.1605 +** <dd>There are no arguments to this option.  ^This option sets the
  1.1606 +** [threading mode] to Serialized. In other words, this option enables
  1.1607 +** all mutexes including the recursive
  1.1608 +** mutexes on [database connection] and [prepared statement] objects.
  1.1609 +** In this mode (which is the default when SQLite is compiled with
  1.1610 +** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  1.1611 +** to [database connections] and [prepared statements] so that the
  1.1612 +** application is free to use the same [database connection] or the
  1.1613 +** same [prepared statement] in different threads at the same time.
  1.1614 +** ^If SQLite is compiled with
  1.1615 +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1.1616 +** it is not possible to set the Serialized [threading mode] and
  1.1617 +** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1.1618 +** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  1.1619 +**
  1.1620 +** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  1.1621 +** <dd> ^(This option takes a single argument which is a pointer to an
  1.1622 +** instance of the [sqlite3_mem_methods] structure.  The argument specifies
  1.1623 +** alternative low-level memory allocation routines to be used in place of
  1.1624 +** the memory allocation routines built into SQLite.)^ ^SQLite makes
  1.1625 +** its own private copy of the content of the [sqlite3_mem_methods] structure
  1.1626 +** before the [sqlite3_config()] call returns.</dd>
  1.1627 +**
  1.1628 +** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  1.1629 +** <dd> ^(This option takes a single argument which is a pointer to an
  1.1630 +** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
  1.1631 +** structure is filled with the currently defined memory allocation routines.)^
  1.1632 +** This option can be used to overload the default memory allocation
  1.1633 +** routines with a wrapper that simulations memory allocation failure or
  1.1634 +** tracks memory usage, for example. </dd>
  1.1635 +**
  1.1636 +** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  1.1637 +** <dd> ^This option takes single argument of type int, interpreted as a 
  1.1638 +** boolean, which enables or disables the collection of memory allocation 
  1.1639 +** statistics. ^(When memory allocation statistics are disabled, the 
  1.1640 +** following SQLite interfaces become non-operational:
  1.1641 +**   <ul>
  1.1642 +**   <li> [sqlite3_memory_used()]
  1.1643 +**   <li> [sqlite3_memory_highwater()]
  1.1644 +**   <li> [sqlite3_soft_heap_limit64()]
  1.1645 +**   <li> [sqlite3_status()]
  1.1646 +**   </ul>)^
  1.1647 +** ^Memory allocation statistics are enabled by default unless SQLite is
  1.1648 +** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  1.1649 +** allocation statistics are disabled by default.
  1.1650 +** </dd>
  1.1651 +**
  1.1652 +** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  1.1653 +** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1.1654 +** scratch memory.  There are three arguments:  A pointer an 8-byte
  1.1655 +** aligned memory buffer from which the scratch allocations will be
  1.1656 +** drawn, the size of each scratch allocation (sz),
  1.1657 +** and the maximum number of scratch allocations (N).  The sz
  1.1658 +** argument must be a multiple of 16.
  1.1659 +** The first argument must be a pointer to an 8-byte aligned buffer
  1.1660 +** of at least sz*N bytes of memory.
  1.1661 +** ^SQLite will use no more than two scratch buffers per thread.  So
  1.1662 +** N should be set to twice the expected maximum number of threads.
  1.1663 +** ^SQLite will never require a scratch buffer that is more than 6
  1.1664 +** times the database page size. ^If SQLite needs needs additional
  1.1665 +** scratch memory beyond what is provided by this configuration option, then 
  1.1666 +** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
  1.1667 +**
  1.1668 +** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  1.1669 +** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1.1670 +** the database page cache with the default page cache implementation.  
  1.1671 +** This configuration should not be used if an application-define page
  1.1672 +** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
  1.1673 +** There are three arguments to this option: A pointer to 8-byte aligned
  1.1674 +** memory, the size of each page buffer (sz), and the number of pages (N).
  1.1675 +** The sz argument should be the size of the largest database page
  1.1676 +** (a power of two between 512 and 32768) plus a little extra for each
  1.1677 +** page header.  ^The page header size is 20 to 40 bytes depending on
  1.1678 +** the host architecture.  ^It is harmless, apart from the wasted memory,
  1.1679 +** to make sz a little too large.  The first
  1.1680 +** argument should point to an allocation of at least sz*N bytes of memory.
  1.1681 +** ^SQLite will use the memory provided by the first argument to satisfy its
  1.1682 +** memory needs for the first N pages that it adds to cache.  ^If additional
  1.1683 +** page cache memory is needed beyond what is provided by this option, then
  1.1684 +** SQLite goes to [sqlite3_malloc()] for the additional storage space.
  1.1685 +** The pointer in the first argument must
  1.1686 +** be aligned to an 8-byte boundary or subsequent behavior of SQLite
  1.1687 +** will be undefined.</dd>
  1.1688 +**
  1.1689 +** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  1.1690 +** <dd> ^This option specifies a static memory buffer that SQLite will use
  1.1691 +** for all of its dynamic memory allocation needs beyond those provided
  1.1692 +** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
  1.1693 +** There are three arguments: An 8-byte aligned pointer to the memory,
  1.1694 +** the number of bytes in the memory buffer, and the minimum allocation size.
  1.1695 +** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  1.1696 +** to using its default memory allocator (the system malloc() implementation),
  1.1697 +** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
  1.1698 +** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
  1.1699 +** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
  1.1700 +** allocator is engaged to handle all of SQLites memory allocation needs.
  1.1701 +** The first pointer (the memory pointer) must be aligned to an 8-byte
  1.1702 +** boundary or subsequent behavior of SQLite will be undefined.
  1.1703 +** The minimum allocation size is capped at 2**12. Reasonable values
  1.1704 +** for the minimum allocation size are 2**5 through 2**8.</dd>
  1.1705 +**
  1.1706 +** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  1.1707 +** <dd> ^(This option takes a single argument which is a pointer to an
  1.1708 +** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
  1.1709 +** alternative low-level mutex routines to be used in place
  1.1710 +** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
  1.1711 +** content of the [sqlite3_mutex_methods] structure before the call to
  1.1712 +** [sqlite3_config()] returns. ^If SQLite is compiled with
  1.1713 +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1.1714 +** the entire mutexing subsystem is omitted from the build and hence calls to
  1.1715 +** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  1.1716 +** return [SQLITE_ERROR].</dd>
  1.1717 +**
  1.1718 +** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  1.1719 +** <dd> ^(This option takes a single argument which is a pointer to an
  1.1720 +** instance of the [sqlite3_mutex_methods] structure.  The
  1.1721 +** [sqlite3_mutex_methods]
  1.1722 +** structure is filled with the currently defined mutex routines.)^
  1.1723 +** This option can be used to overload the default mutex allocation
  1.1724 +** routines with a wrapper used to track mutex usage for performance
  1.1725 +** profiling or testing, for example.   ^If SQLite is compiled with
  1.1726 +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1.1727 +** the entire mutexing subsystem is omitted from the build and hence calls to
  1.1728 +** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  1.1729 +** return [SQLITE_ERROR].</dd>
  1.1730 +**
  1.1731 +** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  1.1732 +** <dd> ^(This option takes two arguments that determine the default
  1.1733 +** memory allocation for the lookaside memory allocator on each
  1.1734 +** [database connection].  The first argument is the
  1.1735 +** size of each lookaside buffer slot and the second is the number of
  1.1736 +** slots allocated to each database connection.)^  ^(This option sets the
  1.1737 +** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  1.1738 +** verb to [sqlite3_db_config()] can be used to change the lookaside
  1.1739 +** configuration on individual connections.)^ </dd>
  1.1740 +**
  1.1741 +** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  1.1742 +** <dd> ^(This option takes a single argument which is a pointer to
  1.1743 +** an [sqlite3_pcache_methods2] object.  This object specifies the interface
  1.1744 +** to a custom page cache implementation.)^  ^SQLite makes a copy of the
  1.1745 +** object and uses it for page cache memory allocations.</dd>
  1.1746 +**
  1.1747 +** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  1.1748 +** <dd> ^(This option takes a single argument which is a pointer to an
  1.1749 +** [sqlite3_pcache_methods2] object.  SQLite copies of the current
  1.1750 +** page cache implementation into that object.)^ </dd>
  1.1751 +**
  1.1752 +** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  1.1753 +** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  1.1754 +** global [error log].
  1.1755 +** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  1.1756 +** function with a call signature of void(*)(void*,int,const char*), 
  1.1757 +** and a pointer to void. ^If the function pointer is not NULL, it is
  1.1758 +** invoked by [sqlite3_log()] to process each logging event.  ^If the
  1.1759 +** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  1.1760 +** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  1.1761 +** passed through as the first parameter to the application-defined logger
  1.1762 +** function whenever that function is invoked.  ^The second parameter to
  1.1763 +** the logger function is a copy of the first parameter to the corresponding
  1.1764 +** [sqlite3_log()] call and is intended to be a [result code] or an
  1.1765 +** [extended result code].  ^The third parameter passed to the logger is
  1.1766 +** log message after formatting via [sqlite3_snprintf()].
  1.1767 +** The SQLite logging interface is not reentrant; the logger function
  1.1768 +** supplied by the application must not invoke any SQLite interface.
  1.1769 +** In a multi-threaded application, the application-defined logger
  1.1770 +** function must be threadsafe. </dd>
  1.1771 +**
  1.1772 +** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  1.1773 +** <dd>^(This option takes a single argument of type int. If non-zero, then
  1.1774 +** URI handling is globally enabled. If the parameter is zero, then URI handling
  1.1775 +** is globally disabled.)^ ^If URI handling is globally enabled, all filenames
  1.1776 +** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
  1.1777 +** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  1.1778 +** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  1.1779 +** connection is opened. ^If it is globally disabled, filenames are
  1.1780 +** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  1.1781 +** database connection is opened. ^(By default, URI handling is globally
  1.1782 +** disabled. The default value may be changed by compiling with the
  1.1783 +** [SQLITE_USE_URI] symbol defined.)^
  1.1784 +**
  1.1785 +** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  1.1786 +** <dd>^This option takes a single integer argument which is interpreted as
  1.1787 +** a boolean in order to enable or disable the use of covering indices for
  1.1788 +** full table scans in the query optimizer.  ^The default setting is determined
  1.1789 +** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  1.1790 +** if that compile-time option is omitted.
  1.1791 +** The ability to disable the use of covering indices for full table scans
  1.1792 +** is because some incorrectly coded legacy applications might malfunction
  1.1793 +** when the optimization is enabled.  Providing the ability to
  1.1794 +** disable the optimization allows the older, buggy application code to work
  1.1795 +** without change even with newer versions of SQLite.
  1.1796 +**
  1.1797 +** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  1.1798 +** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  1.1799 +** <dd> These options are obsolete and should not be used by new code.
  1.1800 +** They are retained for backwards compatibility but are now no-ops.
  1.1801 +** </dd>
  1.1802 +**
  1.1803 +** [[SQLITE_CONFIG_SQLLOG]]
  1.1804 +** <dt>SQLITE_CONFIG_SQLLOG
  1.1805 +** <dd>This option is only available if sqlite is compiled with the
  1.1806 +** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  1.1807 +** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  1.1808 +** The second should be of type (void*). The callback is invoked by the library
  1.1809 +** in three separate circumstances, identified by the value passed as the
  1.1810 +** fourth parameter. If the fourth parameter is 0, then the database connection
  1.1811 +** passed as the second argument has just been opened. The third argument
  1.1812 +** points to a buffer containing the name of the main database file. If the
  1.1813 +** fourth parameter is 1, then the SQL statement that the third parameter
  1.1814 +** points to has just been executed. Or, if the fourth parameter is 2, then
  1.1815 +** the connection being passed as the second parameter is being closed. The
  1.1816 +** third parameter is passed NULL In this case.  An example of using this
  1.1817 +** configuration option can be seen in the "test_sqllog.c" source file in
  1.1818 +** the canonical SQLite source tree.</dd>
  1.1819 +**
  1.1820 +** [[SQLITE_CONFIG_MMAP_SIZE]]
  1.1821 +** <dt>SQLITE_CONFIG_MMAP_SIZE
  1.1822 +** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  1.1823 +** that are the default mmap size limit (the default setting for
  1.1824 +** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  1.1825 +** ^The default setting can be overridden by each database connection using
  1.1826 +** either the [PRAGMA mmap_size] command, or by using the
  1.1827 +** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size
  1.1828 +** cannot be changed at run-time.  Nor may the maximum allowed mmap size
  1.1829 +** exceed the compile-time maximum mmap size set by the
  1.1830 +** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  1.1831 +** ^If either argument to this option is negative, then that argument is
  1.1832 +** changed to its compile-time default.
  1.1833 +**
  1.1834 +** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
  1.1835 +** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
  1.1836 +** <dd>^This option is only available if SQLite is compiled for Windows
  1.1837 +** with the [SQLITE_WIN32_MALLOC] pre-processor macro defined.
  1.1838 +** SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
  1.1839 +** that specifies the maximum size of the created heap.
  1.1840 +** </dl>
  1.1841 +*/
  1.1842 +#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
  1.1843 +#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
  1.1844 +#define SQLITE_CONFIG_SERIALIZED    3  /* nil */
  1.1845 +#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
  1.1846 +#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
  1.1847 +#define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
  1.1848 +#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
  1.1849 +#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
  1.1850 +#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
  1.1851 +#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
  1.1852 +#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
  1.1853 +/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
  1.1854 +#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
  1.1855 +#define SQLITE_CONFIG_PCACHE       14  /* no-op */
  1.1856 +#define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
  1.1857 +#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
  1.1858 +#define SQLITE_CONFIG_URI          17  /* int */
  1.1859 +#define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
  1.1860 +#define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
  1.1861 +#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
  1.1862 +#define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
  1.1863 +#define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
  1.1864 +#define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
  1.1865 +
  1.1866 +/*
  1.1867 +** CAPI3REF: Database Connection Configuration Options
  1.1868 +**
  1.1869 +** These constants are the available integer configuration options that
  1.1870 +** can be passed as the second argument to the [sqlite3_db_config()] interface.
  1.1871 +**
  1.1872 +** New configuration options may be added in future releases of SQLite.
  1.1873 +** Existing configuration options might be discontinued.  Applications
  1.1874 +** should check the return code from [sqlite3_db_config()] to make sure that
  1.1875 +** the call worked.  ^The [sqlite3_db_config()] interface will return a
  1.1876 +** non-zero [error code] if a discontinued or unsupported configuration option
  1.1877 +** is invoked.
  1.1878 +**
  1.1879 +** <dl>
  1.1880 +** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  1.1881 +** <dd> ^This option takes three additional arguments that determine the 
  1.1882 +** [lookaside memory allocator] configuration for the [database connection].
  1.1883 +** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  1.1884 +** pointer to a memory buffer to use for lookaside memory.
  1.1885 +** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  1.1886 +** may be NULL in which case SQLite will allocate the
  1.1887 +** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  1.1888 +** size of each lookaside buffer slot.  ^The third argument is the number of
  1.1889 +** slots.  The size of the buffer in the first argument must be greater than
  1.1890 +** or equal to the product of the second and third arguments.  The buffer
  1.1891 +** must be aligned to an 8-byte boundary.  ^If the second argument to
  1.1892 +** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  1.1893 +** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
  1.1894 +** configuration for a database connection can only be changed when that
  1.1895 +** connection is not currently using lookaside memory, or in other words
  1.1896 +** when the "current value" returned by
  1.1897 +** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  1.1898 +** Any attempt to change the lookaside memory configuration when lookaside
  1.1899 +** memory is in use leaves the configuration unchanged and returns 
  1.1900 +** [SQLITE_BUSY].)^</dd>
  1.1901 +**
  1.1902 +** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  1.1903 +** <dd> ^This option is used to enable or disable the enforcement of
  1.1904 +** [foreign key constraints].  There should be two additional arguments.
  1.1905 +** The first argument is an integer which is 0 to disable FK enforcement,
  1.1906 +** positive to enable FK enforcement or negative to leave FK enforcement
  1.1907 +** unchanged.  The second parameter is a pointer to an integer into which
  1.1908 +** is written 0 or 1 to indicate whether FK enforcement is off or on
  1.1909 +** following this call.  The second parameter may be a NULL pointer, in
  1.1910 +** which case the FK enforcement setting is not reported back. </dd>
  1.1911 +**
  1.1912 +** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  1.1913 +** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  1.1914 +** There should be two additional arguments.
  1.1915 +** The first argument is an integer which is 0 to disable triggers,
  1.1916 +** positive to enable triggers or negative to leave the setting unchanged.
  1.1917 +** The second parameter is a pointer to an integer into which
  1.1918 +** is written 0 or 1 to indicate whether triggers are disabled or enabled
  1.1919 +** following this call.  The second parameter may be a NULL pointer, in
  1.1920 +** which case the trigger setting is not reported back. </dd>
  1.1921 +**
  1.1922 +** </dl>
  1.1923 +*/
  1.1924 +#define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
  1.1925 +#define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
  1.1926 +#define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
  1.1927 +
  1.1928 +
  1.1929 +/*
  1.1930 +** CAPI3REF: Enable Or Disable Extended Result Codes
  1.1931 +**
  1.1932 +** ^The sqlite3_extended_result_codes() routine enables or disables the
  1.1933 +** [extended result codes] feature of SQLite. ^The extended result
  1.1934 +** codes are disabled by default for historical compatibility.
  1.1935 +*/
  1.1936 +SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  1.1937 +
  1.1938 +/*
  1.1939 +** CAPI3REF: Last Insert Rowid
  1.1940 +**
  1.1941 +** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
  1.1942 +** has a unique 64-bit signed
  1.1943 +** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  1.1944 +** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  1.1945 +** names are not also used by explicitly declared columns. ^If
  1.1946 +** the table has a column of type [INTEGER PRIMARY KEY] then that column
  1.1947 +** is another alias for the rowid.
  1.1948 +**
  1.1949 +** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the 
  1.1950 +** most recent successful [INSERT] into a rowid table or [virtual table]
  1.1951 +** on database connection D.
  1.1952 +** ^Inserts into [WITHOUT ROWID] tables are not recorded.
  1.1953 +** ^If no successful [INSERT]s into rowid tables
  1.1954 +** have ever occurred on the database connection D, 
  1.1955 +** then sqlite3_last_insert_rowid(D) returns zero.
  1.1956 +**
  1.1957 +** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
  1.1958 +** method, then this routine will return the [rowid] of the inserted
  1.1959 +** row as long as the trigger or virtual table method is running.
  1.1960 +** But once the trigger or virtual table method ends, the value returned 
  1.1961 +** by this routine reverts to what it was before the trigger or virtual
  1.1962 +** table method began.)^
  1.1963 +**
  1.1964 +** ^An [INSERT] that fails due to a constraint violation is not a
  1.1965 +** successful [INSERT] and does not change the value returned by this
  1.1966 +** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  1.1967 +** and INSERT OR ABORT make no changes to the return value of this
  1.1968 +** routine when their insertion fails.  ^(When INSERT OR REPLACE
  1.1969 +** encounters a constraint violation, it does not fail.  The
  1.1970 +** INSERT continues to completion after deleting rows that caused
  1.1971 +** the constraint problem so INSERT OR REPLACE will always change
  1.1972 +** the return value of this interface.)^
  1.1973 +**
  1.1974 +** ^For the purposes of this routine, an [INSERT] is considered to
  1.1975 +** be successful even if it is subsequently rolled back.
  1.1976 +**
  1.1977 +** This function is accessible to SQL statements via the
  1.1978 +** [last_insert_rowid() SQL function].
  1.1979 +**
  1.1980 +** If a separate thread performs a new [INSERT] on the same
  1.1981 +** database connection while the [sqlite3_last_insert_rowid()]
  1.1982 +** function is running and thus changes the last insert [rowid],
  1.1983 +** then the value returned by [sqlite3_last_insert_rowid()] is
  1.1984 +** unpredictable and might not equal either the old or the new
  1.1985 +** last insert [rowid].
  1.1986 +*/
  1.1987 +SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  1.1988 +
  1.1989 +/*
  1.1990 +** CAPI3REF: Count The Number Of Rows Modified
  1.1991 +**
  1.1992 +** ^This function returns the number of database rows that were changed
  1.1993 +** or inserted or deleted by the most recently completed SQL statement
  1.1994 +** on the [database connection] specified by the first parameter.
  1.1995 +** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
  1.1996 +** or [DELETE] statement are counted.  Auxiliary changes caused by
  1.1997 +** triggers or [foreign key actions] are not counted.)^ Use the
  1.1998 +** [sqlite3_total_changes()] function to find the total number of changes
  1.1999 +** including changes caused by triggers and foreign key actions.
  1.2000 +**
  1.2001 +** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
  1.2002 +** are not counted.  Only real table changes are counted.
  1.2003 +**
  1.2004 +** ^(A "row change" is a change to a single row of a single table
  1.2005 +** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
  1.2006 +** are changed as side effects of [REPLACE] constraint resolution,
  1.2007 +** rollback, ABORT processing, [DROP TABLE], or by any other
  1.2008 +** mechanisms do not count as direct row changes.)^
  1.2009 +**
  1.2010 +** A "trigger context" is a scope of execution that begins and
  1.2011 +** ends with the script of a [CREATE TRIGGER | trigger]. 
  1.2012 +** Most SQL statements are
  1.2013 +** evaluated outside of any trigger.  This is the "top level"
  1.2014 +** trigger context.  If a trigger fires from the top level, a
  1.2015 +** new trigger context is entered for the duration of that one
  1.2016 +** trigger.  Subtriggers create subcontexts for their duration.
  1.2017 +**
  1.2018 +** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
  1.2019 +** not create a new trigger context.
  1.2020 +**
  1.2021 +** ^This function returns the number of direct row changes in the
  1.2022 +** most recent INSERT, UPDATE, or DELETE statement within the same
  1.2023 +** trigger context.
  1.2024 +**
  1.2025 +** ^Thus, when called from the top level, this function returns the
  1.2026 +** number of changes in the most recent INSERT, UPDATE, or DELETE
  1.2027 +** that also occurred at the top level.  ^(Within the body of a trigger,
  1.2028 +** the sqlite3_changes() interface can be called to find the number of
  1.2029 +** changes in the most recently completed INSERT, UPDATE, or DELETE
  1.2030 +** statement within the body of the same trigger.
  1.2031 +** However, the number returned does not include changes
  1.2032 +** caused by subtriggers since those have their own context.)^
  1.2033 +**
  1.2034 +** See also the [sqlite3_total_changes()] interface, the
  1.2035 +** [count_changes pragma], and the [changes() SQL function].
  1.2036 +**
  1.2037 +** If a separate thread makes changes on the same database connection
  1.2038 +** while [sqlite3_changes()] is running then the value returned
  1.2039 +** is unpredictable and not meaningful.
  1.2040 +*/
  1.2041 +SQLITE_API int sqlite3_changes(sqlite3*);
  1.2042 +
  1.2043 +/*
  1.2044 +** CAPI3REF: Total Number Of Rows Modified
  1.2045 +**
  1.2046 +** ^This function returns the number of row changes caused by [INSERT],
  1.2047 +** [UPDATE] or [DELETE] statements since the [database connection] was opened.
  1.2048 +** ^(The count returned by sqlite3_total_changes() includes all changes
  1.2049 +** from all [CREATE TRIGGER | trigger] contexts and changes made by
  1.2050 +** [foreign key actions]. However,
  1.2051 +** the count does not include changes used to implement [REPLACE] constraints,
  1.2052 +** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
  1.2053 +** count does not include rows of views that fire an [INSTEAD OF trigger],
  1.2054 +** though if the INSTEAD OF trigger makes changes of its own, those changes 
  1.2055 +** are counted.)^
  1.2056 +** ^The sqlite3_total_changes() function counts the changes as soon as
  1.2057 +** the statement that makes them is completed (when the statement handle
  1.2058 +** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
  1.2059 +**
  1.2060 +** See also the [sqlite3_changes()] interface, the
  1.2061 +** [count_changes pragma], and the [total_changes() SQL function].
  1.2062 +**
  1.2063 +** If a separate thread makes changes on the same database connection
  1.2064 +** while [sqlite3_total_changes()] is running then the value
  1.2065 +** returned is unpredictable and not meaningful.
  1.2066 +*/
  1.2067 +SQLITE_API int sqlite3_total_changes(sqlite3*);
  1.2068 +
  1.2069 +/*
  1.2070 +** CAPI3REF: Interrupt A Long-Running Query
  1.2071 +**
  1.2072 +** ^This function causes any pending database operation to abort and
  1.2073 +** return at its earliest opportunity. This routine is typically
  1.2074 +** called in response to a user action such as pressing "Cancel"
  1.2075 +** or Ctrl-C where the user wants a long query operation to halt
  1.2076 +** immediately.
  1.2077 +**
  1.2078 +** ^It is safe to call this routine from a thread different from the
  1.2079 +** thread that is currently running the database operation.  But it
  1.2080 +** is not safe to call this routine with a [database connection] that
  1.2081 +** is closed or might close before sqlite3_interrupt() returns.
  1.2082 +**
  1.2083 +** ^If an SQL operation is very nearly finished at the time when
  1.2084 +** sqlite3_interrupt() is called, then it might not have an opportunity
  1.2085 +** to be interrupted and might continue to completion.
  1.2086 +**
  1.2087 +** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  1.2088 +** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  1.2089 +** that is inside an explicit transaction, then the entire transaction
  1.2090 +** will be rolled back automatically.
  1.2091 +**
  1.2092 +** ^The sqlite3_interrupt(D) call is in effect until all currently running
  1.2093 +** SQL statements on [database connection] D complete.  ^Any new SQL statements
  1.2094 +** that are started after the sqlite3_interrupt() call and before the 
  1.2095 +** running statements reaches zero are interrupted as if they had been
  1.2096 +** running prior to the sqlite3_interrupt() call.  ^New SQL statements
  1.2097 +** that are started after the running statement count reaches zero are
  1.2098 +** not effected by the sqlite3_interrupt().
  1.2099 +** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  1.2100 +** SQL statements is a no-op and has no effect on SQL statements
  1.2101 +** that are started after the sqlite3_interrupt() call returns.
  1.2102 +**
  1.2103 +** If the database connection closes while [sqlite3_interrupt()]
  1.2104 +** is running then bad things will likely happen.
  1.2105 +*/
  1.2106 +SQLITE_API void sqlite3_interrupt(sqlite3*);
  1.2107 +
  1.2108 +/*
  1.2109 +** CAPI3REF: Determine If An SQL Statement Is Complete
  1.2110 +**
  1.2111 +** These routines are useful during command-line input to determine if the
  1.2112 +** currently entered text seems to form a complete SQL statement or
  1.2113 +** if additional input is needed before sending the text into
  1.2114 +** SQLite for parsing.  ^These routines return 1 if the input string
  1.2115 +** appears to be a complete SQL statement.  ^A statement is judged to be
  1.2116 +** complete if it ends with a semicolon token and is not a prefix of a
  1.2117 +** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
  1.2118 +** string literals or quoted identifier names or comments are not
  1.2119 +** independent tokens (they are part of the token in which they are
  1.2120 +** embedded) and thus do not count as a statement terminator.  ^Whitespace
  1.2121 +** and comments that follow the final semicolon are ignored.
  1.2122 +**
  1.2123 +** ^These routines return 0 if the statement is incomplete.  ^If a
  1.2124 +** memory allocation fails, then SQLITE_NOMEM is returned.
  1.2125 +**
  1.2126 +** ^These routines do not parse the SQL statements thus
  1.2127 +** will not detect syntactically incorrect SQL.
  1.2128 +**
  1.2129 +** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
  1.2130 +** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  1.2131 +** automatically by sqlite3_complete16().  If that initialization fails,
  1.2132 +** then the return value from sqlite3_complete16() will be non-zero
  1.2133 +** regardless of whether or not the input SQL is complete.)^
  1.2134 +**
  1.2135 +** The input to [sqlite3_complete()] must be a zero-terminated
  1.2136 +** UTF-8 string.
  1.2137 +**
  1.2138 +** The input to [sqlite3_complete16()] must be a zero-terminated
  1.2139 +** UTF-16 string in native byte order.
  1.2140 +*/
  1.2141 +SQLITE_API int sqlite3_complete(const char *sql);
  1.2142 +SQLITE_API int sqlite3_complete16(const void *sql);
  1.2143 +
  1.2144 +/*
  1.2145 +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  1.2146 +**
  1.2147 +** ^This routine sets a callback function that might be invoked whenever
  1.2148 +** an attempt is made to open a database table that another thread
  1.2149 +** or process has locked.
  1.2150 +**
  1.2151 +** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
  1.2152 +** is returned immediately upon encountering the lock.  ^If the busy callback
  1.2153 +** is not NULL, then the callback might be invoked with two arguments.
  1.2154 +**
  1.2155 +** ^The first argument to the busy handler is a copy of the void* pointer which
  1.2156 +** is the third argument to sqlite3_busy_handler().  ^The second argument to
  1.2157 +** the busy handler callback is the number of times that the busy handler has
  1.2158 +** been invoked for this locking event.  ^If the
  1.2159 +** busy callback returns 0, then no additional attempts are made to
  1.2160 +** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
  1.2161 +** ^If the callback returns non-zero, then another attempt
  1.2162 +** is made to open the database for reading and the cycle repeats.
  1.2163 +**
  1.2164 +** The presence of a busy handler does not guarantee that it will be invoked
  1.2165 +** when there is lock contention. ^If SQLite determines that invoking the busy
  1.2166 +** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  1.2167 +** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
  1.2168 +** Consider a scenario where one process is holding a read lock that
  1.2169 +** it is trying to promote to a reserved lock and
  1.2170 +** a second process is holding a reserved lock that it is trying
  1.2171 +** to promote to an exclusive lock.  The first process cannot proceed
  1.2172 +** because it is blocked by the second and the second process cannot
  1.2173 +** proceed because it is blocked by the first.  If both processes
  1.2174 +** invoke the busy handlers, neither will make any progress.  Therefore,
  1.2175 +** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  1.2176 +** will induce the first process to release its read lock and allow
  1.2177 +** the second process to proceed.
  1.2178 +**
  1.2179 +** ^The default busy callback is NULL.
  1.2180 +**
  1.2181 +** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
  1.2182 +** when SQLite is in the middle of a large transaction where all the
  1.2183 +** changes will not fit into the in-memory cache.  SQLite will
  1.2184 +** already hold a RESERVED lock on the database file, but it needs
  1.2185 +** to promote this lock to EXCLUSIVE so that it can spill cache
  1.2186 +** pages into the database file without harm to concurrent
  1.2187 +** readers.  ^If it is unable to promote the lock, then the in-memory
  1.2188 +** cache will be left in an inconsistent state and so the error
  1.2189 +** code is promoted from the relatively benign [SQLITE_BUSY] to
  1.2190 +** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
  1.2191 +** forces an automatic rollback of the changes.  See the
  1.2192 +** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
  1.2193 +** CorruptionFollowingBusyError</a> wiki page for a discussion of why
  1.2194 +** this is important.
  1.2195 +**
  1.2196 +** ^(There can only be a single busy handler defined for each
  1.2197 +** [database connection].  Setting a new busy handler clears any
  1.2198 +** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
  1.2199 +** will also set or clear the busy handler.
  1.2200 +**
  1.2201 +** The busy callback should not take any actions which modify the
  1.2202 +** database connection that invoked the busy handler.  Any such actions
  1.2203 +** result in undefined behavior.
  1.2204 +** 
  1.2205 +** A busy handler must not close the database connection
  1.2206 +** or [prepared statement] that invoked the busy handler.
  1.2207 +*/
  1.2208 +SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
  1.2209 +
  1.2210 +/*
  1.2211 +** CAPI3REF: Set A Busy Timeout
  1.2212 +**
  1.2213 +** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  1.2214 +** for a specified amount of time when a table is locked.  ^The handler
  1.2215 +** will sleep multiple times until at least "ms" milliseconds of sleeping
  1.2216 +** have accumulated.  ^After at least "ms" milliseconds of sleeping,
  1.2217 +** the handler returns 0 which causes [sqlite3_step()] to return
  1.2218 +** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
  1.2219 +**
  1.2220 +** ^Calling this routine with an argument less than or equal to zero
  1.2221 +** turns off all busy handlers.
  1.2222 +**
  1.2223 +** ^(There can only be a single busy handler for a particular
  1.2224 +** [database connection] any any given moment.  If another busy handler
  1.2225 +** was defined  (using [sqlite3_busy_handler()]) prior to calling
  1.2226 +** this routine, that other busy handler is cleared.)^
  1.2227 +*/
  1.2228 +SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  1.2229 +
  1.2230 +/*
  1.2231 +** CAPI3REF: Convenience Routines For Running Queries
  1.2232 +**
  1.2233 +** This is a legacy interface that is preserved for backwards compatibility.
  1.2234 +** Use of this interface is not recommended.
  1.2235 +**
  1.2236 +** Definition: A <b>result table</b> is memory data structure created by the
  1.2237 +** [sqlite3_get_table()] interface.  A result table records the
  1.2238 +** complete query results from one or more queries.
  1.2239 +**
  1.2240 +** The table conceptually has a number of rows and columns.  But
  1.2241 +** these numbers are not part of the result table itself.  These
  1.2242 +** numbers are obtained separately.  Let N be the number of rows
  1.2243 +** and M be the number of columns.
  1.2244 +**
  1.2245 +** A result table is an array of pointers to zero-terminated UTF-8 strings.
  1.2246 +** There are (N+1)*M elements in the array.  The first M pointers point
  1.2247 +** to zero-terminated strings that  contain the names of the columns.
  1.2248 +** The remaining entries all point to query results.  NULL values result
  1.2249 +** in NULL pointers.  All other values are in their UTF-8 zero-terminated
  1.2250 +** string representation as returned by [sqlite3_column_text()].
  1.2251 +**
  1.2252 +** A result table might consist of one or more memory allocations.
  1.2253 +** It is not safe to pass a result table directly to [sqlite3_free()].
  1.2254 +** A result table should be deallocated using [sqlite3_free_table()].
  1.2255 +**
  1.2256 +** ^(As an example of the result table format, suppose a query result
  1.2257 +** is as follows:
  1.2258 +**
  1.2259 +** <blockquote><pre>
  1.2260 +**        Name        | Age
  1.2261 +**        -----------------------
  1.2262 +**        Alice       | 43
  1.2263 +**        Bob         | 28
  1.2264 +**        Cindy       | 21
  1.2265 +** </pre></blockquote>
  1.2266 +**
  1.2267 +** There are two column (M==2) and three rows (N==3).  Thus the
  1.2268 +** result table has 8 entries.  Suppose the result table is stored
  1.2269 +** in an array names azResult.  Then azResult holds this content:
  1.2270 +**
  1.2271 +** <blockquote><pre>
  1.2272 +**        azResult&#91;0] = "Name";
  1.2273 +**        azResult&#91;1] = "Age";
  1.2274 +**        azResult&#91;2] = "Alice";
  1.2275 +**        azResult&#91;3] = "43";
  1.2276 +**        azResult&#91;4] = "Bob";
  1.2277 +**        azResult&#91;5] = "28";
  1.2278 +**        azResult&#91;6] = "Cindy";
  1.2279 +**        azResult&#91;7] = "21";
  1.2280 +** </pre></blockquote>)^
  1.2281 +**
  1.2282 +** ^The sqlite3_get_table() function evaluates one or more
  1.2283 +** semicolon-separated SQL statements in the zero-terminated UTF-8
  1.2284 +** string of its 2nd parameter and returns a result table to the
  1.2285 +** pointer given in its 3rd parameter.
  1.2286 +**
  1.2287 +** After the application has finished with the result from sqlite3_get_table(),
  1.2288 +** it must pass the result table pointer to sqlite3_free_table() in order to
  1.2289 +** release the memory that was malloced.  Because of the way the
  1.2290 +** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  1.2291 +** function must not try to call [sqlite3_free()] directly.  Only
  1.2292 +** [sqlite3_free_table()] is able to release the memory properly and safely.
  1.2293 +**
  1.2294 +** The sqlite3_get_table() interface is implemented as a wrapper around
  1.2295 +** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
  1.2296 +** to any internal data structures of SQLite.  It uses only the public
  1.2297 +** interface defined here.  As a consequence, errors that occur in the
  1.2298 +** wrapper layer outside of the internal [sqlite3_exec()] call are not
  1.2299 +** reflected in subsequent calls to [sqlite3_errcode()] or
  1.2300 +** [sqlite3_errmsg()].
  1.2301 +*/
  1.2302 +SQLITE_API int sqlite3_get_table(
  1.2303 +  sqlite3 *db,          /* An open database */
  1.2304 +  const char *zSql,     /* SQL to be evaluated */
  1.2305 +  char ***pazResult,    /* Results of the query */
  1.2306 +  int *pnRow,           /* Number of result rows written here */
  1.2307 +  int *pnColumn,        /* Number of result columns written here */
  1.2308 +  char **pzErrmsg       /* Error msg written here */
  1.2309 +);
  1.2310 +SQLITE_API void sqlite3_free_table(char **result);
  1.2311 +
  1.2312 +/*
  1.2313 +** CAPI3REF: Formatted String Printing Functions
  1.2314 +**
  1.2315 +** These routines are work-alikes of the "printf()" family of functions
  1.2316 +** from the standard C library.
  1.2317 +**
  1.2318 +** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  1.2319 +** results into memory obtained from [sqlite3_malloc()].
  1.2320 +** The strings returned by these two routines should be
  1.2321 +** released by [sqlite3_free()].  ^Both routines return a
  1.2322 +** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  1.2323 +** memory to hold the resulting string.
  1.2324 +**
  1.2325 +** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  1.2326 +** the standard C library.  The result is written into the
  1.2327 +** buffer supplied as the second parameter whose size is given by
  1.2328 +** the first parameter. Note that the order of the
  1.2329 +** first two parameters is reversed from snprintf().)^  This is an
  1.2330 +** historical accident that cannot be fixed without breaking
  1.2331 +** backwards compatibility.  ^(Note also that sqlite3_snprintf()
  1.2332 +** returns a pointer to its buffer instead of the number of
  1.2333 +** characters actually written into the buffer.)^  We admit that
  1.2334 +** the number of characters written would be a more useful return
  1.2335 +** value but we cannot change the implementation of sqlite3_snprintf()
  1.2336 +** now without breaking compatibility.
  1.2337 +**
  1.2338 +** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  1.2339 +** guarantees that the buffer is always zero-terminated.  ^The first
  1.2340 +** parameter "n" is the total size of the buffer, including space for
  1.2341 +** the zero terminator.  So the longest string that can be completely
  1.2342 +** written will be n-1 characters.
  1.2343 +**
  1.2344 +** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  1.2345 +**
  1.2346 +** These routines all implement some additional formatting
  1.2347 +** options that are useful for constructing SQL statements.
  1.2348 +** All of the usual printf() formatting options apply.  In addition, there
  1.2349 +** is are "%q", "%Q", and "%z" options.
  1.2350 +**
  1.2351 +** ^(The %q option works like %s in that it substitutes a nul-terminated
  1.2352 +** string from the argument list.  But %q also doubles every '\'' character.
  1.2353 +** %q is designed for use inside a string literal.)^  By doubling each '\''
  1.2354 +** character it escapes that character and allows it to be inserted into
  1.2355 +** the string.
  1.2356 +**
  1.2357 +** For example, assume the string variable zText contains text as follows:
  1.2358 +**
  1.2359 +** <blockquote><pre>
  1.2360 +**  char *zText = "It's a happy day!";
  1.2361 +** </pre></blockquote>
  1.2362 +**
  1.2363 +** One can use this text in an SQL statement as follows:
  1.2364 +**
  1.2365 +** <blockquote><pre>
  1.2366 +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  1.2367 +**  sqlite3_exec(db, zSQL, 0, 0, 0);
  1.2368 +**  sqlite3_free(zSQL);
  1.2369 +** </pre></blockquote>
  1.2370 +**
  1.2371 +** Because the %q format string is used, the '\'' character in zText
  1.2372 +** is escaped and the SQL generated is as follows:
  1.2373 +**
  1.2374 +** <blockquote><pre>
  1.2375 +**  INSERT INTO table1 VALUES('It''s a happy day!')
  1.2376 +** </pre></blockquote>
  1.2377 +**
  1.2378 +** This is correct.  Had we used %s instead of %q, the generated SQL
  1.2379 +** would have looked like this:
  1.2380 +**
  1.2381 +** <blockquote><pre>
  1.2382 +**  INSERT INTO table1 VALUES('It's a happy day!');
  1.2383 +** </pre></blockquote>
  1.2384 +**
  1.2385 +** This second example is an SQL syntax error.  As a general rule you should
  1.2386 +** always use %q instead of %s when inserting text into a string literal.
  1.2387 +**
  1.2388 +** ^(The %Q option works like %q except it also adds single quotes around
  1.2389 +** the outside of the total string.  Additionally, if the parameter in the
  1.2390 +** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  1.2391 +** single quotes).)^  So, for example, one could say:
  1.2392 +**
  1.2393 +** <blockquote><pre>
  1.2394 +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  1.2395 +**  sqlite3_exec(db, zSQL, 0, 0, 0);
  1.2396 +**  sqlite3_free(zSQL);
  1.2397 +** </pre></blockquote>
  1.2398 +**
  1.2399 +** The code above will render a correct SQL statement in the zSQL
  1.2400 +** variable even if the zText variable is a NULL pointer.
  1.2401 +**
  1.2402 +** ^(The "%z" formatting option works like "%s" but with the
  1.2403 +** addition that after the string has been read and copied into
  1.2404 +** the result, [sqlite3_free()] is called on the input string.)^
  1.2405 +*/
  1.2406 +SQLITE_API char *sqlite3_mprintf(const char*,...);
  1.2407 +SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  1.2408 +SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  1.2409 +SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  1.2410 +
  1.2411 +/*
  1.2412 +** CAPI3REF: Memory Allocation Subsystem
  1.2413 +**
  1.2414 +** The SQLite core uses these three routines for all of its own
  1.2415 +** internal memory allocation needs. "Core" in the previous sentence
  1.2416 +** does not include operating-system specific VFS implementation.  The
  1.2417 +** Windows VFS uses native malloc() and free() for some operations.
  1.2418 +**
  1.2419 +** ^The sqlite3_malloc() routine returns a pointer to a block
  1.2420 +** of memory at least N bytes in length, where N is the parameter.
  1.2421 +** ^If sqlite3_malloc() is unable to obtain sufficient free
  1.2422 +** memory, it returns a NULL pointer.  ^If the parameter N to
  1.2423 +** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  1.2424 +** a NULL pointer.
  1.2425 +**
  1.2426 +** ^Calling sqlite3_free() with a pointer previously returned
  1.2427 +** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  1.2428 +** that it might be reused.  ^The sqlite3_free() routine is
  1.2429 +** a no-op if is called with a NULL pointer.  Passing a NULL pointer
  1.2430 +** to sqlite3_free() is harmless.  After being freed, memory
  1.2431 +** should neither be read nor written.  Even reading previously freed
  1.2432 +** memory might result in a segmentation fault or other severe error.
  1.2433 +** Memory corruption, a segmentation fault, or other severe error
  1.2434 +** might result if sqlite3_free() is called with a non-NULL pointer that
  1.2435 +** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  1.2436 +**
  1.2437 +** ^(The sqlite3_realloc() interface attempts to resize a
  1.2438 +** prior memory allocation to be at least N bytes, where N is the
  1.2439 +** second parameter.  The memory allocation to be resized is the first
  1.2440 +** parameter.)^ ^ If the first parameter to sqlite3_realloc()
  1.2441 +** is a NULL pointer then its behavior is identical to calling
  1.2442 +** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
  1.2443 +** ^If the second parameter to sqlite3_realloc() is zero or
  1.2444 +** negative then the behavior is exactly the same as calling
  1.2445 +** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
  1.2446 +** ^sqlite3_realloc() returns a pointer to a memory allocation
  1.2447 +** of at least N bytes in size or NULL if sufficient memory is unavailable.
  1.2448 +** ^If M is the size of the prior allocation, then min(N,M) bytes
  1.2449 +** of the prior allocation are copied into the beginning of buffer returned
  1.2450 +** by sqlite3_realloc() and the prior allocation is freed.
  1.2451 +** ^If sqlite3_realloc() returns NULL, then the prior allocation
  1.2452 +** is not freed.
  1.2453 +**
  1.2454 +** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
  1.2455 +** is always aligned to at least an 8 byte boundary, or to a
  1.2456 +** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  1.2457 +** option is used.
  1.2458 +**
  1.2459 +** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  1.2460 +** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  1.2461 +** implementation of these routines to be omitted.  That capability
  1.2462 +** is no longer provided.  Only built-in memory allocators can be used.
  1.2463 +**
  1.2464 +** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  1.2465 +** the system malloc() and free() directly when converting
  1.2466 +** filenames between the UTF-8 encoding used by SQLite
  1.2467 +** and whatever filename encoding is used by the particular Windows
  1.2468 +** installation.  Memory allocation errors were detected, but
  1.2469 +** they were reported back as [SQLITE_CANTOPEN] or
  1.2470 +** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  1.2471 +**
  1.2472 +** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  1.2473 +** must be either NULL or else pointers obtained from a prior
  1.2474 +** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  1.2475 +** not yet been released.
  1.2476 +**
  1.2477 +** The application must not read or write any part of
  1.2478 +** a block of memory after it has been released using
  1.2479 +** [sqlite3_free()] or [sqlite3_realloc()].
  1.2480 +*/
  1.2481 +SQLITE_API void *sqlite3_malloc(int);
  1.2482 +SQLITE_API void *sqlite3_realloc(void*, int);
  1.2483 +SQLITE_API void sqlite3_free(void*);
  1.2484 +
  1.2485 +/*
  1.2486 +** CAPI3REF: Memory Allocator Statistics
  1.2487 +**
  1.2488 +** SQLite provides these two interfaces for reporting on the status
  1.2489 +** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  1.2490 +** routines, which form the built-in memory allocation subsystem.
  1.2491 +**
  1.2492 +** ^The [sqlite3_memory_used()] routine returns the number of bytes
  1.2493 +** of memory currently outstanding (malloced but not freed).
  1.2494 +** ^The [sqlite3_memory_highwater()] routine returns the maximum
  1.2495 +** value of [sqlite3_memory_used()] since the high-water mark
  1.2496 +** was last reset.  ^The values returned by [sqlite3_memory_used()] and
  1.2497 +** [sqlite3_memory_highwater()] include any overhead
  1.2498 +** added by SQLite in its implementation of [sqlite3_malloc()],
  1.2499 +** but not overhead added by the any underlying system library
  1.2500 +** routines that [sqlite3_malloc()] may call.
  1.2501 +**
  1.2502 +** ^The memory high-water mark is reset to the current value of
  1.2503 +** [sqlite3_memory_used()] if and only if the parameter to
  1.2504 +** [sqlite3_memory_highwater()] is true.  ^The value returned
  1.2505 +** by [sqlite3_memory_highwater(1)] is the high-water mark
  1.2506 +** prior to the reset.
  1.2507 +*/
  1.2508 +SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  1.2509 +SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  1.2510 +
  1.2511 +/*
  1.2512 +** CAPI3REF: Pseudo-Random Number Generator
  1.2513 +**
  1.2514 +** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  1.2515 +** select random [ROWID | ROWIDs] when inserting new records into a table that
  1.2516 +** already uses the largest possible [ROWID].  The PRNG is also used for
  1.2517 +** the build-in random() and randomblob() SQL functions.  This interface allows
  1.2518 +** applications to access the same PRNG for other purposes.
  1.2519 +**
  1.2520 +** ^A call to this routine stores N bytes of randomness into buffer P.
  1.2521 +** ^If N is less than one, then P can be a NULL pointer.
  1.2522 +**
  1.2523 +** ^If this routine has not been previously called or if the previous
  1.2524 +** call had N less than one, then the PRNG is seeded using randomness
  1.2525 +** obtained from the xRandomness method of the default [sqlite3_vfs] object.
  1.2526 +** ^If the previous call to this routine had an N of 1 or more then
  1.2527 +** the pseudo-randomness is generated
  1.2528 +** internally and without recourse to the [sqlite3_vfs] xRandomness
  1.2529 +** method.
  1.2530 +*/
  1.2531 +SQLITE_API void sqlite3_randomness(int N, void *P);
  1.2532 +
  1.2533 +/*
  1.2534 +** CAPI3REF: Compile-Time Authorization Callbacks
  1.2535 +**
  1.2536 +** ^This routine registers an authorizer callback with a particular
  1.2537 +** [database connection], supplied in the first argument.
  1.2538 +** ^The authorizer callback is invoked as SQL statements are being compiled
  1.2539 +** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  1.2540 +** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
  1.2541 +** points during the compilation process, as logic is being created
  1.2542 +** to perform various actions, the authorizer callback is invoked to
  1.2543 +** see if those actions are allowed.  ^The authorizer callback should
  1.2544 +** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  1.2545 +** specific action but allow the SQL statement to continue to be
  1.2546 +** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  1.2547 +** rejected with an error.  ^If the authorizer callback returns
  1.2548 +** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  1.2549 +** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  1.2550 +** the authorizer will fail with an error message.
  1.2551 +**
  1.2552 +** When the callback returns [SQLITE_OK], that means the operation
  1.2553 +** requested is ok.  ^When the callback returns [SQLITE_DENY], the
  1.2554 +** [sqlite3_prepare_v2()] or equivalent call that triggered the
  1.2555 +** authorizer will fail with an error message explaining that
  1.2556 +** access is denied. 
  1.2557 +**
  1.2558 +** ^The first parameter to the authorizer callback is a copy of the third
  1.2559 +** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  1.2560 +** to the callback is an integer [SQLITE_COPY | action code] that specifies
  1.2561 +** the particular action to be authorized. ^The third through sixth parameters
  1.2562 +** to the callback are zero-terminated strings that contain additional
  1.2563 +** details about the action to be authorized.
  1.2564 +**
  1.2565 +** ^If the action code is [SQLITE_READ]
  1.2566 +** and the callback returns [SQLITE_IGNORE] then the
  1.2567 +** [prepared statement] statement is constructed to substitute
  1.2568 +** a NULL value in place of the table column that would have
  1.2569 +** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
  1.2570 +** return can be used to deny an untrusted user access to individual
  1.2571 +** columns of a table.
  1.2572 +** ^If the action code is [SQLITE_DELETE] and the callback returns
  1.2573 +** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  1.2574 +** [truncate optimization] is disabled and all rows are deleted individually.
  1.2575 +**
  1.2576 +** An authorizer is used when [sqlite3_prepare | preparing]
  1.2577 +** SQL statements from an untrusted source, to ensure that the SQL statements
  1.2578 +** do not try to access data they are not allowed to see, or that they do not
  1.2579 +** try to execute malicious statements that damage the database.  For
  1.2580 +** example, an application may allow a user to enter arbitrary
  1.2581 +** SQL queries for evaluation by a database.  But the application does
  1.2582 +** not want the user to be able to make arbitrary changes to the
  1.2583 +** database.  An authorizer could then be put in place while the
  1.2584 +** user-entered SQL is being [sqlite3_prepare | prepared] that
  1.2585 +** disallows everything except [SELECT] statements.
  1.2586 +**
  1.2587 +** Applications that need to process SQL from untrusted sources
  1.2588 +** might also consider lowering resource limits using [sqlite3_limit()]
  1.2589 +** and limiting database size using the [max_page_count] [PRAGMA]
  1.2590 +** in addition to using an authorizer.
  1.2591 +**
  1.2592 +** ^(Only a single authorizer can be in place on a database connection
  1.2593 +** at a time.  Each call to sqlite3_set_authorizer overrides the
  1.2594 +** previous call.)^  ^Disable the authorizer by installing a NULL callback.
  1.2595 +** The authorizer is disabled by default.
  1.2596 +**
  1.2597 +** The authorizer callback must not do anything that will modify
  1.2598 +** the database connection that invoked the authorizer callback.
  1.2599 +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  1.2600 +** database connections for the meaning of "modify" in this paragraph.
  1.2601 +**
  1.2602 +** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  1.2603 +** statement might be re-prepared during [sqlite3_step()] due to a 
  1.2604 +** schema change.  Hence, the application should ensure that the
  1.2605 +** correct authorizer callback remains in place during the [sqlite3_step()].
  1.2606 +**
  1.2607 +** ^Note that the authorizer callback is invoked only during
  1.2608 +** [sqlite3_prepare()] or its variants.  Authorization is not
  1.2609 +** performed during statement evaluation in [sqlite3_step()], unless
  1.2610 +** as stated in the previous paragraph, sqlite3_step() invokes
  1.2611 +** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  1.2612 +*/
  1.2613 +SQLITE_API int sqlite3_set_authorizer(
  1.2614 +  sqlite3*,
  1.2615 +  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  1.2616 +  void *pUserData
  1.2617 +);
  1.2618 +
  1.2619 +/*
  1.2620 +** CAPI3REF: Authorizer Return Codes
  1.2621 +**
  1.2622 +** The [sqlite3_set_authorizer | authorizer callback function] must
  1.2623 +** return either [SQLITE_OK] or one of these two constants in order
  1.2624 +** to signal SQLite whether or not the action is permitted.  See the
  1.2625 +** [sqlite3_set_authorizer | authorizer documentation] for additional
  1.2626 +** information.
  1.2627 +**
  1.2628 +** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
  1.2629 +** from the [sqlite3_vtab_on_conflict()] interface.
  1.2630 +*/
  1.2631 +#define SQLITE_DENY   1   /* Abort the SQL statement with an error */
  1.2632 +#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
  1.2633 +
  1.2634 +/*
  1.2635 +** CAPI3REF: Authorizer Action Codes
  1.2636 +**
  1.2637 +** The [sqlite3_set_authorizer()] interface registers a callback function
  1.2638 +** that is invoked to authorize certain SQL statement actions.  The
  1.2639 +** second parameter to the callback is an integer code that specifies
  1.2640 +** what action is being authorized.  These are the integer action codes that
  1.2641 +** the authorizer callback may be passed.
  1.2642 +**
  1.2643 +** These action code values signify what kind of operation is to be
  1.2644 +** authorized.  The 3rd and 4th parameters to the authorization
  1.2645 +** callback function will be parameters or NULL depending on which of these
  1.2646 +** codes is used as the second parameter.  ^(The 5th parameter to the
  1.2647 +** authorizer callback is the name of the database ("main", "temp",
  1.2648 +** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
  1.2649 +** is the name of the inner-most trigger or view that is responsible for
  1.2650 +** the access attempt or NULL if this access attempt is directly from
  1.2651 +** top-level SQL code.
  1.2652 +*/
  1.2653 +/******************************************* 3rd ************ 4th ***********/
  1.2654 +#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
  1.2655 +#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
  1.2656 +#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
  1.2657 +#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
  1.2658 +#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
  1.2659 +#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
  1.2660 +#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
  1.2661 +#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
  1.2662 +#define SQLITE_DELETE                9   /* Table Name      NULL            */
  1.2663 +#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
  1.2664 +#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
  1.2665 +#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
  1.2666 +#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
  1.2667 +#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
  1.2668 +#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
  1.2669 +#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
  1.2670 +#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
  1.2671 +#define SQLITE_INSERT               18   /* Table Name      NULL            */
  1.2672 +#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
  1.2673 +#define SQLITE_READ                 20   /* Table Name      Column Name     */
  1.2674 +#define SQLITE_SELECT               21   /* NULL            NULL            */
  1.2675 +#define SQLITE_TRANSACTION          22   /* Operation       NULL            */
  1.2676 +#define SQLITE_UPDATE               23   /* Table Name      Column Name     */
  1.2677 +#define SQLITE_ATTACH               24   /* Filename        NULL            */
  1.2678 +#define SQLITE_DETACH               25   /* Database Name   NULL            */
  1.2679 +#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
  1.2680 +#define SQLITE_REINDEX              27   /* Index Name      NULL            */
  1.2681 +#define SQLITE_ANALYZE              28   /* Table Name      NULL            */
  1.2682 +#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
  1.2683 +#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
  1.2684 +#define SQLITE_FUNCTION             31   /* NULL            Function Name   */
  1.2685 +#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
  1.2686 +#define SQLITE_COPY                  0   /* No longer used */
  1.2687 +#define SQLITE_RECURSIVE            33   /* NULL            NULL            */
  1.2688 +
  1.2689 +/*
  1.2690 +** CAPI3REF: Tracing And Profiling Functions
  1.2691 +**
  1.2692 +** These routines register callback functions that can be used for
  1.2693 +** tracing and profiling the execution of SQL statements.
  1.2694 +**
  1.2695 +** ^The callback function registered by sqlite3_trace() is invoked at
  1.2696 +** various times when an SQL statement is being run by [sqlite3_step()].
  1.2697 +** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  1.2698 +** SQL statement text as the statement first begins executing.
  1.2699 +** ^(Additional sqlite3_trace() callbacks might occur
  1.2700 +** as each triggered subprogram is entered.  The callbacks for triggers
  1.2701 +** contain a UTF-8 SQL comment that identifies the trigger.)^
  1.2702 +**
  1.2703 +** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  1.2704 +** the length of [bound parameter] expansion in the output of sqlite3_trace().
  1.2705 +**
  1.2706 +** ^The callback function registered by sqlite3_profile() is invoked
  1.2707 +** as each SQL statement finishes.  ^The profile callback contains
  1.2708 +** the original statement text and an estimate of wall-clock time
  1.2709 +** of how long that statement took to run.  ^The profile callback
  1.2710 +** time is in units of nanoseconds, however the current implementation
  1.2711 +** is only capable of millisecond resolution so the six least significant
  1.2712 +** digits in the time are meaningless.  Future versions of SQLite
  1.2713 +** might provide greater resolution on the profiler callback.  The
  1.2714 +** sqlite3_profile() function is considered experimental and is
  1.2715 +** subject to change in future versions of SQLite.
  1.2716 +*/
  1.2717 +SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
  1.2718 +SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
  1.2719 +   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  1.2720 +
  1.2721 +/*
  1.2722 +** CAPI3REF: Query Progress Callbacks
  1.2723 +**
  1.2724 +** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  1.2725 +** function X to be invoked periodically during long running calls to
  1.2726 +** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  1.2727 +** database connection D.  An example use for this
  1.2728 +** interface is to keep a GUI updated during a large query.
  1.2729 +**
  1.2730 +** ^The parameter P is passed through as the only parameter to the 
  1.2731 +** callback function X.  ^The parameter N is the approximate number of 
  1.2732 +** [virtual machine instructions] that are evaluated between successive
  1.2733 +** invocations of the callback X.  ^If N is less than one then the progress
  1.2734 +** handler is disabled.
  1.2735 +**
  1.2736 +** ^Only a single progress handler may be defined at one time per
  1.2737 +** [database connection]; setting a new progress handler cancels the
  1.2738 +** old one.  ^Setting parameter X to NULL disables the progress handler.
  1.2739 +** ^The progress handler is also disabled by setting N to a value less
  1.2740 +** than 1.
  1.2741 +**
  1.2742 +** ^If the progress callback returns non-zero, the operation is
  1.2743 +** interrupted.  This feature can be used to implement a
  1.2744 +** "Cancel" button on a GUI progress dialog box.
  1.2745 +**
  1.2746 +** The progress handler callback must not do anything that will modify
  1.2747 +** the database connection that invoked the progress handler.
  1.2748 +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  1.2749 +** database connections for the meaning of "modify" in this paragraph.
  1.2750 +**
  1.2751 +*/
  1.2752 +SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  1.2753 +
  1.2754 +/*
  1.2755 +** CAPI3REF: Opening A New Database Connection
  1.2756 +**
  1.2757 +** ^These routines open an SQLite database file as specified by the 
  1.2758 +** filename argument. ^The filename argument is interpreted as UTF-8 for
  1.2759 +** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  1.2760 +** order for sqlite3_open16(). ^(A [database connection] handle is usually
  1.2761 +** returned in *ppDb, even if an error occurs.  The only exception is that
  1.2762 +** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  1.2763 +** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  1.2764 +** object.)^ ^(If the database is opened (and/or created) successfully, then
  1.2765 +** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
  1.2766 +** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  1.2767 +** an English language description of the error following a failure of any
  1.2768 +** of the sqlite3_open() routines.
  1.2769 +**
  1.2770 +** ^The default encoding for the database will be UTF-8 if
  1.2771 +** sqlite3_open() or sqlite3_open_v2() is called and
  1.2772 +** UTF-16 in the native byte order if sqlite3_open16() is used.
  1.2773 +**
  1.2774 +** Whether or not an error occurs when it is opened, resources
  1.2775 +** associated with the [database connection] handle should be released by
  1.2776 +** passing it to [sqlite3_close()] when it is no longer required.
  1.2777 +**
  1.2778 +** The sqlite3_open_v2() interface works like sqlite3_open()
  1.2779 +** except that it accepts two additional parameters for additional control
  1.2780 +** over the new database connection.  ^(The flags parameter to
  1.2781 +** sqlite3_open_v2() can take one of
  1.2782 +** the following three values, optionally combined with the 
  1.2783 +** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  1.2784 +** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  1.2785 +**
  1.2786 +** <dl>
  1.2787 +** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  1.2788 +** <dd>The database is opened in read-only mode.  If the database does not
  1.2789 +** already exist, an error is returned.</dd>)^
  1.2790 +**
  1.2791 +** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  1.2792 +** <dd>The database is opened for reading and writing if possible, or reading
  1.2793 +** only if the file is write protected by the operating system.  In either
  1.2794 +** case the database must already exist, otherwise an error is returned.</dd>)^
  1.2795 +**
  1.2796 +** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  1.2797 +** <dd>The database is opened for reading and writing, and is created if
  1.2798 +** it does not already exist. This is the behavior that is always used for
  1.2799 +** sqlite3_open() and sqlite3_open16().</dd>)^
  1.2800 +** </dl>
  1.2801 +**
  1.2802 +** If the 3rd parameter to sqlite3_open_v2() is not one of the
  1.2803 +** combinations shown above optionally combined with other
  1.2804 +** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  1.2805 +** then the behavior is undefined.
  1.2806 +**
  1.2807 +** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  1.2808 +** opens in the multi-thread [threading mode] as long as the single-thread
  1.2809 +** mode has not been set at compile-time or start-time.  ^If the
  1.2810 +** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  1.2811 +** in the serialized [threading mode] unless single-thread was
  1.2812 +** previously selected at compile-time or start-time.
  1.2813 +** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  1.2814 +** eligible to use [shared cache mode], regardless of whether or not shared
  1.2815 +** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
  1.2816 +** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  1.2817 +** participate in [shared cache mode] even if it is enabled.
  1.2818 +**
  1.2819 +** ^The fourth parameter to sqlite3_open_v2() is the name of the
  1.2820 +** [sqlite3_vfs] object that defines the operating system interface that
  1.2821 +** the new database connection should use.  ^If the fourth parameter is
  1.2822 +** a NULL pointer then the default [sqlite3_vfs] object is used.
  1.2823 +**
  1.2824 +** ^If the filename is ":memory:", then a private, temporary in-memory database
  1.2825 +** is created for the connection.  ^This in-memory database will vanish when
  1.2826 +** the database connection is closed.  Future versions of SQLite might
  1.2827 +** make use of additional special filenames that begin with the ":" character.
  1.2828 +** It is recommended that when a database filename actually does begin with
  1.2829 +** a ":" character you should prefix the filename with a pathname such as
  1.2830 +** "./" to avoid ambiguity.
  1.2831 +**
  1.2832 +** ^If the filename is an empty string, then a private, temporary
  1.2833 +** on-disk database will be created.  ^This private database will be
  1.2834 +** automatically deleted as soon as the database connection is closed.
  1.2835 +**
  1.2836 +** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  1.2837 +**
  1.2838 +** ^If [URI filename] interpretation is enabled, and the filename argument
  1.2839 +** begins with "file:", then the filename is interpreted as a URI. ^URI
  1.2840 +** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  1.2841 +** set in the fourth argument to sqlite3_open_v2(), or if it has
  1.2842 +** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  1.2843 +** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  1.2844 +** As of SQLite version 3.7.7, URI filename interpretation is turned off
  1.2845 +** by default, but future releases of SQLite might enable URI filename
  1.2846 +** interpretation by default.  See "[URI filenames]" for additional
  1.2847 +** information.
  1.2848 +**
  1.2849 +** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  1.2850 +** authority, then it must be either an empty string or the string 
  1.2851 +** "localhost". ^If the authority is not an empty string or "localhost", an 
  1.2852 +** error is returned to the caller. ^The fragment component of a URI, if 
  1.2853 +** present, is ignored.
  1.2854 +**
  1.2855 +** ^SQLite uses the path component of the URI as the name of the disk file
  1.2856 +** which contains the database. ^If the path begins with a '/' character, 
  1.2857 +** then it is interpreted as an absolute path. ^If the path does not begin 
  1.2858 +** with a '/' (meaning that the authority section is omitted from the URI)
  1.2859 +** then the path is interpreted as a relative path. 
  1.2860 +** ^On windows, the first component of an absolute path 
  1.2861 +** is a drive specification (e.g. "C:").
  1.2862 +**
  1.2863 +** [[core URI query parameters]]
  1.2864 +** The query component of a URI may contain parameters that are interpreted
  1.2865 +** either by SQLite itself, or by a [VFS | custom VFS implementation].
  1.2866 +** SQLite interprets the following three query parameters:
  1.2867 +**
  1.2868 +** <ul>
  1.2869 +**   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  1.2870 +**     a VFS object that provides the operating system interface that should
  1.2871 +**     be used to access the database file on disk. ^If this option is set to
  1.2872 +**     an empty string the default VFS object is used. ^Specifying an unknown
  1.2873 +**     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  1.2874 +**     present, then the VFS specified by the option takes precedence over
  1.2875 +**     the value passed as the fourth parameter to sqlite3_open_v2().
  1.2876 +**
  1.2877 +**   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  1.2878 +**     "rwc", or "memory". Attempting to set it to any other value is
  1.2879 +**     an error)^. 
  1.2880 +**     ^If "ro" is specified, then the database is opened for read-only 
  1.2881 +**     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the 
  1.2882 +**     third argument to sqlite3_open_v2(). ^If the mode option is set to 
  1.2883 +**     "rw", then the database is opened for read-write (but not create) 
  1.2884 +**     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had 
  1.2885 +**     been set. ^Value "rwc" is equivalent to setting both 
  1.2886 +**     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
  1.2887 +**     set to "memory" then a pure [in-memory database] that never reads
  1.2888 +**     or writes from disk is used. ^It is an error to specify a value for
  1.2889 +**     the mode parameter that is less restrictive than that specified by
  1.2890 +**     the flags passed in the third parameter to sqlite3_open_v2().
  1.2891 +**
  1.2892 +**   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  1.2893 +**     "private". ^Setting it to "shared" is equivalent to setting the
  1.2894 +**     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  1.2895 +**     sqlite3_open_v2(). ^Setting the cache parameter to "private" is 
  1.2896 +**     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  1.2897 +**     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  1.2898 +**     a URI filename, its value overrides any behavior requested by setting
  1.2899 +**     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  1.2900 +** </ul>
  1.2901 +**
  1.2902 +** ^Specifying an unknown parameter in the query component of a URI is not an
  1.2903 +** error.  Future versions of SQLite might understand additional query
  1.2904 +** parameters.  See "[query parameters with special meaning to SQLite]" for
  1.2905 +** additional information.
  1.2906 +**
  1.2907 +** [[URI filename examples]] <h3>URI filename examples</h3>
  1.2908 +**
  1.2909 +** <table border="1" align=center cellpadding=5>
  1.2910 +** <tr><th> URI filenames <th> Results
  1.2911 +** <tr><td> file:data.db <td> 
  1.2912 +**          Open the file "data.db" in the current directory.
  1.2913 +** <tr><td> file:/home/fred/data.db<br>
  1.2914 +**          file:///home/fred/data.db <br> 
  1.2915 +**          file://localhost/home/fred/data.db <br> <td> 
  1.2916 +**          Open the database file "/home/fred/data.db".
  1.2917 +** <tr><td> file://darkstar/home/fred/data.db <td> 
  1.2918 +**          An error. "darkstar" is not a recognized authority.
  1.2919 +** <tr><td style="white-space:nowrap"> 
  1.2920 +**          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  1.2921 +**     <td> Windows only: Open the file "data.db" on fred's desktop on drive
  1.2922 +**          C:. Note that the %20 escaping in this example is not strictly 
  1.2923 +**          necessary - space characters can be used literally
  1.2924 +**          in URI filenames.
  1.2925 +** <tr><td> file:data.db?mode=ro&cache=private <td> 
  1.2926 +**          Open file "data.db" in the current directory for read-only access.
  1.2927 +**          Regardless of whether or not shared-cache mode is enabled by
  1.2928 +**          default, use a private cache.
  1.2929 +** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
  1.2930 +**          Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
  1.2931 +** <tr><td> file:data.db?mode=readonly <td> 
  1.2932 +**          An error. "readonly" is not a valid option for the "mode" parameter.
  1.2933 +** </table>
  1.2934 +**
  1.2935 +** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  1.2936 +** query components of a URI. A hexadecimal escape sequence consists of a
  1.2937 +** percent sign - "%" - followed by exactly two hexadecimal digits 
  1.2938 +** specifying an octet value. ^Before the path or query components of a
  1.2939 +** URI filename are interpreted, they are encoded using UTF-8 and all 
  1.2940 +** hexadecimal escape sequences replaced by a single byte containing the
  1.2941 +** corresponding octet. If this process generates an invalid UTF-8 encoding,
  1.2942 +** the results are undefined.
  1.2943 +**
  1.2944 +** <b>Note to Windows users:</b>  The encoding used for the filename argument
  1.2945 +** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  1.2946 +** codepage is currently defined.  Filenames containing international
  1.2947 +** characters must be converted to UTF-8 prior to passing them into
  1.2948 +** sqlite3_open() or sqlite3_open_v2().
  1.2949 +**
  1.2950 +** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
  1.2951 +** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
  1.2952 +** features that require the use of temporary files may fail.
  1.2953 +**
  1.2954 +** See also: [sqlite3_temp_directory]
  1.2955 +*/
  1.2956 +SQLITE_API int sqlite3_open(
  1.2957 +  const char *filename,   /* Database filename (UTF-8) */
  1.2958 +  sqlite3 **ppDb          /* OUT: SQLite db handle */
  1.2959 +);
  1.2960 +SQLITE_API int sqlite3_open16(
  1.2961 +  const void *filename,   /* Database filename (UTF-16) */
  1.2962 +  sqlite3 **ppDb          /* OUT: SQLite db handle */
  1.2963 +);
  1.2964 +SQLITE_API int sqlite3_open_v2(
  1.2965 +  const char *filename,   /* Database filename (UTF-8) */
  1.2966 +  sqlite3 **ppDb,         /* OUT: SQLite db handle */
  1.2967 +  int flags,              /* Flags */
  1.2968 +  const char *zVfs        /* Name of VFS module to use */
  1.2969 +);
  1.2970 +
  1.2971 +/*
  1.2972 +** CAPI3REF: Obtain Values For URI Parameters
  1.2973 +**
  1.2974 +** These are utility routines, useful to VFS implementations, that check
  1.2975 +** to see if a database file was a URI that contained a specific query 
  1.2976 +** parameter, and if so obtains the value of that query parameter.
  1.2977 +**
  1.2978 +** If F is the database filename pointer passed into the xOpen() method of 
  1.2979 +** a VFS implementation when the flags parameter to xOpen() has one or 
  1.2980 +** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  1.2981 +** P is the name of the query parameter, then
  1.2982 +** sqlite3_uri_parameter(F,P) returns the value of the P
  1.2983 +** parameter if it exists or a NULL pointer if P does not appear as a 
  1.2984 +** query parameter on F.  If P is a query parameter of F
  1.2985 +** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  1.2986 +** a pointer to an empty string.
  1.2987 +**
  1.2988 +** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  1.2989 +** parameter and returns true (1) or false (0) according to the value
  1.2990 +** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  1.2991 +** value of query parameter P is one of "yes", "true", or "on" in any
  1.2992 +** case or if the value begins with a non-zero number.  The 
  1.2993 +** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  1.2994 +** query parameter P is one of "no", "false", or "off" in any case or
  1.2995 +** if the value begins with a numeric zero.  If P is not a query
  1.2996 +** parameter on F or if the value of P is does not match any of the
  1.2997 +** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  1.2998 +**
  1.2999 +** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  1.3000 +** 64-bit signed integer and returns that integer, or D if P does not
  1.3001 +** exist.  If the value of P is something other than an integer, then
  1.3002 +** zero is returned.
  1.3003 +** 
  1.3004 +** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  1.3005 +** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
  1.3006 +** is not a database file pathname pointer that SQLite passed into the xOpen
  1.3007 +** VFS method, then the behavior of this routine is undefined and probably
  1.3008 +** undesirable.
  1.3009 +*/
  1.3010 +SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  1.3011 +SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  1.3012 +SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  1.3013 +
  1.3014 +
  1.3015 +/*
  1.3016 +** CAPI3REF: Error Codes And Messages
  1.3017 +**
  1.3018 +** ^The sqlite3_errcode() interface returns the numeric [result code] or
  1.3019 +** [extended result code] for the most recent failed sqlite3_* API call
  1.3020 +** associated with a [database connection]. If a prior API call failed
  1.3021 +** but the most recent API call succeeded, the return value from
  1.3022 +** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
  1.3023 +** interface is the same except that it always returns the 
  1.3024 +** [extended result code] even when extended result codes are
  1.3025 +** disabled.
  1.3026 +**
  1.3027 +** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  1.3028 +** text that describes the error, as either UTF-8 or UTF-16 respectively.
  1.3029 +** ^(Memory to hold the error message string is managed internally.
  1.3030 +** The application does not need to worry about freeing the result.
  1.3031 +** However, the error string might be overwritten or deallocated by
  1.3032 +** subsequent calls to other SQLite interface functions.)^
  1.3033 +**
  1.3034 +** ^The sqlite3_errstr() interface returns the English-language text
  1.3035 +** that describes the [result code], as UTF-8.
  1.3036 +** ^(Memory to hold the error message string is managed internally
  1.3037 +** and must not be freed by the application)^.
  1.3038 +**
  1.3039 +** When the serialized [threading mode] is in use, it might be the
  1.3040 +** case that a second error occurs on a separate thread in between
  1.3041 +** the time of the first error and the call to these interfaces.
  1.3042 +** When that happens, the second error will be reported since these
  1.3043 +** interfaces always report the most recent result.  To avoid
  1.3044 +** this, each thread can obtain exclusive use of the [database connection] D
  1.3045 +** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  1.3046 +** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  1.3047 +** all calls to the interfaces listed here are completed.
  1.3048 +**
  1.3049 +** If an interface fails with SQLITE_MISUSE, that means the interface
  1.3050 +** was invoked incorrectly by the application.  In that case, the
  1.3051 +** error code and message may or may not be set.
  1.3052 +*/
  1.3053 +SQLITE_API int sqlite3_errcode(sqlite3 *db);
  1.3054 +SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  1.3055 +SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  1.3056 +SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  1.3057 +SQLITE_API const char *sqlite3_errstr(int);
  1.3058 +
  1.3059 +/*
  1.3060 +** CAPI3REF: SQL Statement Object
  1.3061 +** KEYWORDS: {prepared statement} {prepared statements}
  1.3062 +**
  1.3063 +** An instance of this object represents a single SQL statement.
  1.3064 +** This object is variously known as a "prepared statement" or a
  1.3065 +** "compiled SQL statement" or simply as a "statement".
  1.3066 +**
  1.3067 +** The life of a statement object goes something like this:
  1.3068 +**
  1.3069 +** <ol>
  1.3070 +** <li> Create the object using [sqlite3_prepare_v2()] or a related
  1.3071 +**      function.
  1.3072 +** <li> Bind values to [host parameters] using the sqlite3_bind_*()
  1.3073 +**      interfaces.
  1.3074 +** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  1.3075 +** <li> Reset the statement using [sqlite3_reset()] then go back
  1.3076 +**      to step 2.  Do this zero or more times.
  1.3077 +** <li> Destroy the object using [sqlite3_finalize()].
  1.3078 +** </ol>
  1.3079 +**
  1.3080 +** Refer to documentation on individual methods above for additional
  1.3081 +** information.
  1.3082 +*/
  1.3083 +typedef struct sqlite3_stmt sqlite3_stmt;
  1.3084 +
  1.3085 +/*
  1.3086 +** CAPI3REF: Run-time Limits
  1.3087 +**
  1.3088 +** ^(This interface allows the size of various constructs to be limited
  1.3089 +** on a connection by connection basis.  The first parameter is the
  1.3090 +** [database connection] whose limit is to be set or queried.  The
  1.3091 +** second parameter is one of the [limit categories] that define a
  1.3092 +** class of constructs to be size limited.  The third parameter is the
  1.3093 +** new limit for that construct.)^
  1.3094 +**
  1.3095 +** ^If the new limit is a negative number, the limit is unchanged.
  1.3096 +** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a 
  1.3097 +** [limits | hard upper bound]
  1.3098 +** set at compile-time by a C preprocessor macro called
  1.3099 +** [limits | SQLITE_MAX_<i>NAME</i>].
  1.3100 +** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  1.3101 +** ^Attempts to increase a limit above its hard upper bound are
  1.3102 +** silently truncated to the hard upper bound.
  1.3103 +**
  1.3104 +** ^Regardless of whether or not the limit was changed, the 
  1.3105 +** [sqlite3_limit()] interface returns the prior value of the limit.
  1.3106 +** ^Hence, to find the current value of a limit without changing it,
  1.3107 +** simply invoke this interface with the third parameter set to -1.
  1.3108 +**
  1.3109 +** Run-time limits are intended for use in applications that manage
  1.3110 +** both their own internal database and also databases that are controlled
  1.3111 +** by untrusted external sources.  An example application might be a
  1.3112 +** web browser that has its own databases for storing history and
  1.3113 +** separate databases controlled by JavaScript applications downloaded
  1.3114 +** off the Internet.  The internal databases can be given the
  1.3115 +** large, default limits.  Databases managed by external sources can
  1.3116 +** be given much smaller limits designed to prevent a denial of service
  1.3117 +** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
  1.3118 +** interface to further control untrusted SQL.  The size of the database
  1.3119 +** created by an untrusted script can be contained using the
  1.3120 +** [max_page_count] [PRAGMA].
  1.3121 +**
  1.3122 +** New run-time limit categories may be added in future releases.
  1.3123 +*/
  1.3124 +SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  1.3125 +
  1.3126 +/*
  1.3127 +** CAPI3REF: Run-Time Limit Categories
  1.3128 +** KEYWORDS: {limit category} {*limit categories}
  1.3129 +**
  1.3130 +** These constants define various performance limits
  1.3131 +** that can be lowered at run-time using [sqlite3_limit()].
  1.3132 +** The synopsis of the meanings of the various limits is shown below.
  1.3133 +** Additional information is available at [limits | Limits in SQLite].
  1.3134 +**
  1.3135 +** <dl>
  1.3136 +** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  1.3137 +** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  1.3138 +**
  1.3139 +** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  1.3140 +** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  1.3141 +**
  1.3142 +** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  1.3143 +** <dd>The maximum number of columns in a table definition or in the
  1.3144 +** result set of a [SELECT] or the maximum number of columns in an index
  1.3145 +** or in an ORDER BY or GROUP BY clause.</dd>)^
  1.3146 +**
  1.3147 +** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  1.3148 +** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  1.3149 +**
  1.3150 +** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  1.3151 +** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  1.3152 +**
  1.3153 +** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  1.3154 +** <dd>The maximum number of instructions in a virtual machine program
  1.3155 +** used to implement an SQL statement.  This limit is not currently
  1.3156 +** enforced, though that might be added in some future release of
  1.3157 +** SQLite.</dd>)^
  1.3158 +**
  1.3159 +** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  1.3160 +** <dd>The maximum number of arguments on a function.</dd>)^
  1.3161 +**
  1.3162 +** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  1.3163 +** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  1.3164 +**
  1.3165 +** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  1.3166 +** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  1.3167 +** <dd>The maximum length of the pattern argument to the [LIKE] or
  1.3168 +** [GLOB] operators.</dd>)^
  1.3169 +**
  1.3170 +** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  1.3171 +** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  1.3172 +** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  1.3173 +**
  1.3174 +** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  1.3175 +** <dd>The maximum depth of recursion for triggers.</dd>)^
  1.3176 +** </dl>
  1.3177 +*/
  1.3178 +#define SQLITE_LIMIT_LENGTH                    0
  1.3179 +#define SQLITE_LIMIT_SQL_LENGTH                1
  1.3180 +#define SQLITE_LIMIT_COLUMN                    2
  1.3181 +#define SQLITE_LIMIT_EXPR_DEPTH                3
  1.3182 +#define SQLITE_LIMIT_COMPOUND_SELECT           4
  1.3183 +#define SQLITE_LIMIT_VDBE_OP                   5
  1.3184 +#define SQLITE_LIMIT_FUNCTION_ARG              6
  1.3185 +#define SQLITE_LIMIT_ATTACHED                  7
  1.3186 +#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
  1.3187 +#define SQLITE_LIMIT_VARIABLE_NUMBER           9
  1.3188 +#define SQLITE_LIMIT_TRIGGER_DEPTH            10
  1.3189 +
  1.3190 +/*
  1.3191 +** CAPI3REF: Compiling An SQL Statement
  1.3192 +** KEYWORDS: {SQL statement compiler}
  1.3193 +**
  1.3194 +** To execute an SQL query, it must first be compiled into a byte-code
  1.3195 +** program using one of these routines.
  1.3196 +**
  1.3197 +** The first argument, "db", is a [database connection] obtained from a
  1.3198 +** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  1.3199 +** [sqlite3_open16()].  The database connection must not have been closed.
  1.3200 +**
  1.3201 +** The second argument, "zSql", is the statement to be compiled, encoded
  1.3202 +** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
  1.3203 +** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  1.3204 +** use UTF-16.
  1.3205 +**
  1.3206 +** ^If the nByte argument is less than zero, then zSql is read up to the
  1.3207 +** first zero terminator. ^If nByte is non-negative, then it is the maximum
  1.3208 +** number of  bytes read from zSql.  ^When nByte is non-negative, the
  1.3209 +** zSql string ends at either the first '\000' or '\u0000' character or
  1.3210 +** the nByte-th byte, whichever comes first. If the caller knows
  1.3211 +** that the supplied string is nul-terminated, then there is a small
  1.3212 +** performance advantage to be gained by passing an nByte parameter that
  1.3213 +** is equal to the number of bytes in the input string <i>including</i>
  1.3214 +** the nul-terminator bytes as this saves SQLite from having to
  1.3215 +** make a copy of the input string.
  1.3216 +**
  1.3217 +** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  1.3218 +** past the end of the first SQL statement in zSql.  These routines only
  1.3219 +** compile the first statement in zSql, so *pzTail is left pointing to
  1.3220 +** what remains uncompiled.
  1.3221 +**
  1.3222 +** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  1.3223 +** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
  1.3224 +** to NULL.  ^If the input text contains no SQL (if the input is an empty
  1.3225 +** string or a comment) then *ppStmt is set to NULL.
  1.3226 +** The calling procedure is responsible for deleting the compiled
  1.3227 +** SQL statement using [sqlite3_finalize()] after it has finished with it.
  1.3228 +** ppStmt may not be NULL.
  1.3229 +**
  1.3230 +** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  1.3231 +** otherwise an [error code] is returned.
  1.3232 +**
  1.3233 +** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  1.3234 +** recommended for all new programs. The two older interfaces are retained
  1.3235 +** for backwards compatibility, but their use is discouraged.
  1.3236 +** ^In the "v2" interfaces, the prepared statement
  1.3237 +** that is returned (the [sqlite3_stmt] object) contains a copy of the
  1.3238 +** original SQL text. This causes the [sqlite3_step()] interface to
  1.3239 +** behave differently in three ways:
  1.3240 +**
  1.3241 +** <ol>
  1.3242 +** <li>
  1.3243 +** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  1.3244 +** always used to do, [sqlite3_step()] will automatically recompile the SQL
  1.3245 +** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  1.3246 +** retries will occur before sqlite3_step() gives up and returns an error.
  1.3247 +** </li>
  1.3248 +**
  1.3249 +** <li>
  1.3250 +** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  1.3251 +** [error codes] or [extended error codes].  ^The legacy behavior was that
  1.3252 +** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  1.3253 +** and the application would have to make a second call to [sqlite3_reset()]
  1.3254 +** in order to find the underlying cause of the problem. With the "v2" prepare
  1.3255 +** interfaces, the underlying reason for the error is returned immediately.
  1.3256 +** </li>
  1.3257 +**
  1.3258 +** <li>
  1.3259 +** ^If the specific value bound to [parameter | host parameter] in the 
  1.3260 +** WHERE clause might influence the choice of query plan for a statement,
  1.3261 +** then the statement will be automatically recompiled, as if there had been 
  1.3262 +** a schema change, on the first  [sqlite3_step()] call following any change
  1.3263 +** to the [sqlite3_bind_text | bindings] of that [parameter]. 
  1.3264 +** ^The specific value of WHERE-clause [parameter] might influence the 
  1.3265 +** choice of query plan if the parameter is the left-hand side of a [LIKE]
  1.3266 +** or [GLOB] operator or if the parameter is compared to an indexed column
  1.3267 +** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  1.3268 +** </li>
  1.3269 +** </ol>
  1.3270 +*/
  1.3271 +SQLITE_API int sqlite3_prepare(
  1.3272 +  sqlite3 *db,            /* Database handle */
  1.3273 +  const char *zSql,       /* SQL statement, UTF-8 encoded */
  1.3274 +  int nByte,              /* Maximum length of zSql in bytes. */
  1.3275 +  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  1.3276 +  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
  1.3277 +);
  1.3278 +SQLITE_API int sqlite3_prepare_v2(
  1.3279 +  sqlite3 *db,            /* Database handle */
  1.3280 +  const char *zSql,       /* SQL statement, UTF-8 encoded */
  1.3281 +  int nByte,              /* Maximum length of zSql in bytes. */
  1.3282 +  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  1.3283 +  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
  1.3284 +);
  1.3285 +SQLITE_API int sqlite3_prepare16(
  1.3286 +  sqlite3 *db,            /* Database handle */
  1.3287 +  const void *zSql,       /* SQL statement, UTF-16 encoded */
  1.3288 +  int nByte,              /* Maximum length of zSql in bytes. */
  1.3289 +  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  1.3290 +  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
  1.3291 +);
  1.3292 +SQLITE_API int sqlite3_prepare16_v2(
  1.3293 +  sqlite3 *db,            /* Database handle */
  1.3294 +  const void *zSql,       /* SQL statement, UTF-16 encoded */
  1.3295 +  int nByte,              /* Maximum length of zSql in bytes. */
  1.3296 +  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  1.3297 +  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
  1.3298 +);
  1.3299 +
  1.3300 +/*
  1.3301 +** CAPI3REF: Retrieving Statement SQL
  1.3302 +**
  1.3303 +** ^This interface can be used to retrieve a saved copy of the original
  1.3304 +** SQL text used to create a [prepared statement] if that statement was
  1.3305 +** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  1.3306 +*/
  1.3307 +SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  1.3308 +
  1.3309 +/*
  1.3310 +** CAPI3REF: Determine If An SQL Statement Writes The Database
  1.3311 +**
  1.3312 +** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  1.3313 +** and only if the [prepared statement] X makes no direct changes to
  1.3314 +** the content of the database file.
  1.3315 +**
  1.3316 +** Note that [application-defined SQL functions] or
  1.3317 +** [virtual tables] might change the database indirectly as a side effect.  
  1.3318 +** ^(For example, if an application defines a function "eval()" that 
  1.3319 +** calls [sqlite3_exec()], then the following SQL statement would
  1.3320 +** change the database file through side-effects:
  1.3321 +**
  1.3322 +** <blockquote><pre>
  1.3323 +**    SELECT eval('DELETE FROM t1') FROM t2;
  1.3324 +** </pre></blockquote>
  1.3325 +**
  1.3326 +** But because the [SELECT] statement does not change the database file
  1.3327 +** directly, sqlite3_stmt_readonly() would still return true.)^
  1.3328 +**
  1.3329 +** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  1.3330 +** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  1.3331 +** since the statements themselves do not actually modify the database but
  1.3332 +** rather they control the timing of when other statements modify the 
  1.3333 +** database.  ^The [ATTACH] and [DETACH] statements also cause
  1.3334 +** sqlite3_stmt_readonly() to return true since, while those statements
  1.3335 +** change the configuration of a database connection, they do not make 
  1.3336 +** changes to the content of the database files on disk.
  1.3337 +*/
  1.3338 +SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  1.3339 +
  1.3340 +/*
  1.3341 +** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  1.3342 +**
  1.3343 +** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  1.3344 +** [prepared statement] S has been stepped at least once using 
  1.3345 +** [sqlite3_step(S)] but has not run to completion and/or has not 
  1.3346 +** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
  1.3347 +** interface returns false if S is a NULL pointer.  If S is not a 
  1.3348 +** NULL pointer and is not a pointer to a valid [prepared statement]
  1.3349 +** object, then the behavior is undefined and probably undesirable.
  1.3350 +**
  1.3351 +** This interface can be used in combination [sqlite3_next_stmt()]
  1.3352 +** to locate all prepared statements associated with a database 
  1.3353 +** connection that are in need of being reset.  This can be used,
  1.3354 +** for example, in diagnostic routines to search for prepared 
  1.3355 +** statements that are holding a transaction open.
  1.3356 +*/
  1.3357 +SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  1.3358 +
  1.3359 +/*
  1.3360 +** CAPI3REF: Dynamically Typed Value Object
  1.3361 +** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  1.3362 +**
  1.3363 +** SQLite uses the sqlite3_value object to represent all values
  1.3364 +** that can be stored in a database table. SQLite uses dynamic typing
  1.3365 +** for the values it stores.  ^Values stored in sqlite3_value objects
  1.3366 +** can be integers, floating point values, strings, BLOBs, or NULL.
  1.3367 +**
  1.3368 +** An sqlite3_value object may be either "protected" or "unprotected".
  1.3369 +** Some interfaces require a protected sqlite3_value.  Other interfaces
  1.3370 +** will accept either a protected or an unprotected sqlite3_value.
  1.3371 +** Every interface that accepts sqlite3_value arguments specifies
  1.3372 +** whether or not it requires a protected sqlite3_value.
  1.3373 +**
  1.3374 +** The terms "protected" and "unprotected" refer to whether or not
  1.3375 +** a mutex is held.  An internal mutex is held for a protected
  1.3376 +** sqlite3_value object but no mutex is held for an unprotected
  1.3377 +** sqlite3_value object.  If SQLite is compiled to be single-threaded
  1.3378 +** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  1.3379 +** or if SQLite is run in one of reduced mutex modes 
  1.3380 +** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  1.3381 +** then there is no distinction between protected and unprotected
  1.3382 +** sqlite3_value objects and they can be used interchangeably.  However,
  1.3383 +** for maximum code portability it is recommended that applications
  1.3384 +** still make the distinction between protected and unprotected
  1.3385 +** sqlite3_value objects even when not strictly required.
  1.3386 +**
  1.3387 +** ^The sqlite3_value objects that are passed as parameters into the
  1.3388 +** implementation of [application-defined SQL functions] are protected.
  1.3389 +** ^The sqlite3_value object returned by
  1.3390 +** [sqlite3_column_value()] is unprotected.
  1.3391 +** Unprotected sqlite3_value objects may only be used with
  1.3392 +** [sqlite3_result_value()] and [sqlite3_bind_value()].
  1.3393 +** The [sqlite3_value_blob | sqlite3_value_type()] family of
  1.3394 +** interfaces require protected sqlite3_value objects.
  1.3395 +*/
  1.3396 +typedef struct Mem sqlite3_value;
  1.3397 +
  1.3398 +/*
  1.3399 +** CAPI3REF: SQL Function Context Object
  1.3400 +**
  1.3401 +** The context in which an SQL function executes is stored in an
  1.3402 +** sqlite3_context object.  ^A pointer to an sqlite3_context object
  1.3403 +** is always first parameter to [application-defined SQL functions].
  1.3404 +** The application-defined SQL function implementation will pass this
  1.3405 +** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  1.3406 +** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  1.3407 +** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  1.3408 +** and/or [sqlite3_set_auxdata()].
  1.3409 +*/
  1.3410 +typedef struct sqlite3_context sqlite3_context;
  1.3411 +
  1.3412 +/*
  1.3413 +** CAPI3REF: Binding Values To Prepared Statements
  1.3414 +** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  1.3415 +** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  1.3416 +**
  1.3417 +** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  1.3418 +** literals may be replaced by a [parameter] that matches one of following
  1.3419 +** templates:
  1.3420 +**
  1.3421 +** <ul>
  1.3422 +** <li>  ?
  1.3423 +** <li>  ?NNN
  1.3424 +** <li>  :VVV
  1.3425 +** <li>  @VVV
  1.3426 +** <li>  $VVV
  1.3427 +** </ul>
  1.3428 +**
  1.3429 +** In the templates above, NNN represents an integer literal,
  1.3430 +** and VVV represents an alphanumeric identifier.)^  ^The values of these
  1.3431 +** parameters (also called "host parameter names" or "SQL parameters")
  1.3432 +** can be set using the sqlite3_bind_*() routines defined here.
  1.3433 +**
  1.3434 +** ^The first argument to the sqlite3_bind_*() routines is always
  1.3435 +** a pointer to the [sqlite3_stmt] object returned from
  1.3436 +** [sqlite3_prepare_v2()] or its variants.
  1.3437 +**
  1.3438 +** ^The second argument is the index of the SQL parameter to be set.
  1.3439 +** ^The leftmost SQL parameter has an index of 1.  ^When the same named
  1.3440 +** SQL parameter is used more than once, second and subsequent
  1.3441 +** occurrences have the same index as the first occurrence.
  1.3442 +** ^The index for named parameters can be looked up using the
  1.3443 +** [sqlite3_bind_parameter_index()] API if desired.  ^The index
  1.3444 +** for "?NNN" parameters is the value of NNN.
  1.3445 +** ^The NNN value must be between 1 and the [sqlite3_limit()]
  1.3446 +** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  1.3447 +**
  1.3448 +** ^The third argument is the value to bind to the parameter.
  1.3449 +** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  1.3450 +** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  1.3451 +** is ignored and the end result is the same as sqlite3_bind_null().
  1.3452 +**
  1.3453 +** ^(In those routines that have a fourth argument, its value is the
  1.3454 +** number of bytes in the parameter.  To be clear: the value is the
  1.3455 +** number of <u>bytes</u> in the value, not the number of characters.)^
  1.3456 +** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  1.3457 +** is negative, then the length of the string is
  1.3458 +** the number of bytes up to the first zero terminator.
  1.3459 +** If the fourth parameter to sqlite3_bind_blob() is negative, then
  1.3460 +** the behavior is undefined.
  1.3461 +** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  1.3462 +** or sqlite3_bind_text16() then that parameter must be the byte offset
  1.3463 +** where the NUL terminator would occur assuming the string were NUL
  1.3464 +** terminated.  If any NUL characters occur at byte offsets less than 
  1.3465 +** the value of the fourth parameter then the resulting string value will
  1.3466 +** contain embedded NULs.  The result of expressions involving strings
  1.3467 +** with embedded NULs is undefined.
  1.3468 +**
  1.3469 +** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
  1.3470 +** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
  1.3471 +** string after SQLite has finished with it.  ^The destructor is called
  1.3472 +** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
  1.3473 +** sqlite3_bind_text(), or sqlite3_bind_text16() fails.  
  1.3474 +** ^If the fifth argument is
  1.3475 +** the special value [SQLITE_STATIC], then SQLite assumes that the
  1.3476 +** information is in static, unmanaged space and does not need to be freed.
  1.3477 +** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  1.3478 +** SQLite makes its own private copy of the data immediately, before
  1.3479 +** the sqlite3_bind_*() routine returns.
  1.3480 +**
  1.3481 +** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  1.3482 +** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
  1.3483 +** (just an integer to hold its size) while it is being processed.
  1.3484 +** Zeroblobs are intended to serve as placeholders for BLOBs whose
  1.3485 +** content is later written using
  1.3486 +** [sqlite3_blob_open | incremental BLOB I/O] routines.
  1.3487 +** ^A negative value for the zeroblob results in a zero-length BLOB.
  1.3488 +**
  1.3489 +** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  1.3490 +** for the [prepared statement] or with a prepared statement for which
  1.3491 +** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  1.3492 +** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
  1.3493 +** routine is passed a [prepared statement] that has been finalized, the
  1.3494 +** result is undefined and probably harmful.
  1.3495 +**
  1.3496 +** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  1.3497 +** ^Unbound parameters are interpreted as NULL.
  1.3498 +**
  1.3499 +** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  1.3500 +** [error code] if anything goes wrong.
  1.3501 +** ^[SQLITE_RANGE] is returned if the parameter
  1.3502 +** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
  1.3503 +**
  1.3504 +** See also: [sqlite3_bind_parameter_count()],
  1.3505 +** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  1.3506 +*/
  1.3507 +SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  1.3508 +SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  1.3509 +SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  1.3510 +SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  1.3511 +SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  1.3512 +SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
  1.3513 +SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  1.3514 +SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  1.3515 +SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  1.3516 +
  1.3517 +/*
  1.3518 +** CAPI3REF: Number Of SQL Parameters
  1.3519 +**
  1.3520 +** ^This routine can be used to find the number of [SQL parameters]
  1.3521 +** in a [prepared statement].  SQL parameters are tokens of the
  1.3522 +** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  1.3523 +** placeholders for values that are [sqlite3_bind_blob | bound]
  1.3524 +** to the parameters at a later time.
  1.3525 +**
  1.3526 +** ^(This routine actually returns the index of the largest (rightmost)
  1.3527 +** parameter. For all forms except ?NNN, this will correspond to the
  1.3528 +** number of unique parameters.  If parameters of the ?NNN form are used,
  1.3529 +** there may be gaps in the list.)^
  1.3530 +**
  1.3531 +** See also: [sqlite3_bind_blob|sqlite3_bind()],
  1.3532 +** [sqlite3_bind_parameter_name()], and
  1.3533 +** [sqlite3_bind_parameter_index()].
  1.3534 +*/
  1.3535 +SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  1.3536 +
  1.3537 +/*
  1.3538 +** CAPI3REF: Name Of A Host Parameter
  1.3539 +**
  1.3540 +** ^The sqlite3_bind_parameter_name(P,N) interface returns
  1.3541 +** the name of the N-th [SQL parameter] in the [prepared statement] P.
  1.3542 +** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  1.3543 +** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  1.3544 +** respectively.
  1.3545 +** In other words, the initial ":" or "$" or "@" or "?"
  1.3546 +** is included as part of the name.)^
  1.3547 +** ^Parameters of the form "?" without a following integer have no name
  1.3548 +** and are referred to as "nameless" or "anonymous parameters".
  1.3549 +**
  1.3550 +** ^The first host parameter has an index of 1, not 0.
  1.3551 +**
  1.3552 +** ^If the value N is out of range or if the N-th parameter is
  1.3553 +** nameless, then NULL is returned.  ^The returned string is
  1.3554 +** always in UTF-8 encoding even if the named parameter was
  1.3555 +** originally specified as UTF-16 in [sqlite3_prepare16()] or
  1.3556 +** [sqlite3_prepare16_v2()].
  1.3557 +**
  1.3558 +** See also: [sqlite3_bind_blob|sqlite3_bind()],
  1.3559 +** [sqlite3_bind_parameter_count()], and
  1.3560 +** [sqlite3_bind_parameter_index()].
  1.3561 +*/
  1.3562 +SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  1.3563 +
  1.3564 +/*
  1.3565 +** CAPI3REF: Index Of A Parameter With A Given Name
  1.3566 +**
  1.3567 +** ^Return the index of an SQL parameter given its name.  ^The
  1.3568 +** index value returned is suitable for use as the second
  1.3569 +** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
  1.3570 +** is returned if no matching parameter is found.  ^The parameter
  1.3571 +** name must be given in UTF-8 even if the original statement
  1.3572 +** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  1.3573 +**
  1.3574 +** See also: [sqlite3_bind_blob|sqlite3_bind()],
  1.3575 +** [sqlite3_bind_parameter_count()], and
  1.3576 +** [sqlite3_bind_parameter_index()].
  1.3577 +*/
  1.3578 +SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  1.3579 +
  1.3580 +/*
  1.3581 +** CAPI3REF: Reset All Bindings On A Prepared Statement
  1.3582 +**
  1.3583 +** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  1.3584 +** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  1.3585 +** ^Use this routine to reset all host parameters to NULL.
  1.3586 +*/
  1.3587 +SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  1.3588 +
  1.3589 +/*
  1.3590 +** CAPI3REF: Number Of Columns In A Result Set
  1.3591 +**
  1.3592 +** ^Return the number of columns in the result set returned by the
  1.3593 +** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
  1.3594 +** statement that does not return data (for example an [UPDATE]).
  1.3595 +**
  1.3596 +** See also: [sqlite3_data_count()]
  1.3597 +*/
  1.3598 +SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  1.3599 +
  1.3600 +/*
  1.3601 +** CAPI3REF: Column Names In A Result Set
  1.3602 +**
  1.3603 +** ^These routines return the name assigned to a particular column
  1.3604 +** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
  1.3605 +** interface returns a pointer to a zero-terminated UTF-8 string
  1.3606 +** and sqlite3_column_name16() returns a pointer to a zero-terminated
  1.3607 +** UTF-16 string.  ^The first parameter is the [prepared statement]
  1.3608 +** that implements the [SELECT] statement. ^The second parameter is the
  1.3609 +** column number.  ^The leftmost column is number 0.
  1.3610 +**
  1.3611 +** ^The returned string pointer is valid until either the [prepared statement]
  1.3612 +** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  1.3613 +** reprepared by the first call to [sqlite3_step()] for a particular run
  1.3614 +** or until the next call to
  1.3615 +** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  1.3616 +**
  1.3617 +** ^If sqlite3_malloc() fails during the processing of either routine
  1.3618 +** (for example during a conversion from UTF-8 to UTF-16) then a
  1.3619 +** NULL pointer is returned.
  1.3620 +**
  1.3621 +** ^The name of a result column is the value of the "AS" clause for
  1.3622 +** that column, if there is an AS clause.  If there is no AS clause
  1.3623 +** then the name of the column is unspecified and may change from
  1.3624 +** one release of SQLite to the next.
  1.3625 +*/
  1.3626 +SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  1.3627 +SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  1.3628 +
  1.3629 +/*
  1.3630 +** CAPI3REF: Source Of Data In A Query Result
  1.3631 +**
  1.3632 +** ^These routines provide a means to determine the database, table, and
  1.3633 +** table column that is the origin of a particular result column in
  1.3634 +** [SELECT] statement.
  1.3635 +** ^The name of the database or table or column can be returned as
  1.3636 +** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
  1.3637 +** the database name, the _table_ routines return the table name, and
  1.3638 +** the origin_ routines return the column name.
  1.3639 +** ^The returned string is valid until the [prepared statement] is destroyed
  1.3640 +** using [sqlite3_finalize()] or until the statement is automatically
  1.3641 +** reprepared by the first call to [sqlite3_step()] for a particular run
  1.3642 +** or until the same information is requested
  1.3643 +** again in a different encoding.
  1.3644 +**
  1.3645 +** ^The names returned are the original un-aliased names of the
  1.3646 +** database, table, and column.
  1.3647 +**
  1.3648 +** ^The first argument to these interfaces is a [prepared statement].
  1.3649 +** ^These functions return information about the Nth result column returned by
  1.3650 +** the statement, where N is the second function argument.
  1.3651 +** ^The left-most column is column 0 for these routines.
  1.3652 +**
  1.3653 +** ^If the Nth column returned by the statement is an expression or
  1.3654 +** subquery and is not a column value, then all of these functions return
  1.3655 +** NULL.  ^These routine might also return NULL if a memory allocation error
  1.3656 +** occurs.  ^Otherwise, they return the name of the attached database, table,
  1.3657 +** or column that query result column was extracted from.
  1.3658 +**
  1.3659 +** ^As with all other SQLite APIs, those whose names end with "16" return
  1.3660 +** UTF-16 encoded strings and the other functions return UTF-8.
  1.3661 +**
  1.3662 +** ^These APIs are only available if the library was compiled with the
  1.3663 +** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  1.3664 +**
  1.3665 +** If two or more threads call one or more of these routines against the same
  1.3666 +** prepared statement and column at the same time then the results are
  1.3667 +** undefined.
  1.3668 +**
  1.3669 +** If two or more threads call one or more
  1.3670 +** [sqlite3_column_database_name | column metadata interfaces]
  1.3671 +** for the same [prepared statement] and result column
  1.3672 +** at the same time then the results are undefined.
  1.3673 +*/
  1.3674 +SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  1.3675 +SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  1.3676 +SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  1.3677 +SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  1.3678 +SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  1.3679 +SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  1.3680 +
  1.3681 +/*
  1.3682 +** CAPI3REF: Declared Datatype Of A Query Result
  1.3683 +**
  1.3684 +** ^(The first parameter is a [prepared statement].
  1.3685 +** If this statement is a [SELECT] statement and the Nth column of the
  1.3686 +** returned result set of that [SELECT] is a table column (not an
  1.3687 +** expression or subquery) then the declared type of the table
  1.3688 +** column is returned.)^  ^If the Nth column of the result set is an
  1.3689 +** expression or subquery, then a NULL pointer is returned.
  1.3690 +** ^The returned string is always UTF-8 encoded.
  1.3691 +**
  1.3692 +** ^(For example, given the database schema:
  1.3693 +**
  1.3694 +** CREATE TABLE t1(c1 VARIANT);
  1.3695 +**
  1.3696 +** and the following statement to be compiled:
  1.3697 +**
  1.3698 +** SELECT c1 + 1, c1 FROM t1;
  1.3699 +**
  1.3700 +** this routine would return the string "VARIANT" for the second result
  1.3701 +** column (i==1), and a NULL pointer for the first result column (i==0).)^
  1.3702 +**
  1.3703 +** ^SQLite uses dynamic run-time typing.  ^So just because a column
  1.3704 +** is declared to contain a particular type does not mean that the
  1.3705 +** data stored in that column is of the declared type.  SQLite is
  1.3706 +** strongly typed, but the typing is dynamic not static.  ^Type
  1.3707 +** is associated with individual values, not with the containers
  1.3708 +** used to hold those values.
  1.3709 +*/
  1.3710 +SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  1.3711 +SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  1.3712 +
  1.3713 +/*
  1.3714 +** CAPI3REF: Evaluate An SQL Statement
  1.3715 +**
  1.3716 +** After a [prepared statement] has been prepared using either
  1.3717 +** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  1.3718 +** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  1.3719 +** must be called one or more times to evaluate the statement.
  1.3720 +**
  1.3721 +** The details of the behavior of the sqlite3_step() interface depend
  1.3722 +** on whether the statement was prepared using the newer "v2" interface
  1.3723 +** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  1.3724 +** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
  1.3725 +** new "v2" interface is recommended for new applications but the legacy
  1.3726 +** interface will continue to be supported.
  1.3727 +**
  1.3728 +** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  1.3729 +** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  1.3730 +** ^With the "v2" interface, any of the other [result codes] or
  1.3731 +** [extended result codes] might be returned as well.
  1.3732 +**
  1.3733 +** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  1.3734 +** database locks it needs to do its job.  ^If the statement is a [COMMIT]
  1.3735 +** or occurs outside of an explicit transaction, then you can retry the
  1.3736 +** statement.  If the statement is not a [COMMIT] and occurs within an
  1.3737 +** explicit transaction then you should rollback the transaction before
  1.3738 +** continuing.
  1.3739 +**
  1.3740 +** ^[SQLITE_DONE] means that the statement has finished executing
  1.3741 +** successfully.  sqlite3_step() should not be called again on this virtual
  1.3742 +** machine without first calling [sqlite3_reset()] to reset the virtual
  1.3743 +** machine back to its initial state.
  1.3744 +**
  1.3745 +** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  1.3746 +** is returned each time a new row of data is ready for processing by the
  1.3747 +** caller. The values may be accessed using the [column access functions].
  1.3748 +** sqlite3_step() is called again to retrieve the next row of data.
  1.3749 +**
  1.3750 +** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  1.3751 +** violation) has occurred.  sqlite3_step() should not be called again on
  1.3752 +** the VM. More information may be found by calling [sqlite3_errmsg()].
  1.3753 +** ^With the legacy interface, a more specific error code (for example,
  1.3754 +** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  1.3755 +** can be obtained by calling [sqlite3_reset()] on the
  1.3756 +** [prepared statement].  ^In the "v2" interface,
  1.3757 +** the more specific error code is returned directly by sqlite3_step().
  1.3758 +**
  1.3759 +** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  1.3760 +** Perhaps it was called on a [prepared statement] that has
  1.3761 +** already been [sqlite3_finalize | finalized] or on one that had
  1.3762 +** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
  1.3763 +** be the case that the same database connection is being used by two or
  1.3764 +** more threads at the same moment in time.
  1.3765 +**
  1.3766 +** For all versions of SQLite up to and including 3.6.23.1, a call to
  1.3767 +** [sqlite3_reset()] was required after sqlite3_step() returned anything
  1.3768 +** other than [SQLITE_ROW] before any subsequent invocation of
  1.3769 +** sqlite3_step().  Failure to reset the prepared statement using 
  1.3770 +** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  1.3771 +** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
  1.3772 +** calling [sqlite3_reset()] automatically in this circumstance rather
  1.3773 +** than returning [SQLITE_MISUSE].  This is not considered a compatibility
  1.3774 +** break because any application that ever receives an SQLITE_MISUSE error
  1.3775 +** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
  1.3776 +** can be used to restore the legacy behavior.
  1.3777 +**
  1.3778 +** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  1.3779 +** API always returns a generic error code, [SQLITE_ERROR], following any
  1.3780 +** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
  1.3781 +** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  1.3782 +** specific [error codes] that better describes the error.
  1.3783 +** We admit that this is a goofy design.  The problem has been fixed
  1.3784 +** with the "v2" interface.  If you prepare all of your SQL statements
  1.3785 +** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  1.3786 +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  1.3787 +** then the more specific [error codes] are returned directly
  1.3788 +** by sqlite3_step().  The use of the "v2" interface is recommended.
  1.3789 +*/
  1.3790 +SQLITE_API int sqlite3_step(sqlite3_stmt*);
  1.3791 +
  1.3792 +/*
  1.3793 +** CAPI3REF: Number of columns in a result set
  1.3794 +**
  1.3795 +** ^The sqlite3_data_count(P) interface returns the number of columns in the
  1.3796 +** current row of the result set of [prepared statement] P.
  1.3797 +** ^If prepared statement P does not have results ready to return
  1.3798 +** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  1.3799 +** interfaces) then sqlite3_data_count(P) returns 0.
  1.3800 +** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  1.3801 +** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  1.3802 +** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
  1.3803 +** will return non-zero if previous call to [sqlite3_step](P) returned
  1.3804 +** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  1.3805 +** where it always returns zero since each step of that multi-step
  1.3806 +** pragma returns 0 columns of data.
  1.3807 +**
  1.3808 +** See also: [sqlite3_column_count()]
  1.3809 +*/
  1.3810 +SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  1.3811 +
  1.3812 +/*
  1.3813 +** CAPI3REF: Fundamental Datatypes
  1.3814 +** KEYWORDS: SQLITE_TEXT
  1.3815 +**
  1.3816 +** ^(Every value in SQLite has one of five fundamental datatypes:
  1.3817 +**
  1.3818 +** <ul>
  1.3819 +** <li> 64-bit signed integer
  1.3820 +** <li> 64-bit IEEE floating point number
  1.3821 +** <li> string
  1.3822 +** <li> BLOB
  1.3823 +** <li> NULL
  1.3824 +** </ul>)^
  1.3825 +**
  1.3826 +** These constants are codes for each of those types.
  1.3827 +**
  1.3828 +** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  1.3829 +** for a completely different meaning.  Software that links against both
  1.3830 +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  1.3831 +** SQLITE_TEXT.
  1.3832 +*/
  1.3833 +#define SQLITE_INTEGER  1
  1.3834 +#define SQLITE_FLOAT    2
  1.3835 +#define SQLITE_BLOB     4
  1.3836 +#define SQLITE_NULL     5
  1.3837 +#ifdef SQLITE_TEXT
  1.3838 +# undef SQLITE_TEXT
  1.3839 +#else
  1.3840 +# define SQLITE_TEXT     3
  1.3841 +#endif
  1.3842 +#define SQLITE3_TEXT     3
  1.3843 +
  1.3844 +/*
  1.3845 +** CAPI3REF: Result Values From A Query
  1.3846 +** KEYWORDS: {column access functions}
  1.3847 +**
  1.3848 +** These routines form the "result set" interface.
  1.3849 +**
  1.3850 +** ^These routines return information about a single column of the current
  1.3851 +** result row of a query.  ^In every case the first argument is a pointer
  1.3852 +** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  1.3853 +** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  1.3854 +** and the second argument is the index of the column for which information
  1.3855 +** should be returned. ^The leftmost column of the result set has the index 0.
  1.3856 +** ^The number of columns in the result can be determined using
  1.3857 +** [sqlite3_column_count()].
  1.3858 +**
  1.3859 +** If the SQL statement does not currently point to a valid row, or if the
  1.3860 +** column index is out of range, the result is undefined.
  1.3861 +** These routines may only be called when the most recent call to
  1.3862 +** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  1.3863 +** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  1.3864 +** If any of these routines are called after [sqlite3_reset()] or
  1.3865 +** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  1.3866 +** something other than [SQLITE_ROW], the results are undefined.
  1.3867 +** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  1.3868 +** are called from a different thread while any of these routines
  1.3869 +** are pending, then the results are undefined.
  1.3870 +**
  1.3871 +** ^The sqlite3_column_type() routine returns the
  1.3872 +** [SQLITE_INTEGER | datatype code] for the initial data type
  1.3873 +** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
  1.3874 +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
  1.3875 +** returned by sqlite3_column_type() is only meaningful if no type
  1.3876 +** conversions have occurred as described below.  After a type conversion,
  1.3877 +** the value returned by sqlite3_column_type() is undefined.  Future
  1.3878 +** versions of SQLite may change the behavior of sqlite3_column_type()
  1.3879 +** following a type conversion.
  1.3880 +**
  1.3881 +** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  1.3882 +** routine returns the number of bytes in that BLOB or string.
  1.3883 +** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  1.3884 +** the string to UTF-8 and then returns the number of bytes.
  1.3885 +** ^If the result is a numeric value then sqlite3_column_bytes() uses
  1.3886 +** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  1.3887 +** the number of bytes in that string.
  1.3888 +** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  1.3889 +**
  1.3890 +** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  1.3891 +** routine returns the number of bytes in that BLOB or string.
  1.3892 +** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  1.3893 +** the string to UTF-16 and then returns the number of bytes.
  1.3894 +** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  1.3895 +** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  1.3896 +** the number of bytes in that string.
  1.3897 +** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  1.3898 +**
  1.3899 +** ^The values returned by [sqlite3_column_bytes()] and 
  1.3900 +** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  1.3901 +** of the string.  ^For clarity: the values returned by
  1.3902 +** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  1.3903 +** bytes in the string, not the number of characters.
  1.3904 +**
  1.3905 +** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  1.3906 +** even empty strings, are always zero-terminated.  ^The return
  1.3907 +** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  1.3908 +**
  1.3909 +** ^The object returned by [sqlite3_column_value()] is an
  1.3910 +** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
  1.3911 +** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
  1.3912 +** If the [unprotected sqlite3_value] object returned by
  1.3913 +** [sqlite3_column_value()] is used in any other way, including calls
  1.3914 +** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  1.3915 +** or [sqlite3_value_bytes()], then the behavior is undefined.
  1.3916 +**
  1.3917 +** These routines attempt to convert the value where appropriate.  ^For
  1.3918 +** example, if the internal representation is FLOAT and a text result
  1.3919 +** is requested, [sqlite3_snprintf()] is used internally to perform the
  1.3920 +** conversion automatically.  ^(The following table details the conversions
  1.3921 +** that are applied:
  1.3922 +**
  1.3923 +** <blockquote>
  1.3924 +** <table border="1">
  1.3925 +** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
  1.3926 +**
  1.3927 +** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
  1.3928 +** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
  1.3929 +** <tr><td>  NULL    <td>   TEXT    <td> Result is a NULL pointer
  1.3930 +** <tr><td>  NULL    <td>   BLOB    <td> Result is a NULL pointer
  1.3931 +** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
  1.3932 +** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
  1.3933 +** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
  1.3934 +** <tr><td>  FLOAT   <td> INTEGER   <td> [CAST] to INTEGER
  1.3935 +** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
  1.3936 +** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB
  1.3937 +** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER
  1.3938 +** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL
  1.3939 +** <tr><td>  TEXT    <td>   BLOB    <td> No change
  1.3940 +** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
  1.3941 +** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
  1.3942 +** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
  1.3943 +** </table>
  1.3944 +** </blockquote>)^
  1.3945 +**
  1.3946 +** The table above makes reference to standard C library functions atoi()
  1.3947 +** and atof().  SQLite does not really use these functions.  It has its
  1.3948 +** own equivalent internal routines.  The atoi() and atof() names are
  1.3949 +** used in the table for brevity and because they are familiar to most
  1.3950 +** C programmers.
  1.3951 +**
  1.3952 +** Note that when type conversions occur, pointers returned by prior
  1.3953 +** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  1.3954 +** sqlite3_column_text16() may be invalidated.
  1.3955 +** Type conversions and pointer invalidations might occur
  1.3956 +** in the following cases:
  1.3957 +**
  1.3958 +** <ul>
  1.3959 +** <li> The initial content is a BLOB and sqlite3_column_text() or
  1.3960 +**      sqlite3_column_text16() is called.  A zero-terminator might
  1.3961 +**      need to be added to the string.</li>
  1.3962 +** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  1.3963 +**      sqlite3_column_text16() is called.  The content must be converted
  1.3964 +**      to UTF-16.</li>
  1.3965 +** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  1.3966 +**      sqlite3_column_text() is called.  The content must be converted
  1.3967 +**      to UTF-8.</li>
  1.3968 +** </ul>
  1.3969 +**
  1.3970 +** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  1.3971 +** not invalidate a prior pointer, though of course the content of the buffer
  1.3972 +** that the prior pointer references will have been modified.  Other kinds
  1.3973 +** of conversion are done in place when it is possible, but sometimes they
  1.3974 +** are not possible and in those cases prior pointers are invalidated.
  1.3975 +**
  1.3976 +** The safest and easiest to remember policy is to invoke these routines
  1.3977 +** in one of the following ways:
  1.3978 +**
  1.3979 +** <ul>
  1.3980 +**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  1.3981 +**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  1.3982 +**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  1.3983 +** </ul>
  1.3984 +**
  1.3985 +** In other words, you should call sqlite3_column_text(),
  1.3986 +** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  1.3987 +** into the desired format, then invoke sqlite3_column_bytes() or
  1.3988 +** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
  1.3989 +** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  1.3990 +** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  1.3991 +** with calls to sqlite3_column_bytes().
  1.3992 +**
  1.3993 +** ^The pointers returned are valid until a type conversion occurs as
  1.3994 +** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  1.3995 +** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
  1.3996 +** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
  1.3997 +** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  1.3998 +** [sqlite3_free()].
  1.3999 +**
  1.4000 +** ^(If a memory allocation error occurs during the evaluation of any
  1.4001 +** of these routines, a default value is returned.  The default value
  1.4002 +** is either the integer 0, the floating point number 0.0, or a NULL
  1.4003 +** pointer.  Subsequent calls to [sqlite3_errcode()] will return
  1.4004 +** [SQLITE_NOMEM].)^
  1.4005 +*/
  1.4006 +SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  1.4007 +SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  1.4008 +SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  1.4009 +SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  1.4010 +SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  1.4011 +SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  1.4012 +SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  1.4013 +SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  1.4014 +SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  1.4015 +SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  1.4016 +
  1.4017 +/*
  1.4018 +** CAPI3REF: Destroy A Prepared Statement Object
  1.4019 +**
  1.4020 +** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  1.4021 +** ^If the most recent evaluation of the statement encountered no errors
  1.4022 +** or if the statement is never been evaluated, then sqlite3_finalize() returns
  1.4023 +** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
  1.4024 +** sqlite3_finalize(S) returns the appropriate [error code] or
  1.4025 +** [extended error code].
  1.4026 +**
  1.4027 +** ^The sqlite3_finalize(S) routine can be called at any point during
  1.4028 +** the life cycle of [prepared statement] S:
  1.4029 +** before statement S is ever evaluated, after
  1.4030 +** one or more calls to [sqlite3_reset()], or after any call
  1.4031 +** to [sqlite3_step()] regardless of whether or not the statement has
  1.4032 +** completed execution.
  1.4033 +**
  1.4034 +** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  1.4035 +**
  1.4036 +** The application must finalize every [prepared statement] in order to avoid
  1.4037 +** resource leaks.  It is a grievous error for the application to try to use
  1.4038 +** a prepared statement after it has been finalized.  Any use of a prepared
  1.4039 +** statement after it has been finalized can result in undefined and
  1.4040 +** undesirable behavior such as segfaults and heap corruption.
  1.4041 +*/
  1.4042 +SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  1.4043 +
  1.4044 +/*
  1.4045 +** CAPI3REF: Reset A Prepared Statement Object
  1.4046 +**
  1.4047 +** The sqlite3_reset() function is called to reset a [prepared statement]
  1.4048 +** object back to its initial state, ready to be re-executed.
  1.4049 +** ^Any SQL statement variables that had values bound to them using
  1.4050 +** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  1.4051 +** Use [sqlite3_clear_bindings()] to reset the bindings.
  1.4052 +**
  1.4053 +** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  1.4054 +** back to the beginning of its program.
  1.4055 +**
  1.4056 +** ^If the most recent call to [sqlite3_step(S)] for the
  1.4057 +** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  1.4058 +** or if [sqlite3_step(S)] has never before been called on S,
  1.4059 +** then [sqlite3_reset(S)] returns [SQLITE_OK].
  1.4060 +**
  1.4061 +** ^If the most recent call to [sqlite3_step(S)] for the
  1.4062 +** [prepared statement] S indicated an error, then
  1.4063 +** [sqlite3_reset(S)] returns an appropriate [error code].
  1.4064 +**
  1.4065 +** ^The [sqlite3_reset(S)] interface does not change the values
  1.4066 +** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  1.4067 +*/
  1.4068 +SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  1.4069 +
  1.4070 +/*
  1.4071 +** CAPI3REF: Create Or Redefine SQL Functions
  1.4072 +** KEYWORDS: {function creation routines}
  1.4073 +** KEYWORDS: {application-defined SQL function}
  1.4074 +** KEYWORDS: {application-defined SQL functions}
  1.4075 +**
  1.4076 +** ^These functions (collectively known as "function creation routines")
  1.4077 +** are used to add SQL functions or aggregates or to redefine the behavior
  1.4078 +** of existing SQL functions or aggregates.  The only differences between
  1.4079 +** these routines are the text encoding expected for
  1.4080 +** the second parameter (the name of the function being created)
  1.4081 +** and the presence or absence of a destructor callback for
  1.4082 +** the application data pointer.
  1.4083 +**
  1.4084 +** ^The first parameter is the [database connection] to which the SQL
  1.4085 +** function is to be added.  ^If an application uses more than one database
  1.4086 +** connection then application-defined SQL functions must be added
  1.4087 +** to each database connection separately.
  1.4088 +**
  1.4089 +** ^The second parameter is the name of the SQL function to be created or
  1.4090 +** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
  1.4091 +** representation, exclusive of the zero-terminator.  ^Note that the name
  1.4092 +** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
  1.4093 +** ^Any attempt to create a function with a longer name
  1.4094 +** will result in [SQLITE_MISUSE] being returned.
  1.4095 +**
  1.4096 +** ^The third parameter (nArg)
  1.4097 +** is the number of arguments that the SQL function or
  1.4098 +** aggregate takes. ^If this parameter is -1, then the SQL function or
  1.4099 +** aggregate may take any number of arguments between 0 and the limit
  1.4100 +** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
  1.4101 +** parameter is less than -1 or greater than 127 then the behavior is
  1.4102 +** undefined.
  1.4103 +**
  1.4104 +** ^The fourth parameter, eTextRep, specifies what
  1.4105 +** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  1.4106 +** its parameters.  The application should set this parameter to
  1.4107 +** [SQLITE_UTF16LE] if the function implementation invokes 
  1.4108 +** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
  1.4109 +** implementation invokes [sqlite3_value_text16be()] on an input, or
  1.4110 +** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
  1.4111 +** otherwise.  ^The same SQL function may be registered multiple times using
  1.4112 +** different preferred text encodings, with different implementations for
  1.4113 +** each encoding.
  1.4114 +** ^When multiple implementations of the same function are available, SQLite
  1.4115 +** will pick the one that involves the least amount of data conversion.
  1.4116 +**
  1.4117 +** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
  1.4118 +** to signal that the function will always return the same result given
  1.4119 +** the same inputs within a single SQL statement.  Most SQL functions are
  1.4120 +** deterministic.  The built-in [random()] SQL function is an example of a
  1.4121 +** function that is not deterministic.  The SQLite query planner is able to
  1.4122 +** perform additional optimizations on deterministic functions, so use
  1.4123 +** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
  1.4124 +**
  1.4125 +** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
  1.4126 +** function can gain access to this pointer using [sqlite3_user_data()].)^
  1.4127 +**
  1.4128 +** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  1.4129 +** pointers to C-language functions that implement the SQL function or
  1.4130 +** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  1.4131 +** callback only; NULL pointers must be passed as the xStep and xFinal
  1.4132 +** parameters. ^An aggregate SQL function requires an implementation of xStep
  1.4133 +** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  1.4134 +** SQL function or aggregate, pass NULL pointers for all three function
  1.4135 +** callbacks.
  1.4136 +**
  1.4137 +** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  1.4138 +** then it is destructor for the application data pointer. 
  1.4139 +** The destructor is invoked when the function is deleted, either by being
  1.4140 +** overloaded or when the database connection closes.)^
  1.4141 +** ^The destructor is also invoked if the call to
  1.4142 +** sqlite3_create_function_v2() fails.
  1.4143 +** ^When the destructor callback of the tenth parameter is invoked, it
  1.4144 +** is passed a single argument which is a copy of the application data 
  1.4145 +** pointer which was the fifth parameter to sqlite3_create_function_v2().
  1.4146 +**
  1.4147 +** ^It is permitted to register multiple implementations of the same
  1.4148 +** functions with the same name but with either differing numbers of
  1.4149 +** arguments or differing preferred text encodings.  ^SQLite will use
  1.4150 +** the implementation that most closely matches the way in which the
  1.4151 +** SQL function is used.  ^A function implementation with a non-negative
  1.4152 +** nArg parameter is a better match than a function implementation with
  1.4153 +** a negative nArg.  ^A function where the preferred text encoding
  1.4154 +** matches the database encoding is a better
  1.4155 +** match than a function where the encoding is different.  
  1.4156 +** ^A function where the encoding difference is between UTF16le and UTF16be
  1.4157 +** is a closer match than a function where the encoding difference is
  1.4158 +** between UTF8 and UTF16.
  1.4159 +**
  1.4160 +** ^Built-in functions may be overloaded by new application-defined functions.
  1.4161 +**
  1.4162 +** ^An application-defined function is permitted to call other
  1.4163 +** SQLite interfaces.  However, such calls must not
  1.4164 +** close the database connection nor finalize or reset the prepared
  1.4165 +** statement in which the function is running.
  1.4166 +*/
  1.4167 +SQLITE_API int sqlite3_create_function(
  1.4168 +  sqlite3 *db,
  1.4169 +  const char *zFunctionName,
  1.4170 +  int nArg,
  1.4171 +  int eTextRep,
  1.4172 +  void *pApp,
  1.4173 +  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  1.4174 +  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  1.4175 +  void (*xFinal)(sqlite3_context*)
  1.4176 +);
  1.4177 +SQLITE_API int sqlite3_create_function16(
  1.4178 +  sqlite3 *db,
  1.4179 +  const void *zFunctionName,
  1.4180 +  int nArg,
  1.4181 +  int eTextRep,
  1.4182 +  void *pApp,
  1.4183 +  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  1.4184 +  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  1.4185 +  void (*xFinal)(sqlite3_context*)
  1.4186 +);
  1.4187 +SQLITE_API int sqlite3_create_function_v2(
  1.4188 +  sqlite3 *db,
  1.4189 +  const char *zFunctionName,
  1.4190 +  int nArg,
  1.4191 +  int eTextRep,
  1.4192 +  void *pApp,
  1.4193 +  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  1.4194 +  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  1.4195 +  void (*xFinal)(sqlite3_context*),
  1.4196 +  void(*xDestroy)(void*)
  1.4197 +);
  1.4198 +
  1.4199 +/*
  1.4200 +** CAPI3REF: Text Encodings
  1.4201 +**
  1.4202 +** These constant define integer codes that represent the various
  1.4203 +** text encodings supported by SQLite.
  1.4204 +*/
  1.4205 +#define SQLITE_UTF8           1
  1.4206 +#define SQLITE_UTF16LE        2
  1.4207 +#define SQLITE_UTF16BE        3
  1.4208 +#define SQLITE_UTF16          4    /* Use native byte order */
  1.4209 +#define SQLITE_ANY            5    /* Deprecated */
  1.4210 +#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
  1.4211 +
  1.4212 +/*
  1.4213 +** CAPI3REF: Function Flags
  1.4214 +**
  1.4215 +** These constants may be ORed together with the 
  1.4216 +** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
  1.4217 +** to [sqlite3_create_function()], [sqlite3_create_function16()], or
  1.4218 +** [sqlite3_create_function_v2()].
  1.4219 +*/
  1.4220 +#define SQLITE_DETERMINISTIC    0x800
  1.4221 +
  1.4222 +/*
  1.4223 +** CAPI3REF: Deprecated Functions
  1.4224 +** DEPRECATED
  1.4225 +**
  1.4226 +** These functions are [deprecated].  In order to maintain
  1.4227 +** backwards compatibility with older code, these functions continue 
  1.4228 +** to be supported.  However, new applications should avoid
  1.4229 +** the use of these functions.  To help encourage people to avoid
  1.4230 +** using these functions, we are not going to tell you what they do.
  1.4231 +*/
  1.4232 +#ifndef SQLITE_OMIT_DEPRECATED
  1.4233 +SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  1.4234 +SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  1.4235 +SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  1.4236 +SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  1.4237 +SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  1.4238 +SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  1.4239 +                      void*,sqlite3_int64);
  1.4240 +#endif
  1.4241 +
  1.4242 +/*
  1.4243 +** CAPI3REF: Obtaining SQL Function Parameter Values
  1.4244 +**
  1.4245 +** The C-language implementation of SQL functions and aggregates uses
  1.4246 +** this set of interface routines to access the parameter values on
  1.4247 +** the function or aggregate.
  1.4248 +**
  1.4249 +** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  1.4250 +** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  1.4251 +** define callbacks that implement the SQL functions and aggregates.
  1.4252 +** The 3rd parameter to these callbacks is an array of pointers to
  1.4253 +** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
  1.4254 +** each parameter to the SQL function.  These routines are used to
  1.4255 +** extract values from the [sqlite3_value] objects.
  1.4256 +**
  1.4257 +** These routines work only with [protected sqlite3_value] objects.
  1.4258 +** Any attempt to use these routines on an [unprotected sqlite3_value]
  1.4259 +** object results in undefined behavior.
  1.4260 +**
  1.4261 +** ^These routines work just like the corresponding [column access functions]
  1.4262 +** except that  these routines take a single [protected sqlite3_value] object
  1.4263 +** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  1.4264 +**
  1.4265 +** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  1.4266 +** in the native byte-order of the host machine.  ^The
  1.4267 +** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  1.4268 +** extract UTF-16 strings as big-endian and little-endian respectively.
  1.4269 +**
  1.4270 +** ^(The sqlite3_value_numeric_type() interface attempts to apply
  1.4271 +** numeric affinity to the value.  This means that an attempt is
  1.4272 +** made to convert the value to an integer or floating point.  If
  1.4273 +** such a conversion is possible without loss of information (in other
  1.4274 +** words, if the value is a string that looks like a number)
  1.4275 +** then the conversion is performed.  Otherwise no conversion occurs.
  1.4276 +** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  1.4277 +**
  1.4278 +** Please pay particular attention to the fact that the pointer returned
  1.4279 +** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  1.4280 +** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  1.4281 +** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  1.4282 +** or [sqlite3_value_text16()].
  1.4283 +**
  1.4284 +** These routines must be called from the same thread as
  1.4285 +** the SQL function that supplied the [sqlite3_value*] parameters.
  1.4286 +*/
  1.4287 +SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  1.4288 +SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  1.4289 +SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  1.4290 +SQLITE_API double sqlite3_value_double(sqlite3_value*);
  1.4291 +SQLITE_API int sqlite3_value_int(sqlite3_value*);
  1.4292 +SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  1.4293 +SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  1.4294 +SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  1.4295 +SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  1.4296 +SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  1.4297 +SQLITE_API int sqlite3_value_type(sqlite3_value*);
  1.4298 +SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  1.4299 +
  1.4300 +/*
  1.4301 +** CAPI3REF: Obtain Aggregate Function Context
  1.4302 +**
  1.4303 +** Implementations of aggregate SQL functions use this
  1.4304 +** routine to allocate memory for storing their state.
  1.4305 +**
  1.4306 +** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
  1.4307 +** for a particular aggregate function, SQLite
  1.4308 +** allocates N of memory, zeroes out that memory, and returns a pointer
  1.4309 +** to the new memory. ^On second and subsequent calls to
  1.4310 +** sqlite3_aggregate_context() for the same aggregate function instance,
  1.4311 +** the same buffer is returned.  Sqlite3_aggregate_context() is normally
  1.4312 +** called once for each invocation of the xStep callback and then one
  1.4313 +** last time when the xFinal callback is invoked.  ^(When no rows match
  1.4314 +** an aggregate query, the xStep() callback of the aggregate function
  1.4315 +** implementation is never called and xFinal() is called exactly once.
  1.4316 +** In those cases, sqlite3_aggregate_context() might be called for the
  1.4317 +** first time from within xFinal().)^
  1.4318 +**
  1.4319 +** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer 
  1.4320 +** when first called if N is less than or equal to zero or if a memory
  1.4321 +** allocate error occurs.
  1.4322 +**
  1.4323 +** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  1.4324 +** determined by the N parameter on first successful call.  Changing the
  1.4325 +** value of N in subsequent call to sqlite3_aggregate_context() within
  1.4326 +** the same aggregate function instance will not resize the memory
  1.4327 +** allocation.)^  Within the xFinal callback, it is customary to set
  1.4328 +** N=0 in calls to sqlite3_aggregate_context(C,N) so that no 
  1.4329 +** pointless memory allocations occur.
  1.4330 +**
  1.4331 +** ^SQLite automatically frees the memory allocated by 
  1.4332 +** sqlite3_aggregate_context() when the aggregate query concludes.
  1.4333 +**
  1.4334 +** The first parameter must be a copy of the
  1.4335 +** [sqlite3_context | SQL function context] that is the first parameter
  1.4336 +** to the xStep or xFinal callback routine that implements the aggregate
  1.4337 +** function.
  1.4338 +**
  1.4339 +** This routine must be called from the same thread in which
  1.4340 +** the aggregate SQL function is running.
  1.4341 +*/
  1.4342 +SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  1.4343 +
  1.4344 +/*
  1.4345 +** CAPI3REF: User Data For Functions
  1.4346 +**
  1.4347 +** ^The sqlite3_user_data() interface returns a copy of
  1.4348 +** the pointer that was the pUserData parameter (the 5th parameter)
  1.4349 +** of the [sqlite3_create_function()]
  1.4350 +** and [sqlite3_create_function16()] routines that originally
  1.4351 +** registered the application defined function.
  1.4352 +**
  1.4353 +** This routine must be called from the same thread in which
  1.4354 +** the application-defined function is running.
  1.4355 +*/
  1.4356 +SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  1.4357 +
  1.4358 +/*
  1.4359 +** CAPI3REF: Database Connection For Functions
  1.4360 +**
  1.4361 +** ^The sqlite3_context_db_handle() interface returns a copy of
  1.4362 +** the pointer to the [database connection] (the 1st parameter)
  1.4363 +** of the [sqlite3_create_function()]
  1.4364 +** and [sqlite3_create_function16()] routines that originally
  1.4365 +** registered the application defined function.
  1.4366 +*/
  1.4367 +SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  1.4368 +
  1.4369 +/*
  1.4370 +** CAPI3REF: Function Auxiliary Data
  1.4371 +**
  1.4372 +** These functions may be used by (non-aggregate) SQL functions to
  1.4373 +** associate metadata with argument values. If the same value is passed to
  1.4374 +** multiple invocations of the same SQL function during query execution, under
  1.4375 +** some circumstances the associated metadata may be preserved.  An example
  1.4376 +** of where this might be useful is in a regular-expression matching
  1.4377 +** function. The compiled version of the regular expression can be stored as
  1.4378 +** metadata associated with the pattern string.  
  1.4379 +** Then as long as the pattern string remains the same,
  1.4380 +** the compiled regular expression can be reused on multiple
  1.4381 +** invocations of the same function.
  1.4382 +**
  1.4383 +** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
  1.4384 +** associated by the sqlite3_set_auxdata() function with the Nth argument
  1.4385 +** value to the application-defined function. ^If there is no metadata
  1.4386 +** associated with the function argument, this sqlite3_get_auxdata() interface
  1.4387 +** returns a NULL pointer.
  1.4388 +**
  1.4389 +** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  1.4390 +** argument of the application-defined function.  ^Subsequent
  1.4391 +** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  1.4392 +** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  1.4393 +** NULL if the metadata has been discarded.
  1.4394 +** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  1.4395 +** SQLite will invoke the destructor function X with parameter P exactly
  1.4396 +** once, when the metadata is discarded.
  1.4397 +** SQLite is free to discard the metadata at any time, including: <ul>
  1.4398 +** <li> when the corresponding function parameter changes, or
  1.4399 +** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  1.4400 +**      SQL statement, or
  1.4401 +** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
  1.4402 +** <li> during the original sqlite3_set_auxdata() call when a memory 
  1.4403 +**      allocation error occurs. </ul>)^
  1.4404 +**
  1.4405 +** Note the last bullet in particular.  The destructor X in 
  1.4406 +** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  1.4407 +** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
  1.4408 +** should be called near the end of the function implementation and the
  1.4409 +** function implementation should not make any use of P after
  1.4410 +** sqlite3_set_auxdata() has been called.
  1.4411 +**
  1.4412 +** ^(In practice, metadata is preserved between function calls for
  1.4413 +** function parameters that are compile-time constants, including literal
  1.4414 +** values and [parameters] and expressions composed from the same.)^
  1.4415 +**
  1.4416 +** These routines must be called from the same thread in which
  1.4417 +** the SQL function is running.
  1.4418 +*/
  1.4419 +SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  1.4420 +SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  1.4421 +
  1.4422 +
  1.4423 +/*
  1.4424 +** CAPI3REF: Constants Defining Special Destructor Behavior
  1.4425 +**
  1.4426 +** These are special values for the destructor that is passed in as the
  1.4427 +** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
  1.4428 +** argument is SQLITE_STATIC, it means that the content pointer is constant
  1.4429 +** and will never change.  It does not need to be destroyed.  ^The
  1.4430 +** SQLITE_TRANSIENT value means that the content will likely change in
  1.4431 +** the near future and that SQLite should make its own private copy of
  1.4432 +** the content before returning.
  1.4433 +**
  1.4434 +** The typedef is necessary to work around problems in certain
  1.4435 +** C++ compilers.
  1.4436 +*/
  1.4437 +typedef void (*sqlite3_destructor_type)(void*);
  1.4438 +#define SQLITE_STATIC      ((sqlite3_destructor_type)0)
  1.4439 +#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
  1.4440 +
  1.4441 +/*
  1.4442 +** CAPI3REF: Setting The Result Of An SQL Function
  1.4443 +**
  1.4444 +** These routines are used by the xFunc or xFinal callbacks that
  1.4445 +** implement SQL functions and aggregates.  See
  1.4446 +** [sqlite3_create_function()] and [sqlite3_create_function16()]
  1.4447 +** for additional information.
  1.4448 +**
  1.4449 +** These functions work very much like the [parameter binding] family of
  1.4450 +** functions used to bind values to host parameters in prepared statements.
  1.4451 +** Refer to the [SQL parameter] documentation for additional information.
  1.4452 +**
  1.4453 +** ^The sqlite3_result_blob() interface sets the result from
  1.4454 +** an application-defined function to be the BLOB whose content is pointed
  1.4455 +** to by the second parameter and which is N bytes long where N is the
  1.4456 +** third parameter.
  1.4457 +**
  1.4458 +** ^The sqlite3_result_zeroblob() interfaces set the result of
  1.4459 +** the application-defined function to be a BLOB containing all zero
  1.4460 +** bytes and N bytes in size, where N is the value of the 2nd parameter.
  1.4461 +**
  1.4462 +** ^The sqlite3_result_double() interface sets the result from
  1.4463 +** an application-defined function to be a floating point value specified
  1.4464 +** by its 2nd argument.
  1.4465 +**
  1.4466 +** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  1.4467 +** cause the implemented SQL function to throw an exception.
  1.4468 +** ^SQLite uses the string pointed to by the
  1.4469 +** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  1.4470 +** as the text of an error message.  ^SQLite interprets the error
  1.4471 +** message string from sqlite3_result_error() as UTF-8. ^SQLite
  1.4472 +** interprets the string from sqlite3_result_error16() as UTF-16 in native
  1.4473 +** byte order.  ^If the third parameter to sqlite3_result_error()
  1.4474 +** or sqlite3_result_error16() is negative then SQLite takes as the error
  1.4475 +** message all text up through the first zero character.
  1.4476 +** ^If the third parameter to sqlite3_result_error() or
  1.4477 +** sqlite3_result_error16() is non-negative then SQLite takes that many
  1.4478 +** bytes (not characters) from the 2nd parameter as the error message.
  1.4479 +** ^The sqlite3_result_error() and sqlite3_result_error16()
  1.4480 +** routines make a private copy of the error message text before
  1.4481 +** they return.  Hence, the calling function can deallocate or
  1.4482 +** modify the text after they return without harm.
  1.4483 +** ^The sqlite3_result_error_code() function changes the error code
  1.4484 +** returned by SQLite as a result of an error in a function.  ^By default,
  1.4485 +** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
  1.4486 +** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  1.4487 +**
  1.4488 +** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  1.4489 +** error indicating that a string or BLOB is too long to represent.
  1.4490 +**
  1.4491 +** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  1.4492 +** error indicating that a memory allocation failed.
  1.4493 +**
  1.4494 +** ^The sqlite3_result_int() interface sets the return value
  1.4495 +** of the application-defined function to be the 32-bit signed integer
  1.4496 +** value given in the 2nd argument.
  1.4497 +** ^The sqlite3_result_int64() interface sets the return value
  1.4498 +** of the application-defined function to be the 64-bit signed integer
  1.4499 +** value given in the 2nd argument.
  1.4500 +**
  1.4501 +** ^The sqlite3_result_null() interface sets the return value
  1.4502 +** of the application-defined function to be NULL.
  1.4503 +**
  1.4504 +** ^The sqlite3_result_text(), sqlite3_result_text16(),
  1.4505 +** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  1.4506 +** set the return value of the application-defined function to be
  1.4507 +** a text string which is represented as UTF-8, UTF-16 native byte order,
  1.4508 +** UTF-16 little endian, or UTF-16 big endian, respectively.
  1.4509 +** ^SQLite takes the text result from the application from
  1.4510 +** the 2nd parameter of the sqlite3_result_text* interfaces.
  1.4511 +** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  1.4512 +** is negative, then SQLite takes result text from the 2nd parameter
  1.4513 +** through the first zero character.
  1.4514 +** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  1.4515 +** is non-negative, then as many bytes (not characters) of the text
  1.4516 +** pointed to by the 2nd parameter are taken as the application-defined
  1.4517 +** function result.  If the 3rd parameter is non-negative, then it
  1.4518 +** must be the byte offset into the string where the NUL terminator would
  1.4519 +** appear if the string where NUL terminated.  If any NUL characters occur
  1.4520 +** in the string at a byte offset that is less than the value of the 3rd
  1.4521 +** parameter, then the resulting string will contain embedded NULs and the
  1.4522 +** result of expressions operating on strings with embedded NULs is undefined.
  1.4523 +** ^If the 4th parameter to the sqlite3_result_text* interfaces
  1.4524 +** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  1.4525 +** function as the destructor on the text or BLOB result when it has
  1.4526 +** finished using that result.
  1.4527 +** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  1.4528 +** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  1.4529 +** assumes that the text or BLOB result is in constant space and does not
  1.4530 +** copy the content of the parameter nor call a destructor on the content
  1.4531 +** when it has finished using that result.
  1.4532 +** ^If the 4th parameter to the sqlite3_result_text* interfaces
  1.4533 +** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  1.4534 +** then SQLite makes a copy of the result into space obtained from
  1.4535 +** from [sqlite3_malloc()] before it returns.
  1.4536 +**
  1.4537 +** ^The sqlite3_result_value() interface sets the result of
  1.4538 +** the application-defined function to be a copy the
  1.4539 +** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
  1.4540 +** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  1.4541 +** so that the [sqlite3_value] specified in the parameter may change or
  1.4542 +** be deallocated after sqlite3_result_value() returns without harm.
  1.4543 +** ^A [protected sqlite3_value] object may always be used where an
  1.4544 +** [unprotected sqlite3_value] object is required, so either
  1.4545 +** kind of [sqlite3_value] object can be used with this interface.
  1.4546 +**
  1.4547 +** If these routines are called from within the different thread
  1.4548 +** than the one containing the application-defined function that received
  1.4549 +** the [sqlite3_context] pointer, the results are undefined.
  1.4550 +*/
  1.4551 +SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  1.4552 +SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  1.4553 +SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  1.4554 +SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  1.4555 +SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  1.4556 +SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  1.4557 +SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  1.4558 +SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  1.4559 +SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  1.4560 +SQLITE_API void sqlite3_result_null(sqlite3_context*);
  1.4561 +SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  1.4562 +SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  1.4563 +SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  1.4564 +SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  1.4565 +SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  1.4566 +SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  1.4567 +
  1.4568 +/*
  1.4569 +** CAPI3REF: Define New Collating Sequences
  1.4570 +**
  1.4571 +** ^These functions add, remove, or modify a [collation] associated
  1.4572 +** with the [database connection] specified as the first argument.
  1.4573 +**
  1.4574 +** ^The name of the collation is a UTF-8 string
  1.4575 +** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  1.4576 +** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  1.4577 +** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  1.4578 +** considered to be the same name.
  1.4579 +**
  1.4580 +** ^(The third argument (eTextRep) must be one of the constants:
  1.4581 +** <ul>
  1.4582 +** <li> [SQLITE_UTF8],
  1.4583 +** <li> [SQLITE_UTF16LE],
  1.4584 +** <li> [SQLITE_UTF16BE],
  1.4585 +** <li> [SQLITE_UTF16], or
  1.4586 +** <li> [SQLITE_UTF16_ALIGNED].
  1.4587 +** </ul>)^
  1.4588 +** ^The eTextRep argument determines the encoding of strings passed
  1.4589 +** to the collating function callback, xCallback.
  1.4590 +** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  1.4591 +** force strings to be UTF16 with native byte order.
  1.4592 +** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  1.4593 +** on an even byte address.
  1.4594 +**
  1.4595 +** ^The fourth argument, pArg, is an application data pointer that is passed
  1.4596 +** through as the first argument to the collating function callback.
  1.4597 +**
  1.4598 +** ^The fifth argument, xCallback, is a pointer to the collating function.
  1.4599 +** ^Multiple collating functions can be registered using the same name but
  1.4600 +** with different eTextRep parameters and SQLite will use whichever
  1.4601 +** function requires the least amount of data transformation.
  1.4602 +** ^If the xCallback argument is NULL then the collating function is
  1.4603 +** deleted.  ^When all collating functions having the same name are deleted,
  1.4604 +** that collation is no longer usable.
  1.4605 +**
  1.4606 +** ^The collating function callback is invoked with a copy of the pArg 
  1.4607 +** application data pointer and with two strings in the encoding specified
  1.4608 +** by the eTextRep argument.  The collating function must return an
  1.4609 +** integer that is negative, zero, or positive
  1.4610 +** if the first string is less than, equal to, or greater than the second,
  1.4611 +** respectively.  A collating function must always return the same answer
  1.4612 +** given the same inputs.  If two or more collating functions are registered
  1.4613 +** to the same collation name (using different eTextRep values) then all
  1.4614 +** must give an equivalent answer when invoked with equivalent strings.
  1.4615 +** The collating function must obey the following properties for all
  1.4616 +** strings A, B, and C:
  1.4617 +**
  1.4618 +** <ol>
  1.4619 +** <li> If A==B then B==A.
  1.4620 +** <li> If A==B and B==C then A==C.
  1.4621 +** <li> If A&lt;B THEN B&gt;A.
  1.4622 +** <li> If A&lt;B and B&lt;C then A&lt;C.
  1.4623 +** </ol>
  1.4624 +**
  1.4625 +** If a collating function fails any of the above constraints and that
  1.4626 +** collating function is  registered and used, then the behavior of SQLite
  1.4627 +** is undefined.
  1.4628 +**
  1.4629 +** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  1.4630 +** with the addition that the xDestroy callback is invoked on pArg when
  1.4631 +** the collating function is deleted.
  1.4632 +** ^Collating functions are deleted when they are overridden by later
  1.4633 +** calls to the collation creation functions or when the
  1.4634 +** [database connection] is closed using [sqlite3_close()].
  1.4635 +**
  1.4636 +** ^The xDestroy callback is <u>not</u> called if the 
  1.4637 +** sqlite3_create_collation_v2() function fails.  Applications that invoke
  1.4638 +** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should 
  1.4639 +** check the return code and dispose of the application data pointer
  1.4640 +** themselves rather than expecting SQLite to deal with it for them.
  1.4641 +** This is different from every other SQLite interface.  The inconsistency 
  1.4642 +** is unfortunate but cannot be changed without breaking backwards 
  1.4643 +** compatibility.
  1.4644 +**
  1.4645 +** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  1.4646 +*/
  1.4647 +SQLITE_API int sqlite3_create_collation(
  1.4648 +  sqlite3*, 
  1.4649 +  const char *zName, 
  1.4650 +  int eTextRep, 
  1.4651 +  void *pArg,
  1.4652 +  int(*xCompare)(void*,int,const void*,int,const void*)
  1.4653 +);
  1.4654 +SQLITE_API int sqlite3_create_collation_v2(
  1.4655 +  sqlite3*, 
  1.4656 +  const char *zName, 
  1.4657 +  int eTextRep, 
  1.4658 +  void *pArg,
  1.4659 +  int(*xCompare)(void*,int,const void*,int,const void*),
  1.4660 +  void(*xDestroy)(void*)
  1.4661 +);
  1.4662 +SQLITE_API int sqlite3_create_collation16(
  1.4663 +  sqlite3*, 
  1.4664 +  const void *zName,
  1.4665 +  int eTextRep, 
  1.4666 +  void *pArg,
  1.4667 +  int(*xCompare)(void*,int,const void*,int,const void*)
  1.4668 +);
  1.4669 +
  1.4670 +/*
  1.4671 +** CAPI3REF: Collation Needed Callbacks
  1.4672 +**
  1.4673 +** ^To avoid having to register all collation sequences before a database
  1.4674 +** can be used, a single callback function may be registered with the
  1.4675 +** [database connection] to be invoked whenever an undefined collation
  1.4676 +** sequence is required.
  1.4677 +**
  1.4678 +** ^If the function is registered using the sqlite3_collation_needed() API,
  1.4679 +** then it is passed the names of undefined collation sequences as strings
  1.4680 +** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  1.4681 +** the names are passed as UTF-16 in machine native byte order.
  1.4682 +** ^A call to either function replaces the existing collation-needed callback.
  1.4683 +**
  1.4684 +** ^(When the callback is invoked, the first argument passed is a copy
  1.4685 +** of the second argument to sqlite3_collation_needed() or
  1.4686 +** sqlite3_collation_needed16().  The second argument is the database
  1.4687 +** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  1.4688 +** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  1.4689 +** sequence function required.  The fourth parameter is the name of the
  1.4690 +** required collation sequence.)^
  1.4691 +**
  1.4692 +** The callback function should register the desired collation using
  1.4693 +** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  1.4694 +** [sqlite3_create_collation_v2()].
  1.4695 +*/
  1.4696 +SQLITE_API int sqlite3_collation_needed(
  1.4697 +  sqlite3*, 
  1.4698 +  void*, 
  1.4699 +  void(*)(void*,sqlite3*,int eTextRep,const char*)
  1.4700 +);
  1.4701 +SQLITE_API int sqlite3_collation_needed16(
  1.4702 +  sqlite3*, 
  1.4703 +  void*,
  1.4704 +  void(*)(void*,sqlite3*,int eTextRep,const void*)
  1.4705 +);
  1.4706 +
  1.4707 +#ifdef SQLITE_HAS_CODEC
  1.4708 +/*
  1.4709 +** Specify the key for an encrypted database.  This routine should be
  1.4710 +** called right after sqlite3_open().
  1.4711 +**
  1.4712 +** The code to implement this API is not available in the public release
  1.4713 +** of SQLite.
  1.4714 +*/
  1.4715 +SQLITE_API int sqlite3_key(
  1.4716 +  sqlite3 *db,                   /* Database to be rekeyed */
  1.4717 +  const void *pKey, int nKey     /* The key */
  1.4718 +);
  1.4719 +SQLITE_API int sqlite3_key_v2(
  1.4720 +  sqlite3 *db,                   /* Database to be rekeyed */
  1.4721 +  const char *zDbName,           /* Name of the database */
  1.4722 +  const void *pKey, int nKey     /* The key */
  1.4723 +);
  1.4724 +
  1.4725 +/*
  1.4726 +** Change the key on an open database.  If the current database is not
  1.4727 +** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
  1.4728 +** database is decrypted.
  1.4729 +**
  1.4730 +** The code to implement this API is not available in the public release
  1.4731 +** of SQLite.
  1.4732 +*/
  1.4733 +SQLITE_API int sqlite3_rekey(
  1.4734 +  sqlite3 *db,                   /* Database to be rekeyed */
  1.4735 +  const void *pKey, int nKey     /* The new key */
  1.4736 +);
  1.4737 +SQLITE_API int sqlite3_rekey_v2(
  1.4738 +  sqlite3 *db,                   /* Database to be rekeyed */
  1.4739 +  const char *zDbName,           /* Name of the database */
  1.4740 +  const void *pKey, int nKey     /* The new key */
  1.4741 +);
  1.4742 +
  1.4743 +/*
  1.4744 +** Specify the activation key for a SEE database.  Unless 
  1.4745 +** activated, none of the SEE routines will work.
  1.4746 +*/
  1.4747 +SQLITE_API void sqlite3_activate_see(
  1.4748 +  const char *zPassPhrase        /* Activation phrase */
  1.4749 +);
  1.4750 +#endif
  1.4751 +
  1.4752 +#ifdef SQLITE_ENABLE_CEROD
  1.4753 +/*
  1.4754 +** Specify the activation key for a CEROD database.  Unless 
  1.4755 +** activated, none of the CEROD routines will work.
  1.4756 +*/
  1.4757 +SQLITE_API void sqlite3_activate_cerod(
  1.4758 +  const char *zPassPhrase        /* Activation phrase */
  1.4759 +);
  1.4760 +#endif
  1.4761 +
  1.4762 +/*
  1.4763 +** CAPI3REF: Suspend Execution For A Short Time
  1.4764 +**
  1.4765 +** The sqlite3_sleep() function causes the current thread to suspend execution
  1.4766 +** for at least a number of milliseconds specified in its parameter.
  1.4767 +**
  1.4768 +** If the operating system does not support sleep requests with
  1.4769 +** millisecond time resolution, then the time will be rounded up to
  1.4770 +** the nearest second. The number of milliseconds of sleep actually
  1.4771 +** requested from the operating system is returned.
  1.4772 +**
  1.4773 +** ^SQLite implements this interface by calling the xSleep()
  1.4774 +** method of the default [sqlite3_vfs] object.  If the xSleep() method
  1.4775 +** of the default VFS is not implemented correctly, or not implemented at
  1.4776 +** all, then the behavior of sqlite3_sleep() may deviate from the description
  1.4777 +** in the previous paragraphs.
  1.4778 +*/
  1.4779 +SQLITE_API int sqlite3_sleep(int);
  1.4780 +
  1.4781 +/*
  1.4782 +** CAPI3REF: Name Of The Folder Holding Temporary Files
  1.4783 +**
  1.4784 +** ^(If this global variable is made to point to a string which is
  1.4785 +** the name of a folder (a.k.a. directory), then all temporary files
  1.4786 +** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  1.4787 +** will be placed in that directory.)^  ^If this variable
  1.4788 +** is a NULL pointer, then SQLite performs a search for an appropriate
  1.4789 +** temporary file directory.
  1.4790 +**
  1.4791 +** It is not safe to read or modify this variable in more than one
  1.4792 +** thread at a time.  It is not safe to read or modify this variable
  1.4793 +** if a [database connection] is being used at the same time in a separate
  1.4794 +** thread.
  1.4795 +** It is intended that this variable be set once
  1.4796 +** as part of process initialization and before any SQLite interface
  1.4797 +** routines have been called and that this variable remain unchanged
  1.4798 +** thereafter.
  1.4799 +**
  1.4800 +** ^The [temp_store_directory pragma] may modify this variable and cause
  1.4801 +** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
  1.4802 +** the [temp_store_directory pragma] always assumes that any string
  1.4803 +** that this variable points to is held in memory obtained from 
  1.4804 +** [sqlite3_malloc] and the pragma may attempt to free that memory
  1.4805 +** using [sqlite3_free].
  1.4806 +** Hence, if this variable is modified directly, either it should be
  1.4807 +** made NULL or made to point to memory obtained from [sqlite3_malloc]
  1.4808 +** or else the use of the [temp_store_directory pragma] should be avoided.
  1.4809 +**
  1.4810 +** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
  1.4811 +** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
  1.4812 +** features that require the use of temporary files may fail.  Here is an
  1.4813 +** example of how to do this using C++ with the Windows Runtime:
  1.4814 +**
  1.4815 +** <blockquote><pre>
  1.4816 +** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  1.4817 +** &nbsp;     TemporaryFolder->Path->Data();
  1.4818 +** char zPathBuf&#91;MAX_PATH + 1&#93;;
  1.4819 +** memset(zPathBuf, 0, sizeof(zPathBuf));
  1.4820 +** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  1.4821 +** &nbsp;     NULL, NULL);
  1.4822 +** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  1.4823 +** </pre></blockquote>
  1.4824 +*/
  1.4825 +SQLITE_API char *sqlite3_temp_directory;
  1.4826 +
  1.4827 +/*
  1.4828 +** CAPI3REF: Name Of The Folder Holding Database Files
  1.4829 +**
  1.4830 +** ^(If this global variable is made to point to a string which is
  1.4831 +** the name of a folder (a.k.a. directory), then all database files
  1.4832 +** specified with a relative pathname and created or accessed by
  1.4833 +** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  1.4834 +** to be relative to that directory.)^ ^If this variable is a NULL
  1.4835 +** pointer, then SQLite assumes that all database files specified
  1.4836 +** with a relative pathname are relative to the current directory
  1.4837 +** for the process.  Only the windows VFS makes use of this global
  1.4838 +** variable; it is ignored by the unix VFS.
  1.4839 +**
  1.4840 +** Changing the value of this variable while a database connection is
  1.4841 +** open can result in a corrupt database.
  1.4842 +**
  1.4843 +** It is not safe to read or modify this variable in more than one
  1.4844 +** thread at a time.  It is not safe to read or modify this variable
  1.4845 +** if a [database connection] is being used at the same time in a separate
  1.4846 +** thread.
  1.4847 +** It is intended that this variable be set once
  1.4848 +** as part of process initialization and before any SQLite interface
  1.4849 +** routines have been called and that this variable remain unchanged
  1.4850 +** thereafter.
  1.4851 +**
  1.4852 +** ^The [data_store_directory pragma] may modify this variable and cause
  1.4853 +** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
  1.4854 +** the [data_store_directory pragma] always assumes that any string
  1.4855 +** that this variable points to is held in memory obtained from 
  1.4856 +** [sqlite3_malloc] and the pragma may attempt to free that memory
  1.4857 +** using [sqlite3_free].
  1.4858 +** Hence, if this variable is modified directly, either it should be
  1.4859 +** made NULL or made to point to memory obtained from [sqlite3_malloc]
  1.4860 +** or else the use of the [data_store_directory pragma] should be avoided.
  1.4861 +*/
  1.4862 +SQLITE_API char *sqlite3_data_directory;
  1.4863 +
  1.4864 +/*
  1.4865 +** CAPI3REF: Test For Auto-Commit Mode
  1.4866 +** KEYWORDS: {autocommit mode}
  1.4867 +**
  1.4868 +** ^The sqlite3_get_autocommit() interface returns non-zero or
  1.4869 +** zero if the given database connection is or is not in autocommit mode,
  1.4870 +** respectively.  ^Autocommit mode is on by default.
  1.4871 +** ^Autocommit mode is disabled by a [BEGIN] statement.
  1.4872 +** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  1.4873 +**
  1.4874 +** If certain kinds of errors occur on a statement within a multi-statement
  1.4875 +** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  1.4876 +** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  1.4877 +** transaction might be rolled back automatically.  The only way to
  1.4878 +** find out whether SQLite automatically rolled back the transaction after
  1.4879 +** an error is to use this function.
  1.4880 +**
  1.4881 +** If another thread changes the autocommit status of the database
  1.4882 +** connection while this routine is running, then the return value
  1.4883 +** is undefined.
  1.4884 +*/
  1.4885 +SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  1.4886 +
  1.4887 +/*
  1.4888 +** CAPI3REF: Find The Database Handle Of A Prepared Statement
  1.4889 +**
  1.4890 +** ^The sqlite3_db_handle interface returns the [database connection] handle
  1.4891 +** to which a [prepared statement] belongs.  ^The [database connection]
  1.4892 +** returned by sqlite3_db_handle is the same [database connection]
  1.4893 +** that was the first argument
  1.4894 +** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  1.4895 +** create the statement in the first place.
  1.4896 +*/
  1.4897 +SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  1.4898 +
  1.4899 +/*
  1.4900 +** CAPI3REF: Return The Filename For A Database Connection
  1.4901 +**
  1.4902 +** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  1.4903 +** associated with database N of connection D.  ^The main database file
  1.4904 +** has the name "main".  If there is no attached database N on the database
  1.4905 +** connection D, or if database N is a temporary or in-memory database, then
  1.4906 +** a NULL pointer is returned.
  1.4907 +**
  1.4908 +** ^The filename returned by this function is the output of the
  1.4909 +** xFullPathname method of the [VFS].  ^In other words, the filename
  1.4910 +** will be an absolute pathname, even if the filename used
  1.4911 +** to open the database originally was a URI or relative pathname.
  1.4912 +*/
  1.4913 +SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  1.4914 +
  1.4915 +/*
  1.4916 +** CAPI3REF: Determine if a database is read-only
  1.4917 +**
  1.4918 +** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  1.4919 +** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  1.4920 +** the name of a database on connection D.
  1.4921 +*/
  1.4922 +SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  1.4923 +
  1.4924 +/*
  1.4925 +** CAPI3REF: Find the next prepared statement
  1.4926 +**
  1.4927 +** ^This interface returns a pointer to the next [prepared statement] after
  1.4928 +** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
  1.4929 +** then this interface returns a pointer to the first prepared statement
  1.4930 +** associated with the database connection pDb.  ^If no prepared statement
  1.4931 +** satisfies the conditions of this routine, it returns NULL.
  1.4932 +**
  1.4933 +** The [database connection] pointer D in a call to
  1.4934 +** [sqlite3_next_stmt(D,S)] must refer to an open database
  1.4935 +** connection and in particular must not be a NULL pointer.
  1.4936 +*/
  1.4937 +SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  1.4938 +
  1.4939 +/*
  1.4940 +** CAPI3REF: Commit And Rollback Notification Callbacks
  1.4941 +**
  1.4942 +** ^The sqlite3_commit_hook() interface registers a callback
  1.4943 +** function to be invoked whenever a transaction is [COMMIT | committed].
  1.4944 +** ^Any callback set by a previous call to sqlite3_commit_hook()
  1.4945 +** for the same database connection is overridden.
  1.4946 +** ^The sqlite3_rollback_hook() interface registers a callback
  1.4947 +** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  1.4948 +** ^Any callback set by a previous call to sqlite3_rollback_hook()
  1.4949 +** for the same database connection is overridden.
  1.4950 +** ^The pArg argument is passed through to the callback.
  1.4951 +** ^If the callback on a commit hook function returns non-zero,
  1.4952 +** then the commit is converted into a rollback.
  1.4953 +**
  1.4954 +** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  1.4955 +** return the P argument from the previous call of the same function
  1.4956 +** on the same [database connection] D, or NULL for
  1.4957 +** the first call for each function on D.
  1.4958 +**
  1.4959 +** The commit and rollback hook callbacks are not reentrant.
  1.4960 +** The callback implementation must not do anything that will modify
  1.4961 +** the database connection that invoked the callback.  Any actions
  1.4962 +** to modify the database connection must be deferred until after the
  1.4963 +** completion of the [sqlite3_step()] call that triggered the commit
  1.4964 +** or rollback hook in the first place.
  1.4965 +** Note that running any other SQL statements, including SELECT statements,
  1.4966 +** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  1.4967 +** the database connections for the meaning of "modify" in this paragraph.
  1.4968 +**
  1.4969 +** ^Registering a NULL function disables the callback.
  1.4970 +**
  1.4971 +** ^When the commit hook callback routine returns zero, the [COMMIT]
  1.4972 +** operation is allowed to continue normally.  ^If the commit hook
  1.4973 +** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  1.4974 +** ^The rollback hook is invoked on a rollback that results from a commit
  1.4975 +** hook returning non-zero, just as it would be with any other rollback.
  1.4976 +**
  1.4977 +** ^For the purposes of this API, a transaction is said to have been
  1.4978 +** rolled back if an explicit "ROLLBACK" statement is executed, or
  1.4979 +** an error or constraint causes an implicit rollback to occur.
  1.4980 +** ^The rollback callback is not invoked if a transaction is
  1.4981 +** automatically rolled back because the database connection is closed.
  1.4982 +**
  1.4983 +** See also the [sqlite3_update_hook()] interface.
  1.4984 +*/
  1.4985 +SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  1.4986 +SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  1.4987 +
  1.4988 +/*
  1.4989 +** CAPI3REF: Data Change Notification Callbacks
  1.4990 +**
  1.4991 +** ^The sqlite3_update_hook() interface registers a callback function
  1.4992 +** with the [database connection] identified by the first argument
  1.4993 +** to be invoked whenever a row is updated, inserted or deleted in
  1.4994 +** a rowid table.
  1.4995 +** ^Any callback set by a previous call to this function
  1.4996 +** for the same database connection is overridden.
  1.4997 +**
  1.4998 +** ^The second argument is a pointer to the function to invoke when a
  1.4999 +** row is updated, inserted or deleted in a rowid table.
  1.5000 +** ^The first argument to the callback is a copy of the third argument
  1.5001 +** to sqlite3_update_hook().
  1.5002 +** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  1.5003 +** or [SQLITE_UPDATE], depending on the operation that caused the callback
  1.5004 +** to be invoked.
  1.5005 +** ^The third and fourth arguments to the callback contain pointers to the
  1.5006 +** database and table name containing the affected row.
  1.5007 +** ^The final callback parameter is the [rowid] of the row.
  1.5008 +** ^In the case of an update, this is the [rowid] after the update takes place.
  1.5009 +**
  1.5010 +** ^(The update hook is not invoked when internal system tables are
  1.5011 +** modified (i.e. sqlite_master and sqlite_sequence).)^
  1.5012 +** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
  1.5013 +**
  1.5014 +** ^In the current implementation, the update hook
  1.5015 +** is not invoked when duplication rows are deleted because of an
  1.5016 +** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
  1.5017 +** invoked when rows are deleted using the [truncate optimization].
  1.5018 +** The exceptions defined in this paragraph might change in a future
  1.5019 +** release of SQLite.
  1.5020 +**
  1.5021 +** The update hook implementation must not do anything that will modify
  1.5022 +** the database connection that invoked the update hook.  Any actions
  1.5023 +** to modify the database connection must be deferred until after the
  1.5024 +** completion of the [sqlite3_step()] call that triggered the update hook.
  1.5025 +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  1.5026 +** database connections for the meaning of "modify" in this paragraph.
  1.5027 +**
  1.5028 +** ^The sqlite3_update_hook(D,C,P) function
  1.5029 +** returns the P argument from the previous call
  1.5030 +** on the same [database connection] D, or NULL for
  1.5031 +** the first call on D.
  1.5032 +**
  1.5033 +** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
  1.5034 +** interfaces.
  1.5035 +*/
  1.5036 +SQLITE_API void *sqlite3_update_hook(
  1.5037 +  sqlite3*, 
  1.5038 +  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  1.5039 +  void*
  1.5040 +);
  1.5041 +
  1.5042 +/*
  1.5043 +** CAPI3REF: Enable Or Disable Shared Pager Cache
  1.5044 +**
  1.5045 +** ^(This routine enables or disables the sharing of the database cache
  1.5046 +** and schema data structures between [database connection | connections]
  1.5047 +** to the same database. Sharing is enabled if the argument is true
  1.5048 +** and disabled if the argument is false.)^
  1.5049 +**
  1.5050 +** ^Cache sharing is enabled and disabled for an entire process.
  1.5051 +** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
  1.5052 +** sharing was enabled or disabled for each thread separately.
  1.5053 +**
  1.5054 +** ^(The cache sharing mode set by this interface effects all subsequent
  1.5055 +** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  1.5056 +** Existing database connections continue use the sharing mode
  1.5057 +** that was in effect at the time they were opened.)^
  1.5058 +**
  1.5059 +** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  1.5060 +** successfully.  An [error code] is returned otherwise.)^
  1.5061 +**
  1.5062 +** ^Shared cache is disabled by default. But this might change in
  1.5063 +** future releases of SQLite.  Applications that care about shared
  1.5064 +** cache setting should set it explicitly.
  1.5065 +**
  1.5066 +** This interface is threadsafe on processors where writing a
  1.5067 +** 32-bit integer is atomic.
  1.5068 +**
  1.5069 +** See Also:  [SQLite Shared-Cache Mode]
  1.5070 +*/
  1.5071 +SQLITE_API int sqlite3_enable_shared_cache(int);
  1.5072 +
  1.5073 +/*
  1.5074 +** CAPI3REF: Attempt To Free Heap Memory
  1.5075 +**
  1.5076 +** ^The sqlite3_release_memory() interface attempts to free N bytes
  1.5077 +** of heap memory by deallocating non-essential memory allocations
  1.5078 +** held by the database library.   Memory used to cache database
  1.5079 +** pages to improve performance is an example of non-essential memory.
  1.5080 +** ^sqlite3_release_memory() returns the number of bytes actually freed,
  1.5081 +** which might be more or less than the amount requested.
  1.5082 +** ^The sqlite3_release_memory() routine is a no-op returning zero
  1.5083 +** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  1.5084 +**
  1.5085 +** See also: [sqlite3_db_release_memory()]
  1.5086 +*/
  1.5087 +SQLITE_API int sqlite3_release_memory(int);
  1.5088 +
  1.5089 +/*
  1.5090 +** CAPI3REF: Free Memory Used By A Database Connection
  1.5091 +**
  1.5092 +** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  1.5093 +** memory as possible from database connection D. Unlike the
  1.5094 +** [sqlite3_release_memory()] interface, this interface is in effect even
  1.5095 +** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  1.5096 +** omitted.
  1.5097 +**
  1.5098 +** See also: [sqlite3_release_memory()]
  1.5099 +*/
  1.5100 +SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  1.5101 +
  1.5102 +/*
  1.5103 +** CAPI3REF: Impose A Limit On Heap Size
  1.5104 +**
  1.5105 +** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  1.5106 +** soft limit on the amount of heap memory that may be allocated by SQLite.
  1.5107 +** ^SQLite strives to keep heap memory utilization below the soft heap
  1.5108 +** limit by reducing the number of pages held in the page cache
  1.5109 +** as heap memory usages approaches the limit.
  1.5110 +** ^The soft heap limit is "soft" because even though SQLite strives to stay
  1.5111 +** below the limit, it will exceed the limit rather than generate
  1.5112 +** an [SQLITE_NOMEM] error.  In other words, the soft heap limit 
  1.5113 +** is advisory only.
  1.5114 +**
  1.5115 +** ^The return value from sqlite3_soft_heap_limit64() is the size of
  1.5116 +** the soft heap limit prior to the call, or negative in the case of an
  1.5117 +** error.  ^If the argument N is negative
  1.5118 +** then no change is made to the soft heap limit.  Hence, the current
  1.5119 +** size of the soft heap limit can be determined by invoking
  1.5120 +** sqlite3_soft_heap_limit64() with a negative argument.
  1.5121 +**
  1.5122 +** ^If the argument N is zero then the soft heap limit is disabled.
  1.5123 +**
  1.5124 +** ^(The soft heap limit is not enforced in the current implementation
  1.5125 +** if one or more of following conditions are true:
  1.5126 +**
  1.5127 +** <ul>
  1.5128 +** <li> The soft heap limit is set to zero.
  1.5129 +** <li> Memory accounting is disabled using a combination of the
  1.5130 +**      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  1.5131 +**      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  1.5132 +** <li> An alternative page cache implementation is specified using
  1.5133 +**      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  1.5134 +** <li> The page cache allocates from its own memory pool supplied
  1.5135 +**      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  1.5136 +**      from the heap.
  1.5137 +** </ul>)^
  1.5138 +**
  1.5139 +** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
  1.5140 +** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  1.5141 +** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  1.5142 +** the soft heap limit is enforced on every memory allocation.  Without
  1.5143 +** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  1.5144 +** when memory is allocated by the page cache.  Testing suggests that because
  1.5145 +** the page cache is the predominate memory user in SQLite, most
  1.5146 +** applications will achieve adequate soft heap limit enforcement without
  1.5147 +** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  1.5148 +**
  1.5149 +** The circumstances under which SQLite will enforce the soft heap limit may
  1.5150 +** changes in future releases of SQLite.
  1.5151 +*/
  1.5152 +SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  1.5153 +
  1.5154 +/*
  1.5155 +** CAPI3REF: Deprecated Soft Heap Limit Interface
  1.5156 +** DEPRECATED
  1.5157 +**
  1.5158 +** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  1.5159 +** interface.  This routine is provided for historical compatibility
  1.5160 +** only.  All new applications should use the
  1.5161 +** [sqlite3_soft_heap_limit64()] interface rather than this one.
  1.5162 +*/
  1.5163 +SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  1.5164 +
  1.5165 +
  1.5166 +/*
  1.5167 +** CAPI3REF: Extract Metadata About A Column Of A Table
  1.5168 +**
  1.5169 +** ^This routine returns metadata about a specific column of a specific
  1.5170 +** database table accessible using the [database connection] handle
  1.5171 +** passed as the first function argument.
  1.5172 +**
  1.5173 +** ^The column is identified by the second, third and fourth parameters to
  1.5174 +** this function. ^The second parameter is either the name of the database
  1.5175 +** (i.e. "main", "temp", or an attached database) containing the specified
  1.5176 +** table or NULL. ^If it is NULL, then all attached databases are searched
  1.5177 +** for the table using the same algorithm used by the database engine to
  1.5178 +** resolve unqualified table references.
  1.5179 +**
  1.5180 +** ^The third and fourth parameters to this function are the table and column
  1.5181 +** name of the desired column, respectively. Neither of these parameters
  1.5182 +** may be NULL.
  1.5183 +**
  1.5184 +** ^Metadata is returned by writing to the memory locations passed as the 5th
  1.5185 +** and subsequent parameters to this function. ^Any of these arguments may be
  1.5186 +** NULL, in which case the corresponding element of metadata is omitted.
  1.5187 +**
  1.5188 +** ^(<blockquote>
  1.5189 +** <table border="1">
  1.5190 +** <tr><th> Parameter <th> Output<br>Type <th>  Description
  1.5191 +**
  1.5192 +** <tr><td> 5th <td> const char* <td> Data type
  1.5193 +** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  1.5194 +** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
  1.5195 +** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
  1.5196 +** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
  1.5197 +** </table>
  1.5198 +** </blockquote>)^
  1.5199 +**
  1.5200 +** ^The memory pointed to by the character pointers returned for the
  1.5201 +** declaration type and collation sequence is valid only until the next
  1.5202 +** call to any SQLite API function.
  1.5203 +**
  1.5204 +** ^If the specified table is actually a view, an [error code] is returned.
  1.5205 +**
  1.5206 +** ^If the specified column is "rowid", "oid" or "_rowid_" and an
  1.5207 +** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  1.5208 +** parameters are set for the explicitly declared column. ^(If there is no
  1.5209 +** explicitly declared [INTEGER PRIMARY KEY] column, then the output
  1.5210 +** parameters are set as follows:
  1.5211 +**
  1.5212 +** <pre>
  1.5213 +**     data type: "INTEGER"
  1.5214 +**     collation sequence: "BINARY"
  1.5215 +**     not null: 0
  1.5216 +**     primary key: 1
  1.5217 +**     auto increment: 0
  1.5218 +** </pre>)^
  1.5219 +**
  1.5220 +** ^(This function may load one or more schemas from database files. If an
  1.5221 +** error occurs during this process, or if the requested table or column
  1.5222 +** cannot be found, an [error code] is returned and an error message left
  1.5223 +** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
  1.5224 +**
  1.5225 +** ^This API is only available if the library was compiled with the
  1.5226 +** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
  1.5227 +*/
  1.5228 +SQLITE_API int sqlite3_table_column_metadata(
  1.5229 +  sqlite3 *db,                /* Connection handle */
  1.5230 +  const char *zDbName,        /* Database name or NULL */
  1.5231 +  const char *zTableName,     /* Table name */
  1.5232 +  const char *zColumnName,    /* Column name */
  1.5233 +  char const **pzDataType,    /* OUTPUT: Declared data type */
  1.5234 +  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
  1.5235 +  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
  1.5236 +  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
  1.5237 +  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
  1.5238 +);
  1.5239 +
  1.5240 +/*
  1.5241 +** CAPI3REF: Load An Extension
  1.5242 +**
  1.5243 +** ^This interface loads an SQLite extension library from the named file.
  1.5244 +**
  1.5245 +** ^The sqlite3_load_extension() interface attempts to load an
  1.5246 +** [SQLite extension] library contained in the file zFile.  If
  1.5247 +** the file cannot be loaded directly, attempts are made to load
  1.5248 +** with various operating-system specific extensions added.
  1.5249 +** So for example, if "samplelib" cannot be loaded, then names like
  1.5250 +** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  1.5251 +** be tried also.
  1.5252 +**
  1.5253 +** ^The entry point is zProc.
  1.5254 +** ^(zProc may be 0, in which case SQLite will try to come up with an
  1.5255 +** entry point name on its own.  It first tries "sqlite3_extension_init".
  1.5256 +** If that does not work, it constructs a name "sqlite3_X_init" where the
  1.5257 +** X is consists of the lower-case equivalent of all ASCII alphabetic
  1.5258 +** characters in the filename from the last "/" to the first following
  1.5259 +** "." and omitting any initial "lib".)^
  1.5260 +** ^The sqlite3_load_extension() interface returns
  1.5261 +** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  1.5262 +** ^If an error occurs and pzErrMsg is not 0, then the
  1.5263 +** [sqlite3_load_extension()] interface shall attempt to
  1.5264 +** fill *pzErrMsg with error message text stored in memory
  1.5265 +** obtained from [sqlite3_malloc()]. The calling function
  1.5266 +** should free this memory by calling [sqlite3_free()].
  1.5267 +**
  1.5268 +** ^Extension loading must be enabled using
  1.5269 +** [sqlite3_enable_load_extension()] prior to calling this API,
  1.5270 +** otherwise an error will be returned.
  1.5271 +**
  1.5272 +** See also the [load_extension() SQL function].
  1.5273 +*/
  1.5274 +SQLITE_API int sqlite3_load_extension(
  1.5275 +  sqlite3 *db,          /* Load the extension into this database connection */
  1.5276 +  const char *zFile,    /* Name of the shared library containing extension */
  1.5277 +  const char *zProc,    /* Entry point.  Derived from zFile if 0 */
  1.5278 +  char **pzErrMsg       /* Put error message here if not 0 */
  1.5279 +);
  1.5280 +
  1.5281 +/*
  1.5282 +** CAPI3REF: Enable Or Disable Extension Loading
  1.5283 +**
  1.5284 +** ^So as not to open security holes in older applications that are
  1.5285 +** unprepared to deal with [extension loading], and as a means of disabling
  1.5286 +** [extension loading] while evaluating user-entered SQL, the following API
  1.5287 +** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  1.5288 +**
  1.5289 +** ^Extension loading is off by default.
  1.5290 +** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  1.5291 +** to turn extension loading on and call it with onoff==0 to turn
  1.5292 +** it back off again.
  1.5293 +*/
  1.5294 +SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  1.5295 +
  1.5296 +/*
  1.5297 +** CAPI3REF: Automatically Load Statically Linked Extensions
  1.5298 +**
  1.5299 +** ^This interface causes the xEntryPoint() function to be invoked for
  1.5300 +** each new [database connection] that is created.  The idea here is that
  1.5301 +** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  1.5302 +** that is to be automatically loaded into all new database connections.
  1.5303 +**
  1.5304 +** ^(Even though the function prototype shows that xEntryPoint() takes
  1.5305 +** no arguments and returns void, SQLite invokes xEntryPoint() with three
  1.5306 +** arguments and expects and integer result as if the signature of the
  1.5307 +** entry point where as follows:
  1.5308 +**
  1.5309 +** <blockquote><pre>
  1.5310 +** &nbsp;  int xEntryPoint(
  1.5311 +** &nbsp;    sqlite3 *db,
  1.5312 +** &nbsp;    const char **pzErrMsg,
  1.5313 +** &nbsp;    const struct sqlite3_api_routines *pThunk
  1.5314 +** &nbsp;  );
  1.5315 +** </pre></blockquote>)^
  1.5316 +**
  1.5317 +** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  1.5318 +** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  1.5319 +** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
  1.5320 +** is NULL before calling the xEntryPoint().  ^SQLite will invoke
  1.5321 +** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
  1.5322 +** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  1.5323 +** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  1.5324 +**
  1.5325 +** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  1.5326 +** on the list of automatic extensions is a harmless no-op. ^No entry point
  1.5327 +** will be called more than once for each database connection that is opened.
  1.5328 +**
  1.5329 +** See also: [sqlite3_reset_auto_extension()]
  1.5330 +** and [sqlite3_cancel_auto_extension()]
  1.5331 +*/
  1.5332 +SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
  1.5333 +
  1.5334 +/*
  1.5335 +** CAPI3REF: Cancel Automatic Extension Loading
  1.5336 +**
  1.5337 +** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  1.5338 +** initialization routine X that was registered using a prior call to
  1.5339 +** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]
  1.5340 +** routine returns 1 if initialization routine X was successfully 
  1.5341 +** unregistered and it returns 0 if X was not on the list of initialization
  1.5342 +** routines.
  1.5343 +*/
  1.5344 +SQLITE_API int sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
  1.5345 +
  1.5346 +/*
  1.5347 +** CAPI3REF: Reset Automatic Extension Loading
  1.5348 +**
  1.5349 +** ^This interface disables all automatic extensions previously
  1.5350 +** registered using [sqlite3_auto_extension()].
  1.5351 +*/
  1.5352 +SQLITE_API void sqlite3_reset_auto_extension(void);
  1.5353 +
  1.5354 +/*
  1.5355 +** The interface to the virtual-table mechanism is currently considered
  1.5356 +** to be experimental.  The interface might change in incompatible ways.
  1.5357 +** If this is a problem for you, do not use the interface at this time.
  1.5358 +**
  1.5359 +** When the virtual-table mechanism stabilizes, we will declare the
  1.5360 +** interface fixed, support it indefinitely, and remove this comment.
  1.5361 +*/
  1.5362 +
  1.5363 +/*
  1.5364 +** Structures used by the virtual table interface
  1.5365 +*/
  1.5366 +typedef struct sqlite3_vtab sqlite3_vtab;
  1.5367 +typedef struct sqlite3_index_info sqlite3_index_info;
  1.5368 +typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  1.5369 +typedef struct sqlite3_module sqlite3_module;
  1.5370 +
  1.5371 +/*
  1.5372 +** CAPI3REF: Virtual Table Object
  1.5373 +** KEYWORDS: sqlite3_module {virtual table module}
  1.5374 +**
  1.5375 +** This structure, sometimes called a "virtual table module", 
  1.5376 +** defines the implementation of a [virtual tables].  
  1.5377 +** This structure consists mostly of methods for the module.
  1.5378 +**
  1.5379 +** ^A virtual table module is created by filling in a persistent
  1.5380 +** instance of this structure and passing a pointer to that instance
  1.5381 +** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  1.5382 +** ^The registration remains valid until it is replaced by a different
  1.5383 +** module or until the [database connection] closes.  The content
  1.5384 +** of this structure must not change while it is registered with
  1.5385 +** any database connection.
  1.5386 +*/
  1.5387 +struct sqlite3_module {
  1.5388 +  int iVersion;
  1.5389 +  int (*xCreate)(sqlite3*, void *pAux,
  1.5390 +               int argc, const char *const*argv,
  1.5391 +               sqlite3_vtab **ppVTab, char**);
  1.5392 +  int (*xConnect)(sqlite3*, void *pAux,
  1.5393 +               int argc, const char *const*argv,
  1.5394 +               sqlite3_vtab **ppVTab, char**);
  1.5395 +  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  1.5396 +  int (*xDisconnect)(sqlite3_vtab *pVTab);
  1.5397 +  int (*xDestroy)(sqlite3_vtab *pVTab);
  1.5398 +  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  1.5399 +  int (*xClose)(sqlite3_vtab_cursor*);
  1.5400 +  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  1.5401 +                int argc, sqlite3_value **argv);
  1.5402 +  int (*xNext)(sqlite3_vtab_cursor*);
  1.5403 +  int (*xEof)(sqlite3_vtab_cursor*);
  1.5404 +  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  1.5405 +  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  1.5406 +  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  1.5407 +  int (*xBegin)(sqlite3_vtab *pVTab);
  1.5408 +  int (*xSync)(sqlite3_vtab *pVTab);
  1.5409 +  int (*xCommit)(sqlite3_vtab *pVTab);
  1.5410 +  int (*xRollback)(sqlite3_vtab *pVTab);
  1.5411 +  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  1.5412 +                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  1.5413 +                       void **ppArg);
  1.5414 +  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  1.5415 +  /* The methods above are in version 1 of the sqlite_module object. Those 
  1.5416 +  ** below are for version 2 and greater. */
  1.5417 +  int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  1.5418 +  int (*xRelease)(sqlite3_vtab *pVTab, int);
  1.5419 +  int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  1.5420 +};
  1.5421 +
  1.5422 +/*
  1.5423 +** CAPI3REF: Virtual Table Indexing Information
  1.5424 +** KEYWORDS: sqlite3_index_info
  1.5425 +**
  1.5426 +** The sqlite3_index_info structure and its substructures is used as part
  1.5427 +** of the [virtual table] interface to
  1.5428 +** pass information into and receive the reply from the [xBestIndex]
  1.5429 +** method of a [virtual table module].  The fields under **Inputs** are the
  1.5430 +** inputs to xBestIndex and are read-only.  xBestIndex inserts its
  1.5431 +** results into the **Outputs** fields.
  1.5432 +**
  1.5433 +** ^(The aConstraint[] array records WHERE clause constraints of the form:
  1.5434 +**
  1.5435 +** <blockquote>column OP expr</blockquote>
  1.5436 +**
  1.5437 +** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
  1.5438 +** stored in aConstraint[].op using one of the
  1.5439 +** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  1.5440 +** ^(The index of the column is stored in
  1.5441 +** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
  1.5442 +** expr on the right-hand side can be evaluated (and thus the constraint
  1.5443 +** is usable) and false if it cannot.)^
  1.5444 +**
  1.5445 +** ^The optimizer automatically inverts terms of the form "expr OP column"
  1.5446 +** and makes other simplifications to the WHERE clause in an attempt to
  1.5447 +** get as many WHERE clause terms into the form shown above as possible.
  1.5448 +** ^The aConstraint[] array only reports WHERE clause terms that are
  1.5449 +** relevant to the particular virtual table being queried.
  1.5450 +**
  1.5451 +** ^Information about the ORDER BY clause is stored in aOrderBy[].
  1.5452 +** ^Each term of aOrderBy records a column of the ORDER BY clause.
  1.5453 +**
  1.5454 +** The [xBestIndex] method must fill aConstraintUsage[] with information
  1.5455 +** about what parameters to pass to xFilter.  ^If argvIndex>0 then
  1.5456 +** the right-hand side of the corresponding aConstraint[] is evaluated
  1.5457 +** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
  1.5458 +** is true, then the constraint is assumed to be fully handled by the
  1.5459 +** virtual table and is not checked again by SQLite.)^
  1.5460 +**
  1.5461 +** ^The idxNum and idxPtr values are recorded and passed into the
  1.5462 +** [xFilter] method.
  1.5463 +** ^[sqlite3_free()] is used to free idxPtr if and only if
  1.5464 +** needToFreeIdxPtr is true.
  1.5465 +**
  1.5466 +** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  1.5467 +** the correct order to satisfy the ORDER BY clause so that no separate
  1.5468 +** sorting step is required.
  1.5469 +**
  1.5470 +** ^The estimatedCost value is an estimate of the cost of a particular
  1.5471 +** strategy. A cost of N indicates that the cost of the strategy is similar
  1.5472 +** to a linear scan of an SQLite table with N rows. A cost of log(N) 
  1.5473 +** indicates that the expense of the operation is similar to that of a
  1.5474 +** binary search on a unique indexed field of an SQLite table with N rows.
  1.5475 +**
  1.5476 +** ^The estimatedRows value is an estimate of the number of rows that
  1.5477 +** will be returned by the strategy.
  1.5478 +**
  1.5479 +** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
  1.5480 +** structure for SQLite version 3.8.2. If a virtual table extension is
  1.5481 +** used with an SQLite version earlier than 3.8.2, the results of attempting 
  1.5482 +** to read or write the estimatedRows field are undefined (but are likely 
  1.5483 +** to included crashing the application). The estimatedRows field should
  1.5484 +** therefore only be used if [sqlite3_libversion_number()] returns a
  1.5485 +** value greater than or equal to 3008002.
  1.5486 +*/
  1.5487 +struct sqlite3_index_info {
  1.5488 +  /* Inputs */
  1.5489 +  int nConstraint;           /* Number of entries in aConstraint */
  1.5490 +  struct sqlite3_index_constraint {
  1.5491 +     int iColumn;              /* Column on left-hand side of constraint */
  1.5492 +     unsigned char op;         /* Constraint operator */
  1.5493 +     unsigned char usable;     /* True if this constraint is usable */
  1.5494 +     int iTermOffset;          /* Used internally - xBestIndex should ignore */
  1.5495 +  } *aConstraint;            /* Table of WHERE clause constraints */
  1.5496 +  int nOrderBy;              /* Number of terms in the ORDER BY clause */
  1.5497 +  struct sqlite3_index_orderby {
  1.5498 +     int iColumn;              /* Column number */
  1.5499 +     unsigned char desc;       /* True for DESC.  False for ASC. */
  1.5500 +  } *aOrderBy;               /* The ORDER BY clause */
  1.5501 +  /* Outputs */
  1.5502 +  struct sqlite3_index_constraint_usage {
  1.5503 +    int argvIndex;           /* if >0, constraint is part of argv to xFilter */
  1.5504 +    unsigned char omit;      /* Do not code a test for this constraint */
  1.5505 +  } *aConstraintUsage;
  1.5506 +  int idxNum;                /* Number used to identify the index */
  1.5507 +  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
  1.5508 +  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
  1.5509 +  int orderByConsumed;       /* True if output is already ordered */
  1.5510 +  double estimatedCost;           /* Estimated cost of using this index */
  1.5511 +  /* Fields below are only available in SQLite 3.8.2 and later */
  1.5512 +  sqlite3_int64 estimatedRows;    /* Estimated number of rows returned */
  1.5513 +};
  1.5514 +
  1.5515 +/*
  1.5516 +** CAPI3REF: Virtual Table Constraint Operator Codes
  1.5517 +**
  1.5518 +** These macros defined the allowed values for the
  1.5519 +** [sqlite3_index_info].aConstraint[].op field.  Each value represents
  1.5520 +** an operator that is part of a constraint term in the wHERE clause of
  1.5521 +** a query that uses a [virtual table].
  1.5522 +*/
  1.5523 +#define SQLITE_INDEX_CONSTRAINT_EQ    2
  1.5524 +#define SQLITE_INDEX_CONSTRAINT_GT    4
  1.5525 +#define SQLITE_INDEX_CONSTRAINT_LE    8
  1.5526 +#define SQLITE_INDEX_CONSTRAINT_LT    16
  1.5527 +#define SQLITE_INDEX_CONSTRAINT_GE    32
  1.5528 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64
  1.5529 +
  1.5530 +/*
  1.5531 +** CAPI3REF: Register A Virtual Table Implementation
  1.5532 +**
  1.5533 +** ^These routines are used to register a new [virtual table module] name.
  1.5534 +** ^Module names must be registered before
  1.5535 +** creating a new [virtual table] using the module and before using a
  1.5536 +** preexisting [virtual table] for the module.
  1.5537 +**
  1.5538 +** ^The module name is registered on the [database connection] specified
  1.5539 +** by the first parameter.  ^The name of the module is given by the 
  1.5540 +** second parameter.  ^The third parameter is a pointer to
  1.5541 +** the implementation of the [virtual table module].   ^The fourth
  1.5542 +** parameter is an arbitrary client data pointer that is passed through
  1.5543 +** into the [xCreate] and [xConnect] methods of the virtual table module
  1.5544 +** when a new virtual table is be being created or reinitialized.
  1.5545 +**
  1.5546 +** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  1.5547 +** is a pointer to a destructor for the pClientData.  ^SQLite will
  1.5548 +** invoke the destructor function (if it is not NULL) when SQLite
  1.5549 +** no longer needs the pClientData pointer.  ^The destructor will also
  1.5550 +** be invoked if the call to sqlite3_create_module_v2() fails.
  1.5551 +** ^The sqlite3_create_module()
  1.5552 +** interface is equivalent to sqlite3_create_module_v2() with a NULL
  1.5553 +** destructor.
  1.5554 +*/
  1.5555 +SQLITE_API int sqlite3_create_module(
  1.5556 +  sqlite3 *db,               /* SQLite connection to register module with */
  1.5557 +  const char *zName,         /* Name of the module */
  1.5558 +  const sqlite3_module *p,   /* Methods for the module */
  1.5559 +  void *pClientData          /* Client data for xCreate/xConnect */
  1.5560 +);
  1.5561 +SQLITE_API int sqlite3_create_module_v2(
  1.5562 +  sqlite3 *db,               /* SQLite connection to register module with */
  1.5563 +  const char *zName,         /* Name of the module */
  1.5564 +  const sqlite3_module *p,   /* Methods for the module */
  1.5565 +  void *pClientData,         /* Client data for xCreate/xConnect */
  1.5566 +  void(*xDestroy)(void*)     /* Module destructor function */
  1.5567 +);
  1.5568 +
  1.5569 +/*
  1.5570 +** CAPI3REF: Virtual Table Instance Object
  1.5571 +** KEYWORDS: sqlite3_vtab
  1.5572 +**
  1.5573 +** Every [virtual table module] implementation uses a subclass
  1.5574 +** of this object to describe a particular instance
  1.5575 +** of the [virtual table].  Each subclass will
  1.5576 +** be tailored to the specific needs of the module implementation.
  1.5577 +** The purpose of this superclass is to define certain fields that are
  1.5578 +** common to all module implementations.
  1.5579 +**
  1.5580 +** ^Virtual tables methods can set an error message by assigning a
  1.5581 +** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
  1.5582 +** take care that any prior string is freed by a call to [sqlite3_free()]
  1.5583 +** prior to assigning a new string to zErrMsg.  ^After the error message
  1.5584 +** is delivered up to the client application, the string will be automatically
  1.5585 +** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  1.5586 +*/
  1.5587 +struct sqlite3_vtab {
  1.5588 +  const sqlite3_module *pModule;  /* The module for this virtual table */
  1.5589 +  int nRef;                       /* NO LONGER USED */
  1.5590 +  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
  1.5591 +  /* Virtual table implementations will typically add additional fields */
  1.5592 +};
  1.5593 +
  1.5594 +/*
  1.5595 +** CAPI3REF: Virtual Table Cursor Object
  1.5596 +** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  1.5597 +**
  1.5598 +** Every [virtual table module] implementation uses a subclass of the
  1.5599 +** following structure to describe cursors that point into the
  1.5600 +** [virtual table] and are used
  1.5601 +** to loop through the virtual table.  Cursors are created using the
  1.5602 +** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  1.5603 +** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
  1.5604 +** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  1.5605 +** of the module.  Each module implementation will define
  1.5606 +** the content of a cursor structure to suit its own needs.
  1.5607 +**
  1.5608 +** This superclass exists in order to define fields of the cursor that
  1.5609 +** are common to all implementations.
  1.5610 +*/
  1.5611 +struct sqlite3_vtab_cursor {
  1.5612 +  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
  1.5613 +  /* Virtual table implementations will typically add additional fields */
  1.5614 +};
  1.5615 +
  1.5616 +/*
  1.5617 +** CAPI3REF: Declare The Schema Of A Virtual Table
  1.5618 +**
  1.5619 +** ^The [xCreate] and [xConnect] methods of a
  1.5620 +** [virtual table module] call this interface
  1.5621 +** to declare the format (the names and datatypes of the columns) of
  1.5622 +** the virtual tables they implement.
  1.5623 +*/
  1.5624 +SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  1.5625 +
  1.5626 +/*
  1.5627 +** CAPI3REF: Overload A Function For A Virtual Table
  1.5628 +**
  1.5629 +** ^(Virtual tables can provide alternative implementations of functions
  1.5630 +** using the [xFindFunction] method of the [virtual table module].  
  1.5631 +** But global versions of those functions
  1.5632 +** must exist in order to be overloaded.)^
  1.5633 +**
  1.5634 +** ^(This API makes sure a global version of a function with a particular
  1.5635 +** name and number of parameters exists.  If no such function exists
  1.5636 +** before this API is called, a new function is created.)^  ^The implementation
  1.5637 +** of the new function always causes an exception to be thrown.  So
  1.5638 +** the new function is not good for anything by itself.  Its only
  1.5639 +** purpose is to be a placeholder function that can be overloaded
  1.5640 +** by a [virtual table].
  1.5641 +*/
  1.5642 +SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  1.5643 +
  1.5644 +/*
  1.5645 +** The interface to the virtual-table mechanism defined above (back up
  1.5646 +** to a comment remarkably similar to this one) is currently considered
  1.5647 +** to be experimental.  The interface might change in incompatible ways.
  1.5648 +** If this is a problem for you, do not use the interface at this time.
  1.5649 +**
  1.5650 +** When the virtual-table mechanism stabilizes, we will declare the
  1.5651 +** interface fixed, support it indefinitely, and remove this comment.
  1.5652 +*/
  1.5653 +
  1.5654 +/*
  1.5655 +** CAPI3REF: A Handle To An Open BLOB
  1.5656 +** KEYWORDS: {BLOB handle} {BLOB handles}
  1.5657 +**
  1.5658 +** An instance of this object represents an open BLOB on which
  1.5659 +** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  1.5660 +** ^Objects of this type are created by [sqlite3_blob_open()]
  1.5661 +** and destroyed by [sqlite3_blob_close()].
  1.5662 +** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  1.5663 +** can be used to read or write small subsections of the BLOB.
  1.5664 +** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  1.5665 +*/
  1.5666 +typedef struct sqlite3_blob sqlite3_blob;
  1.5667 +
  1.5668 +/*
  1.5669 +** CAPI3REF: Open A BLOB For Incremental I/O
  1.5670 +**
  1.5671 +** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  1.5672 +** in row iRow, column zColumn, table zTable in database zDb;
  1.5673 +** in other words, the same BLOB that would be selected by:
  1.5674 +**
  1.5675 +** <pre>
  1.5676 +**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  1.5677 +** </pre>)^
  1.5678 +**
  1.5679 +** ^If the flags parameter is non-zero, then the BLOB is opened for read
  1.5680 +** and write access. ^If it is zero, the BLOB is opened for read access.
  1.5681 +** ^It is not possible to open a column that is part of an index or primary 
  1.5682 +** key for writing. ^If [foreign key constraints] are enabled, it is 
  1.5683 +** not possible to open a column that is part of a [child key] for writing.
  1.5684 +**
  1.5685 +** ^Note that the database name is not the filename that contains
  1.5686 +** the database but rather the symbolic name of the database that
  1.5687 +** appears after the AS keyword when the database is connected using [ATTACH].
  1.5688 +** ^For the main database file, the database name is "main".
  1.5689 +** ^For TEMP tables, the database name is "temp".
  1.5690 +**
  1.5691 +** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
  1.5692 +** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
  1.5693 +** to be a null pointer.)^
  1.5694 +** ^This function sets the [database connection] error code and message
  1.5695 +** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
  1.5696 +** functions. ^Note that the *ppBlob variable is always initialized in a
  1.5697 +** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
  1.5698 +** regardless of the success or failure of this routine.
  1.5699 +**
  1.5700 +** ^(If the row that a BLOB handle points to is modified by an
  1.5701 +** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  1.5702 +** then the BLOB handle is marked as "expired".
  1.5703 +** This is true if any column of the row is changed, even a column
  1.5704 +** other than the one the BLOB handle is open on.)^
  1.5705 +** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  1.5706 +** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  1.5707 +** ^(Changes written into a BLOB prior to the BLOB expiring are not
  1.5708 +** rolled back by the expiration of the BLOB.  Such changes will eventually
  1.5709 +** commit if the transaction continues to completion.)^
  1.5710 +**
  1.5711 +** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  1.5712 +** the opened blob.  ^The size of a blob may not be changed by this
  1.5713 +** interface.  Use the [UPDATE] SQL command to change the size of a
  1.5714 +** blob.
  1.5715 +**
  1.5716 +** ^The [sqlite3_blob_open()] interface will fail for a [WITHOUT ROWID]
  1.5717 +** table.  Incremental BLOB I/O is not possible on [WITHOUT ROWID] tables.
  1.5718 +**
  1.5719 +** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  1.5720 +** and the built-in [zeroblob] SQL function can be used, if desired,
  1.5721 +** to create an empty, zero-filled blob in which to read or write using
  1.5722 +** this interface.
  1.5723 +**
  1.5724 +** To avoid a resource leak, every open [BLOB handle] should eventually
  1.5725 +** be released by a call to [sqlite3_blob_close()].
  1.5726 +*/
  1.5727 +SQLITE_API int sqlite3_blob_open(
  1.5728 +  sqlite3*,
  1.5729 +  const char *zDb,
  1.5730 +  const char *zTable,
  1.5731 +  const char *zColumn,
  1.5732 +  sqlite3_int64 iRow,
  1.5733 +  int flags,
  1.5734 +  sqlite3_blob **ppBlob
  1.5735 +);
  1.5736 +
  1.5737 +/*
  1.5738 +** CAPI3REF: Move a BLOB Handle to a New Row
  1.5739 +**
  1.5740 +** ^This function is used to move an existing blob handle so that it points
  1.5741 +** to a different row of the same database table. ^The new row is identified
  1.5742 +** by the rowid value passed as the second argument. Only the row can be
  1.5743 +** changed. ^The database, table and column on which the blob handle is open
  1.5744 +** remain the same. Moving an existing blob handle to a new row can be
  1.5745 +** faster than closing the existing handle and opening a new one.
  1.5746 +**
  1.5747 +** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  1.5748 +** it must exist and there must be either a blob or text value stored in
  1.5749 +** the nominated column.)^ ^If the new row is not present in the table, or if
  1.5750 +** it does not contain a blob or text value, or if another error occurs, an
  1.5751 +** SQLite error code is returned and the blob handle is considered aborted.
  1.5752 +** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  1.5753 +** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  1.5754 +** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  1.5755 +** always returns zero.
  1.5756 +**
  1.5757 +** ^This function sets the database handle error code and message.
  1.5758 +*/
  1.5759 +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  1.5760 +
  1.5761 +/*
  1.5762 +** CAPI3REF: Close A BLOB Handle
  1.5763 +**
  1.5764 +** ^Closes an open [BLOB handle].
  1.5765 +**
  1.5766 +** ^Closing a BLOB shall cause the current transaction to commit
  1.5767 +** if there are no other BLOBs, no pending prepared statements, and the
  1.5768 +** database connection is in [autocommit mode].
  1.5769 +** ^If any writes were made to the BLOB, they might be held in cache
  1.5770 +** until the close operation if they will fit.
  1.5771 +**
  1.5772 +** ^(Closing the BLOB often forces the changes
  1.5773 +** out to disk and so if any I/O errors occur, they will likely occur
  1.5774 +** at the time when the BLOB is closed.  Any errors that occur during
  1.5775 +** closing are reported as a non-zero return value.)^
  1.5776 +**
  1.5777 +** ^(The BLOB is closed unconditionally.  Even if this routine returns
  1.5778 +** an error code, the BLOB is still closed.)^
  1.5779 +**
  1.5780 +** ^Calling this routine with a null pointer (such as would be returned
  1.5781 +** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
  1.5782 +*/
  1.5783 +SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  1.5784 +
  1.5785 +/*
  1.5786 +** CAPI3REF: Return The Size Of An Open BLOB
  1.5787 +**
  1.5788 +** ^Returns the size in bytes of the BLOB accessible via the 
  1.5789 +** successfully opened [BLOB handle] in its only argument.  ^The
  1.5790 +** incremental blob I/O routines can only read or overwriting existing
  1.5791 +** blob content; they cannot change the size of a blob.
  1.5792 +**
  1.5793 +** This routine only works on a [BLOB handle] which has been created
  1.5794 +** by a prior successful call to [sqlite3_blob_open()] and which has not
  1.5795 +** been closed by [sqlite3_blob_close()].  Passing any other pointer in
  1.5796 +** to this routine results in undefined and probably undesirable behavior.
  1.5797 +*/
  1.5798 +SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  1.5799 +
  1.5800 +/*
  1.5801 +** CAPI3REF: Read Data From A BLOB Incrementally
  1.5802 +**
  1.5803 +** ^(This function is used to read data from an open [BLOB handle] into a
  1.5804 +** caller-supplied buffer. N bytes of data are copied into buffer Z
  1.5805 +** from the open BLOB, starting at offset iOffset.)^
  1.5806 +**
  1.5807 +** ^If offset iOffset is less than N bytes from the end of the BLOB,
  1.5808 +** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
  1.5809 +** less than zero, [SQLITE_ERROR] is returned and no data is read.
  1.5810 +** ^The size of the blob (and hence the maximum value of N+iOffset)
  1.5811 +** can be determined using the [sqlite3_blob_bytes()] interface.
  1.5812 +**
  1.5813 +** ^An attempt to read from an expired [BLOB handle] fails with an
  1.5814 +** error code of [SQLITE_ABORT].
  1.5815 +**
  1.5816 +** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  1.5817 +** Otherwise, an [error code] or an [extended error code] is returned.)^
  1.5818 +**
  1.5819 +** This routine only works on a [BLOB handle] which has been created
  1.5820 +** by a prior successful call to [sqlite3_blob_open()] and which has not
  1.5821 +** been closed by [sqlite3_blob_close()].  Passing any other pointer in
  1.5822 +** to this routine results in undefined and probably undesirable behavior.
  1.5823 +**
  1.5824 +** See also: [sqlite3_blob_write()].
  1.5825 +*/
  1.5826 +SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  1.5827 +
  1.5828 +/*
  1.5829 +** CAPI3REF: Write Data Into A BLOB Incrementally
  1.5830 +**
  1.5831 +** ^This function is used to write data into an open [BLOB handle] from a
  1.5832 +** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
  1.5833 +** into the open BLOB, starting at offset iOffset.
  1.5834 +**
  1.5835 +** ^If the [BLOB handle] passed as the first argument was not opened for
  1.5836 +** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  1.5837 +** this function returns [SQLITE_READONLY].
  1.5838 +**
  1.5839 +** ^This function may only modify the contents of the BLOB; it is
  1.5840 +** not possible to increase the size of a BLOB using this API.
  1.5841 +** ^If offset iOffset is less than N bytes from the end of the BLOB,
  1.5842 +** [SQLITE_ERROR] is returned and no data is written.  ^If N is
  1.5843 +** less than zero [SQLITE_ERROR] is returned and no data is written.
  1.5844 +** The size of the BLOB (and hence the maximum value of N+iOffset)
  1.5845 +** can be determined using the [sqlite3_blob_bytes()] interface.
  1.5846 +**
  1.5847 +** ^An attempt to write to an expired [BLOB handle] fails with an
  1.5848 +** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
  1.5849 +** before the [BLOB handle] expired are not rolled back by the
  1.5850 +** expiration of the handle, though of course those changes might
  1.5851 +** have been overwritten by the statement that expired the BLOB handle
  1.5852 +** or by other independent statements.
  1.5853 +**
  1.5854 +** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  1.5855 +** Otherwise, an  [error code] or an [extended error code] is returned.)^
  1.5856 +**
  1.5857 +** This routine only works on a [BLOB handle] which has been created
  1.5858 +** by a prior successful call to [sqlite3_blob_open()] and which has not
  1.5859 +** been closed by [sqlite3_blob_close()].  Passing any other pointer in
  1.5860 +** to this routine results in undefined and probably undesirable behavior.
  1.5861 +**
  1.5862 +** See also: [sqlite3_blob_read()].
  1.5863 +*/
  1.5864 +SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  1.5865 +
  1.5866 +/*
  1.5867 +** CAPI3REF: Virtual File System Objects
  1.5868 +**
  1.5869 +** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  1.5870 +** that SQLite uses to interact
  1.5871 +** with the underlying operating system.  Most SQLite builds come with a
  1.5872 +** single default VFS that is appropriate for the host computer.
  1.5873 +** New VFSes can be registered and existing VFSes can be unregistered.
  1.5874 +** The following interfaces are provided.
  1.5875 +**
  1.5876 +** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  1.5877 +** ^Names are case sensitive.
  1.5878 +** ^Names are zero-terminated UTF-8 strings.
  1.5879 +** ^If there is no match, a NULL pointer is returned.
  1.5880 +** ^If zVfsName is NULL then the default VFS is returned.
  1.5881 +**
  1.5882 +** ^New VFSes are registered with sqlite3_vfs_register().
  1.5883 +** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  1.5884 +** ^The same VFS can be registered multiple times without injury.
  1.5885 +** ^To make an existing VFS into the default VFS, register it again
  1.5886 +** with the makeDflt flag set.  If two different VFSes with the
  1.5887 +** same name are registered, the behavior is undefined.  If a
  1.5888 +** VFS is registered with a name that is NULL or an empty string,
  1.5889 +** then the behavior is undefined.
  1.5890 +**
  1.5891 +** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  1.5892 +** ^(If the default VFS is unregistered, another VFS is chosen as
  1.5893 +** the default.  The choice for the new VFS is arbitrary.)^
  1.5894 +*/
  1.5895 +SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  1.5896 +SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  1.5897 +SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  1.5898 +
  1.5899 +/*
  1.5900 +** CAPI3REF: Mutexes
  1.5901 +**
  1.5902 +** The SQLite core uses these routines for thread
  1.5903 +** synchronization. Though they are intended for internal
  1.5904 +** use by SQLite, code that links against SQLite is
  1.5905 +** permitted to use any of these routines.
  1.5906 +**
  1.5907 +** The SQLite source code contains multiple implementations
  1.5908 +** of these mutex routines.  An appropriate implementation
  1.5909 +** is selected automatically at compile-time.  ^(The following
  1.5910 +** implementations are available in the SQLite core:
  1.5911 +**
  1.5912 +** <ul>
  1.5913 +** <li>   SQLITE_MUTEX_PTHREADS
  1.5914 +** <li>   SQLITE_MUTEX_W32
  1.5915 +** <li>   SQLITE_MUTEX_NOOP
  1.5916 +** </ul>)^
  1.5917 +**
  1.5918 +** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
  1.5919 +** that does no real locking and is appropriate for use in
  1.5920 +** a single-threaded application.  ^The SQLITE_MUTEX_PTHREADS and
  1.5921 +** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  1.5922 +** and Windows.
  1.5923 +**
  1.5924 +** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  1.5925 +** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  1.5926 +** implementation is included with the library. In this case the
  1.5927 +** application must supply a custom mutex implementation using the
  1.5928 +** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  1.5929 +** before calling sqlite3_initialize() or any other public sqlite3_
  1.5930 +** function that calls sqlite3_initialize().)^
  1.5931 +**
  1.5932 +** ^The sqlite3_mutex_alloc() routine allocates a new
  1.5933 +** mutex and returns a pointer to it. ^If it returns NULL
  1.5934 +** that means that a mutex could not be allocated.  ^SQLite
  1.5935 +** will unwind its stack and return an error.  ^(The argument
  1.5936 +** to sqlite3_mutex_alloc() is one of these integer constants:
  1.5937 +**
  1.5938 +** <ul>
  1.5939 +** <li>  SQLITE_MUTEX_FAST
  1.5940 +** <li>  SQLITE_MUTEX_RECURSIVE
  1.5941 +** <li>  SQLITE_MUTEX_STATIC_MASTER
  1.5942 +** <li>  SQLITE_MUTEX_STATIC_MEM
  1.5943 +** <li>  SQLITE_MUTEX_STATIC_MEM2
  1.5944 +** <li>  SQLITE_MUTEX_STATIC_PRNG
  1.5945 +** <li>  SQLITE_MUTEX_STATIC_LRU
  1.5946 +** <li>  SQLITE_MUTEX_STATIC_LRU2
  1.5947 +** </ul>)^
  1.5948 +**
  1.5949 +** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  1.5950 +** cause sqlite3_mutex_alloc() to create
  1.5951 +** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  1.5952 +** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  1.5953 +** The mutex implementation does not need to make a distinction
  1.5954 +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  1.5955 +** not want to.  ^SQLite will only request a recursive mutex in
  1.5956 +** cases where it really needs one.  ^If a faster non-recursive mutex
  1.5957 +** implementation is available on the host platform, the mutex subsystem
  1.5958 +** might return such a mutex in response to SQLITE_MUTEX_FAST.
  1.5959 +**
  1.5960 +** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  1.5961 +** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  1.5962 +** a pointer to a static preexisting mutex.  ^Six static mutexes are
  1.5963 +** used by the current version of SQLite.  Future versions of SQLite
  1.5964 +** may add additional static mutexes.  Static mutexes are for internal
  1.5965 +** use by SQLite only.  Applications that use SQLite mutexes should
  1.5966 +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  1.5967 +** SQLITE_MUTEX_RECURSIVE.
  1.5968 +**
  1.5969 +** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  1.5970 +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  1.5971 +** returns a different mutex on every call.  ^But for the static
  1.5972 +** mutex types, the same mutex is returned on every call that has
  1.5973 +** the same type number.
  1.5974 +**
  1.5975 +** ^The sqlite3_mutex_free() routine deallocates a previously
  1.5976 +** allocated dynamic mutex.  ^SQLite is careful to deallocate every
  1.5977 +** dynamic mutex that it allocates.  The dynamic mutexes must not be in
  1.5978 +** use when they are deallocated.  Attempting to deallocate a static
  1.5979 +** mutex results in undefined behavior.  ^SQLite never deallocates
  1.5980 +** a static mutex.
  1.5981 +**
  1.5982 +** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  1.5983 +** to enter a mutex.  ^If another thread is already within the mutex,
  1.5984 +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  1.5985 +** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  1.5986 +** upon successful entry.  ^(Mutexes created using
  1.5987 +** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  1.5988 +** In such cases the,
  1.5989 +** mutex must be exited an equal number of times before another thread
  1.5990 +** can enter.)^  ^(If the same thread tries to enter any other
  1.5991 +** kind of mutex more than once, the behavior is undefined.
  1.5992 +** SQLite will never exhibit
  1.5993 +** such behavior in its own use of mutexes.)^
  1.5994 +**
  1.5995 +** ^(Some systems (for example, Windows 95) do not support the operation
  1.5996 +** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
  1.5997 +** will always return SQLITE_BUSY.  The SQLite core only ever uses
  1.5998 +** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
  1.5999 +**
  1.6000 +** ^The sqlite3_mutex_leave() routine exits a mutex that was
  1.6001 +** previously entered by the same thread.   ^(The behavior
  1.6002 +** is undefined if the mutex is not currently entered by the
  1.6003 +** calling thread or is not currently allocated.  SQLite will
  1.6004 +** never do either.)^
  1.6005 +**
  1.6006 +** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  1.6007 +** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  1.6008 +** behave as no-ops.
  1.6009 +**
  1.6010 +** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  1.6011 +*/
  1.6012 +SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  1.6013 +SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  1.6014 +SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  1.6015 +SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  1.6016 +SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  1.6017 +
  1.6018 +/*
  1.6019 +** CAPI3REF: Mutex Methods Object
  1.6020 +**
  1.6021 +** An instance of this structure defines the low-level routines
  1.6022 +** used to allocate and use mutexes.
  1.6023 +**
  1.6024 +** Usually, the default mutex implementations provided by SQLite are
  1.6025 +** sufficient, however the user has the option of substituting a custom
  1.6026 +** implementation for specialized deployments or systems for which SQLite
  1.6027 +** does not provide a suitable implementation. In this case, the user
  1.6028 +** creates and populates an instance of this structure to pass
  1.6029 +** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  1.6030 +** Additionally, an instance of this structure can be used as an
  1.6031 +** output variable when querying the system for the current mutex
  1.6032 +** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  1.6033 +**
  1.6034 +** ^The xMutexInit method defined by this structure is invoked as
  1.6035 +** part of system initialization by the sqlite3_initialize() function.
  1.6036 +** ^The xMutexInit routine is called by SQLite exactly once for each
  1.6037 +** effective call to [sqlite3_initialize()].
  1.6038 +**
  1.6039 +** ^The xMutexEnd method defined by this structure is invoked as
  1.6040 +** part of system shutdown by the sqlite3_shutdown() function. The
  1.6041 +** implementation of this method is expected to release all outstanding
  1.6042 +** resources obtained by the mutex methods implementation, especially
  1.6043 +** those obtained by the xMutexInit method.  ^The xMutexEnd()
  1.6044 +** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  1.6045 +**
  1.6046 +** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  1.6047 +** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  1.6048 +** xMutexNotheld) implement the following interfaces (respectively):
  1.6049 +**
  1.6050 +** <ul>
  1.6051 +**   <li>  [sqlite3_mutex_alloc()] </li>
  1.6052 +**   <li>  [sqlite3_mutex_free()] </li>
  1.6053 +**   <li>  [sqlite3_mutex_enter()] </li>
  1.6054 +**   <li>  [sqlite3_mutex_try()] </li>
  1.6055 +**   <li>  [sqlite3_mutex_leave()] </li>
  1.6056 +**   <li>  [sqlite3_mutex_held()] </li>
  1.6057 +**   <li>  [sqlite3_mutex_notheld()] </li>
  1.6058 +** </ul>)^
  1.6059 +**
  1.6060 +** The only difference is that the public sqlite3_XXX functions enumerated
  1.6061 +** above silently ignore any invocations that pass a NULL pointer instead
  1.6062 +** of a valid mutex handle. The implementations of the methods defined
  1.6063 +** by this structure are not required to handle this case, the results
  1.6064 +** of passing a NULL pointer instead of a valid mutex handle are undefined
  1.6065 +** (i.e. it is acceptable to provide an implementation that segfaults if
  1.6066 +** it is passed a NULL pointer).
  1.6067 +**
  1.6068 +** The xMutexInit() method must be threadsafe.  ^It must be harmless to
  1.6069 +** invoke xMutexInit() multiple times within the same process and without
  1.6070 +** intervening calls to xMutexEnd().  Second and subsequent calls to
  1.6071 +** xMutexInit() must be no-ops.
  1.6072 +**
  1.6073 +** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  1.6074 +** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
  1.6075 +** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
  1.6076 +** memory allocation for a fast or recursive mutex.
  1.6077 +**
  1.6078 +** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  1.6079 +** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  1.6080 +** If xMutexInit fails in any way, it is expected to clean up after itself
  1.6081 +** prior to returning.
  1.6082 +*/
  1.6083 +typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  1.6084 +struct sqlite3_mutex_methods {
  1.6085 +  int (*xMutexInit)(void);
  1.6086 +  int (*xMutexEnd)(void);
  1.6087 +  sqlite3_mutex *(*xMutexAlloc)(int);
  1.6088 +  void (*xMutexFree)(sqlite3_mutex *);
  1.6089 +  void (*xMutexEnter)(sqlite3_mutex *);
  1.6090 +  int (*xMutexTry)(sqlite3_mutex *);
  1.6091 +  void (*xMutexLeave)(sqlite3_mutex *);
  1.6092 +  int (*xMutexHeld)(sqlite3_mutex *);
  1.6093 +  int (*xMutexNotheld)(sqlite3_mutex *);
  1.6094 +};
  1.6095 +
  1.6096 +/*
  1.6097 +** CAPI3REF: Mutex Verification Routines
  1.6098 +**
  1.6099 +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  1.6100 +** are intended for use inside assert() statements.  ^The SQLite core
  1.6101 +** never uses these routines except inside an assert() and applications
  1.6102 +** are advised to follow the lead of the core.  ^The SQLite core only
  1.6103 +** provides implementations for these routines when it is compiled
  1.6104 +** with the SQLITE_DEBUG flag.  ^External mutex implementations
  1.6105 +** are only required to provide these routines if SQLITE_DEBUG is
  1.6106 +** defined and if NDEBUG is not defined.
  1.6107 +**
  1.6108 +** ^These routines should return true if the mutex in their argument
  1.6109 +** is held or not held, respectively, by the calling thread.
  1.6110 +**
  1.6111 +** ^The implementation is not required to provide versions of these
  1.6112 +** routines that actually work. If the implementation does not provide working
  1.6113 +** versions of these routines, it should at least provide stubs that always
  1.6114 +** return true so that one does not get spurious assertion failures.
  1.6115 +**
  1.6116 +** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
  1.6117 +** the routine should return 1.   This seems counter-intuitive since
  1.6118 +** clearly the mutex cannot be held if it does not exist.  But
  1.6119 +** the reason the mutex does not exist is because the build is not
  1.6120 +** using mutexes.  And we do not want the assert() containing the
  1.6121 +** call to sqlite3_mutex_held() to fail, so a non-zero return is
  1.6122 +** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
  1.6123 +** interface should also return 1 when given a NULL pointer.
  1.6124 +*/
  1.6125 +#ifndef NDEBUG
  1.6126 +SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  1.6127 +SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  1.6128 +#endif
  1.6129 +
  1.6130 +/*
  1.6131 +** CAPI3REF: Mutex Types
  1.6132 +**
  1.6133 +** The [sqlite3_mutex_alloc()] interface takes a single argument
  1.6134 +** which is one of these integer constants.
  1.6135 +**
  1.6136 +** The set of static mutexes may change from one SQLite release to the
  1.6137 +** next.  Applications that override the built-in mutex logic must be
  1.6138 +** prepared to accommodate additional static mutexes.
  1.6139 +*/
  1.6140 +#define SQLITE_MUTEX_FAST             0
  1.6141 +#define SQLITE_MUTEX_RECURSIVE        1
  1.6142 +#define SQLITE_MUTEX_STATIC_MASTER    2
  1.6143 +#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
  1.6144 +#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
  1.6145 +#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
  1.6146 +#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
  1.6147 +#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
  1.6148 +#define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
  1.6149 +#define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
  1.6150 +
  1.6151 +/*
  1.6152 +** CAPI3REF: Retrieve the mutex for a database connection
  1.6153 +**
  1.6154 +** ^This interface returns a pointer the [sqlite3_mutex] object that 
  1.6155 +** serializes access to the [database connection] given in the argument
  1.6156 +** when the [threading mode] is Serialized.
  1.6157 +** ^If the [threading mode] is Single-thread or Multi-thread then this
  1.6158 +** routine returns a NULL pointer.
  1.6159 +*/
  1.6160 +SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  1.6161 +
  1.6162 +/*
  1.6163 +** CAPI3REF: Low-Level Control Of Database Files
  1.6164 +**
  1.6165 +** ^The [sqlite3_file_control()] interface makes a direct call to the
  1.6166 +** xFileControl method for the [sqlite3_io_methods] object associated
  1.6167 +** with a particular database identified by the second argument. ^The
  1.6168 +** name of the database is "main" for the main database or "temp" for the
  1.6169 +** TEMP database, or the name that appears after the AS keyword for
  1.6170 +** databases that are added using the [ATTACH] SQL command.
  1.6171 +** ^A NULL pointer can be used in place of "main" to refer to the
  1.6172 +** main database file.
  1.6173 +** ^The third and fourth parameters to this routine
  1.6174 +** are passed directly through to the second and third parameters of
  1.6175 +** the xFileControl method.  ^The return value of the xFileControl
  1.6176 +** method becomes the return value of this routine.
  1.6177 +**
  1.6178 +** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
  1.6179 +** a pointer to the underlying [sqlite3_file] object to be written into
  1.6180 +** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
  1.6181 +** case is a short-circuit path which does not actually invoke the
  1.6182 +** underlying sqlite3_io_methods.xFileControl method.
  1.6183 +**
  1.6184 +** ^If the second parameter (zDbName) does not match the name of any
  1.6185 +** open database file, then SQLITE_ERROR is returned.  ^This error
  1.6186 +** code is not remembered and will not be recalled by [sqlite3_errcode()]
  1.6187 +** or [sqlite3_errmsg()].  The underlying xFileControl method might
  1.6188 +** also return SQLITE_ERROR.  There is no way to distinguish between
  1.6189 +** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  1.6190 +** xFileControl method.
  1.6191 +**
  1.6192 +** See also: [SQLITE_FCNTL_LOCKSTATE]
  1.6193 +*/
  1.6194 +SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  1.6195 +
  1.6196 +/*
  1.6197 +** CAPI3REF: Testing Interface
  1.6198 +**
  1.6199 +** ^The sqlite3_test_control() interface is used to read out internal
  1.6200 +** state of SQLite and to inject faults into SQLite for testing
  1.6201 +** purposes.  ^The first parameter is an operation code that determines
  1.6202 +** the number, meaning, and operation of all subsequent parameters.
  1.6203 +**
  1.6204 +** This interface is not for use by applications.  It exists solely
  1.6205 +** for verifying the correct operation of the SQLite library.  Depending
  1.6206 +** on how the SQLite library is compiled, this interface might not exist.
  1.6207 +**
  1.6208 +** The details of the operation codes, their meanings, the parameters
  1.6209 +** they take, and what they do are all subject to change without notice.
  1.6210 +** Unlike most of the SQLite API, this function is not guaranteed to
  1.6211 +** operate consistently from one release to the next.
  1.6212 +*/
  1.6213 +SQLITE_API int sqlite3_test_control(int op, ...);
  1.6214 +
  1.6215 +/*
  1.6216 +** CAPI3REF: Testing Interface Operation Codes
  1.6217 +**
  1.6218 +** These constants are the valid operation code parameters used
  1.6219 +** as the first argument to [sqlite3_test_control()].
  1.6220 +**
  1.6221 +** These parameters and their meanings are subject to change
  1.6222 +** without notice.  These values are for testing purposes only.
  1.6223 +** Applications should not use any of these parameters or the
  1.6224 +** [sqlite3_test_control()] interface.
  1.6225 +*/
  1.6226 +#define SQLITE_TESTCTRL_FIRST                    5
  1.6227 +#define SQLITE_TESTCTRL_PRNG_SAVE                5
  1.6228 +#define SQLITE_TESTCTRL_PRNG_RESTORE             6
  1.6229 +#define SQLITE_TESTCTRL_PRNG_RESET               7
  1.6230 +#define SQLITE_TESTCTRL_BITVEC_TEST              8
  1.6231 +#define SQLITE_TESTCTRL_FAULT_INSTALL            9
  1.6232 +#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
  1.6233 +#define SQLITE_TESTCTRL_PENDING_BYTE            11
  1.6234 +#define SQLITE_TESTCTRL_ASSERT                  12
  1.6235 +#define SQLITE_TESTCTRL_ALWAYS                  13
  1.6236 +#define SQLITE_TESTCTRL_RESERVE                 14
  1.6237 +#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
  1.6238 +#define SQLITE_TESTCTRL_ISKEYWORD               16
  1.6239 +#define SQLITE_TESTCTRL_SCRATCHMALLOC           17
  1.6240 +#define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
  1.6241 +#define SQLITE_TESTCTRL_EXPLAIN_STMT            19
  1.6242 +#define SQLITE_TESTCTRL_NEVER_CORRUPT           20
  1.6243 +#define SQLITE_TESTCTRL_VDBE_COVERAGE           21
  1.6244 +#define SQLITE_TESTCTRL_LAST                    21
  1.6245 +
  1.6246 +/*
  1.6247 +** CAPI3REF: SQLite Runtime Status
  1.6248 +**
  1.6249 +** ^This interface is used to retrieve runtime status information
  1.6250 +** about the performance of SQLite, and optionally to reset various
  1.6251 +** highwater marks.  ^The first argument is an integer code for
  1.6252 +** the specific parameter to measure.  ^(Recognized integer codes
  1.6253 +** are of the form [status parameters | SQLITE_STATUS_...].)^
  1.6254 +** ^The current value of the parameter is returned into *pCurrent.
  1.6255 +** ^The highest recorded value is returned in *pHighwater.  ^If the
  1.6256 +** resetFlag is true, then the highest record value is reset after
  1.6257 +** *pHighwater is written.  ^(Some parameters do not record the highest
  1.6258 +** value.  For those parameters
  1.6259 +** nothing is written into *pHighwater and the resetFlag is ignored.)^
  1.6260 +** ^(Other parameters record only the highwater mark and not the current
  1.6261 +** value.  For these latter parameters nothing is written into *pCurrent.)^
  1.6262 +**
  1.6263 +** ^The sqlite3_status() routine returns SQLITE_OK on success and a
  1.6264 +** non-zero [error code] on failure.
  1.6265 +**
  1.6266 +** This routine is threadsafe but is not atomic.  This routine can be
  1.6267 +** called while other threads are running the same or different SQLite
  1.6268 +** interfaces.  However the values returned in *pCurrent and
  1.6269 +** *pHighwater reflect the status of SQLite at different points in time
  1.6270 +** and it is possible that another thread might change the parameter
  1.6271 +** in between the times when *pCurrent and *pHighwater are written.
  1.6272 +**
  1.6273 +** See also: [sqlite3_db_status()]
  1.6274 +*/
  1.6275 +SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  1.6276 +
  1.6277 +
  1.6278 +/*
  1.6279 +** CAPI3REF: Status Parameters
  1.6280 +** KEYWORDS: {status parameters}
  1.6281 +**
  1.6282 +** These integer constants designate various run-time status parameters
  1.6283 +** that can be returned by [sqlite3_status()].
  1.6284 +**
  1.6285 +** <dl>
  1.6286 +** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  1.6287 +** <dd>This parameter is the current amount of memory checked out
  1.6288 +** using [sqlite3_malloc()], either directly or indirectly.  The
  1.6289 +** figure includes calls made to [sqlite3_malloc()] by the application
  1.6290 +** and internal memory usage by the SQLite library.  Scratch memory
  1.6291 +** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
  1.6292 +** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  1.6293 +** this parameter.  The amount returned is the sum of the allocation
  1.6294 +** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  1.6295 +**
  1.6296 +** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  1.6297 +** <dd>This parameter records the largest memory allocation request
  1.6298 +** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  1.6299 +** internal equivalents).  Only the value returned in the
  1.6300 +** *pHighwater parameter to [sqlite3_status()] is of interest.  
  1.6301 +** The value written into the *pCurrent parameter is undefined.</dd>)^
  1.6302 +**
  1.6303 +** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  1.6304 +** <dd>This parameter records the number of separate memory allocations
  1.6305 +** currently checked out.</dd>)^
  1.6306 +**
  1.6307 +** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  1.6308 +** <dd>This parameter returns the number of pages used out of the
  1.6309 +** [pagecache memory allocator] that was configured using 
  1.6310 +** [SQLITE_CONFIG_PAGECACHE].  The
  1.6311 +** value returned is in pages, not in bytes.</dd>)^
  1.6312 +**
  1.6313 +** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] 
  1.6314 +** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  1.6315 +** <dd>This parameter returns the number of bytes of page cache
  1.6316 +** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  1.6317 +** buffer and where forced to overflow to [sqlite3_malloc()].  The
  1.6318 +** returned value includes allocations that overflowed because they
  1.6319 +** where too large (they were larger than the "sz" parameter to
  1.6320 +** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  1.6321 +** no space was left in the page cache.</dd>)^
  1.6322 +**
  1.6323 +** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  1.6324 +** <dd>This parameter records the largest memory allocation request
  1.6325 +** handed to [pagecache memory allocator].  Only the value returned in the
  1.6326 +** *pHighwater parameter to [sqlite3_status()] is of interest.  
  1.6327 +** The value written into the *pCurrent parameter is undefined.</dd>)^
  1.6328 +**
  1.6329 +** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
  1.6330 +** <dd>This parameter returns the number of allocations used out of the
  1.6331 +** [scratch memory allocator] configured using
  1.6332 +** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
  1.6333 +** in bytes.  Since a single thread may only have one scratch allocation
  1.6334 +** outstanding at time, this parameter also reports the number of threads
  1.6335 +** using scratch memory at the same time.</dd>)^
  1.6336 +**
  1.6337 +** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  1.6338 +** <dd>This parameter returns the number of bytes of scratch memory
  1.6339 +** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
  1.6340 +** buffer and where forced to overflow to [sqlite3_malloc()].  The values
  1.6341 +** returned include overflows because the requested allocation was too
  1.6342 +** larger (that is, because the requested allocation was larger than the
  1.6343 +** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
  1.6344 +** slots were available.
  1.6345 +** </dd>)^
  1.6346 +**
  1.6347 +** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  1.6348 +** <dd>This parameter records the largest memory allocation request
  1.6349 +** handed to [scratch memory allocator].  Only the value returned in the
  1.6350 +** *pHighwater parameter to [sqlite3_status()] is of interest.  
  1.6351 +** The value written into the *pCurrent parameter is undefined.</dd>)^
  1.6352 +**
  1.6353 +** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  1.6354 +** <dd>This parameter records the deepest parser stack.  It is only
  1.6355 +** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  1.6356 +** </dl>
  1.6357 +**
  1.6358 +** New status parameters may be added from time to time.
  1.6359 +*/
  1.6360 +#define SQLITE_STATUS_MEMORY_USED          0
  1.6361 +#define SQLITE_STATUS_PAGECACHE_USED       1
  1.6362 +#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
  1.6363 +#define SQLITE_STATUS_SCRATCH_USED         3
  1.6364 +#define SQLITE_STATUS_SCRATCH_OVERFLOW     4
  1.6365 +#define SQLITE_STATUS_MALLOC_SIZE          5
  1.6366 +#define SQLITE_STATUS_PARSER_STACK         6
  1.6367 +#define SQLITE_STATUS_PAGECACHE_SIZE       7
  1.6368 +#define SQLITE_STATUS_SCRATCH_SIZE         8
  1.6369 +#define SQLITE_STATUS_MALLOC_COUNT         9
  1.6370 +
  1.6371 +/*
  1.6372 +** CAPI3REF: Database Connection Status
  1.6373 +**
  1.6374 +** ^This interface is used to retrieve runtime status information 
  1.6375 +** about a single [database connection].  ^The first argument is the
  1.6376 +** database connection object to be interrogated.  ^The second argument
  1.6377 +** is an integer constant, taken from the set of
  1.6378 +** [SQLITE_DBSTATUS options], that
  1.6379 +** determines the parameter to interrogate.  The set of 
  1.6380 +** [SQLITE_DBSTATUS options] is likely
  1.6381 +** to grow in future releases of SQLite.
  1.6382 +**
  1.6383 +** ^The current value of the requested parameter is written into *pCur
  1.6384 +** and the highest instantaneous value is written into *pHiwtr.  ^If
  1.6385 +** the resetFlg is true, then the highest instantaneous value is
  1.6386 +** reset back down to the current value.
  1.6387 +**
  1.6388 +** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  1.6389 +** non-zero [error code] on failure.
  1.6390 +**
  1.6391 +** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  1.6392 +*/
  1.6393 +SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  1.6394 +
  1.6395 +/*
  1.6396 +** CAPI3REF: Status Parameters for database connections
  1.6397 +** KEYWORDS: {SQLITE_DBSTATUS options}
  1.6398 +**
  1.6399 +** These constants are the available integer "verbs" that can be passed as
  1.6400 +** the second argument to the [sqlite3_db_status()] interface.
  1.6401 +**
  1.6402 +** New verbs may be added in future releases of SQLite. Existing verbs
  1.6403 +** might be discontinued. Applications should check the return code from
  1.6404 +** [sqlite3_db_status()] to make sure that the call worked.
  1.6405 +** The [sqlite3_db_status()] interface will return a non-zero error code
  1.6406 +** if a discontinued or unsupported verb is invoked.
  1.6407 +**
  1.6408 +** <dl>
  1.6409 +** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  1.6410 +** <dd>This parameter returns the number of lookaside memory slots currently
  1.6411 +** checked out.</dd>)^
  1.6412 +**
  1.6413 +** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  1.6414 +** <dd>This parameter returns the number malloc attempts that were 
  1.6415 +** satisfied using lookaside memory. Only the high-water value is meaningful;
  1.6416 +** the current value is always zero.)^
  1.6417 +**
  1.6418 +** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  1.6419 +** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  1.6420 +** <dd>This parameter returns the number malloc attempts that might have
  1.6421 +** been satisfied using lookaside memory but failed due to the amount of
  1.6422 +** memory requested being larger than the lookaside slot size.
  1.6423 +** Only the high-water value is meaningful;
  1.6424 +** the current value is always zero.)^
  1.6425 +**
  1.6426 +** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  1.6427 +** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  1.6428 +** <dd>This parameter returns the number malloc attempts that might have
  1.6429 +** been satisfied using lookaside memory but failed due to all lookaside
  1.6430 +** memory already being in use.
  1.6431 +** Only the high-water value is meaningful;
  1.6432 +** the current value is always zero.)^
  1.6433 +**
  1.6434 +** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  1.6435 +** <dd>This parameter returns the approximate number of of bytes of heap
  1.6436 +** memory used by all pager caches associated with the database connection.)^
  1.6437 +** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  1.6438 +**
  1.6439 +** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  1.6440 +** <dd>This parameter returns the approximate number of of bytes of heap
  1.6441 +** memory used to store the schema for all databases associated
  1.6442 +** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
  1.6443 +** ^The full amount of memory used by the schemas is reported, even if the
  1.6444 +** schema memory is shared with other database connections due to
  1.6445 +** [shared cache mode] being enabled.
  1.6446 +** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  1.6447 +**
  1.6448 +** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  1.6449 +** <dd>This parameter returns the approximate number of of bytes of heap
  1.6450 +** and lookaside memory used by all prepared statements associated with
  1.6451 +** the database connection.)^
  1.6452 +** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  1.6453 +** </dd>
  1.6454 +**
  1.6455 +** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  1.6456 +** <dd>This parameter returns the number of pager cache hits that have
  1.6457 +** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT 
  1.6458 +** is always 0.
  1.6459 +** </dd>
  1.6460 +**
  1.6461 +** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  1.6462 +** <dd>This parameter returns the number of pager cache misses that have
  1.6463 +** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS 
  1.6464 +** is always 0.
  1.6465 +** </dd>
  1.6466 +**
  1.6467 +** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  1.6468 +** <dd>This parameter returns the number of dirty cache entries that have
  1.6469 +** been written to disk. Specifically, the number of pages written to the
  1.6470 +** wal file in wal mode databases, or the number of pages written to the
  1.6471 +** database file in rollback mode databases. Any pages written as part of
  1.6472 +** transaction rollback or database recovery operations are not included.
  1.6473 +** If an IO or other error occurs while writing a page to disk, the effect
  1.6474 +** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  1.6475 +** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  1.6476 +** </dd>
  1.6477 +**
  1.6478 +** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  1.6479 +** <dd>This parameter returns zero for the current value if and only if
  1.6480 +** all foreign key constraints (deferred or immediate) have been
  1.6481 +** resolved.)^  ^The highwater mark is always 0.
  1.6482 +** </dd>
  1.6483 +** </dl>
  1.6484 +*/
  1.6485 +#define SQLITE_DBSTATUS_LOOKASIDE_USED       0
  1.6486 +#define SQLITE_DBSTATUS_CACHE_USED           1
  1.6487 +#define SQLITE_DBSTATUS_SCHEMA_USED          2
  1.6488 +#define SQLITE_DBSTATUS_STMT_USED            3
  1.6489 +#define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
  1.6490 +#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
  1.6491 +#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
  1.6492 +#define SQLITE_DBSTATUS_CACHE_HIT            7
  1.6493 +#define SQLITE_DBSTATUS_CACHE_MISS           8
  1.6494 +#define SQLITE_DBSTATUS_CACHE_WRITE          9
  1.6495 +#define SQLITE_DBSTATUS_DEFERRED_FKS        10
  1.6496 +#define SQLITE_DBSTATUS_MAX                 10   /* Largest defined DBSTATUS */
  1.6497 +
  1.6498 +
  1.6499 +/*
  1.6500 +** CAPI3REF: Prepared Statement Status
  1.6501 +**
  1.6502 +** ^(Each prepared statement maintains various
  1.6503 +** [SQLITE_STMTSTATUS counters] that measure the number
  1.6504 +** of times it has performed specific operations.)^  These counters can
  1.6505 +** be used to monitor the performance characteristics of the prepared
  1.6506 +** statements.  For example, if the number of table steps greatly exceeds
  1.6507 +** the number of table searches or result rows, that would tend to indicate
  1.6508 +** that the prepared statement is using a full table scan rather than
  1.6509 +** an index.  
  1.6510 +**
  1.6511 +** ^(This interface is used to retrieve and reset counter values from
  1.6512 +** a [prepared statement].  The first argument is the prepared statement
  1.6513 +** object to be interrogated.  The second argument
  1.6514 +** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  1.6515 +** to be interrogated.)^
  1.6516 +** ^The current value of the requested counter is returned.
  1.6517 +** ^If the resetFlg is true, then the counter is reset to zero after this
  1.6518 +** interface call returns.
  1.6519 +**
  1.6520 +** See also: [sqlite3_status()] and [sqlite3_db_status()].
  1.6521 +*/
  1.6522 +SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  1.6523 +
  1.6524 +/*
  1.6525 +** CAPI3REF: Status Parameters for prepared statements
  1.6526 +** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  1.6527 +**
  1.6528 +** These preprocessor macros define integer codes that name counter
  1.6529 +** values associated with the [sqlite3_stmt_status()] interface.
  1.6530 +** The meanings of the various counters are as follows:
  1.6531 +**
  1.6532 +** <dl>
  1.6533 +** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  1.6534 +** <dd>^This is the number of times that SQLite has stepped forward in
  1.6535 +** a table as part of a full table scan.  Large numbers for this counter
  1.6536 +** may indicate opportunities for performance improvement through 
  1.6537 +** careful use of indices.</dd>
  1.6538 +**
  1.6539 +** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  1.6540 +** <dd>^This is the number of sort operations that have occurred.
  1.6541 +** A non-zero value in this counter may indicate an opportunity to
  1.6542 +** improvement performance through careful use of indices.</dd>
  1.6543 +**
  1.6544 +** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  1.6545 +** <dd>^This is the number of rows inserted into transient indices that
  1.6546 +** were created automatically in order to help joins run faster.
  1.6547 +** A non-zero value in this counter may indicate an opportunity to
  1.6548 +** improvement performance by adding permanent indices that do not
  1.6549 +** need to be reinitialized each time the statement is run.</dd>
  1.6550 +**
  1.6551 +** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  1.6552 +** <dd>^This is the number of virtual machine operations executed
  1.6553 +** by the prepared statement if that number is less than or equal
  1.6554 +** to 2147483647.  The number of virtual machine operations can be 
  1.6555 +** used as a proxy for the total work done by the prepared statement.
  1.6556 +** If the number of virtual machine operations exceeds 2147483647
  1.6557 +** then the value returned by this statement status code is undefined.
  1.6558 +** </dd>
  1.6559 +** </dl>
  1.6560 +*/
  1.6561 +#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
  1.6562 +#define SQLITE_STMTSTATUS_SORT              2
  1.6563 +#define SQLITE_STMTSTATUS_AUTOINDEX         3
  1.6564 +#define SQLITE_STMTSTATUS_VM_STEP           4
  1.6565 +
  1.6566 +/*
  1.6567 +** CAPI3REF: Custom Page Cache Object
  1.6568 +**
  1.6569 +** The sqlite3_pcache type is opaque.  It is implemented by
  1.6570 +** the pluggable module.  The SQLite core has no knowledge of
  1.6571 +** its size or internal structure and never deals with the
  1.6572 +** sqlite3_pcache object except by holding and passing pointers
  1.6573 +** to the object.
  1.6574 +**
  1.6575 +** See [sqlite3_pcache_methods2] for additional information.
  1.6576 +*/
  1.6577 +typedef struct sqlite3_pcache sqlite3_pcache;
  1.6578 +
  1.6579 +/*
  1.6580 +** CAPI3REF: Custom Page Cache Object
  1.6581 +**
  1.6582 +** The sqlite3_pcache_page object represents a single page in the
  1.6583 +** page cache.  The page cache will allocate instances of this
  1.6584 +** object.  Various methods of the page cache use pointers to instances
  1.6585 +** of this object as parameters or as their return value.
  1.6586 +**
  1.6587 +** See [sqlite3_pcache_methods2] for additional information.
  1.6588 +*/
  1.6589 +typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  1.6590 +struct sqlite3_pcache_page {
  1.6591 +  void *pBuf;        /* The content of the page */
  1.6592 +  void *pExtra;      /* Extra information associated with the page */
  1.6593 +};
  1.6594 +
  1.6595 +/*
  1.6596 +** CAPI3REF: Application Defined Page Cache.
  1.6597 +** KEYWORDS: {page cache}
  1.6598 +**
  1.6599 +** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  1.6600 +** register an alternative page cache implementation by passing in an 
  1.6601 +** instance of the sqlite3_pcache_methods2 structure.)^
  1.6602 +** In many applications, most of the heap memory allocated by 
  1.6603 +** SQLite is used for the page cache.
  1.6604 +** By implementing a 
  1.6605 +** custom page cache using this API, an application can better control
  1.6606 +** the amount of memory consumed by SQLite, the way in which 
  1.6607 +** that memory is allocated and released, and the policies used to 
  1.6608 +** determine exactly which parts of a database file are cached and for 
  1.6609 +** how long.
  1.6610 +**
  1.6611 +** The alternative page cache mechanism is an
  1.6612 +** extreme measure that is only needed by the most demanding applications.
  1.6613 +** The built-in page cache is recommended for most uses.
  1.6614 +**
  1.6615 +** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  1.6616 +** internal buffer by SQLite within the call to [sqlite3_config].  Hence
  1.6617 +** the application may discard the parameter after the call to
  1.6618 +** [sqlite3_config()] returns.)^
  1.6619 +**
  1.6620 +** [[the xInit() page cache method]]
  1.6621 +** ^(The xInit() method is called once for each effective 
  1.6622 +** call to [sqlite3_initialize()])^
  1.6623 +** (usually only once during the lifetime of the process). ^(The xInit()
  1.6624 +** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  1.6625 +** The intent of the xInit() method is to set up global data structures 
  1.6626 +** required by the custom page cache implementation. 
  1.6627 +** ^(If the xInit() method is NULL, then the 
  1.6628 +** built-in default page cache is used instead of the application defined
  1.6629 +** page cache.)^
  1.6630 +**
  1.6631 +** [[the xShutdown() page cache method]]
  1.6632 +** ^The xShutdown() method is called by [sqlite3_shutdown()].
  1.6633 +** It can be used to clean up 
  1.6634 +** any outstanding resources before process shutdown, if required.
  1.6635 +** ^The xShutdown() method may be NULL.
  1.6636 +**
  1.6637 +** ^SQLite automatically serializes calls to the xInit method,
  1.6638 +** so the xInit method need not be threadsafe.  ^The
  1.6639 +** xShutdown method is only called from [sqlite3_shutdown()] so it does
  1.6640 +** not need to be threadsafe either.  All other methods must be threadsafe
  1.6641 +** in multithreaded applications.
  1.6642 +**
  1.6643 +** ^SQLite will never invoke xInit() more than once without an intervening
  1.6644 +** call to xShutdown().
  1.6645 +**
  1.6646 +** [[the xCreate() page cache methods]]
  1.6647 +** ^SQLite invokes the xCreate() method to construct a new cache instance.
  1.6648 +** SQLite will typically create one cache instance for each open database file,
  1.6649 +** though this is not guaranteed. ^The
  1.6650 +** first parameter, szPage, is the size in bytes of the pages that must
  1.6651 +** be allocated by the cache.  ^szPage will always a power of two.  ^The
  1.6652 +** second parameter szExtra is a number of bytes of extra storage 
  1.6653 +** associated with each page cache entry.  ^The szExtra parameter will
  1.6654 +** a number less than 250.  SQLite will use the
  1.6655 +** extra szExtra bytes on each page to store metadata about the underlying
  1.6656 +** database page on disk.  The value passed into szExtra depends
  1.6657 +** on the SQLite version, the target platform, and how SQLite was compiled.
  1.6658 +** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  1.6659 +** created will be used to cache database pages of a file stored on disk, or
  1.6660 +** false if it is used for an in-memory database. The cache implementation
  1.6661 +** does not have to do anything special based with the value of bPurgeable;
  1.6662 +** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
  1.6663 +** never invoke xUnpin() except to deliberately delete a page.
  1.6664 +** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  1.6665 +** false will always have the "discard" flag set to true.  
  1.6666 +** ^Hence, a cache created with bPurgeable false will
  1.6667 +** never contain any unpinned pages.
  1.6668 +**
  1.6669 +** [[the xCachesize() page cache method]]
  1.6670 +** ^(The xCachesize() method may be called at any time by SQLite to set the
  1.6671 +** suggested maximum cache-size (number of pages stored by) the cache
  1.6672 +** instance passed as the first argument. This is the value configured using
  1.6673 +** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
  1.6674 +** parameter, the implementation is not required to do anything with this
  1.6675 +** value; it is advisory only.
  1.6676 +**
  1.6677 +** [[the xPagecount() page cache methods]]
  1.6678 +** The xPagecount() method must return the number of pages currently
  1.6679 +** stored in the cache, both pinned and unpinned.
  1.6680 +** 
  1.6681 +** [[the xFetch() page cache methods]]
  1.6682 +** The xFetch() method locates a page in the cache and returns a pointer to 
  1.6683 +** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  1.6684 +** The pBuf element of the returned sqlite3_pcache_page object will be a
  1.6685 +** pointer to a buffer of szPage bytes used to store the content of a 
  1.6686 +** single database page.  The pExtra element of sqlite3_pcache_page will be
  1.6687 +** a pointer to the szExtra bytes of extra storage that SQLite has requested
  1.6688 +** for each entry in the page cache.
  1.6689 +**
  1.6690 +** The page to be fetched is determined by the key. ^The minimum key value
  1.6691 +** is 1.  After it has been retrieved using xFetch, the page is considered
  1.6692 +** to be "pinned".
  1.6693 +**
  1.6694 +** If the requested page is already in the page cache, then the page cache
  1.6695 +** implementation must return a pointer to the page buffer with its content
  1.6696 +** intact.  If the requested page is not already in the cache, then the
  1.6697 +** cache implementation should use the value of the createFlag
  1.6698 +** parameter to help it determined what action to take:
  1.6699 +**
  1.6700 +** <table border=1 width=85% align=center>
  1.6701 +** <tr><th> createFlag <th> Behavior when page is not already in cache
  1.6702 +** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
  1.6703 +** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  1.6704 +**                 Otherwise return NULL.
  1.6705 +** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
  1.6706 +**                 NULL if allocating a new page is effectively impossible.
  1.6707 +** </table>
  1.6708 +**
  1.6709 +** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
  1.6710 +** will only use a createFlag of 2 after a prior call with a createFlag of 1
  1.6711 +** failed.)^  In between the to xFetch() calls, SQLite may
  1.6712 +** attempt to unpin one or more cache pages by spilling the content of
  1.6713 +** pinned pages to disk and synching the operating system disk cache.
  1.6714 +**
  1.6715 +** [[the xUnpin() page cache method]]
  1.6716 +** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  1.6717 +** as its second argument.  If the third parameter, discard, is non-zero,
  1.6718 +** then the page must be evicted from the cache.
  1.6719 +** ^If the discard parameter is
  1.6720 +** zero, then the page may be discarded or retained at the discretion of
  1.6721 +** page cache implementation. ^The page cache implementation
  1.6722 +** may choose to evict unpinned pages at any time.
  1.6723 +**
  1.6724 +** The cache must not perform any reference counting. A single 
  1.6725 +** call to xUnpin() unpins the page regardless of the number of prior calls 
  1.6726 +** to xFetch().
  1.6727 +**
  1.6728 +** [[the xRekey() page cache methods]]
  1.6729 +** The xRekey() method is used to change the key value associated with the
  1.6730 +** page passed as the second argument. If the cache
  1.6731 +** previously contains an entry associated with newKey, it must be
  1.6732 +** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  1.6733 +** to be pinned.
  1.6734 +**
  1.6735 +** When SQLite calls the xTruncate() method, the cache must discard all
  1.6736 +** existing cache entries with page numbers (keys) greater than or equal
  1.6737 +** to the value of the iLimit parameter passed to xTruncate(). If any
  1.6738 +** of these pages are pinned, they are implicitly unpinned, meaning that
  1.6739 +** they can be safely discarded.
  1.6740 +**
  1.6741 +** [[the xDestroy() page cache method]]
  1.6742 +** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  1.6743 +** All resources associated with the specified cache should be freed. ^After
  1.6744 +** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  1.6745 +** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  1.6746 +** functions.
  1.6747 +**
  1.6748 +** [[the xShrink() page cache method]]
  1.6749 +** ^SQLite invokes the xShrink() method when it wants the page cache to
  1.6750 +** free up as much of heap memory as possible.  The page cache implementation
  1.6751 +** is not obligated to free any memory, but well-behaved implementations should
  1.6752 +** do their best.
  1.6753 +*/
  1.6754 +typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  1.6755 +struct sqlite3_pcache_methods2 {
  1.6756 +  int iVersion;
  1.6757 +  void *pArg;
  1.6758 +  int (*xInit)(void*);
  1.6759 +  void (*xShutdown)(void*);
  1.6760 +  sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  1.6761 +  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  1.6762 +  int (*xPagecount)(sqlite3_pcache*);
  1.6763 +  sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  1.6764 +  void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  1.6765 +  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, 
  1.6766 +      unsigned oldKey, unsigned newKey);
  1.6767 +  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  1.6768 +  void (*xDestroy)(sqlite3_pcache*);
  1.6769 +  void (*xShrink)(sqlite3_pcache*);
  1.6770 +};
  1.6771 +
  1.6772 +/*
  1.6773 +** This is the obsolete pcache_methods object that has now been replaced
  1.6774 +** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
  1.6775 +** retained in the header file for backwards compatibility only.
  1.6776 +*/
  1.6777 +typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  1.6778 +struct sqlite3_pcache_methods {
  1.6779 +  void *pArg;
  1.6780 +  int (*xInit)(void*);
  1.6781 +  void (*xShutdown)(void*);
  1.6782 +  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  1.6783 +  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  1.6784 +  int (*xPagecount)(sqlite3_pcache*);
  1.6785 +  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  1.6786 +  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  1.6787 +  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  1.6788 +  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  1.6789 +  void (*xDestroy)(sqlite3_pcache*);
  1.6790 +};
  1.6791 +
  1.6792 +
  1.6793 +/*
  1.6794 +** CAPI3REF: Online Backup Object
  1.6795 +**
  1.6796 +** The sqlite3_backup object records state information about an ongoing
  1.6797 +** online backup operation.  ^The sqlite3_backup object is created by
  1.6798 +** a call to [sqlite3_backup_init()] and is destroyed by a call to
  1.6799 +** [sqlite3_backup_finish()].
  1.6800 +**
  1.6801 +** See Also: [Using the SQLite Online Backup API]
  1.6802 +*/
  1.6803 +typedef struct sqlite3_backup sqlite3_backup;
  1.6804 +
  1.6805 +/*
  1.6806 +** CAPI3REF: Online Backup API.
  1.6807 +**
  1.6808 +** The backup API copies the content of one database into another.
  1.6809 +** It is useful either for creating backups of databases or
  1.6810 +** for copying in-memory databases to or from persistent files. 
  1.6811 +**
  1.6812 +** See Also: [Using the SQLite Online Backup API]
  1.6813 +**
  1.6814 +** ^SQLite holds a write transaction open on the destination database file
  1.6815 +** for the duration of the backup operation.
  1.6816 +** ^The source database is read-locked only while it is being read;
  1.6817 +** it is not locked continuously for the entire backup operation.
  1.6818 +** ^Thus, the backup may be performed on a live source database without
  1.6819 +** preventing other database connections from
  1.6820 +** reading or writing to the source database while the backup is underway.
  1.6821 +** 
  1.6822 +** ^(To perform a backup operation: 
  1.6823 +**   <ol>
  1.6824 +**     <li><b>sqlite3_backup_init()</b> is called once to initialize the
  1.6825 +**         backup, 
  1.6826 +**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
  1.6827 +**         the data between the two databases, and finally
  1.6828 +**     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
  1.6829 +**         associated with the backup operation. 
  1.6830 +**   </ol>)^
  1.6831 +** There should be exactly one call to sqlite3_backup_finish() for each
  1.6832 +** successful call to sqlite3_backup_init().
  1.6833 +**
  1.6834 +** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  1.6835 +**
  1.6836 +** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
  1.6837 +** [database connection] associated with the destination database 
  1.6838 +** and the database name, respectively.
  1.6839 +** ^The database name is "main" for the main database, "temp" for the
  1.6840 +** temporary database, or the name specified after the AS keyword in
  1.6841 +** an [ATTACH] statement for an attached database.
  1.6842 +** ^The S and M arguments passed to 
  1.6843 +** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  1.6844 +** and database name of the source database, respectively.
  1.6845 +** ^The source and destination [database connections] (parameters S and D)
  1.6846 +** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  1.6847 +** an error.
  1.6848 +**
  1.6849 +** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  1.6850 +** returned and an error code and error message are stored in the
  1.6851 +** destination [database connection] D.
  1.6852 +** ^The error code and message for the failed call to sqlite3_backup_init()
  1.6853 +** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  1.6854 +** [sqlite3_errmsg16()] functions.
  1.6855 +** ^A successful call to sqlite3_backup_init() returns a pointer to an
  1.6856 +** [sqlite3_backup] object.
  1.6857 +** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  1.6858 +** sqlite3_backup_finish() functions to perform the specified backup 
  1.6859 +** operation.
  1.6860 +**
  1.6861 +** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  1.6862 +**
  1.6863 +** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
  1.6864 +** the source and destination databases specified by [sqlite3_backup] object B.
  1.6865 +** ^If N is negative, all remaining source pages are copied. 
  1.6866 +** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  1.6867 +** are still more pages to be copied, then the function returns [SQLITE_OK].
  1.6868 +** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  1.6869 +** from source to destination, then it returns [SQLITE_DONE].
  1.6870 +** ^If an error occurs while running sqlite3_backup_step(B,N),
  1.6871 +** then an [error code] is returned. ^As well as [SQLITE_OK] and
  1.6872 +** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  1.6873 +** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  1.6874 +** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  1.6875 +**
  1.6876 +** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  1.6877 +** <ol>
  1.6878 +** <li> the destination database was opened read-only, or
  1.6879 +** <li> the destination database is using write-ahead-log journaling
  1.6880 +** and the destination and source page sizes differ, or
  1.6881 +** <li> the destination database is an in-memory database and the
  1.6882 +** destination and source page sizes differ.
  1.6883 +** </ol>)^
  1.6884 +**
  1.6885 +** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  1.6886 +** the [sqlite3_busy_handler | busy-handler function]
  1.6887 +** is invoked (if one is specified). ^If the 
  1.6888 +** busy-handler returns non-zero before the lock is available, then 
  1.6889 +** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  1.6890 +** sqlite3_backup_step() can be retried later. ^If the source
  1.6891 +** [database connection]
  1.6892 +** is being used to write to the source database when sqlite3_backup_step()
  1.6893 +** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  1.6894 +** case the call to sqlite3_backup_step() can be retried later on. ^(If
  1.6895 +** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  1.6896 +** [SQLITE_READONLY] is returned, then 
  1.6897 +** there is no point in retrying the call to sqlite3_backup_step(). These 
  1.6898 +** errors are considered fatal.)^  The application must accept 
  1.6899 +** that the backup operation has failed and pass the backup operation handle 
  1.6900 +** to the sqlite3_backup_finish() to release associated resources.
  1.6901 +**
  1.6902 +** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  1.6903 +** on the destination file. ^The exclusive lock is not released until either 
  1.6904 +** sqlite3_backup_finish() is called or the backup operation is complete 
  1.6905 +** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
  1.6906 +** sqlite3_backup_step() obtains a [shared lock] on the source database that
  1.6907 +** lasts for the duration of the sqlite3_backup_step() call.
  1.6908 +** ^Because the source database is not locked between calls to
  1.6909 +** sqlite3_backup_step(), the source database may be modified mid-way
  1.6910 +** through the backup process.  ^If the source database is modified by an
  1.6911 +** external process or via a database connection other than the one being
  1.6912 +** used by the backup operation, then the backup will be automatically
  1.6913 +** restarted by the next call to sqlite3_backup_step(). ^If the source 
  1.6914 +** database is modified by the using the same database connection as is used
  1.6915 +** by the backup operation, then the backup database is automatically
  1.6916 +** updated at the same time.
  1.6917 +**
  1.6918 +** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  1.6919 +**
  1.6920 +** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
  1.6921 +** application wishes to abandon the backup operation, the application
  1.6922 +** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  1.6923 +** ^The sqlite3_backup_finish() interfaces releases all
  1.6924 +** resources associated with the [sqlite3_backup] object. 
  1.6925 +** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  1.6926 +** active write-transaction on the destination database is rolled back.
  1.6927 +** The [sqlite3_backup] object is invalid
  1.6928 +** and may not be used following a call to sqlite3_backup_finish().
  1.6929 +**
  1.6930 +** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  1.6931 +** sqlite3_backup_step() errors occurred, regardless or whether or not
  1.6932 +** sqlite3_backup_step() completed.
  1.6933 +** ^If an out-of-memory condition or IO error occurred during any prior
  1.6934 +** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  1.6935 +** sqlite3_backup_finish() returns the corresponding [error code].
  1.6936 +**
  1.6937 +** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  1.6938 +** is not a permanent error and does not affect the return value of
  1.6939 +** sqlite3_backup_finish().
  1.6940 +**
  1.6941 +** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
  1.6942 +** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  1.6943 +**
  1.6944 +** ^Each call to sqlite3_backup_step() sets two values inside
  1.6945 +** the [sqlite3_backup] object: the number of pages still to be backed
  1.6946 +** up and the total number of pages in the source database file.
  1.6947 +** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
  1.6948 +** retrieve these two values, respectively.
  1.6949 +**
  1.6950 +** ^The values returned by these functions are only updated by
  1.6951 +** sqlite3_backup_step(). ^If the source database is modified during a backup
  1.6952 +** operation, then the values are not updated to account for any extra
  1.6953 +** pages that need to be updated or the size of the source database file
  1.6954 +** changing.
  1.6955 +**
  1.6956 +** <b>Concurrent Usage of Database Handles</b>
  1.6957 +**
  1.6958 +** ^The source [database connection] may be used by the application for other
  1.6959 +** purposes while a backup operation is underway or being initialized.
  1.6960 +** ^If SQLite is compiled and configured to support threadsafe database
  1.6961 +** connections, then the source database connection may be used concurrently
  1.6962 +** from within other threads.
  1.6963 +**
  1.6964 +** However, the application must guarantee that the destination 
  1.6965 +** [database connection] is not passed to any other API (by any thread) after 
  1.6966 +** sqlite3_backup_init() is called and before the corresponding call to
  1.6967 +** sqlite3_backup_finish().  SQLite does not currently check to see
  1.6968 +** if the application incorrectly accesses the destination [database connection]
  1.6969 +** and so no error code is reported, but the operations may malfunction
  1.6970 +** nevertheless.  Use of the destination database connection while a
  1.6971 +** backup is in progress might also also cause a mutex deadlock.
  1.6972 +**
  1.6973 +** If running in [shared cache mode], the application must
  1.6974 +** guarantee that the shared cache used by the destination database
  1.6975 +** is not accessed while the backup is running. In practice this means
  1.6976 +** that the application must guarantee that the disk file being 
  1.6977 +** backed up to is not accessed by any connection within the process,
  1.6978 +** not just the specific connection that was passed to sqlite3_backup_init().
  1.6979 +**
  1.6980 +** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
  1.6981 +** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  1.6982 +** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  1.6983 +** APIs are not strictly speaking threadsafe. If they are invoked at the
  1.6984 +** same time as another thread is invoking sqlite3_backup_step() it is
  1.6985 +** possible that they return invalid values.
  1.6986 +*/
  1.6987 +SQLITE_API sqlite3_backup *sqlite3_backup_init(
  1.6988 +  sqlite3 *pDest,                        /* Destination database handle */
  1.6989 +  const char *zDestName,                 /* Destination database name */
  1.6990 +  sqlite3 *pSource,                      /* Source database handle */
  1.6991 +  const char *zSourceName                /* Source database name */
  1.6992 +);
  1.6993 +SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  1.6994 +SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  1.6995 +SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  1.6996 +SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  1.6997 +
  1.6998 +/*
  1.6999 +** CAPI3REF: Unlock Notification
  1.7000 +**
  1.7001 +** ^When running in shared-cache mode, a database operation may fail with
  1.7002 +** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  1.7003 +** individual tables within the shared-cache cannot be obtained. See
  1.7004 +** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
  1.7005 +** ^This API may be used to register a callback that SQLite will invoke 
  1.7006 +** when the connection currently holding the required lock relinquishes it.
  1.7007 +** ^This API is only available if the library was compiled with the
  1.7008 +** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  1.7009 +**
  1.7010 +** See Also: [Using the SQLite Unlock Notification Feature].
  1.7011 +**
  1.7012 +** ^Shared-cache locks are released when a database connection concludes
  1.7013 +** its current transaction, either by committing it or rolling it back. 
  1.7014 +**
  1.7015 +** ^When a connection (known as the blocked connection) fails to obtain a
  1.7016 +** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  1.7017 +** identity of the database connection (the blocking connection) that
  1.7018 +** has locked the required resource is stored internally. ^After an 
  1.7019 +** application receives an SQLITE_LOCKED error, it may call the
  1.7020 +** sqlite3_unlock_notify() method with the blocked connection handle as 
  1.7021 +** the first argument to register for a callback that will be invoked
  1.7022 +** when the blocking connections current transaction is concluded. ^The
  1.7023 +** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  1.7024 +** call that concludes the blocking connections transaction.
  1.7025 +**
  1.7026 +** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  1.7027 +** there is a chance that the blocking connection will have already
  1.7028 +** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  1.7029 +** If this happens, then the specified callback is invoked immediately,
  1.7030 +** from within the call to sqlite3_unlock_notify().)^
  1.7031 +**
  1.7032 +** ^If the blocked connection is attempting to obtain a write-lock on a
  1.7033 +** shared-cache table, and more than one other connection currently holds
  1.7034 +** a read-lock on the same table, then SQLite arbitrarily selects one of 
  1.7035 +** the other connections to use as the blocking connection.
  1.7036 +**
  1.7037 +** ^(There may be at most one unlock-notify callback registered by a 
  1.7038 +** blocked connection. If sqlite3_unlock_notify() is called when the
  1.7039 +** blocked connection already has a registered unlock-notify callback,
  1.7040 +** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  1.7041 +** called with a NULL pointer as its second argument, then any existing
  1.7042 +** unlock-notify callback is canceled. ^The blocked connections 
  1.7043 +** unlock-notify callback may also be canceled by closing the blocked
  1.7044 +** connection using [sqlite3_close()].
  1.7045 +**
  1.7046 +** The unlock-notify callback is not reentrant. If an application invokes
  1.7047 +** any sqlite3_xxx API functions from within an unlock-notify callback, a
  1.7048 +** crash or deadlock may be the result.
  1.7049 +**
  1.7050 +** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  1.7051 +** returns SQLITE_OK.
  1.7052 +**
  1.7053 +** <b>Callback Invocation Details</b>
  1.7054 +**
  1.7055 +** When an unlock-notify callback is registered, the application provides a 
  1.7056 +** single void* pointer that is passed to the callback when it is invoked.
  1.7057 +** However, the signature of the callback function allows SQLite to pass
  1.7058 +** it an array of void* context pointers. The first argument passed to
  1.7059 +** an unlock-notify callback is a pointer to an array of void* pointers,
  1.7060 +** and the second is the number of entries in the array.
  1.7061 +**
  1.7062 +** When a blocking connections transaction is concluded, there may be
  1.7063 +** more than one blocked connection that has registered for an unlock-notify
  1.7064 +** callback. ^If two or more such blocked connections have specified the
  1.7065 +** same callback function, then instead of invoking the callback function
  1.7066 +** multiple times, it is invoked once with the set of void* context pointers
  1.7067 +** specified by the blocked connections bundled together into an array.
  1.7068 +** This gives the application an opportunity to prioritize any actions 
  1.7069 +** related to the set of unblocked database connections.
  1.7070 +**
  1.7071 +** <b>Deadlock Detection</b>
  1.7072 +**
  1.7073 +** Assuming that after registering for an unlock-notify callback a 
  1.7074 +** database waits for the callback to be issued before taking any further
  1.7075 +** action (a reasonable assumption), then using this API may cause the
  1.7076 +** application to deadlock. For example, if connection X is waiting for
  1.7077 +** connection Y's transaction to be concluded, and similarly connection
  1.7078 +** Y is waiting on connection X's transaction, then neither connection
  1.7079 +** will proceed and the system may remain deadlocked indefinitely.
  1.7080 +**
  1.7081 +** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  1.7082 +** detection. ^If a given call to sqlite3_unlock_notify() would put the
  1.7083 +** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  1.7084 +** unlock-notify callback is registered. The system is said to be in
  1.7085 +** a deadlocked state if connection A has registered for an unlock-notify
  1.7086 +** callback on the conclusion of connection B's transaction, and connection
  1.7087 +** B has itself registered for an unlock-notify callback when connection
  1.7088 +** A's transaction is concluded. ^Indirect deadlock is also detected, so
  1.7089 +** the system is also considered to be deadlocked if connection B has
  1.7090 +** registered for an unlock-notify callback on the conclusion of connection
  1.7091 +** C's transaction, where connection C is waiting on connection A. ^Any
  1.7092 +** number of levels of indirection are allowed.
  1.7093 +**
  1.7094 +** <b>The "DROP TABLE" Exception</b>
  1.7095 +**
  1.7096 +** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
  1.7097 +** always appropriate to call sqlite3_unlock_notify(). There is however,
  1.7098 +** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  1.7099 +** SQLite checks if there are any currently executing SELECT statements
  1.7100 +** that belong to the same connection. If there are, SQLITE_LOCKED is
  1.7101 +** returned. In this case there is no "blocking connection", so invoking
  1.7102 +** sqlite3_unlock_notify() results in the unlock-notify callback being
  1.7103 +** invoked immediately. If the application then re-attempts the "DROP TABLE"
  1.7104 +** or "DROP INDEX" query, an infinite loop might be the result.
  1.7105 +**
  1.7106 +** One way around this problem is to check the extended error code returned
  1.7107 +** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  1.7108 +** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  1.7109 +** the special "DROP TABLE/INDEX" case, the extended error code is just 
  1.7110 +** SQLITE_LOCKED.)^
  1.7111 +*/
  1.7112 +SQLITE_API int sqlite3_unlock_notify(
  1.7113 +  sqlite3 *pBlocked,                          /* Waiting connection */
  1.7114 +  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
  1.7115 +  void *pNotifyArg                            /* Argument to pass to xNotify */
  1.7116 +);
  1.7117 +
  1.7118 +
  1.7119 +/*
  1.7120 +** CAPI3REF: String Comparison
  1.7121 +**
  1.7122 +** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  1.7123 +** and extensions to compare the contents of two buffers containing UTF-8
  1.7124 +** strings in a case-independent fashion, using the same definition of "case
  1.7125 +** independence" that SQLite uses internally when comparing identifiers.
  1.7126 +*/
  1.7127 +SQLITE_API int sqlite3_stricmp(const char *, const char *);
  1.7128 +SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  1.7129 +
  1.7130 +/*
  1.7131 +** CAPI3REF: String Globbing
  1.7132 +*
  1.7133 +** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
  1.7134 +** the glob pattern P, and it returns non-zero if string X does not match
  1.7135 +** the glob pattern P.  ^The definition of glob pattern matching used in
  1.7136 +** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  1.7137 +** SQL dialect used by SQLite.  ^The sqlite3_strglob(P,X) function is case
  1.7138 +** sensitive.
  1.7139 +**
  1.7140 +** Note that this routine returns zero on a match and non-zero if the strings
  1.7141 +** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  1.7142 +*/
  1.7143 +SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
  1.7144 +
  1.7145 +/*
  1.7146 +** CAPI3REF: Error Logging Interface
  1.7147 +**
  1.7148 +** ^The [sqlite3_log()] interface writes a message into the [error log]
  1.7149 +** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  1.7150 +** ^If logging is enabled, the zFormat string and subsequent arguments are
  1.7151 +** used with [sqlite3_snprintf()] to generate the final output string.
  1.7152 +**
  1.7153 +** The sqlite3_log() interface is intended for use by extensions such as
  1.7154 +** virtual tables, collating functions, and SQL functions.  While there is
  1.7155 +** nothing to prevent an application from calling sqlite3_log(), doing so
  1.7156 +** is considered bad form.
  1.7157 +**
  1.7158 +** The zFormat string must not be NULL.
  1.7159 +**
  1.7160 +** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  1.7161 +** will not use dynamically allocated memory.  The log message is stored in
  1.7162 +** a fixed-length buffer on the stack.  If the log message is longer than
  1.7163 +** a few hundred characters, it will be truncated to the length of the
  1.7164 +** buffer.
  1.7165 +*/
  1.7166 +SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  1.7167 +
  1.7168 +/*
  1.7169 +** CAPI3REF: Write-Ahead Log Commit Hook
  1.7170 +**
  1.7171 +** ^The [sqlite3_wal_hook()] function is used to register a callback that
  1.7172 +** will be invoked each time a database connection commits data to a
  1.7173 +** [write-ahead log] (i.e. whenever a transaction is committed in
  1.7174 +** [journal_mode | journal_mode=WAL mode]). 
  1.7175 +**
  1.7176 +** ^The callback is invoked by SQLite after the commit has taken place and 
  1.7177 +** the associated write-lock on the database released, so the implementation 
  1.7178 +** may read, write or [checkpoint] the database as required.
  1.7179 +**
  1.7180 +** ^The first parameter passed to the callback function when it is invoked
  1.7181 +** is a copy of the third parameter passed to sqlite3_wal_hook() when
  1.7182 +** registering the callback. ^The second is a copy of the database handle.
  1.7183 +** ^The third parameter is the name of the database that was written to -
  1.7184 +** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  1.7185 +** is the number of pages currently in the write-ahead log file,
  1.7186 +** including those that were just committed.
  1.7187 +**
  1.7188 +** The callback function should normally return [SQLITE_OK].  ^If an error
  1.7189 +** code is returned, that error will propagate back up through the
  1.7190 +** SQLite code base to cause the statement that provoked the callback
  1.7191 +** to report an error, though the commit will have still occurred. If the
  1.7192 +** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  1.7193 +** that does not correspond to any valid SQLite error code, the results
  1.7194 +** are undefined.
  1.7195 +**
  1.7196 +** A single database handle may have at most a single write-ahead log callback 
  1.7197 +** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  1.7198 +** previously registered write-ahead log callback. ^Note that the
  1.7199 +** [sqlite3_wal_autocheckpoint()] interface and the
  1.7200 +** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  1.7201 +** those overwrite any prior [sqlite3_wal_hook()] settings.
  1.7202 +*/
  1.7203 +SQLITE_API void *sqlite3_wal_hook(
  1.7204 +  sqlite3*, 
  1.7205 +  int(*)(void *,sqlite3*,const char*,int),
  1.7206 +  void*
  1.7207 +);
  1.7208 +
  1.7209 +/*
  1.7210 +** CAPI3REF: Configure an auto-checkpoint
  1.7211 +**
  1.7212 +** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  1.7213 +** [sqlite3_wal_hook()] that causes any database on [database connection] D
  1.7214 +** to automatically [checkpoint]
  1.7215 +** after committing a transaction if there are N or
  1.7216 +** more frames in the [write-ahead log] file.  ^Passing zero or 
  1.7217 +** a negative value as the nFrame parameter disables automatic
  1.7218 +** checkpoints entirely.
  1.7219 +**
  1.7220 +** ^The callback registered by this function replaces any existing callback
  1.7221 +** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
  1.7222 +** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  1.7223 +** configured by this function.
  1.7224 +**
  1.7225 +** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  1.7226 +** from SQL.
  1.7227 +**
  1.7228 +** ^Every new [database connection] defaults to having the auto-checkpoint
  1.7229 +** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  1.7230 +** pages.  The use of this interface
  1.7231 +** is only necessary if the default setting is found to be suboptimal
  1.7232 +** for a particular application.
  1.7233 +*/
  1.7234 +SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  1.7235 +
  1.7236 +/*
  1.7237 +** CAPI3REF: Checkpoint a database
  1.7238 +**
  1.7239 +** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
  1.7240 +** on [database connection] D to be [checkpointed].  ^If X is NULL or an
  1.7241 +** empty string, then a checkpoint is run on all databases of
  1.7242 +** connection D.  ^If the database connection D is not in
  1.7243 +** [WAL | write-ahead log mode] then this interface is a harmless no-op.
  1.7244 +**
  1.7245 +** ^The [wal_checkpoint pragma] can be used to invoke this interface
  1.7246 +** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
  1.7247 +** [wal_autocheckpoint pragma] can be used to cause this interface to be
  1.7248 +** run whenever the WAL reaches a certain size threshold.
  1.7249 +**
  1.7250 +** See also: [sqlite3_wal_checkpoint_v2()]
  1.7251 +*/
  1.7252 +SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  1.7253 +
  1.7254 +/*
  1.7255 +** CAPI3REF: Checkpoint a database
  1.7256 +**
  1.7257 +** Run a checkpoint operation on WAL database zDb attached to database 
  1.7258 +** handle db. The specific operation is determined by the value of the 
  1.7259 +** eMode parameter:
  1.7260 +**
  1.7261 +** <dl>
  1.7262 +** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  1.7263 +**   Checkpoint as many frames as possible without waiting for any database 
  1.7264 +**   readers or writers to finish. Sync the db file if all frames in the log
  1.7265 +**   are checkpointed. This mode is the same as calling 
  1.7266 +**   sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
  1.7267 +**
  1.7268 +** <dt>SQLITE_CHECKPOINT_FULL<dd>
  1.7269 +**   This mode blocks (calls the busy-handler callback) until there is no
  1.7270 +**   database writer and all readers are reading from the most recent database
  1.7271 +**   snapshot. It then checkpoints all frames in the log file and syncs the
  1.7272 +**   database file. This call blocks database writers while it is running,
  1.7273 +**   but not database readers.
  1.7274 +**
  1.7275 +** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  1.7276 +**   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after 
  1.7277 +**   checkpointing the log file it blocks (calls the busy-handler callback)
  1.7278 +**   until all readers are reading from the database file only. This ensures 
  1.7279 +**   that the next client to write to the database file restarts the log file 
  1.7280 +**   from the beginning. This call blocks database writers while it is running,
  1.7281 +**   but not database readers.
  1.7282 +** </dl>
  1.7283 +**
  1.7284 +** If pnLog is not NULL, then *pnLog is set to the total number of frames in
  1.7285 +** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
  1.7286 +** the total number of checkpointed frames (including any that were already
  1.7287 +** checkpointed when this function is called). *pnLog and *pnCkpt may be
  1.7288 +** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
  1.7289 +** If no values are available because of an error, they are both set to -1
  1.7290 +** before returning to communicate this to the caller.
  1.7291 +**
  1.7292 +** All calls obtain an exclusive "checkpoint" lock on the database file. If
  1.7293 +** any other process is running a checkpoint operation at the same time, the 
  1.7294 +** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a 
  1.7295 +** busy-handler configured, it will not be invoked in this case.
  1.7296 +**
  1.7297 +** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive 
  1.7298 +** "writer" lock on the database file. If the writer lock cannot be obtained
  1.7299 +** immediately, and a busy-handler is configured, it is invoked and the writer
  1.7300 +** lock retried until either the busy-handler returns 0 or the lock is
  1.7301 +** successfully obtained. The busy-handler is also invoked while waiting for
  1.7302 +** database readers as described above. If the busy-handler returns 0 before
  1.7303 +** the writer lock is obtained or while waiting for database readers, the
  1.7304 +** checkpoint operation proceeds from that point in the same way as 
  1.7305 +** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible 
  1.7306 +** without blocking any further. SQLITE_BUSY is returned in this case.
  1.7307 +**
  1.7308 +** If parameter zDb is NULL or points to a zero length string, then the
  1.7309 +** specified operation is attempted on all WAL databases. In this case the
  1.7310 +** values written to output parameters *pnLog and *pnCkpt are undefined. If 
  1.7311 +** an SQLITE_BUSY error is encountered when processing one or more of the 
  1.7312 +** attached WAL databases, the operation is still attempted on any remaining 
  1.7313 +** attached databases and SQLITE_BUSY is returned to the caller. If any other 
  1.7314 +** error occurs while processing an attached database, processing is abandoned 
  1.7315 +** and the error code returned to the caller immediately. If no error 
  1.7316 +** (SQLITE_BUSY or otherwise) is encountered while processing the attached 
  1.7317 +** databases, SQLITE_OK is returned.
  1.7318 +**
  1.7319 +** If database zDb is the name of an attached database that is not in WAL
  1.7320 +** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
  1.7321 +** zDb is not NULL (or a zero length string) and is not the name of any
  1.7322 +** attached database, SQLITE_ERROR is returned to the caller.
  1.7323 +*/
  1.7324 +SQLITE_API int sqlite3_wal_checkpoint_v2(
  1.7325 +  sqlite3 *db,                    /* Database handle */
  1.7326 +  const char *zDb,                /* Name of attached database (or NULL) */
  1.7327 +  int eMode,                      /* SQLITE_CHECKPOINT_* value */
  1.7328 +  int *pnLog,                     /* OUT: Size of WAL log in frames */
  1.7329 +  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
  1.7330 +);
  1.7331 +
  1.7332 +/*
  1.7333 +** CAPI3REF: Checkpoint operation parameters
  1.7334 +**
  1.7335 +** These constants can be used as the 3rd parameter to
  1.7336 +** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]
  1.7337 +** documentation for additional information about the meaning and use of
  1.7338 +** each of these values.
  1.7339 +*/
  1.7340 +#define SQLITE_CHECKPOINT_PASSIVE 0
  1.7341 +#define SQLITE_CHECKPOINT_FULL    1
  1.7342 +#define SQLITE_CHECKPOINT_RESTART 2
  1.7343 +
  1.7344 +/*
  1.7345 +** CAPI3REF: Virtual Table Interface Configuration
  1.7346 +**
  1.7347 +** This function may be called by either the [xConnect] or [xCreate] method
  1.7348 +** of a [virtual table] implementation to configure
  1.7349 +** various facets of the virtual table interface.
  1.7350 +**
  1.7351 +** If this interface is invoked outside the context of an xConnect or
  1.7352 +** xCreate virtual table method then the behavior is undefined.
  1.7353 +**
  1.7354 +** At present, there is only one option that may be configured using
  1.7355 +** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
  1.7356 +** may be added in the future.
  1.7357 +*/
  1.7358 +SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  1.7359 +
  1.7360 +/*
  1.7361 +** CAPI3REF: Virtual Table Configuration Options
  1.7362 +**
  1.7363 +** These macros define the various options to the
  1.7364 +** [sqlite3_vtab_config()] interface that [virtual table] implementations
  1.7365 +** can use to customize and optimize their behavior.
  1.7366 +**
  1.7367 +** <dl>
  1.7368 +** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  1.7369 +** <dd>Calls of the form
  1.7370 +** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  1.7371 +** where X is an integer.  If X is zero, then the [virtual table] whose
  1.7372 +** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  1.7373 +** support constraints.  In this configuration (which is the default) if
  1.7374 +** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  1.7375 +** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  1.7376 +** specified as part of the users SQL statement, regardless of the actual
  1.7377 +** ON CONFLICT mode specified.
  1.7378 +**
  1.7379 +** If X is non-zero, then the virtual table implementation guarantees
  1.7380 +** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  1.7381 +** any modifications to internal or persistent data structures have been made.
  1.7382 +** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite 
  1.7383 +** is able to roll back a statement or database transaction, and abandon
  1.7384 +** or continue processing the current SQL statement as appropriate. 
  1.7385 +** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  1.7386 +** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  1.7387 +** had been ABORT.
  1.7388 +**
  1.7389 +** Virtual table implementations that are required to handle OR REPLACE
  1.7390 +** must do so within the [xUpdate] method. If a call to the 
  1.7391 +** [sqlite3_vtab_on_conflict()] function indicates that the current ON 
  1.7392 +** CONFLICT policy is REPLACE, the virtual table implementation should 
  1.7393 +** silently replace the appropriate rows within the xUpdate callback and
  1.7394 +** return SQLITE_OK. Or, if this is not possible, it may return
  1.7395 +** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT 
  1.7396 +** constraint handling.
  1.7397 +** </dl>
  1.7398 +*/
  1.7399 +#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  1.7400 +
  1.7401 +/*
  1.7402 +** CAPI3REF: Determine The Virtual Table Conflict Policy
  1.7403 +**
  1.7404 +** This function may only be called from within a call to the [xUpdate] method
  1.7405 +** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  1.7406 +** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  1.7407 +** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  1.7408 +** of the SQL statement that triggered the call to the [xUpdate] method of the
  1.7409 +** [virtual table].
  1.7410 +*/
  1.7411 +SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  1.7412 +
  1.7413 +/*
  1.7414 +** CAPI3REF: Conflict resolution modes
  1.7415 +**
  1.7416 +** These constants are returned by [sqlite3_vtab_on_conflict()] to
  1.7417 +** inform a [virtual table] implementation what the [ON CONFLICT] mode
  1.7418 +** is for the SQL statement being evaluated.
  1.7419 +**
  1.7420 +** Note that the [SQLITE_IGNORE] constant is also used as a potential
  1.7421 +** return value from the [sqlite3_set_authorizer()] callback and that
  1.7422 +** [SQLITE_ABORT] is also a [result code].
  1.7423 +*/
  1.7424 +#define SQLITE_ROLLBACK 1
  1.7425 +/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  1.7426 +#define SQLITE_FAIL     3
  1.7427 +/* #define SQLITE_ABORT 4  // Also an error code */
  1.7428 +#define SQLITE_REPLACE  5
  1.7429 +
  1.7430 +
  1.7431 +
  1.7432 +/*
  1.7433 +** Undo the hack that converts floating point types to integer for
  1.7434 +** builds on processors without floating point support.
  1.7435 +*/
  1.7436 +#ifdef SQLITE_OMIT_FLOATING_POINT
  1.7437 +# undef double
  1.7438 +#endif
  1.7439 +
  1.7440 +#if 0
  1.7441 +}  /* End of the 'extern "C"' block */
  1.7442 +#endif
  1.7443 +#endif /* _SQLITE3_H_ */
  1.7444 +
  1.7445 +/*
  1.7446 +** 2010 August 30
  1.7447 +**
  1.7448 +** The author disclaims copyright to this source code.  In place of
  1.7449 +** a legal notice, here is a blessing:
  1.7450 +**
  1.7451 +**    May you do good and not evil.
  1.7452 +**    May you find forgiveness for yourself and forgive others.
  1.7453 +**    May you share freely, never taking more than you give.
  1.7454 +**
  1.7455 +*************************************************************************
  1.7456 +*/
  1.7457 +
  1.7458 +#ifndef _SQLITE3RTREE_H_
  1.7459 +#define _SQLITE3RTREE_H_
  1.7460 +
  1.7461 +
  1.7462 +#if 0
  1.7463 +extern "C" {
  1.7464 +#endif
  1.7465 +
  1.7466 +typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  1.7467 +
  1.7468 +/*
  1.7469 +** Register a geometry callback named zGeom that can be used as part of an
  1.7470 +** R-Tree geometry query as follows:
  1.7471 +**
  1.7472 +**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  1.7473 +*/
  1.7474 +SQLITE_API int sqlite3_rtree_geometry_callback(
  1.7475 +  sqlite3 *db,
  1.7476 +  const char *zGeom,
  1.7477 +#ifdef SQLITE_RTREE_INT_ONLY
  1.7478 +  int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes),
  1.7479 +#else
  1.7480 +  int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes),
  1.7481 +#endif
  1.7482 +  void *pContext
  1.7483 +);
  1.7484 +
  1.7485 +
  1.7486 +/*
  1.7487 +** A pointer to a structure of the following type is passed as the first
  1.7488 +** argument to callbacks registered using rtree_geometry_callback().
  1.7489 +*/
  1.7490 +struct sqlite3_rtree_geometry {
  1.7491 +  void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
  1.7492 +  int nParam;                     /* Size of array aParam[] */
  1.7493 +  double *aParam;                 /* Parameters passed to SQL geom function */
  1.7494 +  void *pUser;                    /* Callback implementation user data */
  1.7495 +  void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
  1.7496 +};
  1.7497 +
  1.7498 +
  1.7499 +#if 0
  1.7500 +}  /* end of the 'extern "C"' block */
  1.7501 +#endif
  1.7502 +
  1.7503 +#endif  /* ifndef _SQLITE3RTREE_H_ */
  1.7504 +
  1.7505 +
  1.7506 +/************** End of sqlite3.h *********************************************/
  1.7507 +/************** Continuing where we left off in sqliteInt.h ******************/
  1.7508 +
  1.7509 +/*
  1.7510 +** Include the configuration header output by 'configure' if we're using the
  1.7511 +** autoconf-based build
  1.7512 +*/
  1.7513 +#ifdef _HAVE_SQLITE_CONFIG_H
  1.7514 +#include "config.h"
  1.7515 +#endif
  1.7516 +
  1.7517 +/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  1.7518 +/************** Begin file sqliteLimit.h *************************************/
  1.7519 +/*
  1.7520 +** 2007 May 7
  1.7521 +**
  1.7522 +** The author disclaims copyright to this source code.  In place of
  1.7523 +** a legal notice, here is a blessing:
  1.7524 +**
  1.7525 +**    May you do good and not evil.
  1.7526 +**    May you find forgiveness for yourself and forgive others.
  1.7527 +**    May you share freely, never taking more than you give.
  1.7528 +**
  1.7529 +*************************************************************************
  1.7530 +** 
  1.7531 +** This file defines various limits of what SQLite can process.
  1.7532 +*/
  1.7533 +
  1.7534 +/*
  1.7535 +** The maximum length of a TEXT or BLOB in bytes.   This also
  1.7536 +** limits the size of a row in a table or index.
  1.7537 +**
  1.7538 +** The hard limit is the ability of a 32-bit signed integer
  1.7539 +** to count the size: 2^31-1 or 2147483647.
  1.7540 +*/
  1.7541 +#ifndef SQLITE_MAX_LENGTH
  1.7542 +# define SQLITE_MAX_LENGTH 1000000000
  1.7543 +#endif
  1.7544 +
  1.7545 +/*
  1.7546 +** This is the maximum number of
  1.7547 +**
  1.7548 +**    * Columns in a table
  1.7549 +**    * Columns in an index
  1.7550 +**    * Columns in a view
  1.7551 +**    * Terms in the SET clause of an UPDATE statement
  1.7552 +**    * Terms in the result set of a SELECT statement
  1.7553 +**    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  1.7554 +**    * Terms in the VALUES clause of an INSERT statement
  1.7555 +**
  1.7556 +** The hard upper limit here is 32676.  Most database people will
  1.7557 +** tell you that in a well-normalized database, you usually should
  1.7558 +** not have more than a dozen or so columns in any table.  And if
  1.7559 +** that is the case, there is no point in having more than a few
  1.7560 +** dozen values in any of the other situations described above.
  1.7561 +*/
  1.7562 +#ifndef SQLITE_MAX_COLUMN
  1.7563 +# define SQLITE_MAX_COLUMN 2000
  1.7564 +#endif
  1.7565 +
  1.7566 +/*
  1.7567 +** The maximum length of a single SQL statement in bytes.
  1.7568 +**
  1.7569 +** It used to be the case that setting this value to zero would
  1.7570 +** turn the limit off.  That is no longer true.  It is not possible
  1.7571 +** to turn this limit off.
  1.7572 +*/
  1.7573 +#ifndef SQLITE_MAX_SQL_LENGTH
  1.7574 +# define SQLITE_MAX_SQL_LENGTH 1000000000
  1.7575 +#endif
  1.7576 +
  1.7577 +/*
  1.7578 +** The maximum depth of an expression tree. This is limited to 
  1.7579 +** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
  1.7580 +** want to place more severe limits on the complexity of an 
  1.7581 +** expression.
  1.7582 +**
  1.7583 +** A value of 0 used to mean that the limit was not enforced.
  1.7584 +** But that is no longer true.  The limit is now strictly enforced
  1.7585 +** at all times.
  1.7586 +*/
  1.7587 +#ifndef SQLITE_MAX_EXPR_DEPTH
  1.7588 +# define SQLITE_MAX_EXPR_DEPTH 1000
  1.7589 +#endif
  1.7590 +
  1.7591 +/*
  1.7592 +** The maximum number of terms in a compound SELECT statement.
  1.7593 +** The code generator for compound SELECT statements does one
  1.7594 +** level of recursion for each term.  A stack overflow can result
  1.7595 +** if the number of terms is too large.  In practice, most SQL
  1.7596 +** never has more than 3 or 4 terms.  Use a value of 0 to disable
  1.7597 +** any limit on the number of terms in a compount SELECT.
  1.7598 +*/
  1.7599 +#ifndef SQLITE_MAX_COMPOUND_SELECT
  1.7600 +# define SQLITE_MAX_COMPOUND_SELECT 500
  1.7601 +#endif
  1.7602 +
  1.7603 +/*
  1.7604 +** The maximum number of opcodes in a VDBE program.
  1.7605 +** Not currently enforced.
  1.7606 +*/
  1.7607 +#ifndef SQLITE_MAX_VDBE_OP
  1.7608 +# define SQLITE_MAX_VDBE_OP 25000
  1.7609 +#endif
  1.7610 +
  1.7611 +/*
  1.7612 +** The maximum number of arguments to an SQL function.
  1.7613 +*/
  1.7614 +#ifndef SQLITE_MAX_FUNCTION_ARG
  1.7615 +# define SQLITE_MAX_FUNCTION_ARG 127
  1.7616 +#endif
  1.7617 +
  1.7618 +/*
  1.7619 +** The maximum number of in-memory pages to use for the main database
  1.7620 +** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
  1.7621 +*/
  1.7622 +#ifndef SQLITE_DEFAULT_CACHE_SIZE
  1.7623 +# define SQLITE_DEFAULT_CACHE_SIZE  2000
  1.7624 +#endif
  1.7625 +#ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
  1.7626 +# define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
  1.7627 +#endif
  1.7628 +
  1.7629 +/*
  1.7630 +** The default number of frames to accumulate in the log file before
  1.7631 +** checkpointing the database in WAL mode.
  1.7632 +*/
  1.7633 +#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  1.7634 +# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
  1.7635 +#endif
  1.7636 +
  1.7637 +/*
  1.7638 +** The maximum number of attached databases.  This must be between 0
  1.7639 +** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
  1.7640 +** is used internally to track attached databases.
  1.7641 +*/
  1.7642 +#ifndef SQLITE_MAX_ATTACHED
  1.7643 +# define SQLITE_MAX_ATTACHED 10
  1.7644 +#endif
  1.7645 +
  1.7646 +
  1.7647 +/*
  1.7648 +** The maximum value of a ?nnn wildcard that the parser will accept.
  1.7649 +*/
  1.7650 +#ifndef SQLITE_MAX_VARIABLE_NUMBER
  1.7651 +# define SQLITE_MAX_VARIABLE_NUMBER 999
  1.7652 +#endif
  1.7653 +
  1.7654 +/* Maximum page size.  The upper bound on this value is 65536.  This a limit
  1.7655 +** imposed by the use of 16-bit offsets within each page.
  1.7656 +**
  1.7657 +** Earlier versions of SQLite allowed the user to change this value at
  1.7658 +** compile time. This is no longer permitted, on the grounds that it creates
  1.7659 +** a library that is technically incompatible with an SQLite library 
  1.7660 +** compiled with a different limit. If a process operating on a database 
  1.7661 +** with a page-size of 65536 bytes crashes, then an instance of SQLite 
  1.7662 +** compiled with the default page-size limit will not be able to rollback 
  1.7663 +** the aborted transaction. This could lead to database corruption.
  1.7664 +*/
  1.7665 +#ifdef SQLITE_MAX_PAGE_SIZE
  1.7666 +# undef SQLITE_MAX_PAGE_SIZE
  1.7667 +#endif
  1.7668 +#define SQLITE_MAX_PAGE_SIZE 65536
  1.7669 +
  1.7670 +
  1.7671 +/*
  1.7672 +** The default size of a database page.
  1.7673 +*/
  1.7674 +#ifndef SQLITE_DEFAULT_PAGE_SIZE
  1.7675 +# define SQLITE_DEFAULT_PAGE_SIZE 1024
  1.7676 +#endif
  1.7677 +#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  1.7678 +# undef SQLITE_DEFAULT_PAGE_SIZE
  1.7679 +# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  1.7680 +#endif
  1.7681 +
  1.7682 +/*
  1.7683 +** Ordinarily, if no value is explicitly provided, SQLite creates databases
  1.7684 +** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  1.7685 +** device characteristics (sector-size and atomic write() support),
  1.7686 +** SQLite may choose a larger value. This constant is the maximum value
  1.7687 +** SQLite will choose on its own.
  1.7688 +*/
  1.7689 +#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  1.7690 +# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  1.7691 +#endif
  1.7692 +#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  1.7693 +# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  1.7694 +# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  1.7695 +#endif
  1.7696 +
  1.7697 +
  1.7698 +/*
  1.7699 +** Maximum number of pages in one database file.
  1.7700 +**
  1.7701 +** This is really just the default value for the max_page_count pragma.
  1.7702 +** This value can be lowered (or raised) at run-time using that the
  1.7703 +** max_page_count macro.
  1.7704 +*/
  1.7705 +#ifndef SQLITE_MAX_PAGE_COUNT
  1.7706 +# define SQLITE_MAX_PAGE_COUNT 1073741823
  1.7707 +#endif
  1.7708 +
  1.7709 +/*
  1.7710 +** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  1.7711 +** operator.
  1.7712 +*/
  1.7713 +#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  1.7714 +# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  1.7715 +#endif
  1.7716 +
  1.7717 +/*
  1.7718 +** Maximum depth of recursion for triggers.
  1.7719 +**
  1.7720 +** A value of 1 means that a trigger program will not be able to itself
  1.7721 +** fire any triggers. A value of 0 means that no trigger programs at all 
  1.7722 +** may be executed.
  1.7723 +*/
  1.7724 +#ifndef SQLITE_MAX_TRIGGER_DEPTH
  1.7725 +# define SQLITE_MAX_TRIGGER_DEPTH 1000
  1.7726 +#endif
  1.7727 +
  1.7728 +/************** End of sqliteLimit.h *****************************************/
  1.7729 +/************** Continuing where we left off in sqliteInt.h ******************/
  1.7730 +
  1.7731 +/* Disable nuisance warnings on Borland compilers */
  1.7732 +#if defined(__BORLANDC__)
  1.7733 +#pragma warn -rch /* unreachable code */
  1.7734 +#pragma warn -ccc /* Condition is always true or false */
  1.7735 +#pragma warn -aus /* Assigned value is never used */
  1.7736 +#pragma warn -csu /* Comparing signed and unsigned */
  1.7737 +#pragma warn -spa /* Suspicious pointer arithmetic */
  1.7738 +#endif
  1.7739 +
  1.7740 +/* Needed for various definitions... */
  1.7741 +#ifndef _GNU_SOURCE
  1.7742 +# define _GNU_SOURCE
  1.7743 +#endif
  1.7744 +
  1.7745 +#if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  1.7746 +# define _BSD_SOURCE
  1.7747 +#endif
  1.7748 +
  1.7749 +/*
  1.7750 +** Include standard header files as necessary
  1.7751 +*/
  1.7752 +#ifdef HAVE_STDINT_H
  1.7753 +#include <stdint.h>
  1.7754 +#endif
  1.7755 +#ifdef HAVE_INTTYPES_H
  1.7756 +#include <inttypes.h>
  1.7757 +#endif
  1.7758 +
  1.7759 +/*
  1.7760 +** The following macros are used to cast pointers to integers and
  1.7761 +** integers to pointers.  The way you do this varies from one compiler
  1.7762 +** to the next, so we have developed the following set of #if statements
  1.7763 +** to generate appropriate macros for a wide range of compilers.
  1.7764 +**
  1.7765 +** The correct "ANSI" way to do this is to use the intptr_t type. 
  1.7766 +** Unfortunately, that typedef is not available on all compilers, or
  1.7767 +** if it is available, it requires an #include of specific headers
  1.7768 +** that vary from one machine to the next.
  1.7769 +**
  1.7770 +** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
  1.7771 +** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
  1.7772 +** So we have to define the macros in different ways depending on the
  1.7773 +** compiler.
  1.7774 +*/
  1.7775 +#if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
  1.7776 +# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
  1.7777 +# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
  1.7778 +#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
  1.7779 +# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
  1.7780 +# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
  1.7781 +#elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
  1.7782 +# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
  1.7783 +# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
  1.7784 +#else                          /* Generates a warning - but it always works */
  1.7785 +# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
  1.7786 +# define SQLITE_PTR_TO_INT(X)  ((int)(X))
  1.7787 +#endif
  1.7788 +
  1.7789 +/*
  1.7790 +** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  1.7791 +** 0 means mutexes are permanently disable and the library is never
  1.7792 +** threadsafe.  1 means the library is serialized which is the highest
  1.7793 +** level of threadsafety.  2 means the library is multithreaded - multiple
  1.7794 +** threads can use SQLite as long as no two threads try to use the same
  1.7795 +** database connection at the same time.
  1.7796 +**
  1.7797 +** Older versions of SQLite used an optional THREADSAFE macro.
  1.7798 +** We support that for legacy.
  1.7799 +*/
  1.7800 +#if !defined(SQLITE_THREADSAFE)
  1.7801 +# if defined(THREADSAFE)
  1.7802 +#   define SQLITE_THREADSAFE THREADSAFE
  1.7803 +# else
  1.7804 +#   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  1.7805 +# endif
  1.7806 +#endif
  1.7807 +
  1.7808 +/*
  1.7809 +** Powersafe overwrite is on by default.  But can be turned off using
  1.7810 +** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  1.7811 +*/
  1.7812 +#ifndef SQLITE_POWERSAFE_OVERWRITE
  1.7813 +# define SQLITE_POWERSAFE_OVERWRITE 1
  1.7814 +#endif
  1.7815 +
  1.7816 +/*
  1.7817 +** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
  1.7818 +** It determines whether or not the features related to 
  1.7819 +** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
  1.7820 +** be overridden at runtime using the sqlite3_config() API.
  1.7821 +*/
  1.7822 +#if !defined(SQLITE_DEFAULT_MEMSTATUS)
  1.7823 +# define SQLITE_DEFAULT_MEMSTATUS 1
  1.7824 +#endif
  1.7825 +
  1.7826 +/*
  1.7827 +** Exactly one of the following macros must be defined in order to
  1.7828 +** specify which memory allocation subsystem to use.
  1.7829 +**
  1.7830 +**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
  1.7831 +**     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
  1.7832 +**     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
  1.7833 +**     SQLITE_MEMDEBUG               // Debugging version of system malloc()
  1.7834 +**
  1.7835 +** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  1.7836 +** assert() macro is enabled, each call into the Win32 native heap subsystem
  1.7837 +** will cause HeapValidate to be called.  If heap validation should fail, an
  1.7838 +** assertion will be triggered.
  1.7839 +**
  1.7840 +** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  1.7841 +** the default.
  1.7842 +*/
  1.7843 +#if defined(SQLITE_SYSTEM_MALLOC) \
  1.7844 +  + defined(SQLITE_WIN32_MALLOC) \
  1.7845 +  + defined(SQLITE_ZERO_MALLOC) \
  1.7846 +  + defined(SQLITE_MEMDEBUG)>1
  1.7847 +# error "Two or more of the following compile-time configuration options\
  1.7848 + are defined but at most one is allowed:\
  1.7849 + SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  1.7850 + SQLITE_ZERO_MALLOC"
  1.7851 +#endif
  1.7852 +#if defined(SQLITE_SYSTEM_MALLOC) \
  1.7853 +  + defined(SQLITE_WIN32_MALLOC) \
  1.7854 +  + defined(SQLITE_ZERO_MALLOC) \
  1.7855 +  + defined(SQLITE_MEMDEBUG)==0
  1.7856 +# define SQLITE_SYSTEM_MALLOC 1
  1.7857 +#endif
  1.7858 +
  1.7859 +/*
  1.7860 +** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  1.7861 +** sizes of memory allocations below this value where possible.
  1.7862 +*/
  1.7863 +#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  1.7864 +# define SQLITE_MALLOC_SOFT_LIMIT 1024
  1.7865 +#endif
  1.7866 +
  1.7867 +/*
  1.7868 +** We need to define _XOPEN_SOURCE as follows in order to enable
  1.7869 +** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  1.7870 +** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  1.7871 +** it.
  1.7872 +*/
  1.7873 +#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  1.7874 +#  define _XOPEN_SOURCE 600
  1.7875 +#endif
  1.7876 +
  1.7877 +/*
  1.7878 +** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
  1.7879 +** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
  1.7880 +** make it true by defining or undefining NDEBUG.
  1.7881 +**
  1.7882 +** Setting NDEBUG makes the code smaller and faster by disabling the
  1.7883 +** assert() statements in the code.  So we want the default action
  1.7884 +** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  1.7885 +** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
  1.7886 +** feature.
  1.7887 +*/
  1.7888 +#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
  1.7889 +# define NDEBUG 1
  1.7890 +#endif
  1.7891 +#if defined(NDEBUG) && defined(SQLITE_DEBUG)
  1.7892 +# undef NDEBUG
  1.7893 +#endif
  1.7894 +
  1.7895 +/*
  1.7896 +** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
  1.7897 +*/
  1.7898 +#if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
  1.7899 +# define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
  1.7900 +#endif
  1.7901 +
  1.7902 +/*
  1.7903 +** The testcase() macro is used to aid in coverage testing.  When 
  1.7904 +** doing coverage testing, the condition inside the argument to
  1.7905 +** testcase() must be evaluated both true and false in order to
  1.7906 +** get full branch coverage.  The testcase() macro is inserted
  1.7907 +** to help ensure adequate test coverage in places where simple
  1.7908 +** condition/decision coverage is inadequate.  For example, testcase()
  1.7909 +** can be used to make sure boundary values are tested.  For
  1.7910 +** bitmask tests, testcase() can be used to make sure each bit
  1.7911 +** is significant and used at least once.  On switch statements
  1.7912 +** where multiple cases go to the same block of code, testcase()
  1.7913 +** can insure that all cases are evaluated.
  1.7914 +**
  1.7915 +*/
  1.7916 +#ifdef SQLITE_COVERAGE_TEST
  1.7917 +SQLITE_PRIVATE   void sqlite3Coverage(int);
  1.7918 +# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
  1.7919 +#else
  1.7920 +# define testcase(X)
  1.7921 +#endif
  1.7922 +
  1.7923 +/*
  1.7924 +** The TESTONLY macro is used to enclose variable declarations or
  1.7925 +** other bits of code that are needed to support the arguments
  1.7926 +** within testcase() and assert() macros.
  1.7927 +*/
  1.7928 +#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  1.7929 +# define TESTONLY(X)  X
  1.7930 +#else
  1.7931 +# define TESTONLY(X)
  1.7932 +#endif
  1.7933 +
  1.7934 +/*
  1.7935 +** Sometimes we need a small amount of code such as a variable initialization
  1.7936 +** to setup for a later assert() statement.  We do not want this code to
  1.7937 +** appear when assert() is disabled.  The following macro is therefore
  1.7938 +** used to contain that setup code.  The "VVA" acronym stands for
  1.7939 +** "Verification, Validation, and Accreditation".  In other words, the
  1.7940 +** code within VVA_ONLY() will only run during verification processes.
  1.7941 +*/
  1.7942 +#ifndef NDEBUG
  1.7943 +# define VVA_ONLY(X)  X
  1.7944 +#else
  1.7945 +# define VVA_ONLY(X)
  1.7946 +#endif
  1.7947 +
  1.7948 +/*
  1.7949 +** The ALWAYS and NEVER macros surround boolean expressions which 
  1.7950 +** are intended to always be true or false, respectively.  Such
  1.7951 +** expressions could be omitted from the code completely.  But they
  1.7952 +** are included in a few cases in order to enhance the resilience
  1.7953 +** of SQLite to unexpected behavior - to make the code "self-healing"
  1.7954 +** or "ductile" rather than being "brittle" and crashing at the first
  1.7955 +** hint of unplanned behavior.
  1.7956 +**
  1.7957 +** In other words, ALWAYS and NEVER are added for defensive code.
  1.7958 +**
  1.7959 +** When doing coverage testing ALWAYS and NEVER are hard-coded to
  1.7960 +** be true and false so that the unreachable code they specify will
  1.7961 +** not be counted as untested code.
  1.7962 +*/
  1.7963 +#if defined(SQLITE_COVERAGE_TEST)
  1.7964 +# define ALWAYS(X)      (1)
  1.7965 +# define NEVER(X)       (0)
  1.7966 +#elif !defined(NDEBUG)
  1.7967 +# define ALWAYS(X)      ((X)?1:(assert(0),0))
  1.7968 +# define NEVER(X)       ((X)?(assert(0),1):0)
  1.7969 +#else
  1.7970 +# define ALWAYS(X)      (X)
  1.7971 +# define NEVER(X)       (X)
  1.7972 +#endif
  1.7973 +
  1.7974 +/*
  1.7975 +** Return true (non-zero) if the input is a integer that is too large
  1.7976 +** to fit in 32-bits.  This macro is used inside of various testcase()
  1.7977 +** macros to verify that we have tested SQLite for large-file support.
  1.7978 +*/
  1.7979 +#define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
  1.7980 +
  1.7981 +/*
  1.7982 +** The macro unlikely() is a hint that surrounds a boolean
  1.7983 +** expression that is usually false.  Macro likely() surrounds
  1.7984 +** a boolean expression that is usually true.  These hints could,
  1.7985 +** in theory, be used by the compiler to generate better code, but
  1.7986 +** currently they are just comments for human readers.
  1.7987 +*/
  1.7988 +#define likely(X)    (X)
  1.7989 +#define unlikely(X)  (X)
  1.7990 +
  1.7991 +/************** Include hash.h in the middle of sqliteInt.h ******************/
  1.7992 +/************** Begin file hash.h ********************************************/
  1.7993 +/*
  1.7994 +** 2001 September 22
  1.7995 +**
  1.7996 +** The author disclaims copyright to this source code.  In place of
  1.7997 +** a legal notice, here is a blessing:
  1.7998 +**
  1.7999 +**    May you do good and not evil.
  1.8000 +**    May you find forgiveness for yourself and forgive others.
  1.8001 +**    May you share freely, never taking more than you give.
  1.8002 +**
  1.8003 +*************************************************************************
  1.8004 +** This is the header file for the generic hash-table implementation
  1.8005 +** used in SQLite.
  1.8006 +*/
  1.8007 +#ifndef _SQLITE_HASH_H_
  1.8008 +#define _SQLITE_HASH_H_
  1.8009 +
  1.8010 +/* Forward declarations of structures. */
  1.8011 +typedef struct Hash Hash;
  1.8012 +typedef struct HashElem HashElem;
  1.8013 +
  1.8014 +/* A complete hash table is an instance of the following structure.
  1.8015 +** The internals of this structure are intended to be opaque -- client
  1.8016 +** code should not attempt to access or modify the fields of this structure
  1.8017 +** directly.  Change this structure only by using the routines below.
  1.8018 +** However, some of the "procedures" and "functions" for modifying and
  1.8019 +** accessing this structure are really macros, so we can't really make
  1.8020 +** this structure opaque.
  1.8021 +**
  1.8022 +** All elements of the hash table are on a single doubly-linked list.
  1.8023 +** Hash.first points to the head of this list.
  1.8024 +**
  1.8025 +** There are Hash.htsize buckets.  Each bucket points to a spot in
  1.8026 +** the global doubly-linked list.  The contents of the bucket are the
  1.8027 +** element pointed to plus the next _ht.count-1 elements in the list.
  1.8028 +**
  1.8029 +** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
  1.8030 +** by a linear search of the global list.  For small tables, the 
  1.8031 +** Hash.ht table is never allocated because if there are few elements
  1.8032 +** in the table, it is faster to do a linear search than to manage
  1.8033 +** the hash table.
  1.8034 +*/
  1.8035 +struct Hash {
  1.8036 +  unsigned int htsize;      /* Number of buckets in the hash table */
  1.8037 +  unsigned int count;       /* Number of entries in this table */
  1.8038 +  HashElem *first;          /* The first element of the array */
  1.8039 +  struct _ht {              /* the hash table */
  1.8040 +    int count;                 /* Number of entries with this hash */
  1.8041 +    HashElem *chain;           /* Pointer to first entry with this hash */
  1.8042 +  } *ht;
  1.8043 +};
  1.8044 +
  1.8045 +/* Each element in the hash table is an instance of the following 
  1.8046 +** structure.  All elements are stored on a single doubly-linked list.
  1.8047 +**
  1.8048 +** Again, this structure is intended to be opaque, but it can't really
  1.8049 +** be opaque because it is used by macros.
  1.8050 +*/
  1.8051 +struct HashElem {
  1.8052 +  HashElem *next, *prev;       /* Next and previous elements in the table */
  1.8053 +  void *data;                  /* Data associated with this element */
  1.8054 +  const char *pKey; int nKey;  /* Key associated with this element */
  1.8055 +};
  1.8056 +
  1.8057 +/*
  1.8058 +** Access routines.  To delete, insert a NULL pointer.
  1.8059 +*/
  1.8060 +SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  1.8061 +SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
  1.8062 +SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
  1.8063 +SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  1.8064 +
  1.8065 +/*
  1.8066 +** Macros for looping over all elements of a hash table.  The idiom is
  1.8067 +** like this:
  1.8068 +**
  1.8069 +**   Hash h;
  1.8070 +**   HashElem *p;
  1.8071 +**   ...
  1.8072 +**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  1.8073 +**     SomeStructure *pData = sqliteHashData(p);
  1.8074 +**     // do something with pData
  1.8075 +**   }
  1.8076 +*/
  1.8077 +#define sqliteHashFirst(H)  ((H)->first)
  1.8078 +#define sqliteHashNext(E)   ((E)->next)
  1.8079 +#define sqliteHashData(E)   ((E)->data)
  1.8080 +/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
  1.8081 +/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
  1.8082 +
  1.8083 +/*
  1.8084 +** Number of entries in a hash table
  1.8085 +*/
  1.8086 +/* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
  1.8087 +
  1.8088 +#endif /* _SQLITE_HASH_H_ */
  1.8089 +
  1.8090 +/************** End of hash.h ************************************************/
  1.8091 +/************** Continuing where we left off in sqliteInt.h ******************/
  1.8092 +/************** Include parse.h in the middle of sqliteInt.h *****************/
  1.8093 +/************** Begin file parse.h *******************************************/
  1.8094 +#define TK_SEMI                             1
  1.8095 +#define TK_EXPLAIN                          2
  1.8096 +#define TK_QUERY                            3
  1.8097 +#define TK_PLAN                             4
  1.8098 +#define TK_BEGIN                            5
  1.8099 +#define TK_TRANSACTION                      6
  1.8100 +#define TK_DEFERRED                         7
  1.8101 +#define TK_IMMEDIATE                        8
  1.8102 +#define TK_EXCLUSIVE                        9
  1.8103 +#define TK_COMMIT                          10
  1.8104 +#define TK_END                             11
  1.8105 +#define TK_ROLLBACK                        12
  1.8106 +#define TK_SAVEPOINT                       13
  1.8107 +#define TK_RELEASE                         14
  1.8108 +#define TK_TO                              15
  1.8109 +#define TK_TABLE                           16
  1.8110 +#define TK_CREATE                          17
  1.8111 +#define TK_IF                              18
  1.8112 +#define TK_NOT                             19
  1.8113 +#define TK_EXISTS                          20
  1.8114 +#define TK_TEMP                            21
  1.8115 +#define TK_LP                              22
  1.8116 +#define TK_RP                              23
  1.8117 +#define TK_AS                              24
  1.8118 +#define TK_WITHOUT                         25
  1.8119 +#define TK_COMMA                           26
  1.8120 +#define TK_ID                              27
  1.8121 +#define TK_INDEXED                         28
  1.8122 +#define TK_ABORT                           29
  1.8123 +#define TK_ACTION                          30
  1.8124 +#define TK_AFTER                           31
  1.8125 +#define TK_ANALYZE                         32
  1.8126 +#define TK_ASC                             33
  1.8127 +#define TK_ATTACH                          34
  1.8128 +#define TK_BEFORE                          35
  1.8129 +#define TK_BY                              36
  1.8130 +#define TK_CASCADE                         37
  1.8131 +#define TK_CAST                            38
  1.8132 +#define TK_COLUMNKW                        39
  1.8133 +#define TK_CONFLICT                        40
  1.8134 +#define TK_DATABASE                        41
  1.8135 +#define TK_DESC                            42
  1.8136 +#define TK_DETACH                          43
  1.8137 +#define TK_EACH                            44
  1.8138 +#define TK_FAIL                            45
  1.8139 +#define TK_FOR                             46
  1.8140 +#define TK_IGNORE                          47
  1.8141 +#define TK_INITIALLY                       48
  1.8142 +#define TK_INSTEAD                         49
  1.8143 +#define TK_LIKE_KW                         50
  1.8144 +#define TK_MATCH                           51
  1.8145 +#define TK_NO                              52
  1.8146 +#define TK_KEY                             53
  1.8147 +#define TK_OF                              54
  1.8148 +#define TK_OFFSET                          55
  1.8149 +#define TK_PRAGMA                          56
  1.8150 +#define TK_RAISE                           57
  1.8151 +#define TK_RECURSIVE                       58
  1.8152 +#define TK_REPLACE                         59
  1.8153 +#define TK_RESTRICT                        60
  1.8154 +#define TK_ROW                             61
  1.8155 +#define TK_TRIGGER                         62
  1.8156 +#define TK_VACUUM                          63
  1.8157 +#define TK_VIEW                            64
  1.8158 +#define TK_VIRTUAL                         65
  1.8159 +#define TK_WITH                            66
  1.8160 +#define TK_REINDEX                         67
  1.8161 +#define TK_RENAME                          68
  1.8162 +#define TK_CTIME_KW                        69
  1.8163 +#define TK_ANY                             70
  1.8164 +#define TK_OR                              71
  1.8165 +#define TK_AND                             72
  1.8166 +#define TK_IS                              73
  1.8167 +#define TK_BETWEEN                         74
  1.8168 +#define TK_IN                              75
  1.8169 +#define TK_ISNULL                          76
  1.8170 +#define TK_NOTNULL                         77
  1.8171 +#define TK_NE                              78
  1.8172 +#define TK_EQ                              79
  1.8173 +#define TK_GT                              80
  1.8174 +#define TK_LE                              81
  1.8175 +#define TK_LT                              82
  1.8176 +#define TK_GE                              83
  1.8177 +#define TK_ESCAPE                          84
  1.8178 +#define TK_BITAND                          85
  1.8179 +#define TK_BITOR                           86
  1.8180 +#define TK_LSHIFT                          87
  1.8181 +#define TK_RSHIFT                          88
  1.8182 +#define TK_PLUS                            89
  1.8183 +#define TK_MINUS                           90
  1.8184 +#define TK_STAR                            91
  1.8185 +#define TK_SLASH                           92
  1.8186 +#define TK_REM                             93
  1.8187 +#define TK_CONCAT                          94
  1.8188 +#define TK_COLLATE                         95
  1.8189 +#define TK_BITNOT                          96
  1.8190 +#define TK_STRING                          97
  1.8191 +#define TK_JOIN_KW                         98
  1.8192 +#define TK_CONSTRAINT                      99
  1.8193 +#define TK_DEFAULT                        100
  1.8194 +#define TK_NULL                           101
  1.8195 +#define TK_PRIMARY                        102
  1.8196 +#define TK_UNIQUE                         103
  1.8197 +#define TK_CHECK                          104
  1.8198 +#define TK_REFERENCES                     105
  1.8199 +#define TK_AUTOINCR                       106
  1.8200 +#define TK_ON                             107
  1.8201 +#define TK_INSERT                         108
  1.8202 +#define TK_DELETE                         109
  1.8203 +#define TK_UPDATE                         110
  1.8204 +#define TK_SET                            111
  1.8205 +#define TK_DEFERRABLE                     112
  1.8206 +#define TK_FOREIGN                        113
  1.8207 +#define TK_DROP                           114
  1.8208 +#define TK_UNION                          115
  1.8209 +#define TK_ALL                            116
  1.8210 +#define TK_EXCEPT                         117
  1.8211 +#define TK_INTERSECT                      118
  1.8212 +#define TK_SELECT                         119
  1.8213 +#define TK_VALUES                         120
  1.8214 +#define TK_DISTINCT                       121
  1.8215 +#define TK_DOT                            122
  1.8216 +#define TK_FROM                           123
  1.8217 +#define TK_JOIN                           124
  1.8218 +#define TK_USING                          125
  1.8219 +#define TK_ORDER                          126
  1.8220 +#define TK_GROUP                          127
  1.8221 +#define TK_HAVING                         128
  1.8222 +#define TK_LIMIT                          129
  1.8223 +#define TK_WHERE                          130
  1.8224 +#define TK_INTO                           131
  1.8225 +#define TK_INTEGER                        132
  1.8226 +#define TK_FLOAT                          133
  1.8227 +#define TK_BLOB                           134
  1.8228 +#define TK_VARIABLE                       135
  1.8229 +#define TK_CASE                           136
  1.8230 +#define TK_WHEN                           137
  1.8231 +#define TK_THEN                           138
  1.8232 +#define TK_ELSE                           139
  1.8233 +#define TK_INDEX                          140
  1.8234 +#define TK_ALTER                          141
  1.8235 +#define TK_ADD                            142
  1.8236 +#define TK_TO_TEXT                        143
  1.8237 +#define TK_TO_BLOB                        144
  1.8238 +#define TK_TO_NUMERIC                     145
  1.8239 +#define TK_TO_INT                         146
  1.8240 +#define TK_TO_REAL                        147
  1.8241 +#define TK_ISNOT                          148
  1.8242 +#define TK_END_OF_FILE                    149
  1.8243 +#define TK_ILLEGAL                        150
  1.8244 +#define TK_SPACE                          151
  1.8245 +#define TK_UNCLOSED_STRING                152
  1.8246 +#define TK_FUNCTION                       153
  1.8247 +#define TK_COLUMN                         154
  1.8248 +#define TK_AGG_FUNCTION                   155
  1.8249 +#define TK_AGG_COLUMN                     156
  1.8250 +#define TK_UMINUS                         157
  1.8251 +#define TK_UPLUS                          158
  1.8252 +#define TK_REGISTER                       159
  1.8253 +
  1.8254 +/************** End of parse.h ***********************************************/
  1.8255 +/************** Continuing where we left off in sqliteInt.h ******************/
  1.8256 +#include <stdio.h>
  1.8257 +#include <stdlib.h>
  1.8258 +#include <string.h>
  1.8259 +#include <assert.h>
  1.8260 +#include <stddef.h>
  1.8261 +
  1.8262 +/*
  1.8263 +** If compiling for a processor that lacks floating point support,
  1.8264 +** substitute integer for floating-point
  1.8265 +*/
  1.8266 +#ifdef SQLITE_OMIT_FLOATING_POINT
  1.8267 +# define double sqlite_int64
  1.8268 +# define float sqlite_int64
  1.8269 +# define LONGDOUBLE_TYPE sqlite_int64
  1.8270 +# ifndef SQLITE_BIG_DBL
  1.8271 +#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  1.8272 +# endif
  1.8273 +# define SQLITE_OMIT_DATETIME_FUNCS 1
  1.8274 +# define SQLITE_OMIT_TRACE 1
  1.8275 +# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  1.8276 +# undef SQLITE_HAVE_ISNAN
  1.8277 +#endif
  1.8278 +#ifndef SQLITE_BIG_DBL
  1.8279 +# define SQLITE_BIG_DBL (1e99)
  1.8280 +#endif
  1.8281 +
  1.8282 +/*
  1.8283 +** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  1.8284 +** afterward. Having this macro allows us to cause the C compiler 
  1.8285 +** to omit code used by TEMP tables without messy #ifndef statements.
  1.8286 +*/
  1.8287 +#ifdef SQLITE_OMIT_TEMPDB
  1.8288 +#define OMIT_TEMPDB 1
  1.8289 +#else
  1.8290 +#define OMIT_TEMPDB 0
  1.8291 +#endif
  1.8292 +
  1.8293 +/*
  1.8294 +** The "file format" number is an integer that is incremented whenever
  1.8295 +** the VDBE-level file format changes.  The following macros define the
  1.8296 +** the default file format for new databases and the maximum file format
  1.8297 +** that the library can read.
  1.8298 +*/
  1.8299 +#define SQLITE_MAX_FILE_FORMAT 4
  1.8300 +#ifndef SQLITE_DEFAULT_FILE_FORMAT
  1.8301 +# define SQLITE_DEFAULT_FILE_FORMAT 4
  1.8302 +#endif
  1.8303 +
  1.8304 +/*
  1.8305 +** Determine whether triggers are recursive by default.  This can be
  1.8306 +** changed at run-time using a pragma.
  1.8307 +*/
  1.8308 +#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  1.8309 +# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  1.8310 +#endif
  1.8311 +
  1.8312 +/*
  1.8313 +** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  1.8314 +** on the command-line
  1.8315 +*/
  1.8316 +#ifndef SQLITE_TEMP_STORE
  1.8317 +# define SQLITE_TEMP_STORE 1
  1.8318 +# define SQLITE_TEMP_STORE_xc 1  /* Exclude from ctime.c */
  1.8319 +#endif
  1.8320 +
  1.8321 +/*
  1.8322 +** GCC does not define the offsetof() macro so we'll have to do it
  1.8323 +** ourselves.
  1.8324 +*/
  1.8325 +#ifndef offsetof
  1.8326 +#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  1.8327 +#endif
  1.8328 +
  1.8329 +/*
  1.8330 +** Macros to compute minimum and maximum of two numbers.
  1.8331 +*/
  1.8332 +#define MIN(A,B) ((A)<(B)?(A):(B))
  1.8333 +#define MAX(A,B) ((A)>(B)?(A):(B))
  1.8334 +
  1.8335 +/*
  1.8336 +** Check to see if this machine uses EBCDIC.  (Yes, believe it or
  1.8337 +** not, there are still machines out there that use EBCDIC.)
  1.8338 +*/
  1.8339 +#if 'A' == '\301'
  1.8340 +# define SQLITE_EBCDIC 1
  1.8341 +#else
  1.8342 +# define SQLITE_ASCII 1
  1.8343 +#endif
  1.8344 +
  1.8345 +/*
  1.8346 +** Integers of known sizes.  These typedefs might change for architectures
  1.8347 +** where the sizes very.  Preprocessor macros are available so that the
  1.8348 +** types can be conveniently redefined at compile-type.  Like this:
  1.8349 +**
  1.8350 +**         cc '-DUINTPTR_TYPE=long long int' ...
  1.8351 +*/
  1.8352 +#ifndef UINT32_TYPE
  1.8353 +# ifdef HAVE_UINT32_T
  1.8354 +#  define UINT32_TYPE uint32_t
  1.8355 +# else
  1.8356 +#  define UINT32_TYPE unsigned int
  1.8357 +# endif
  1.8358 +#endif
  1.8359 +#ifndef UINT16_TYPE
  1.8360 +# ifdef HAVE_UINT16_T
  1.8361 +#  define UINT16_TYPE uint16_t
  1.8362 +# else
  1.8363 +#  define UINT16_TYPE unsigned short int
  1.8364 +# endif
  1.8365 +#endif
  1.8366 +#ifndef INT16_TYPE
  1.8367 +# ifdef HAVE_INT16_T
  1.8368 +#  define INT16_TYPE int16_t
  1.8369 +# else
  1.8370 +#  define INT16_TYPE short int
  1.8371 +# endif
  1.8372 +#endif
  1.8373 +#ifndef UINT8_TYPE
  1.8374 +# ifdef HAVE_UINT8_T
  1.8375 +#  define UINT8_TYPE uint8_t
  1.8376 +# else
  1.8377 +#  define UINT8_TYPE unsigned char
  1.8378 +# endif
  1.8379 +#endif
  1.8380 +#ifndef INT8_TYPE
  1.8381 +# ifdef HAVE_INT8_T
  1.8382 +#  define INT8_TYPE int8_t
  1.8383 +# else
  1.8384 +#  define INT8_TYPE signed char
  1.8385 +# endif
  1.8386 +#endif
  1.8387 +#ifndef LONGDOUBLE_TYPE
  1.8388 +# define LONGDOUBLE_TYPE long double
  1.8389 +#endif
  1.8390 +typedef sqlite_int64 i64;          /* 8-byte signed integer */
  1.8391 +typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
  1.8392 +typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
  1.8393 +typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
  1.8394 +typedef INT16_TYPE i16;            /* 2-byte signed integer */
  1.8395 +typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
  1.8396 +typedef INT8_TYPE i8;              /* 1-byte signed integer */
  1.8397 +
  1.8398 +/*
  1.8399 +** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  1.8400 +** that can be stored in a u32 without loss of data.  The value
  1.8401 +** is 0x00000000ffffffff.  But because of quirks of some compilers, we
  1.8402 +** have to specify the value in the less intuitive manner shown:
  1.8403 +*/
  1.8404 +#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
  1.8405 +
  1.8406 +/*
  1.8407 +** The datatype used to store estimates of the number of rows in a
  1.8408 +** table or index.  This is an unsigned integer type.  For 99.9% of
  1.8409 +** the world, a 32-bit integer is sufficient.  But a 64-bit integer
  1.8410 +** can be used at compile-time if desired.
  1.8411 +*/
  1.8412 +#ifdef SQLITE_64BIT_STATS
  1.8413 + typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
  1.8414 +#else
  1.8415 + typedef u32 tRowcnt;    /* 32-bit is the default */
  1.8416 +#endif
  1.8417 +
  1.8418 +/*
  1.8419 +** Estimated quantities used for query planning are stored as 16-bit
  1.8420 +** logarithms.  For quantity X, the value stored is 10*log2(X).  This
  1.8421 +** gives a possible range of values of approximately 1.0e986 to 1e-986.
  1.8422 +** But the allowed values are "grainy".  Not every value is representable.
  1.8423 +** For example, quantities 16 and 17 are both represented by a LogEst
  1.8424 +** of 40.  However, since LogEst quantatites are suppose to be estimates,
  1.8425 +** not exact values, this imprecision is not a problem.
  1.8426 +**
  1.8427 +** "LogEst" is short for "Logarithimic Estimate".
  1.8428 +**
  1.8429 +** Examples:
  1.8430 +**      1 -> 0              20 -> 43          10000 -> 132
  1.8431 +**      2 -> 10             25 -> 46          25000 -> 146
  1.8432 +**      3 -> 16            100 -> 66        1000000 -> 199
  1.8433 +**      4 -> 20           1000 -> 99        1048576 -> 200
  1.8434 +**     10 -> 33           1024 -> 100    4294967296 -> 320
  1.8435 +**
  1.8436 +** The LogEst can be negative to indicate fractional values. 
  1.8437 +** Examples:
  1.8438 +**
  1.8439 +**    0.5 -> -10           0.1 -> -33        0.0625 -> -40
  1.8440 +*/
  1.8441 +typedef INT16_TYPE LogEst;
  1.8442 +
  1.8443 +/*
  1.8444 +** Macros to determine whether the machine is big or little endian,
  1.8445 +** evaluated at runtime.
  1.8446 +*/
  1.8447 +#ifdef SQLITE_AMALGAMATION
  1.8448 +SQLITE_PRIVATE const int sqlite3one = 1;
  1.8449 +#else
  1.8450 +SQLITE_PRIVATE const int sqlite3one;
  1.8451 +#endif
  1.8452 +#if defined(i386) || defined(__i386__) || defined(_M_IX86)\
  1.8453 +                             || defined(__x86_64) || defined(__x86_64__)
  1.8454 +# define SQLITE_BIGENDIAN    0
  1.8455 +# define SQLITE_LITTLEENDIAN 1
  1.8456 +# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
  1.8457 +#else
  1.8458 +# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
  1.8459 +# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  1.8460 +# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  1.8461 +#endif
  1.8462 +
  1.8463 +/*
  1.8464 +** Constants for the largest and smallest possible 64-bit signed integers.
  1.8465 +** These macros are designed to work correctly on both 32-bit and 64-bit
  1.8466 +** compilers.
  1.8467 +*/
  1.8468 +#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
  1.8469 +#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  1.8470 +
  1.8471 +/* 
  1.8472 +** Round up a number to the next larger multiple of 8.  This is used
  1.8473 +** to force 8-byte alignment on 64-bit architectures.
  1.8474 +*/
  1.8475 +#define ROUND8(x)     (((x)+7)&~7)
  1.8476 +
  1.8477 +/*
  1.8478 +** Round down to the nearest multiple of 8
  1.8479 +*/
  1.8480 +#define ROUNDDOWN8(x) ((x)&~7)
  1.8481 +
  1.8482 +/*
  1.8483 +** Assert that the pointer X is aligned to an 8-byte boundary.  This
  1.8484 +** macro is used only within assert() to verify that the code gets
  1.8485 +** all alignment restrictions correct.
  1.8486 +**
  1.8487 +** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  1.8488 +** underlying malloc() implemention might return us 4-byte aligned
  1.8489 +** pointers.  In that case, only verify 4-byte alignment.
  1.8490 +*/
  1.8491 +#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  1.8492 +# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
  1.8493 +#else
  1.8494 +# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
  1.8495 +#endif
  1.8496 +
  1.8497 +/*
  1.8498 +** Disable MMAP on platforms where it is known to not work
  1.8499 +*/
  1.8500 +#if defined(__OpenBSD__) || defined(__QNXNTO__)
  1.8501 +# undef SQLITE_MAX_MMAP_SIZE
  1.8502 +# define SQLITE_MAX_MMAP_SIZE 0
  1.8503 +#endif
  1.8504 +
  1.8505 +/*
  1.8506 +** Default maximum size of memory used by memory-mapped I/O in the VFS
  1.8507 +*/
  1.8508 +#ifdef __APPLE__
  1.8509 +# include <TargetConditionals.h>
  1.8510 +# if TARGET_OS_IPHONE
  1.8511 +#   undef SQLITE_MAX_MMAP_SIZE
  1.8512 +#   define SQLITE_MAX_MMAP_SIZE 0
  1.8513 +# endif
  1.8514 +#endif
  1.8515 +#ifndef SQLITE_MAX_MMAP_SIZE
  1.8516 +# if defined(__linux__) \
  1.8517 +  || defined(_WIN32) \
  1.8518 +  || (defined(__APPLE__) && defined(__MACH__)) \
  1.8519 +  || defined(__sun)
  1.8520 +#   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
  1.8521 +# else
  1.8522 +#   define SQLITE_MAX_MMAP_SIZE 0
  1.8523 +# endif
  1.8524 +# define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
  1.8525 +#endif
  1.8526 +
  1.8527 +/*
  1.8528 +** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
  1.8529 +** default MMAP_SIZE is specified at compile-time, make sure that it does
  1.8530 +** not exceed the maximum mmap size.
  1.8531 +*/
  1.8532 +#ifndef SQLITE_DEFAULT_MMAP_SIZE
  1.8533 +# define SQLITE_DEFAULT_MMAP_SIZE 0
  1.8534 +# define SQLITE_DEFAULT_MMAP_SIZE_xc 1  /* Exclude from ctime.c */
  1.8535 +#endif
  1.8536 +#if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  1.8537 +# undef SQLITE_DEFAULT_MMAP_SIZE
  1.8538 +# define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  1.8539 +#endif
  1.8540 +
  1.8541 +/*
  1.8542 +** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  1.8543 +** Priority is given to SQLITE_ENABLE_STAT4.  If either are defined, also
  1.8544 +** define SQLITE_ENABLE_STAT3_OR_STAT4
  1.8545 +*/
  1.8546 +#ifdef SQLITE_ENABLE_STAT4
  1.8547 +# undef SQLITE_ENABLE_STAT3
  1.8548 +# define SQLITE_ENABLE_STAT3_OR_STAT4 1
  1.8549 +#elif SQLITE_ENABLE_STAT3
  1.8550 +# define SQLITE_ENABLE_STAT3_OR_STAT4 1
  1.8551 +#elif SQLITE_ENABLE_STAT3_OR_STAT4
  1.8552 +# undef SQLITE_ENABLE_STAT3_OR_STAT4
  1.8553 +#endif
  1.8554 +
  1.8555 +/*
  1.8556 +** An instance of the following structure is used to store the busy-handler
  1.8557 +** callback for a given sqlite handle. 
  1.8558 +**
  1.8559 +** The sqlite.busyHandler member of the sqlite struct contains the busy
  1.8560 +** callback for the database handle. Each pager opened via the sqlite
  1.8561 +** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  1.8562 +** callback is currently invoked only from within pager.c.
  1.8563 +*/
  1.8564 +typedef struct BusyHandler BusyHandler;
  1.8565 +struct BusyHandler {
  1.8566 +  int (*xFunc)(void *,int);  /* The busy callback */
  1.8567 +  void *pArg;                /* First arg to busy callback */
  1.8568 +  int nBusy;                 /* Incremented with each busy call */
  1.8569 +};
  1.8570 +
  1.8571 +/*
  1.8572 +** Name of the master database table.  The master database table
  1.8573 +** is a special table that holds the names and attributes of all
  1.8574 +** user tables and indices.
  1.8575 +*/
  1.8576 +#define MASTER_NAME       "sqlite_master"
  1.8577 +#define TEMP_MASTER_NAME  "sqlite_temp_master"
  1.8578 +
  1.8579 +/*
  1.8580 +** The root-page of the master database table.
  1.8581 +*/
  1.8582 +#define MASTER_ROOT       1
  1.8583 +
  1.8584 +/*
  1.8585 +** The name of the schema table.
  1.8586 +*/
  1.8587 +#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  1.8588 +
  1.8589 +/*
  1.8590 +** A convenience macro that returns the number of elements in
  1.8591 +** an array.
  1.8592 +*/
  1.8593 +#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
  1.8594 +
  1.8595 +/*
  1.8596 +** Determine if the argument is a power of two
  1.8597 +*/
  1.8598 +#define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  1.8599 +
  1.8600 +/*
  1.8601 +** The following value as a destructor means to use sqlite3DbFree().
  1.8602 +** The sqlite3DbFree() routine requires two parameters instead of the 
  1.8603 +** one parameter that destructors normally want.  So we have to introduce 
  1.8604 +** this magic value that the code knows to handle differently.  Any 
  1.8605 +** pointer will work here as long as it is distinct from SQLITE_STATIC
  1.8606 +** and SQLITE_TRANSIENT.
  1.8607 +*/
  1.8608 +#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
  1.8609 +
  1.8610 +/*
  1.8611 +** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  1.8612 +** not support Writable Static Data (WSD) such as global and static variables.
  1.8613 +** All variables must either be on the stack or dynamically allocated from
  1.8614 +** the heap.  When WSD is unsupported, the variable declarations scattered
  1.8615 +** throughout the SQLite code must become constants instead.  The SQLITE_WSD
  1.8616 +** macro is used for this purpose.  And instead of referencing the variable
  1.8617 +** directly, we use its constant as a key to lookup the run-time allocated
  1.8618 +** buffer that holds real variable.  The constant is also the initializer
  1.8619 +** for the run-time allocated buffer.
  1.8620 +**
  1.8621 +** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  1.8622 +** macros become no-ops and have zero performance impact.
  1.8623 +*/
  1.8624 +#ifdef SQLITE_OMIT_WSD
  1.8625 +  #define SQLITE_WSD const
  1.8626 +  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  1.8627 +  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  1.8628 +SQLITE_API   int sqlite3_wsd_init(int N, int J);
  1.8629 +SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
  1.8630 +#else
  1.8631 +  #define SQLITE_WSD 
  1.8632 +  #define GLOBAL(t,v) v
  1.8633 +  #define sqlite3GlobalConfig sqlite3Config
  1.8634 +#endif
  1.8635 +
  1.8636 +/*
  1.8637 +** The following macros are used to suppress compiler warnings and to
  1.8638 +** make it clear to human readers when a function parameter is deliberately 
  1.8639 +** left unused within the body of a function. This usually happens when
  1.8640 +** a function is called via a function pointer. For example the 
  1.8641 +** implementation of an SQL aggregate step callback may not use the
  1.8642 +** parameter indicating the number of arguments passed to the aggregate,
  1.8643 +** if it knows that this is enforced elsewhere.
  1.8644 +**
  1.8645 +** When a function parameter is not used at all within the body of a function,
  1.8646 +** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  1.8647 +** However, these macros may also be used to suppress warnings related to
  1.8648 +** parameters that may or may not be used depending on compilation options.
  1.8649 +** For example those parameters only used in assert() statements. In these
  1.8650 +** cases the parameters are named as per the usual conventions.
  1.8651 +*/
  1.8652 +#define UNUSED_PARAMETER(x) (void)(x)
  1.8653 +#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  1.8654 +
  1.8655 +/*
  1.8656 +** Forward references to structures
  1.8657 +*/
  1.8658 +typedef struct AggInfo AggInfo;
  1.8659 +typedef struct AuthContext AuthContext;
  1.8660 +typedef struct AutoincInfo AutoincInfo;
  1.8661 +typedef struct Bitvec Bitvec;
  1.8662 +typedef struct CollSeq CollSeq;
  1.8663 +typedef struct Column Column;
  1.8664 +typedef struct Db Db;
  1.8665 +typedef struct Schema Schema;
  1.8666 +typedef struct Expr Expr;
  1.8667 +typedef struct ExprList ExprList;
  1.8668 +typedef struct ExprSpan ExprSpan;
  1.8669 +typedef struct FKey FKey;
  1.8670 +typedef struct FuncDestructor FuncDestructor;
  1.8671 +typedef struct FuncDef FuncDef;
  1.8672 +typedef struct FuncDefHash FuncDefHash;
  1.8673 +typedef struct IdList IdList;
  1.8674 +typedef struct Index Index;
  1.8675 +typedef struct IndexSample IndexSample;
  1.8676 +typedef struct KeyClass KeyClass;
  1.8677 +typedef struct KeyInfo KeyInfo;
  1.8678 +typedef struct Lookaside Lookaside;
  1.8679 +typedef struct LookasideSlot LookasideSlot;
  1.8680 +typedef struct Module Module;
  1.8681 +typedef struct NameContext NameContext;
  1.8682 +typedef struct Parse Parse;
  1.8683 +typedef struct PrintfArguments PrintfArguments;
  1.8684 +typedef struct RowSet RowSet;
  1.8685 +typedef struct Savepoint Savepoint;
  1.8686 +typedef struct Select Select;
  1.8687 +typedef struct SelectDest SelectDest;
  1.8688 +typedef struct SrcList SrcList;
  1.8689 +typedef struct StrAccum StrAccum;
  1.8690 +typedef struct Table Table;
  1.8691 +typedef struct TableLock TableLock;
  1.8692 +typedef struct Token Token;
  1.8693 +typedef struct Trigger Trigger;
  1.8694 +typedef struct TriggerPrg TriggerPrg;
  1.8695 +typedef struct TriggerStep TriggerStep;
  1.8696 +typedef struct UnpackedRecord UnpackedRecord;
  1.8697 +typedef struct VTable VTable;
  1.8698 +typedef struct VtabCtx VtabCtx;
  1.8699 +typedef struct Walker Walker;
  1.8700 +typedef struct WhereInfo WhereInfo;
  1.8701 +typedef struct With With;
  1.8702 +
  1.8703 +/*
  1.8704 +** Defer sourcing vdbe.h and btree.h until after the "u8" and 
  1.8705 +** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  1.8706 +** pointer types (i.e. FuncDef) defined above.
  1.8707 +*/
  1.8708 +/************** Include btree.h in the middle of sqliteInt.h *****************/
  1.8709 +/************** Begin file btree.h *******************************************/
  1.8710 +/*
  1.8711 +** 2001 September 15
  1.8712 +**
  1.8713 +** The author disclaims copyright to this source code.  In place of
  1.8714 +** a legal notice, here is a blessing:
  1.8715 +**
  1.8716 +**    May you do good and not evil.
  1.8717 +**    May you find forgiveness for yourself and forgive others.
  1.8718 +**    May you share freely, never taking more than you give.
  1.8719 +**
  1.8720 +*************************************************************************
  1.8721 +** This header file defines the interface that the sqlite B-Tree file
  1.8722 +** subsystem.  See comments in the source code for a detailed description
  1.8723 +** of what each interface routine does.
  1.8724 +*/
  1.8725 +#ifndef _BTREE_H_
  1.8726 +#define _BTREE_H_
  1.8727 +
  1.8728 +/* TODO: This definition is just included so other modules compile. It
  1.8729 +** needs to be revisited.
  1.8730 +*/
  1.8731 +#define SQLITE_N_BTREE_META 10
  1.8732 +
  1.8733 +/*
  1.8734 +** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  1.8735 +** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  1.8736 +*/
  1.8737 +#ifndef SQLITE_DEFAULT_AUTOVACUUM
  1.8738 +  #define SQLITE_DEFAULT_AUTOVACUUM 0
  1.8739 +#endif
  1.8740 +
  1.8741 +#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
  1.8742 +#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
  1.8743 +#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
  1.8744 +
  1.8745 +/*
  1.8746 +** Forward declarations of structure
  1.8747 +*/
  1.8748 +typedef struct Btree Btree;
  1.8749 +typedef struct BtCursor BtCursor;
  1.8750 +typedef struct BtShared BtShared;
  1.8751 +
  1.8752 +
  1.8753 +SQLITE_PRIVATE int sqlite3BtreeOpen(
  1.8754 +  sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
  1.8755 +  const char *zFilename,   /* Name of database file to open */
  1.8756 +  sqlite3 *db,             /* Associated database connection */
  1.8757 +  Btree **ppBtree,         /* Return open Btree* here */
  1.8758 +  int flags,               /* Flags */
  1.8759 +  int vfsFlags             /* Flags passed through to VFS open */
  1.8760 +);
  1.8761 +
  1.8762 +/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  1.8763 +** following values.
  1.8764 +**
  1.8765 +** NOTE:  These values must match the corresponding PAGER_ values in
  1.8766 +** pager.h.
  1.8767 +*/
  1.8768 +#define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
  1.8769 +#define BTREE_MEMORY        2  /* This is an in-memory DB */
  1.8770 +#define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
  1.8771 +#define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
  1.8772 +
  1.8773 +SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  1.8774 +SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  1.8775 +SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  1.8776 +SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  1.8777 +SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
  1.8778 +SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  1.8779 +SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  1.8780 +SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  1.8781 +SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  1.8782 +SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  1.8783 +SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
  1.8784 +#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
  1.8785 +SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  1.8786 +#endif
  1.8787 +SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  1.8788 +SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  1.8789 +SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  1.8790 +SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  1.8791 +SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  1.8792 +SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  1.8793 +SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
  1.8794 +SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  1.8795 +SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  1.8796 +SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  1.8797 +SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  1.8798 +SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  1.8799 +SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  1.8800 +SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  1.8801 +SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  1.8802 +SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  1.8803 +
  1.8804 +SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  1.8805 +SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  1.8806 +SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  1.8807 +
  1.8808 +SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  1.8809 +
  1.8810 +/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  1.8811 +** of the flags shown below.
  1.8812 +**
  1.8813 +** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  1.8814 +** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  1.8815 +** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
  1.8816 +** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  1.8817 +** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
  1.8818 +** indices.)
  1.8819 +*/
  1.8820 +#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
  1.8821 +#define BTREE_BLOBKEY    2    /* Table has keys only - no data */
  1.8822 +
  1.8823 +SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  1.8824 +SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  1.8825 +SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
  1.8826 +
  1.8827 +SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  1.8828 +SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  1.8829 +
  1.8830 +SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  1.8831 +
  1.8832 +/*
  1.8833 +** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  1.8834 +** should be one of the following values. The integer values are assigned 
  1.8835 +** to constants so that the offset of the corresponding field in an
  1.8836 +** SQLite database header may be found using the following formula:
  1.8837 +**
  1.8838 +**   offset = 36 + (idx * 4)
  1.8839 +**
  1.8840 +** For example, the free-page-count field is located at byte offset 36 of
  1.8841 +** the database file header. The incr-vacuum-flag field is located at
  1.8842 +** byte offset 64 (== 36+4*7).
  1.8843 +*/
  1.8844 +#define BTREE_FREE_PAGE_COUNT     0
  1.8845 +#define BTREE_SCHEMA_VERSION      1
  1.8846 +#define BTREE_FILE_FORMAT         2
  1.8847 +#define BTREE_DEFAULT_CACHE_SIZE  3
  1.8848 +#define BTREE_LARGEST_ROOT_PAGE   4
  1.8849 +#define BTREE_TEXT_ENCODING       5
  1.8850 +#define BTREE_USER_VERSION        6
  1.8851 +#define BTREE_INCR_VACUUM         7
  1.8852 +#define BTREE_APPLICATION_ID      8
  1.8853 +
  1.8854 +/*
  1.8855 +** Values that may be OR'd together to form the second argument of an
  1.8856 +** sqlite3BtreeCursorHints() call.
  1.8857 +*/
  1.8858 +#define BTREE_BULKLOAD 0x00000001
  1.8859 +
  1.8860 +SQLITE_PRIVATE int sqlite3BtreeCursor(
  1.8861 +  Btree*,                              /* BTree containing table to open */
  1.8862 +  int iTable,                          /* Index of root page */
  1.8863 +  int wrFlag,                          /* 1 for writing.  0 for read-only */
  1.8864 +  struct KeyInfo*,                     /* First argument to compare function */
  1.8865 +  BtCursor *pCursor                    /* Space to write cursor structure */
  1.8866 +);
  1.8867 +SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  1.8868 +SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  1.8869 +
  1.8870 +SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  1.8871 +SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  1.8872 +  BtCursor*,
  1.8873 +  UnpackedRecord *pUnKey,
  1.8874 +  i64 intKey,
  1.8875 +  int bias,
  1.8876 +  int *pRes
  1.8877 +);
  1.8878 +SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
  1.8879 +SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
  1.8880 +SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
  1.8881 +                                  const void *pData, int nData,
  1.8882 +                                  int nZero, int bias, int seekResult);
  1.8883 +SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  1.8884 +SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  1.8885 +SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
  1.8886 +SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  1.8887 +SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
  1.8888 +SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
  1.8889 +SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
  1.8890 +SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
  1.8891 +SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
  1.8892 +SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
  1.8893 +SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
  1.8894 +
  1.8895 +SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  1.8896 +SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  1.8897 +
  1.8898 +SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  1.8899 +SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
  1.8900 +SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  1.8901 +SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  1.8902 +SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
  1.8903 +
  1.8904 +#ifndef NDEBUG
  1.8905 +SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  1.8906 +#endif
  1.8907 +
  1.8908 +#ifndef SQLITE_OMIT_BTREECOUNT
  1.8909 +SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  1.8910 +#endif
  1.8911 +
  1.8912 +#ifdef SQLITE_TEST
  1.8913 +SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  1.8914 +SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  1.8915 +#endif
  1.8916 +
  1.8917 +#ifndef SQLITE_OMIT_WAL
  1.8918 +SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  1.8919 +#endif
  1.8920 +
  1.8921 +/*
  1.8922 +** If we are not using shared cache, then there is no need to
  1.8923 +** use mutexes to access the BtShared structures.  So make the
  1.8924 +** Enter and Leave procedures no-ops.
  1.8925 +*/
  1.8926 +#ifndef SQLITE_OMIT_SHARED_CACHE
  1.8927 +SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
  1.8928 +SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
  1.8929 +#else
  1.8930 +# define sqlite3BtreeEnter(X) 
  1.8931 +# define sqlite3BtreeEnterAll(X)
  1.8932 +#endif
  1.8933 +
  1.8934 +#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  1.8935 +SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
  1.8936 +SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
  1.8937 +SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
  1.8938 +SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
  1.8939 +SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
  1.8940 +#ifndef NDEBUG
  1.8941 +  /* These routines are used inside assert() statements only. */
  1.8942 +SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
  1.8943 +SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  1.8944 +SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  1.8945 +#endif
  1.8946 +#else
  1.8947 +
  1.8948 +# define sqlite3BtreeSharable(X) 0
  1.8949 +# define sqlite3BtreeLeave(X)
  1.8950 +# define sqlite3BtreeEnterCursor(X)
  1.8951 +# define sqlite3BtreeLeaveCursor(X)
  1.8952 +# define sqlite3BtreeLeaveAll(X)
  1.8953 +
  1.8954 +# define sqlite3BtreeHoldsMutex(X) 1
  1.8955 +# define sqlite3BtreeHoldsAllMutexes(X) 1
  1.8956 +# define sqlite3SchemaMutexHeld(X,Y,Z) 1
  1.8957 +#endif
  1.8958 +
  1.8959 +
  1.8960 +#endif /* _BTREE_H_ */
  1.8961 +
  1.8962 +/************** End of btree.h ***********************************************/
  1.8963 +/************** Continuing where we left off in sqliteInt.h ******************/
  1.8964 +/************** Include vdbe.h in the middle of sqliteInt.h ******************/
  1.8965 +/************** Begin file vdbe.h ********************************************/
  1.8966 +/*
  1.8967 +** 2001 September 15
  1.8968 +**
  1.8969 +** The author disclaims copyright to this source code.  In place of
  1.8970 +** a legal notice, here is a blessing:
  1.8971 +**
  1.8972 +**    May you do good and not evil.
  1.8973 +**    May you find forgiveness for yourself and forgive others.
  1.8974 +**    May you share freely, never taking more than you give.
  1.8975 +**
  1.8976 +*************************************************************************
  1.8977 +** Header file for the Virtual DataBase Engine (VDBE)
  1.8978 +**
  1.8979 +** This header defines the interface to the virtual database engine
  1.8980 +** or VDBE.  The VDBE implements an abstract machine that runs a
  1.8981 +** simple program to access and modify the underlying database.
  1.8982 +*/
  1.8983 +#ifndef _SQLITE_VDBE_H_
  1.8984 +#define _SQLITE_VDBE_H_
  1.8985 +/* #include <stdio.h> */
  1.8986 +
  1.8987 +/*
  1.8988 +** A single VDBE is an opaque structure named "Vdbe".  Only routines
  1.8989 +** in the source file sqliteVdbe.c are allowed to see the insides
  1.8990 +** of this structure.
  1.8991 +*/
  1.8992 +typedef struct Vdbe Vdbe;
  1.8993 +
  1.8994 +/*
  1.8995 +** The names of the following types declared in vdbeInt.h are required
  1.8996 +** for the VdbeOp definition.
  1.8997 +*/
  1.8998 +typedef struct Mem Mem;
  1.8999 +typedef struct SubProgram SubProgram;
  1.9000 +
  1.9001 +/*
  1.9002 +** A single instruction of the virtual machine has an opcode
  1.9003 +** and as many as three operands.  The instruction is recorded
  1.9004 +** as an instance of the following structure:
  1.9005 +*/
  1.9006 +struct VdbeOp {
  1.9007 +  u8 opcode;          /* What operation to perform */
  1.9008 +  signed char p4type; /* One of the P4_xxx constants for p4 */
  1.9009 +  u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
  1.9010 +  u8 p5;              /* Fifth parameter is an unsigned character */
  1.9011 +  int p1;             /* First operand */
  1.9012 +  int p2;             /* Second parameter (often the jump destination) */
  1.9013 +  int p3;             /* The third parameter */
  1.9014 +  union {             /* fourth parameter */
  1.9015 +    int i;                 /* Integer value if p4type==P4_INT32 */
  1.9016 +    void *p;               /* Generic pointer */
  1.9017 +    char *z;               /* Pointer to data for string (char array) types */
  1.9018 +    i64 *pI64;             /* Used when p4type is P4_INT64 */
  1.9019 +    double *pReal;         /* Used when p4type is P4_REAL */
  1.9020 +    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
  1.9021 +    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
  1.9022 +    Mem *pMem;             /* Used when p4type is P4_MEM */
  1.9023 +    VTable *pVtab;         /* Used when p4type is P4_VTAB */
  1.9024 +    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
  1.9025 +    int *ai;               /* Used when p4type is P4_INTARRAY */
  1.9026 +    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
  1.9027 +    int (*xAdvance)(BtCursor *, int *);
  1.9028 +  } p4;
  1.9029 +#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  1.9030 +  char *zComment;          /* Comment to improve readability */
  1.9031 +#endif
  1.9032 +#ifdef VDBE_PROFILE
  1.9033 +  u32 cnt;                 /* Number of times this instruction was executed */
  1.9034 +  u64 cycles;              /* Total time spent executing this instruction */
  1.9035 +#endif
  1.9036 +#ifdef SQLITE_VDBE_COVERAGE
  1.9037 +  int iSrcLine;            /* Source-code line that generated this opcode */
  1.9038 +#endif
  1.9039 +};
  1.9040 +typedef struct VdbeOp VdbeOp;
  1.9041 +
  1.9042 +
  1.9043 +/*
  1.9044 +** A sub-routine used to implement a trigger program.
  1.9045 +*/
  1.9046 +struct SubProgram {
  1.9047 +  VdbeOp *aOp;                  /* Array of opcodes for sub-program */
  1.9048 +  int nOp;                      /* Elements in aOp[] */
  1.9049 +  int nMem;                     /* Number of memory cells required */
  1.9050 +  int nCsr;                     /* Number of cursors required */
  1.9051 +  int nOnce;                    /* Number of OP_Once instructions */
  1.9052 +  void *token;                  /* id that may be used to recursive triggers */
  1.9053 +  SubProgram *pNext;            /* Next sub-program already visited */
  1.9054 +};
  1.9055 +
  1.9056 +/*
  1.9057 +** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  1.9058 +** it takes up less space.
  1.9059 +*/
  1.9060 +struct VdbeOpList {
  1.9061 +  u8 opcode;          /* What operation to perform */
  1.9062 +  signed char p1;     /* First operand */
  1.9063 +  signed char p2;     /* Second parameter (often the jump destination) */
  1.9064 +  signed char p3;     /* Third parameter */
  1.9065 +};
  1.9066 +typedef struct VdbeOpList VdbeOpList;
  1.9067 +
  1.9068 +/*
  1.9069 +** Allowed values of VdbeOp.p4type
  1.9070 +*/
  1.9071 +#define P4_NOTUSED    0   /* The P4 parameter is not used */
  1.9072 +#define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
  1.9073 +#define P4_STATIC   (-2)  /* Pointer to a static string */
  1.9074 +#define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
  1.9075 +#define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
  1.9076 +#define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
  1.9077 +#define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
  1.9078 +#define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
  1.9079 +#define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
  1.9080 +#define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
  1.9081 +#define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
  1.9082 +#define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
  1.9083 +#define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
  1.9084 +#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  1.9085 +#define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
  1.9086 +#define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  1.9087 +
  1.9088 +/* Error message codes for OP_Halt */
  1.9089 +#define P5_ConstraintNotNull 1
  1.9090 +#define P5_ConstraintUnique  2
  1.9091 +#define P5_ConstraintCheck   3
  1.9092 +#define P5_ConstraintFK      4
  1.9093 +
  1.9094 +/*
  1.9095 +** The Vdbe.aColName array contains 5n Mem structures, where n is the 
  1.9096 +** number of columns of data returned by the statement.
  1.9097 +*/
  1.9098 +#define COLNAME_NAME     0
  1.9099 +#define COLNAME_DECLTYPE 1
  1.9100 +#define COLNAME_DATABASE 2
  1.9101 +#define COLNAME_TABLE    3
  1.9102 +#define COLNAME_COLUMN   4
  1.9103 +#ifdef SQLITE_ENABLE_COLUMN_METADATA
  1.9104 +# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
  1.9105 +#else
  1.9106 +# ifdef SQLITE_OMIT_DECLTYPE
  1.9107 +#   define COLNAME_N      1      /* Store only the name */
  1.9108 +# else
  1.9109 +#   define COLNAME_N      2      /* Store the name and decltype */
  1.9110 +# endif
  1.9111 +#endif
  1.9112 +
  1.9113 +/*
  1.9114 +** The following macro converts a relative address in the p2 field
  1.9115 +** of a VdbeOp structure into a negative number so that 
  1.9116 +** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
  1.9117 +** the macro again restores the address.
  1.9118 +*/
  1.9119 +#define ADDR(X)  (-1-(X))
  1.9120 +
  1.9121 +/*
  1.9122 +** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  1.9123 +** header file that defines a number for each opcode used by the VDBE.
  1.9124 +*/
  1.9125 +/************** Include opcodes.h in the middle of vdbe.h ********************/
  1.9126 +/************** Begin file opcodes.h *****************************************/
  1.9127 +/* Automatically generated.  Do not edit */
  1.9128 +/* See the mkopcodeh.awk script for details */
  1.9129 +#define OP_Function        1 /* synopsis: r[P3]=func(r[P2@P5])             */
  1.9130 +#define OP_Savepoint       2
  1.9131 +#define OP_AutoCommit      3
  1.9132 +#define OP_Transaction     4
  1.9133 +#define OP_SorterNext      5
  1.9134 +#define OP_PrevIfOpen      6
  1.9135 +#define OP_NextIfOpen      7
  1.9136 +#define OP_Prev            8
  1.9137 +#define OP_Next            9
  1.9138 +#define OP_AggStep        10 /* synopsis: accum=r[P3] step(r[P2@P5])       */
  1.9139 +#define OP_Checkpoint     11
  1.9140 +#define OP_JournalMode    12
  1.9141 +#define OP_Vacuum         13
  1.9142 +#define OP_VFilter        14 /* synopsis: iPlan=r[P3] zPlan='P4'           */
  1.9143 +#define OP_VUpdate        15 /* synopsis: data=r[P3@P2]                    */
  1.9144 +#define OP_Goto           16
  1.9145 +#define OP_Gosub          17
  1.9146 +#define OP_Return         18
  1.9147 +#define OP_Not            19 /* same as TK_NOT, synopsis: r[P2]= !r[P1]    */
  1.9148 +#define OP_InitCoroutine  20
  1.9149 +#define OP_EndCoroutine   21
  1.9150 +#define OP_Yield          22
  1.9151 +#define OP_HaltIfNull     23 /* synopsis: if r[P3]=null halt               */
  1.9152 +#define OP_Halt           24
  1.9153 +#define OP_Integer        25 /* synopsis: r[P2]=P1                         */
  1.9154 +#define OP_Int64          26 /* synopsis: r[P2]=P4                         */
  1.9155 +#define OP_String         27 /* synopsis: r[P2]='P4' (len=P1)              */
  1.9156 +#define OP_Null           28 /* synopsis: r[P2..P3]=NULL                   */
  1.9157 +#define OP_SoftNull       29 /* synopsis: r[P1]=NULL                       */
  1.9158 +#define OP_Blob           30 /* synopsis: r[P2]=P4 (len=P1)                */
  1.9159 +#define OP_Variable       31 /* synopsis: r[P2]=parameter(P1,P4)           */
  1.9160 +#define OP_Move           32 /* synopsis: r[P2@P3]=r[P1@P3]                */
  1.9161 +#define OP_Copy           33 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */
  1.9162 +#define OP_SCopy          34 /* synopsis: r[P2]=r[P1]                      */
  1.9163 +#define OP_ResultRow      35 /* synopsis: output=r[P1@P2]                  */
  1.9164 +#define OP_CollSeq        36
  1.9165 +#define OP_AddImm         37 /* synopsis: r[P1]=r[P1]+P2                   */
  1.9166 +#define OP_MustBeInt      38
  1.9167 +#define OP_RealAffinity   39
  1.9168 +#define OP_Permutation    40
  1.9169 +#define OP_Compare        41
  1.9170 +#define OP_Jump           42
  1.9171 +#define OP_Once           43
  1.9172 +#define OP_If             44
  1.9173 +#define OP_IfNot          45
  1.9174 +#define OP_Column         46 /* synopsis: r[P3]=PX                         */
  1.9175 +#define OP_Affinity       47 /* synopsis: affinity(r[P1@P2])               */
  1.9176 +#define OP_MakeRecord     48 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
  1.9177 +#define OP_Count          49 /* synopsis: r[P2]=count()                    */
  1.9178 +#define OP_ReadCookie     50
  1.9179 +#define OP_SetCookie      51
  1.9180 +#define OP_OpenRead       52 /* synopsis: root=P2 iDb=P3                   */
  1.9181 +#define OP_OpenWrite      53 /* synopsis: root=P2 iDb=P3                   */
  1.9182 +#define OP_OpenAutoindex  54 /* synopsis: nColumn=P2                       */
  1.9183 +#define OP_OpenEphemeral  55 /* synopsis: nColumn=P2                       */
  1.9184 +#define OP_SorterOpen     56
  1.9185 +#define OP_OpenPseudo     57 /* synopsis: P3 columns in r[P2]              */
  1.9186 +#define OP_Close          58
  1.9187 +#define OP_SeekLT         59
  1.9188 +#define OP_SeekLE         60
  1.9189 +#define OP_SeekGE         61
  1.9190 +#define OP_SeekGT         62
  1.9191 +#define OP_Seek           63 /* synopsis: intkey=r[P2]                     */
  1.9192 +#define OP_NoConflict     64 /* synopsis: key=r[P3@P4]                     */
  1.9193 +#define OP_NotFound       65 /* synopsis: key=r[P3@P4]                     */
  1.9194 +#define OP_Found          66 /* synopsis: key=r[P3@P4]                     */
  1.9195 +#define OP_NotExists      67 /* synopsis: intkey=r[P3]                     */
  1.9196 +#define OP_Sequence       68 /* synopsis: r[P2]=rowid                      */
  1.9197 +#define OP_NewRowid       69 /* synopsis: r[P2]=rowid                      */
  1.9198 +#define OP_Insert         70 /* synopsis: intkey=r[P3] data=r[P2]          */
  1.9199 +#define OP_Or             71 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
  1.9200 +#define OP_And            72 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
  1.9201 +#define OP_InsertInt      73 /* synopsis: intkey=P3 data=r[P2]             */
  1.9202 +#define OP_Delete         74
  1.9203 +#define OP_ResetCount     75
  1.9204 +#define OP_IsNull         76 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
  1.9205 +#define OP_NotNull        77 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
  1.9206 +#define OP_Ne             78 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
  1.9207 +#define OP_Eq             79 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
  1.9208 +#define OP_Gt             80 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
  1.9209 +#define OP_Le             81 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
  1.9210 +#define OP_Lt             82 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
  1.9211 +#define OP_Ge             83 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
  1.9212 +#define OP_SorterCompare  84 /* synopsis: if key(P1)!=rtrim(r[P3],P4) goto P2 */
  1.9213 +#define OP_BitAnd         85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
  1.9214 +#define OP_BitOr          86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
  1.9215 +#define OP_ShiftLeft      87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
  1.9216 +#define OP_ShiftRight     88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
  1.9217 +#define OP_Add            89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
  1.9218 +#define OP_Subtract       90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
  1.9219 +#define OP_Multiply       91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
  1.9220 +#define OP_Divide         92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
  1.9221 +#define OP_Remainder      93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
  1.9222 +#define OP_Concat         94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
  1.9223 +#define OP_SorterData     95 /* synopsis: r[P2]=data                       */
  1.9224 +#define OP_BitNot         96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
  1.9225 +#define OP_String8        97 /* same as TK_STRING, synopsis: r[P2]='P4'    */
  1.9226 +#define OP_RowKey         98 /* synopsis: r[P2]=key                        */
  1.9227 +#define OP_RowData        99 /* synopsis: r[P2]=data                       */
  1.9228 +#define OP_Rowid         100 /* synopsis: r[P2]=rowid                      */
  1.9229 +#define OP_NullRow       101
  1.9230 +#define OP_Last          102
  1.9231 +#define OP_SorterSort    103
  1.9232 +#define OP_Sort          104
  1.9233 +#define OP_Rewind        105
  1.9234 +#define OP_SorterInsert  106
  1.9235 +#define OP_IdxInsert     107 /* synopsis: key=r[P2]                        */
  1.9236 +#define OP_IdxDelete     108 /* synopsis: key=r[P2@P3]                     */
  1.9237 +#define OP_IdxRowid      109 /* synopsis: r[P2]=rowid                      */
  1.9238 +#define OP_IdxLE         110 /* synopsis: key=r[P3@P4]                     */
  1.9239 +#define OP_IdxGT         111 /* synopsis: key=r[P3@P4]                     */
  1.9240 +#define OP_IdxLT         112 /* synopsis: key=r[P3@P4]                     */
  1.9241 +#define OP_IdxGE         113 /* synopsis: key=r[P3@P4]                     */
  1.9242 +#define OP_Destroy       114
  1.9243 +#define OP_Clear         115
  1.9244 +#define OP_CreateIndex   116 /* synopsis: r[P2]=root iDb=P1                */
  1.9245 +#define OP_CreateTable   117 /* synopsis: r[P2]=root iDb=P1                */
  1.9246 +#define OP_ParseSchema   118
  1.9247 +#define OP_LoadAnalysis  119
  1.9248 +#define OP_DropTable     120
  1.9249 +#define OP_DropIndex     121
  1.9250 +#define OP_DropTrigger   122
  1.9251 +#define OP_IntegrityCk   123
  1.9252 +#define OP_RowSetAdd     124 /* synopsis: rowset(P1)=r[P2]                 */
  1.9253 +#define OP_RowSetRead    125 /* synopsis: r[P3]=rowset(P1)                 */
  1.9254 +#define OP_RowSetTest    126 /* synopsis: if r[P3] in rowset(P1) goto P2   */
  1.9255 +#define OP_Program       127
  1.9256 +#define OP_Param         128
  1.9257 +#define OP_FkCounter     129 /* synopsis: fkctr[P1]+=P2                    */
  1.9258 +#define OP_FkIfZero      130 /* synopsis: if fkctr[P1]==0 goto P2          */
  1.9259 +#define OP_MemMax        131 /* synopsis: r[P1]=max(r[P1],r[P2])           */
  1.9260 +#define OP_IfPos         132 /* synopsis: if r[P1]>0 goto P2               */
  1.9261 +#define OP_Real          133 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
  1.9262 +#define OP_IfNeg         134 /* synopsis: if r[P1]<0 goto P2               */
  1.9263 +#define OP_IfZero        135 /* synopsis: r[P1]+=P3, if r[P1]==0 goto P2   */
  1.9264 +#define OP_AggFinal      136 /* synopsis: accum=r[P1] N=P2                 */
  1.9265 +#define OP_IncrVacuum    137
  1.9266 +#define OP_Expire        138
  1.9267 +#define OP_TableLock     139 /* synopsis: iDb=P1 root=P2 write=P3          */
  1.9268 +#define OP_VBegin        140
  1.9269 +#define OP_VCreate       141
  1.9270 +#define OP_VDestroy      142
  1.9271 +#define OP_ToText        143 /* same as TK_TO_TEXT                         */
  1.9272 +#define OP_ToBlob        144 /* same as TK_TO_BLOB                         */
  1.9273 +#define OP_ToNumeric     145 /* same as TK_TO_NUMERIC                      */
  1.9274 +#define OP_ToInt         146 /* same as TK_TO_INT                          */
  1.9275 +#define OP_ToReal        147 /* same as TK_TO_REAL                         */
  1.9276 +#define OP_VOpen         148
  1.9277 +#define OP_VColumn       149 /* synopsis: r[P3]=vcolumn(P2)                */
  1.9278 +#define OP_VNext         150
  1.9279 +#define OP_VRename       151
  1.9280 +#define OP_Pagecount     152
  1.9281 +#define OP_MaxPgcnt      153
  1.9282 +#define OP_Init          154 /* synopsis: Start at P2                      */
  1.9283 +#define OP_Noop          155
  1.9284 +#define OP_Explain       156
  1.9285 +
  1.9286 +
  1.9287 +/* Properties such as "out2" or "jump" that are specified in
  1.9288 +** comments following the "case" for each opcode in the vdbe.c
  1.9289 +** are encoded into bitvectors as follows:
  1.9290 +*/
  1.9291 +#define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
  1.9292 +#define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
  1.9293 +#define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
  1.9294 +#define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
  1.9295 +#define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
  1.9296 +#define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
  1.9297 +#define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
  1.9298 +#define OPFLG_INITIALIZER {\
  1.9299 +/*   0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,\
  1.9300 +/*   8 */ 0x01, 0x01, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00,\
  1.9301 +/*  16 */ 0x01, 0x01, 0x04, 0x24, 0x01, 0x04, 0x05, 0x10,\
  1.9302 +/*  24 */ 0x00, 0x02, 0x02, 0x02, 0x02, 0x00, 0x02, 0x02,\
  1.9303 +/*  32 */ 0x00, 0x00, 0x20, 0x00, 0x00, 0x04, 0x05, 0x04,\
  1.9304 +/*  40 */ 0x00, 0x00, 0x01, 0x01, 0x05, 0x05, 0x00, 0x00,\
  1.9305 +/*  48 */ 0x00, 0x02, 0x02, 0x10, 0x00, 0x00, 0x00, 0x00,\
  1.9306 +/*  56 */ 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x08,\
  1.9307 +/*  64 */ 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00, 0x4c,\
  1.9308 +/*  72 */ 0x4c, 0x00, 0x00, 0x00, 0x05, 0x05, 0x15, 0x15,\
  1.9309 +/*  80 */ 0x15, 0x15, 0x15, 0x15, 0x00, 0x4c, 0x4c, 0x4c,\
  1.9310 +/*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x00,\
  1.9311 +/*  96 */ 0x24, 0x02, 0x00, 0x00, 0x02, 0x00, 0x01, 0x01,\
  1.9312 +/* 104 */ 0x01, 0x01, 0x08, 0x08, 0x00, 0x02, 0x01, 0x01,\
  1.9313 +/* 112 */ 0x01, 0x01, 0x02, 0x00, 0x02, 0x02, 0x00, 0x00,\
  1.9314 +/* 120 */ 0x00, 0x00, 0x00, 0x00, 0x0c, 0x45, 0x15, 0x01,\
  1.9315 +/* 128 */ 0x02, 0x00, 0x01, 0x08, 0x05, 0x02, 0x05, 0x05,\
  1.9316 +/* 136 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04,\
  1.9317 +/* 144 */ 0x04, 0x04, 0x04, 0x04, 0x00, 0x00, 0x01, 0x00,\
  1.9318 +/* 152 */ 0x02, 0x02, 0x01, 0x00, 0x00,}
  1.9319 +
  1.9320 +/************** End of opcodes.h *********************************************/
  1.9321 +/************** Continuing where we left off in vdbe.h ***********************/
  1.9322 +
  1.9323 +/*
  1.9324 +** Prototypes for the VDBE interface.  See comments on the implementation
  1.9325 +** for a description of what each of these routines does.
  1.9326 +*/
  1.9327 +SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
  1.9328 +SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  1.9329 +SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  1.9330 +SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  1.9331 +SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  1.9332 +SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  1.9333 +SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  1.9334 +SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
  1.9335 +SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  1.9336 +SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  1.9337 +SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  1.9338 +SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  1.9339 +SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
  1.9340 +SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  1.9341 +SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  1.9342 +SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
  1.9343 +SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  1.9344 +SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
  1.9345 +SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  1.9346 +SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  1.9347 +SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  1.9348 +SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  1.9349 +SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  1.9350 +SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  1.9351 +SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  1.9352 +SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  1.9353 +SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  1.9354 +SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  1.9355 +#ifdef SQLITE_DEBUG
  1.9356 +SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  1.9357 +#endif
  1.9358 +SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  1.9359 +SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  1.9360 +SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  1.9361 +SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  1.9362 +SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  1.9363 +SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  1.9364 +SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  1.9365 +SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
  1.9366 +SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  1.9367 +SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  1.9368 +SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  1.9369 +SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  1.9370 +#ifndef SQLITE_OMIT_TRACE
  1.9371 +SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  1.9372 +#endif
  1.9373 +
  1.9374 +SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  1.9375 +SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,const UnpackedRecord*,int);
  1.9376 +SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
  1.9377 +
  1.9378 +typedef int (*RecordCompare)(int,const void*,const UnpackedRecord*,int);
  1.9379 +SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
  1.9380 +
  1.9381 +#ifndef SQLITE_OMIT_TRIGGER
  1.9382 +SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  1.9383 +#endif
  1.9384 +
  1.9385 +/* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
  1.9386 +** each VDBE opcode.
  1.9387 +**
  1.9388 +** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
  1.9389 +** comments in VDBE programs that show key decision points in the code
  1.9390 +** generator.
  1.9391 +*/
  1.9392 +#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  1.9393 +SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
  1.9394 +# define VdbeComment(X)  sqlite3VdbeComment X
  1.9395 +SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  1.9396 +# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
  1.9397 +# ifdef SQLITE_ENABLE_MODULE_COMMENTS
  1.9398 +#   define VdbeModuleComment(X)  sqlite3VdbeNoopComment X
  1.9399 +# else
  1.9400 +#   define VdbeModuleComment(X)
  1.9401 +# endif
  1.9402 +#else
  1.9403 +# define VdbeComment(X)
  1.9404 +# define VdbeNoopComment(X)
  1.9405 +# define VdbeModuleComment(X)
  1.9406 +#endif
  1.9407 +
  1.9408 +/*
  1.9409 +** The VdbeCoverage macros are used to set a coverage testing point
  1.9410 +** for VDBE branch instructions.  The coverage testing points are line
  1.9411 +** numbers in the sqlite3.c source file.  VDBE branch coverage testing
  1.9412 +** only works with an amalagmation build.  That's ok since a VDBE branch
  1.9413 +** coverage build designed for testing the test suite only.  No application
  1.9414 +** should ever ship with VDBE branch coverage measuring turned on.
  1.9415 +**
  1.9416 +**    VdbeCoverage(v)                  // Mark the previously coded instruction
  1.9417 +**                                     // as a branch
  1.9418 +**
  1.9419 +**    VdbeCoverageIf(v, conditional)   // Mark previous if conditional true
  1.9420 +**
  1.9421 +**    VdbeCoverageAlwaysTaken(v)       // Previous branch is always taken
  1.9422 +**
  1.9423 +**    VdbeCoverageNeverTaken(v)        // Previous branch is never taken
  1.9424 +**
  1.9425 +** Every VDBE branch operation must be tagged with one of the macros above.
  1.9426 +** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
  1.9427 +** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
  1.9428 +** routine in vdbe.c, alerting the developer to the missed tag.
  1.9429 +*/
  1.9430 +#ifdef SQLITE_VDBE_COVERAGE
  1.9431 +SQLITE_PRIVATE   void sqlite3VdbeSetLineNumber(Vdbe*,int);
  1.9432 +# define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
  1.9433 +# define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
  1.9434 +# define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
  1.9435 +# define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
  1.9436 +# define VDBE_OFFSET_LINENO(x) (__LINE__+x)
  1.9437 +#else
  1.9438 +# define VdbeCoverage(v)
  1.9439 +# define VdbeCoverageIf(v,x)
  1.9440 +# define VdbeCoverageAlwaysTaken(v)
  1.9441 +# define VdbeCoverageNeverTaken(v)
  1.9442 +# define VDBE_OFFSET_LINENO(x) 0
  1.9443 +#endif
  1.9444 +
  1.9445 +#endif
  1.9446 +
  1.9447 +/************** End of vdbe.h ************************************************/
  1.9448 +/************** Continuing where we left off in sqliteInt.h ******************/
  1.9449 +/************** Include pager.h in the middle of sqliteInt.h *****************/
  1.9450 +/************** Begin file pager.h *******************************************/
  1.9451 +/*
  1.9452 +** 2001 September 15
  1.9453 +**
  1.9454 +** The author disclaims copyright to this source code.  In place of
  1.9455 +** a legal notice, here is a blessing:
  1.9456 +**
  1.9457 +**    May you do good and not evil.
  1.9458 +**    May you find forgiveness for yourself and forgive others.
  1.9459 +**    May you share freely, never taking more than you give.
  1.9460 +**
  1.9461 +*************************************************************************
  1.9462 +** This header file defines the interface that the sqlite page cache
  1.9463 +** subsystem.  The page cache subsystem reads and writes a file a page
  1.9464 +** at a time and provides a journal for rollback.
  1.9465 +*/
  1.9466 +
  1.9467 +#ifndef _PAGER_H_
  1.9468 +#define _PAGER_H_
  1.9469 +
  1.9470 +/*
  1.9471 +** Default maximum size for persistent journal files. A negative 
  1.9472 +** value means no limit. This value may be overridden using the 
  1.9473 +** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  1.9474 +*/
  1.9475 +#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  1.9476 +  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  1.9477 +#endif
  1.9478 +
  1.9479 +/*
  1.9480 +** The type used to represent a page number.  The first page in a file
  1.9481 +** is called page 1.  0 is used to represent "not a page".
  1.9482 +*/
  1.9483 +typedef u32 Pgno;
  1.9484 +
  1.9485 +/*
  1.9486 +** Each open file is managed by a separate instance of the "Pager" structure.
  1.9487 +*/
  1.9488 +typedef struct Pager Pager;
  1.9489 +
  1.9490 +/*
  1.9491 +** Handle type for pages.
  1.9492 +*/
  1.9493 +typedef struct PgHdr DbPage;
  1.9494 +
  1.9495 +/*
  1.9496 +** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  1.9497 +** reserved for working around a windows/posix incompatibility). It is
  1.9498 +** used in the journal to signify that the remainder of the journal file 
  1.9499 +** is devoted to storing a master journal name - there are no more pages to
  1.9500 +** roll back. See comments for function writeMasterJournal() in pager.c 
  1.9501 +** for details.
  1.9502 +*/
  1.9503 +#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  1.9504 +
  1.9505 +/*
  1.9506 +** Allowed values for the flags parameter to sqlite3PagerOpen().
  1.9507 +**
  1.9508 +** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  1.9509 +*/
  1.9510 +#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
  1.9511 +#define PAGER_MEMORY        0x0002    /* In-memory database */
  1.9512 +
  1.9513 +/*
  1.9514 +** Valid values for the second argument to sqlite3PagerLockingMode().
  1.9515 +*/
  1.9516 +#define PAGER_LOCKINGMODE_QUERY      -1
  1.9517 +#define PAGER_LOCKINGMODE_NORMAL      0
  1.9518 +#define PAGER_LOCKINGMODE_EXCLUSIVE   1
  1.9519 +
  1.9520 +/*
  1.9521 +** Numeric constants that encode the journalmode.  
  1.9522 +*/
  1.9523 +#define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
  1.9524 +#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
  1.9525 +#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
  1.9526 +#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
  1.9527 +#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
  1.9528 +#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
  1.9529 +#define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
  1.9530 +
  1.9531 +/*
  1.9532 +** Flags that make up the mask passed to sqlite3PagerAcquire().
  1.9533 +*/
  1.9534 +#define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */
  1.9535 +#define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */
  1.9536 +
  1.9537 +/*
  1.9538 +** Flags for sqlite3PagerSetFlags()
  1.9539 +*/
  1.9540 +#define PAGER_SYNCHRONOUS_OFF       0x01  /* PRAGMA synchronous=OFF */
  1.9541 +#define PAGER_SYNCHRONOUS_NORMAL    0x02  /* PRAGMA synchronous=NORMAL */
  1.9542 +#define PAGER_SYNCHRONOUS_FULL      0x03  /* PRAGMA synchronous=FULL */
  1.9543 +#define PAGER_SYNCHRONOUS_MASK      0x03  /* Mask for three values above */
  1.9544 +#define PAGER_FULLFSYNC             0x04  /* PRAGMA fullfsync=ON */
  1.9545 +#define PAGER_CKPT_FULLFSYNC        0x08  /* PRAGMA checkpoint_fullfsync=ON */
  1.9546 +#define PAGER_CACHESPILL            0x10  /* PRAGMA cache_spill=ON */
  1.9547 +#define PAGER_FLAGS_MASK            0x1c  /* All above except SYNCHRONOUS */
  1.9548 +
  1.9549 +/*
  1.9550 +** The remainder of this file contains the declarations of the functions
  1.9551 +** that make up the Pager sub-system API. See source code comments for 
  1.9552 +** a detailed description of each routine.
  1.9553 +*/
  1.9554 +
  1.9555 +/* Open and close a Pager connection. */ 
  1.9556 +SQLITE_PRIVATE int sqlite3PagerOpen(
  1.9557 +  sqlite3_vfs*,
  1.9558 +  Pager **ppPager,
  1.9559 +  const char*,
  1.9560 +  int,
  1.9561 +  int,
  1.9562 +  int,
  1.9563 +  void(*)(DbPage*)
  1.9564 +);
  1.9565 +SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
  1.9566 +SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  1.9567 +
  1.9568 +/* Functions used to configure a Pager object. */
  1.9569 +SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  1.9570 +SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  1.9571 +SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  1.9572 +SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  1.9573 +SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  1.9574 +SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  1.9575 +SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  1.9576 +SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  1.9577 +SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  1.9578 +SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  1.9579 +SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  1.9580 +SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  1.9581 +SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  1.9582 +
  1.9583 +/* Functions used to obtain and release page references. */ 
  1.9584 +SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  1.9585 +#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
  1.9586 +SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  1.9587 +SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  1.9588 +SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  1.9589 +SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
  1.9590 +
  1.9591 +/* Operations on page references. */
  1.9592 +SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  1.9593 +SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  1.9594 +SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  1.9595 +SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  1.9596 +SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
  1.9597 +SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
  1.9598 +
  1.9599 +/* Functions used to manage pager transactions and savepoints. */
  1.9600 +SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  1.9601 +SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  1.9602 +SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  1.9603 +SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  1.9604 +SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
  1.9605 +SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  1.9606 +SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  1.9607 +SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  1.9608 +SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  1.9609 +SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  1.9610 +
  1.9611 +#ifndef SQLITE_OMIT_WAL
  1.9612 +SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
  1.9613 +SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
  1.9614 +SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
  1.9615 +SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  1.9616 +SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager);
  1.9617 +#endif
  1.9618 +
  1.9619 +#ifdef SQLITE_ENABLE_ZIPVFS
  1.9620 +SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
  1.9621 +#endif
  1.9622 +
  1.9623 +/* Functions used to query pager state and configuration. */
  1.9624 +SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  1.9625 +SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  1.9626 +SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  1.9627 +SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  1.9628 +SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
  1.9629 +SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  1.9630 +SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  1.9631 +SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
  1.9632 +SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  1.9633 +SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  1.9634 +SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  1.9635 +SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
  1.9636 +SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  1.9637 +
  1.9638 +/* Functions used to truncate the database file. */
  1.9639 +SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  1.9640 +
  1.9641 +#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  1.9642 +SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  1.9643 +#endif
  1.9644 +
  1.9645 +/* Functions to support testing and debugging. */
  1.9646 +#if !defined(NDEBUG) || defined(SQLITE_TEST)
  1.9647 +SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
  1.9648 +SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
  1.9649 +#endif
  1.9650 +#ifdef SQLITE_TEST
  1.9651 +SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
  1.9652 +SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
  1.9653 +  void disable_simulated_io_errors(void);
  1.9654 +  void enable_simulated_io_errors(void);
  1.9655 +#else
  1.9656 +# define disable_simulated_io_errors()
  1.9657 +# define enable_simulated_io_errors()
  1.9658 +#endif
  1.9659 +
  1.9660 +#endif /* _PAGER_H_ */
  1.9661 +
  1.9662 +/************** End of pager.h ***********************************************/
  1.9663 +/************** Continuing where we left off in sqliteInt.h ******************/
  1.9664 +/************** Include pcache.h in the middle of sqliteInt.h ****************/
  1.9665 +/************** Begin file pcache.h ******************************************/
  1.9666 +/*
  1.9667 +** 2008 August 05
  1.9668 +**
  1.9669 +** The author disclaims copyright to this source code.  In place of
  1.9670 +** a legal notice, here is a blessing:
  1.9671 +**
  1.9672 +**    May you do good and not evil.
  1.9673 +**    May you find forgiveness for yourself and forgive others.
  1.9674 +**    May you share freely, never taking more than you give.
  1.9675 +**
  1.9676 +*************************************************************************
  1.9677 +** This header file defines the interface that the sqlite page cache
  1.9678 +** subsystem. 
  1.9679 +*/
  1.9680 +
  1.9681 +#ifndef _PCACHE_H_
  1.9682 +
  1.9683 +typedef struct PgHdr PgHdr;
  1.9684 +typedef struct PCache PCache;
  1.9685 +
  1.9686 +/*
  1.9687 +** Every page in the cache is controlled by an instance of the following
  1.9688 +** structure.
  1.9689 +*/
  1.9690 +struct PgHdr {
  1.9691 +  sqlite3_pcache_page *pPage;    /* Pcache object page handle */
  1.9692 +  void *pData;                   /* Page data */
  1.9693 +  void *pExtra;                  /* Extra content */
  1.9694 +  PgHdr *pDirty;                 /* Transient list of dirty pages */
  1.9695 +  Pager *pPager;                 /* The pager this page is part of */
  1.9696 +  Pgno pgno;                     /* Page number for this page */
  1.9697 +#ifdef SQLITE_CHECK_PAGES
  1.9698 +  u32 pageHash;                  /* Hash of page content */
  1.9699 +#endif
  1.9700 +  u16 flags;                     /* PGHDR flags defined below */
  1.9701 +
  1.9702 +  /**********************************************************************
  1.9703 +  ** Elements above are public.  All that follows is private to pcache.c
  1.9704 +  ** and should not be accessed by other modules.
  1.9705 +  */
  1.9706 +  i16 nRef;                      /* Number of users of this page */
  1.9707 +  PCache *pCache;                /* Cache that owns this page */
  1.9708 +
  1.9709 +  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
  1.9710 +  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
  1.9711 +};
  1.9712 +
  1.9713 +/* Bit values for PgHdr.flags */
  1.9714 +#define PGHDR_DIRTY             0x002  /* Page has changed */
  1.9715 +#define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
  1.9716 +                                       ** writing this page to the database */
  1.9717 +#define PGHDR_NEED_READ         0x008  /* Content is unread */
  1.9718 +#define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
  1.9719 +#define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
  1.9720 +
  1.9721 +#define PGHDR_MMAP              0x040  /* This is an mmap page object */
  1.9722 +
  1.9723 +/* Initialize and shutdown the page cache subsystem */
  1.9724 +SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  1.9725 +SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  1.9726 +
  1.9727 +/* Page cache buffer management:
  1.9728 +** These routines implement SQLITE_CONFIG_PAGECACHE.
  1.9729 +*/
  1.9730 +SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  1.9731 +
  1.9732 +/* Create a new pager cache.
  1.9733 +** Under memory stress, invoke xStress to try to make pages clean.
  1.9734 +** Only clean and unpinned pages can be reclaimed.
  1.9735 +*/
  1.9736 +SQLITE_PRIVATE void sqlite3PcacheOpen(
  1.9737 +  int szPage,                    /* Size of every page */
  1.9738 +  int szExtra,                   /* Extra space associated with each page */
  1.9739 +  int bPurgeable,                /* True if pages are on backing store */
  1.9740 +  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  1.9741 +  void *pStress,                 /* Argument to xStress */
  1.9742 +  PCache *pToInit                /* Preallocated space for the PCache */
  1.9743 +);
  1.9744 +
  1.9745 +/* Modify the page-size after the cache has been created. */
  1.9746 +SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
  1.9747 +
  1.9748 +/* Return the size in bytes of a PCache object.  Used to preallocate
  1.9749 +** storage space.
  1.9750 +*/
  1.9751 +SQLITE_PRIVATE int sqlite3PcacheSize(void);
  1.9752 +
  1.9753 +/* One release per successful fetch.  Page is pinned until released.
  1.9754 +** Reference counted. 
  1.9755 +*/
  1.9756 +SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
  1.9757 +SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  1.9758 +
  1.9759 +SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
  1.9760 +SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
  1.9761 +SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
  1.9762 +SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
  1.9763 +
  1.9764 +/* Change a page number.  Used by incr-vacuum. */
  1.9765 +SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  1.9766 +
  1.9767 +/* Remove all pages with pgno>x.  Reset the cache if x==0 */
  1.9768 +SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  1.9769 +
  1.9770 +/* Get a list of all dirty pages in the cache, sorted by page number */
  1.9771 +SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  1.9772 +
  1.9773 +/* Reset and close the cache object */
  1.9774 +SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  1.9775 +
  1.9776 +/* Clear flags from pages of the page cache */
  1.9777 +SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  1.9778 +
  1.9779 +/* Discard the contents of the cache */
  1.9780 +SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  1.9781 +
  1.9782 +/* Return the total number of outstanding page references */
  1.9783 +SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  1.9784 +
  1.9785 +/* Increment the reference count of an existing page */
  1.9786 +SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  1.9787 +
  1.9788 +SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  1.9789 +
  1.9790 +/* Return the total number of pages stored in the cache */
  1.9791 +SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  1.9792 +
  1.9793 +#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  1.9794 +/* Iterate through all dirty pages currently stored in the cache. This
  1.9795 +** interface is only available if SQLITE_CHECK_PAGES is defined when the 
  1.9796 +** library is built.
  1.9797 +*/
  1.9798 +SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  1.9799 +#endif
  1.9800 +
  1.9801 +/* Set and get the suggested cache-size for the specified pager-cache.
  1.9802 +**
  1.9803 +** If no global maximum is configured, then the system attempts to limit
  1.9804 +** the total number of pages cached by purgeable pager-caches to the sum
  1.9805 +** of the suggested cache-sizes.
  1.9806 +*/
  1.9807 +SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  1.9808 +#ifdef SQLITE_TEST
  1.9809 +SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  1.9810 +#endif
  1.9811 +
  1.9812 +/* Free up as much memory as possible from the page cache */
  1.9813 +SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  1.9814 +
  1.9815 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  1.9816 +/* Try to return memory used by the pcache module to the main memory heap */
  1.9817 +SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  1.9818 +#endif
  1.9819 +
  1.9820 +#ifdef SQLITE_TEST
  1.9821 +SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  1.9822 +#endif
  1.9823 +
  1.9824 +SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  1.9825 +
  1.9826 +#endif /* _PCACHE_H_ */
  1.9827 +
  1.9828 +/************** End of pcache.h **********************************************/
  1.9829 +/************** Continuing where we left off in sqliteInt.h ******************/
  1.9830 +
  1.9831 +/************** Include os.h in the middle of sqliteInt.h ********************/
  1.9832 +/************** Begin file os.h **********************************************/
  1.9833 +/*
  1.9834 +** 2001 September 16
  1.9835 +**
  1.9836 +** The author disclaims copyright to this source code.  In place of
  1.9837 +** a legal notice, here is a blessing:
  1.9838 +**
  1.9839 +**    May you do good and not evil.
  1.9840 +**    May you find forgiveness for yourself and forgive others.
  1.9841 +**    May you share freely, never taking more than you give.
  1.9842 +**
  1.9843 +******************************************************************************
  1.9844 +**
  1.9845 +** This header file (together with is companion C source-code file
  1.9846 +** "os.c") attempt to abstract the underlying operating system so that
  1.9847 +** the SQLite library will work on both POSIX and windows systems.
  1.9848 +**
  1.9849 +** This header file is #include-ed by sqliteInt.h and thus ends up
  1.9850 +** being included by every source file.
  1.9851 +*/
  1.9852 +#ifndef _SQLITE_OS_H_
  1.9853 +#define _SQLITE_OS_H_
  1.9854 +
  1.9855 +/*
  1.9856 +** Figure out if we are dealing with Unix, Windows, or some other
  1.9857 +** operating system.  After the following block of preprocess macros,
  1.9858 +** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER 
  1.9859 +** will defined to either 1 or 0.  One of the four will be 1.  The other 
  1.9860 +** three will be 0.
  1.9861 +*/
  1.9862 +#if defined(SQLITE_OS_OTHER)
  1.9863 +# if SQLITE_OS_OTHER==1
  1.9864 +#   undef SQLITE_OS_UNIX
  1.9865 +#   define SQLITE_OS_UNIX 0
  1.9866 +#   undef SQLITE_OS_WIN
  1.9867 +#   define SQLITE_OS_WIN 0
  1.9868 +# else
  1.9869 +#   undef SQLITE_OS_OTHER
  1.9870 +# endif
  1.9871 +#endif
  1.9872 +#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  1.9873 +# define SQLITE_OS_OTHER 0
  1.9874 +# ifndef SQLITE_OS_WIN
  1.9875 +#   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
  1.9876 +#     define SQLITE_OS_WIN 1
  1.9877 +#     define SQLITE_OS_UNIX 0
  1.9878 +#   else
  1.9879 +#     define SQLITE_OS_WIN 0
  1.9880 +#     define SQLITE_OS_UNIX 1
  1.9881 +#  endif
  1.9882 +# else
  1.9883 +#  define SQLITE_OS_UNIX 0
  1.9884 +# endif
  1.9885 +#else
  1.9886 +# ifndef SQLITE_OS_WIN
  1.9887 +#  define SQLITE_OS_WIN 0
  1.9888 +# endif
  1.9889 +#endif
  1.9890 +
  1.9891 +#if SQLITE_OS_WIN
  1.9892 +# include <windows.h>
  1.9893 +#endif
  1.9894 +
  1.9895 +/*
  1.9896 +** Determine if we are dealing with Windows NT.
  1.9897 +**
  1.9898 +** We ought to be able to determine if we are compiling for win98 or winNT
  1.9899 +** using the _WIN32_WINNT macro as follows:
  1.9900 +**
  1.9901 +** #if defined(_WIN32_WINNT)
  1.9902 +** # define SQLITE_OS_WINNT 1
  1.9903 +** #else
  1.9904 +** # define SQLITE_OS_WINNT 0
  1.9905 +** #endif
  1.9906 +**
  1.9907 +** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,
  1.9908 +** so the above test does not work.  We'll just assume that everything is
  1.9909 +** winNT unless the programmer explicitly says otherwise by setting
  1.9910 +** SQLITE_OS_WINNT to 0.
  1.9911 +*/
  1.9912 +#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  1.9913 +# define SQLITE_OS_WINNT 1
  1.9914 +#endif
  1.9915 +
  1.9916 +/*
  1.9917 +** Determine if we are dealing with WindowsCE - which has a much
  1.9918 +** reduced API.
  1.9919 +*/
  1.9920 +#if defined(_WIN32_WCE)
  1.9921 +# define SQLITE_OS_WINCE 1
  1.9922 +#else
  1.9923 +# define SQLITE_OS_WINCE 0
  1.9924 +#endif
  1.9925 +
  1.9926 +/*
  1.9927 +** Determine if we are dealing with WinRT, which provides only a subset of
  1.9928 +** the full Win32 API.
  1.9929 +*/
  1.9930 +#if !defined(SQLITE_OS_WINRT)
  1.9931 +# define SQLITE_OS_WINRT 0
  1.9932 +#endif
  1.9933 +
  1.9934 +/* If the SET_FULLSYNC macro is not defined above, then make it
  1.9935 +** a no-op
  1.9936 +*/
  1.9937 +#ifndef SET_FULLSYNC
  1.9938 +# define SET_FULLSYNC(x,y)
  1.9939 +#endif
  1.9940 +
  1.9941 +/*
  1.9942 +** The default size of a disk sector
  1.9943 +*/
  1.9944 +#ifndef SQLITE_DEFAULT_SECTOR_SIZE
  1.9945 +# define SQLITE_DEFAULT_SECTOR_SIZE 4096
  1.9946 +#endif
  1.9947 +
  1.9948 +/*
  1.9949 +** Temporary files are named starting with this prefix followed by 16 random
  1.9950 +** alphanumeric characters, and no file extension. They are stored in the
  1.9951 +** OS's standard temporary file directory, and are deleted prior to exit.
  1.9952 +** If sqlite is being embedded in another program, you may wish to change the
  1.9953 +** prefix to reflect your program's name, so that if your program exits
  1.9954 +** prematurely, old temporary files can be easily identified. This can be done
  1.9955 +** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  1.9956 +**
  1.9957 +** 2006-10-31:  The default prefix used to be "sqlite_".  But then
  1.9958 +** Mcafee started using SQLite in their anti-virus product and it
  1.9959 +** started putting files with the "sqlite" name in the c:/temp folder.
  1.9960 +** This annoyed many windows users.  Those users would then do a 
  1.9961 +** Google search for "sqlite", find the telephone numbers of the
  1.9962 +** developers and call to wake them up at night and complain.
  1.9963 +** For this reason, the default name prefix is changed to be "sqlite" 
  1.9964 +** spelled backwards.  So the temp files are still identified, but
  1.9965 +** anybody smart enough to figure out the code is also likely smart
  1.9966 +** enough to know that calling the developer will not help get rid
  1.9967 +** of the file.
  1.9968 +*/
  1.9969 +#ifndef SQLITE_TEMP_FILE_PREFIX
  1.9970 +# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  1.9971 +#endif
  1.9972 +
  1.9973 +/*
  1.9974 +** The following values may be passed as the second argument to
  1.9975 +** sqlite3OsLock(). The various locks exhibit the following semantics:
  1.9976 +**
  1.9977 +** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
  1.9978 +** RESERVED:  A single process may hold a RESERVED lock on a file at
  1.9979 +**            any time. Other processes may hold and obtain new SHARED locks.
  1.9980 +** PENDING:   A single process may hold a PENDING lock on a file at
  1.9981 +**            any one time. Existing SHARED locks may persist, but no new
  1.9982 +**            SHARED locks may be obtained by other processes.
  1.9983 +** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  1.9984 +**
  1.9985 +** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  1.9986 +** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  1.9987 +** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  1.9988 +** sqlite3OsLock().
  1.9989 +*/
  1.9990 +#define NO_LOCK         0
  1.9991 +#define SHARED_LOCK     1
  1.9992 +#define RESERVED_LOCK   2
  1.9993 +#define PENDING_LOCK    3
  1.9994 +#define EXCLUSIVE_LOCK  4
  1.9995 +
  1.9996 +/*
  1.9997 +** File Locking Notes:  (Mostly about windows but also some info for Unix)
  1.9998 +**
  1.9999 +** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
 1.10000 +** those functions are not available.  So we use only LockFile() and
 1.10001 +** UnlockFile().
 1.10002 +**
 1.10003 +** LockFile() prevents not just writing but also reading by other processes.
 1.10004 +** A SHARED_LOCK is obtained by locking a single randomly-chosen 
 1.10005 +** byte out of a specific range of bytes. The lock byte is obtained at 
 1.10006 +** random so two separate readers can probably access the file at the 
 1.10007 +** same time, unless they are unlucky and choose the same lock byte.
 1.10008 +** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
 1.10009 +** There can only be one writer.  A RESERVED_LOCK is obtained by locking
 1.10010 +** a single byte of the file that is designated as the reserved lock byte.
 1.10011 +** A PENDING_LOCK is obtained by locking a designated byte different from
 1.10012 +** the RESERVED_LOCK byte.
 1.10013 +**
 1.10014 +** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
 1.10015 +** which means we can use reader/writer locks.  When reader/writer locks
 1.10016 +** are used, the lock is placed on the same range of bytes that is used
 1.10017 +** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
 1.10018 +** will support two or more Win95 readers or two or more WinNT readers.
 1.10019 +** But a single Win95 reader will lock out all WinNT readers and a single
 1.10020 +** WinNT reader will lock out all other Win95 readers.
 1.10021 +**
 1.10022 +** The following #defines specify the range of bytes used for locking.
 1.10023 +** SHARED_SIZE is the number of bytes available in the pool from which
 1.10024 +** a random byte is selected for a shared lock.  The pool of bytes for
 1.10025 +** shared locks begins at SHARED_FIRST. 
 1.10026 +**
 1.10027 +** The same locking strategy and
 1.10028 +** byte ranges are used for Unix.  This leaves open the possiblity of having
 1.10029 +** clients on win95, winNT, and unix all talking to the same shared file
 1.10030 +** and all locking correctly.  To do so would require that samba (or whatever
 1.10031 +** tool is being used for file sharing) implements locks correctly between
 1.10032 +** windows and unix.  I'm guessing that isn't likely to happen, but by
 1.10033 +** using the same locking range we are at least open to the possibility.
 1.10034 +**
 1.10035 +** Locking in windows is manditory.  For this reason, we cannot store
 1.10036 +** actual data in the bytes used for locking.  The pager never allocates
 1.10037 +** the pages involved in locking therefore.  SHARED_SIZE is selected so
 1.10038 +** that all locks will fit on a single page even at the minimum page size.
 1.10039 +** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
 1.10040 +** is set high so that we don't have to allocate an unused page except
 1.10041 +** for very large databases.  But one should test the page skipping logic 
 1.10042 +** by setting PENDING_BYTE low and running the entire regression suite.
 1.10043 +**
 1.10044 +** Changing the value of PENDING_BYTE results in a subtly incompatible
 1.10045 +** file format.  Depending on how it is changed, you might not notice
 1.10046 +** the incompatibility right away, even running a full regression test.
 1.10047 +** The default location of PENDING_BYTE is the first byte past the
 1.10048 +** 1GB boundary.
 1.10049 +**
 1.10050 +*/
 1.10051 +#ifdef SQLITE_OMIT_WSD
 1.10052 +# define PENDING_BYTE     (0x40000000)
 1.10053 +#else
 1.10054 +# define PENDING_BYTE      sqlite3PendingByte
 1.10055 +#endif
 1.10056 +#define RESERVED_BYTE     (PENDING_BYTE+1)
 1.10057 +#define SHARED_FIRST      (PENDING_BYTE+2)
 1.10058 +#define SHARED_SIZE       510
 1.10059 +
 1.10060 +/*
 1.10061 +** Wrapper around OS specific sqlite3_os_init() function.
 1.10062 +*/
 1.10063 +SQLITE_PRIVATE int sqlite3OsInit(void);
 1.10064 +
 1.10065 +/* 
 1.10066 +** Functions for accessing sqlite3_file methods 
 1.10067 +*/
 1.10068 +SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
 1.10069 +SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
 1.10070 +SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
 1.10071 +SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
 1.10072 +SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
 1.10073 +SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
 1.10074 +SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
 1.10075 +SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
 1.10076 +SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
 1.10077 +SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
 1.10078 +SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
 1.10079 +#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
 1.10080 +SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
 1.10081 +SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
 1.10082 +SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
 1.10083 +SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
 1.10084 +SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
 1.10085 +SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
 1.10086 +SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
 1.10087 +SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
 1.10088 +
 1.10089 +
 1.10090 +/* 
 1.10091 +** Functions for accessing sqlite3_vfs methods 
 1.10092 +*/
 1.10093 +SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
 1.10094 +SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
 1.10095 +SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
 1.10096 +SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
 1.10097 +#ifndef SQLITE_OMIT_LOAD_EXTENSION
 1.10098 +SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
 1.10099 +SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
 1.10100 +SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
 1.10101 +SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
 1.10102 +#endif /* SQLITE_OMIT_LOAD_EXTENSION */
 1.10103 +SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
 1.10104 +SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
 1.10105 +SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
 1.10106 +
 1.10107 +/*
 1.10108 +** Convenience functions for opening and closing files using 
 1.10109 +** sqlite3_malloc() to obtain space for the file-handle structure.
 1.10110 +*/
 1.10111 +SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
 1.10112 +SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
 1.10113 +
 1.10114 +#endif /* _SQLITE_OS_H_ */
 1.10115 +
 1.10116 +/************** End of os.h **************************************************/
 1.10117 +/************** Continuing where we left off in sqliteInt.h ******************/
 1.10118 +/************** Include mutex.h in the middle of sqliteInt.h *****************/
 1.10119 +/************** Begin file mutex.h *******************************************/
 1.10120 +/*
 1.10121 +** 2007 August 28
 1.10122 +**
 1.10123 +** The author disclaims copyright to this source code.  In place of
 1.10124 +** a legal notice, here is a blessing:
 1.10125 +**
 1.10126 +**    May you do good and not evil.
 1.10127 +**    May you find forgiveness for yourself and forgive others.
 1.10128 +**    May you share freely, never taking more than you give.
 1.10129 +**
 1.10130 +*************************************************************************
 1.10131 +**
 1.10132 +** This file contains the common header for all mutex implementations.
 1.10133 +** The sqliteInt.h header #includes this file so that it is available
 1.10134 +** to all source files.  We break it out in an effort to keep the code
 1.10135 +** better organized.
 1.10136 +**
 1.10137 +** NOTE:  source files should *not* #include this header file directly.
 1.10138 +** Source files should #include the sqliteInt.h file and let that file
 1.10139 +** include this one indirectly.
 1.10140 +*/
 1.10141 +
 1.10142 +
 1.10143 +/*
 1.10144 +** Figure out what version of the code to use.  The choices are
 1.10145 +**
 1.10146 +**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
 1.10147 +**                             mutexes implemention cannot be overridden
 1.10148 +**                             at start-time.
 1.10149 +**
 1.10150 +**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
 1.10151 +**                             mutual exclusion is provided.  But this
 1.10152 +**                             implementation can be overridden at
 1.10153 +**                             start-time.
 1.10154 +**
 1.10155 +**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
 1.10156 +**
 1.10157 +**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
 1.10158 +*/
 1.10159 +#if !SQLITE_THREADSAFE
 1.10160 +# define SQLITE_MUTEX_OMIT
 1.10161 +#endif
 1.10162 +#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
 1.10163 +#  if SQLITE_OS_UNIX
 1.10164 +#    define SQLITE_MUTEX_PTHREADS
 1.10165 +#  elif SQLITE_OS_WIN
 1.10166 +#    define SQLITE_MUTEX_W32
 1.10167 +#  else
 1.10168 +#    define SQLITE_MUTEX_NOOP
 1.10169 +#  endif
 1.10170 +#endif
 1.10171 +
 1.10172 +#ifdef SQLITE_MUTEX_OMIT
 1.10173 +/*
 1.10174 +** If this is a no-op implementation, implement everything as macros.
 1.10175 +*/
 1.10176 +#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
 1.10177 +#define sqlite3_mutex_free(X)
 1.10178 +#define sqlite3_mutex_enter(X)    
 1.10179 +#define sqlite3_mutex_try(X)      SQLITE_OK
 1.10180 +#define sqlite3_mutex_leave(X)    
 1.10181 +#define sqlite3_mutex_held(X)     ((void)(X),1)
 1.10182 +#define sqlite3_mutex_notheld(X)  ((void)(X),1)
 1.10183 +#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
 1.10184 +#define sqlite3MutexInit()        SQLITE_OK
 1.10185 +#define sqlite3MutexEnd()
 1.10186 +#define MUTEX_LOGIC(X)
 1.10187 +#else
 1.10188 +#define MUTEX_LOGIC(X)            X
 1.10189 +#endif /* defined(SQLITE_MUTEX_OMIT) */
 1.10190 +
 1.10191 +/************** End of mutex.h ***********************************************/
 1.10192 +/************** Continuing where we left off in sqliteInt.h ******************/
 1.10193 +
 1.10194 +
 1.10195 +/*
 1.10196 +** Each database file to be accessed by the system is an instance
 1.10197 +** of the following structure.  There are normally two of these structures
 1.10198 +** in the sqlite.aDb[] array.  aDb[0] is the main database file and
 1.10199 +** aDb[1] is the database file used to hold temporary tables.  Additional
 1.10200 +** databases may be attached.
 1.10201 +*/
 1.10202 +struct Db {
 1.10203 +  char *zName;         /* Name of this database */
 1.10204 +  Btree *pBt;          /* The B*Tree structure for this database file */
 1.10205 +  u8 safety_level;     /* How aggressive at syncing data to disk */
 1.10206 +  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
 1.10207 +};
 1.10208 +
 1.10209 +/*
 1.10210 +** An instance of the following structure stores a database schema.
 1.10211 +**
 1.10212 +** Most Schema objects are associated with a Btree.  The exception is
 1.10213 +** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
 1.10214 +** In shared cache mode, a single Schema object can be shared by multiple
 1.10215 +** Btrees that refer to the same underlying BtShared object.
 1.10216 +** 
 1.10217 +** Schema objects are automatically deallocated when the last Btree that
 1.10218 +** references them is destroyed.   The TEMP Schema is manually freed by
 1.10219 +** sqlite3_close().
 1.10220 +*
 1.10221 +** A thread must be holding a mutex on the corresponding Btree in order
 1.10222 +** to access Schema content.  This implies that the thread must also be
 1.10223 +** holding a mutex on the sqlite3 connection pointer that owns the Btree.
 1.10224 +** For a TEMP Schema, only the connection mutex is required.
 1.10225 +*/
 1.10226 +struct Schema {
 1.10227 +  int schema_cookie;   /* Database schema version number for this file */
 1.10228 +  int iGeneration;     /* Generation counter.  Incremented with each change */
 1.10229 +  Hash tblHash;        /* All tables indexed by name */
 1.10230 +  Hash idxHash;        /* All (named) indices indexed by name */
 1.10231 +  Hash trigHash;       /* All triggers indexed by name */
 1.10232 +  Hash fkeyHash;       /* All foreign keys by referenced table name */
 1.10233 +  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
 1.10234 +  u8 file_format;      /* Schema format version for this file */
 1.10235 +  u8 enc;              /* Text encoding used by this database */
 1.10236 +  u16 flags;           /* Flags associated with this schema */
 1.10237 +  int cache_size;      /* Number of pages to use in the cache */
 1.10238 +};
 1.10239 +
 1.10240 +/*
 1.10241 +** These macros can be used to test, set, or clear bits in the 
 1.10242 +** Db.pSchema->flags field.
 1.10243 +*/
 1.10244 +#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
 1.10245 +#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
 1.10246 +#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
 1.10247 +#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
 1.10248 +
 1.10249 +/*
 1.10250 +** Allowed values for the DB.pSchema->flags field.
 1.10251 +**
 1.10252 +** The DB_SchemaLoaded flag is set after the database schema has been
 1.10253 +** read into internal hash tables.
 1.10254 +**
 1.10255 +** DB_UnresetViews means that one or more views have column names that
 1.10256 +** have been filled out.  If the schema changes, these column names might
 1.10257 +** changes and so the view will need to be reset.
 1.10258 +*/
 1.10259 +#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
 1.10260 +#define DB_UnresetViews    0x0002  /* Some views have defined column names */
 1.10261 +#define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
 1.10262 +
 1.10263 +/*
 1.10264 +** The number of different kinds of things that can be limited
 1.10265 +** using the sqlite3_limit() interface.
 1.10266 +*/
 1.10267 +#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
 1.10268 +
 1.10269 +/*
 1.10270 +** Lookaside malloc is a set of fixed-size buffers that can be used
 1.10271 +** to satisfy small transient memory allocation requests for objects
 1.10272 +** associated with a particular database connection.  The use of
 1.10273 +** lookaside malloc provides a significant performance enhancement
 1.10274 +** (approx 10%) by avoiding numerous malloc/free requests while parsing
 1.10275 +** SQL statements.
 1.10276 +**
 1.10277 +** The Lookaside structure holds configuration information about the
 1.10278 +** lookaside malloc subsystem.  Each available memory allocation in
 1.10279 +** the lookaside subsystem is stored on a linked list of LookasideSlot
 1.10280 +** objects.
 1.10281 +**
 1.10282 +** Lookaside allocations are only allowed for objects that are associated
 1.10283 +** with a particular database connection.  Hence, schema information cannot
 1.10284 +** be stored in lookaside because in shared cache mode the schema information
 1.10285 +** is shared by multiple database connections.  Therefore, while parsing
 1.10286 +** schema information, the Lookaside.bEnabled flag is cleared so that
 1.10287 +** lookaside allocations are not used to construct the schema objects.
 1.10288 +*/
 1.10289 +struct Lookaside {
 1.10290 +  u16 sz;                 /* Size of each buffer in bytes */
 1.10291 +  u8 bEnabled;            /* False to disable new lookaside allocations */
 1.10292 +  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
 1.10293 +  int nOut;               /* Number of buffers currently checked out */
 1.10294 +  int mxOut;              /* Highwater mark for nOut */
 1.10295 +  int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
 1.10296 +  LookasideSlot *pFree;   /* List of available buffers */
 1.10297 +  void *pStart;           /* First byte of available memory space */
 1.10298 +  void *pEnd;             /* First byte past end of available space */
 1.10299 +};
 1.10300 +struct LookasideSlot {
 1.10301 +  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
 1.10302 +};
 1.10303 +
 1.10304 +/*
 1.10305 +** A hash table for function definitions.
 1.10306 +**
 1.10307 +** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
 1.10308 +** Collisions are on the FuncDef.pHash chain.
 1.10309 +*/
 1.10310 +struct FuncDefHash {
 1.10311 +  FuncDef *a[23];       /* Hash table for functions */
 1.10312 +};
 1.10313 +
 1.10314 +/*
 1.10315 +** Each database connection is an instance of the following structure.
 1.10316 +*/
 1.10317 +struct sqlite3 {
 1.10318 +  sqlite3_vfs *pVfs;            /* OS Interface */
 1.10319 +  struct Vdbe *pVdbe;           /* List of active virtual machines */
 1.10320 +  CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
 1.10321 +  sqlite3_mutex *mutex;         /* Connection mutex */
 1.10322 +  Db *aDb;                      /* All backends */
 1.10323 +  int nDb;                      /* Number of backends currently in use */
 1.10324 +  int flags;                    /* Miscellaneous flags. See below */
 1.10325 +  i64 lastRowid;                /* ROWID of most recent insert (see above) */
 1.10326 +  i64 szMmap;                   /* Default mmap_size setting */
 1.10327 +  unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
 1.10328 +  int errCode;                  /* Most recent error code (SQLITE_*) */
 1.10329 +  int errMask;                  /* & result codes with this before returning */
 1.10330 +  u16 dbOptFlags;               /* Flags to enable/disable optimizations */
 1.10331 +  u8 autoCommit;                /* The auto-commit flag. */
 1.10332 +  u8 temp_store;                /* 1: file 2: memory 0: default */
 1.10333 +  u8 mallocFailed;              /* True if we have seen a malloc failure */
 1.10334 +  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
 1.10335 +  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
 1.10336 +  u8 suppressErr;               /* Do not issue error messages if true */
 1.10337 +  u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
 1.10338 +  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
 1.10339 +  int nextPagesize;             /* Pagesize after VACUUM if >0 */
 1.10340 +  u32 magic;                    /* Magic number for detect library misuse */
 1.10341 +  int nChange;                  /* Value returned by sqlite3_changes() */
 1.10342 +  int nTotalChange;             /* Value returned by sqlite3_total_changes() */
 1.10343 +  int aLimit[SQLITE_N_LIMIT];   /* Limits */
 1.10344 +  struct sqlite3InitInfo {      /* Information used during initialization */
 1.10345 +    int newTnum;                /* Rootpage of table being initialized */
 1.10346 +    u8 iDb;                     /* Which db file is being initialized */
 1.10347 +    u8 busy;                    /* TRUE if currently initializing */
 1.10348 +    u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
 1.10349 +  } init;
 1.10350 +  int nVdbeActive;              /* Number of VDBEs currently running */
 1.10351 +  int nVdbeRead;                /* Number of active VDBEs that read or write */
 1.10352 +  int nVdbeWrite;               /* Number of active VDBEs that read and write */
 1.10353 +  int nVdbeExec;                /* Number of nested calls to VdbeExec() */
 1.10354 +  int nExtension;               /* Number of loaded extensions */
 1.10355 +  void **aExtension;            /* Array of shared library handles */
 1.10356 +  void (*xTrace)(void*,const char*);        /* Trace function */
 1.10357 +  void *pTraceArg;                          /* Argument to the trace function */
 1.10358 +  void (*xProfile)(void*,const char*,u64);  /* Profiling function */
 1.10359 +  void *pProfileArg;                        /* Argument to profile function */
 1.10360 +  void *pCommitArg;                 /* Argument to xCommitCallback() */   
 1.10361 +  int (*xCommitCallback)(void*);    /* Invoked at every commit. */
 1.10362 +  void *pRollbackArg;               /* Argument to xRollbackCallback() */   
 1.10363 +  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
 1.10364 +  void *pUpdateArg;
 1.10365 +  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
 1.10366 +#ifndef SQLITE_OMIT_WAL
 1.10367 +  int (*xWalCallback)(void *, sqlite3 *, const char *, int);
 1.10368 +  void *pWalArg;
 1.10369 +#endif
 1.10370 +  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
 1.10371 +  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
 1.10372 +  void *pCollNeededArg;
 1.10373 +  sqlite3_value *pErr;          /* Most recent error message */
 1.10374 +  union {
 1.10375 +    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
 1.10376 +    double notUsed1;            /* Spacer */
 1.10377 +  } u1;
 1.10378 +  Lookaside lookaside;          /* Lookaside malloc configuration */
 1.10379 +#ifndef SQLITE_OMIT_AUTHORIZATION
 1.10380 +  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
 1.10381 +                                /* Access authorization function */
 1.10382 +  void *pAuthArg;               /* 1st argument to the access auth function */
 1.10383 +#endif
 1.10384 +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
 1.10385 +  int (*xProgress)(void *);     /* The progress callback */
 1.10386 +  void *pProgressArg;           /* Argument to the progress callback */
 1.10387 +  unsigned nProgressOps;        /* Number of opcodes for progress callback */
 1.10388 +#endif
 1.10389 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.10390 +  int nVTrans;                  /* Allocated size of aVTrans */
 1.10391 +  Hash aModule;                 /* populated by sqlite3_create_module() */
 1.10392 +  VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
 1.10393 +  VTable **aVTrans;             /* Virtual tables with open transactions */
 1.10394 +  VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
 1.10395 +#endif
 1.10396 +  FuncDefHash aFunc;            /* Hash table of connection functions */
 1.10397 +  Hash aCollSeq;                /* All collating sequences */
 1.10398 +  BusyHandler busyHandler;      /* Busy callback */
 1.10399 +  Db aDbStatic[2];              /* Static space for the 2 default backends */
 1.10400 +  Savepoint *pSavepoint;        /* List of active savepoints */
 1.10401 +  int busyTimeout;              /* Busy handler timeout, in msec */
 1.10402 +  int nSavepoint;               /* Number of non-transaction savepoints */
 1.10403 +  int nStatement;               /* Number of nested statement-transactions  */
 1.10404 +  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
 1.10405 +  i64 nDeferredImmCons;         /* Net deferred immediate constraints */
 1.10406 +  int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
 1.10407 +
 1.10408 +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
 1.10409 +  /* The following variables are all protected by the STATIC_MASTER 
 1.10410 +  ** mutex, not by sqlite3.mutex. They are used by code in notify.c. 
 1.10411 +  **
 1.10412 +  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
 1.10413 +  ** unlock so that it can proceed.
 1.10414 +  **
 1.10415 +  ** When X.pBlockingConnection==Y, that means that something that X tried
 1.10416 +  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
 1.10417 +  ** held by Y.
 1.10418 +  */
 1.10419 +  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
 1.10420 +  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
 1.10421 +  void *pUnlockArg;                     /* Argument to xUnlockNotify */
 1.10422 +  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
 1.10423 +  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
 1.10424 +#endif
 1.10425 +};
 1.10426 +
 1.10427 +/*
 1.10428 +** A macro to discover the encoding of a database.
 1.10429 +*/
 1.10430 +#define ENC(db) ((db)->aDb[0].pSchema->enc)
 1.10431 +
 1.10432 +/*
 1.10433 +** Possible values for the sqlite3.flags.
 1.10434 +*/
 1.10435 +#define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
 1.10436 +#define SQLITE_InternChanges  0x00000002  /* Uncommitted Hash table changes */
 1.10437 +#define SQLITE_FullFSync      0x00000004  /* Use full fsync on the backend */
 1.10438 +#define SQLITE_CkptFullFSync  0x00000008  /* Use full fsync for checkpoint */
 1.10439 +#define SQLITE_CacheSpill     0x00000010  /* OK to spill pager cache */
 1.10440 +#define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
 1.10441 +#define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
 1.10442 +#define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
 1.10443 +                                          /*   DELETE, or UPDATE and return */
 1.10444 +                                          /*   the count using a callback. */
 1.10445 +#define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
 1.10446 +                                          /*   result set is empty */
 1.10447 +#define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
 1.10448 +#define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
 1.10449 +#define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
 1.10450 +#define SQLITE_VdbeAddopTrace 0x00001000  /* Trace sqlite3VdbeAddOp() calls */
 1.10451 +#define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
 1.10452 +#define SQLITE_ReadUncommitted 0x0004000  /* For shared-cache mode */
 1.10453 +#define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
 1.10454 +#define SQLITE_RecoveryMode   0x00010000  /* Ignore schema errors */
 1.10455 +#define SQLITE_ReverseOrder   0x00020000  /* Reverse unordered SELECTs */
 1.10456 +#define SQLITE_RecTriggers    0x00040000  /* Enable recursive triggers */
 1.10457 +#define SQLITE_ForeignKeys    0x00080000  /* Enforce foreign key constraints  */
 1.10458 +#define SQLITE_AutoIndex      0x00100000  /* Enable automatic indexes */
 1.10459 +#define SQLITE_PreferBuiltin  0x00200000  /* Preference to built-in funcs */
 1.10460 +#define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
 1.10461 +#define SQLITE_EnableTrigger  0x00800000  /* True to enable triggers */
 1.10462 +#define SQLITE_DeferFKs       0x01000000  /* Defer all FK constraints */
 1.10463 +#define SQLITE_QueryOnly      0x02000000  /* Disable database changes */
 1.10464 +#define SQLITE_VdbeEQP        0x04000000  /* Debug EXPLAIN QUERY PLAN */
 1.10465 +
 1.10466 +
 1.10467 +/*
 1.10468 +** Bits of the sqlite3.dbOptFlags field that are used by the
 1.10469 +** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
 1.10470 +** selectively disable various optimizations.
 1.10471 +*/
 1.10472 +#define SQLITE_QueryFlattener 0x0001   /* Query flattening */
 1.10473 +#define SQLITE_ColumnCache    0x0002   /* Column cache */
 1.10474 +#define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
 1.10475 +#define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
 1.10476 +/*                not used    0x0010   // Was: SQLITE_IdxRealAsInt */
 1.10477 +#define SQLITE_DistinctOpt    0x0020   /* DISTINCT using indexes */
 1.10478 +#define SQLITE_CoverIdxScan   0x0040   /* Covering index scans */
 1.10479 +#define SQLITE_OrderByIdxJoin 0x0080   /* ORDER BY of joins via index */
 1.10480 +#define SQLITE_SubqCoroutine  0x0100   /* Evaluate subqueries as coroutines */
 1.10481 +#define SQLITE_Transitive     0x0200   /* Transitive constraints */
 1.10482 +#define SQLITE_OmitNoopJoin   0x0400   /* Omit unused tables in joins */
 1.10483 +#define SQLITE_Stat3          0x0800   /* Use the SQLITE_STAT3 table */
 1.10484 +#define SQLITE_AdjustOutEst   0x1000   /* Adjust output estimates using WHERE */
 1.10485 +#define SQLITE_AllOpts        0xffff   /* All optimizations */
 1.10486 +
 1.10487 +/*
 1.10488 +** Macros for testing whether or not optimizations are enabled or disabled.
 1.10489 +*/
 1.10490 +#ifndef SQLITE_OMIT_BUILTIN_TEST
 1.10491 +#define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
 1.10492 +#define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
 1.10493 +#else
 1.10494 +#define OptimizationDisabled(db, mask)  0
 1.10495 +#define OptimizationEnabled(db, mask)   1
 1.10496 +#endif
 1.10497 +
 1.10498 +/*
 1.10499 +** Return true if it OK to factor constant expressions into the initialization
 1.10500 +** code. The argument is a Parse object for the code generator.
 1.10501 +*/
 1.10502 +#define ConstFactorOk(P) ((P)->okConstFactor)
 1.10503 +
 1.10504 +/*
 1.10505 +** Possible values for the sqlite.magic field.
 1.10506 +** The numbers are obtained at random and have no special meaning, other
 1.10507 +** than being distinct from one another.
 1.10508 +*/
 1.10509 +#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
 1.10510 +#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
 1.10511 +#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
 1.10512 +#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
 1.10513 +#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
 1.10514 +#define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
 1.10515 +
 1.10516 +/*
 1.10517 +** Each SQL function is defined by an instance of the following
 1.10518 +** structure.  A pointer to this structure is stored in the sqlite.aFunc
 1.10519 +** hash table.  When multiple functions have the same name, the hash table
 1.10520 +** points to a linked list of these structures.
 1.10521 +*/
 1.10522 +struct FuncDef {
 1.10523 +  i16 nArg;            /* Number of arguments.  -1 means unlimited */
 1.10524 +  u16 funcFlags;       /* Some combination of SQLITE_FUNC_* */
 1.10525 +  void *pUserData;     /* User data parameter */
 1.10526 +  FuncDef *pNext;      /* Next function with same name */
 1.10527 +  void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
 1.10528 +  void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
 1.10529 +  void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
 1.10530 +  char *zName;         /* SQL name of the function. */
 1.10531 +  FuncDef *pHash;      /* Next with a different name but the same hash */
 1.10532 +  FuncDestructor *pDestructor;   /* Reference counted destructor function */
 1.10533 +};
 1.10534 +
 1.10535 +/*
 1.10536 +** This structure encapsulates a user-function destructor callback (as
 1.10537 +** configured using create_function_v2()) and a reference counter. When
 1.10538 +** create_function_v2() is called to create a function with a destructor,
 1.10539 +** a single object of this type is allocated. FuncDestructor.nRef is set to 
 1.10540 +** the number of FuncDef objects created (either 1 or 3, depending on whether
 1.10541 +** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
 1.10542 +** member of each of the new FuncDef objects is set to point to the allocated
 1.10543 +** FuncDestructor.
 1.10544 +**
 1.10545 +** Thereafter, when one of the FuncDef objects is deleted, the reference
 1.10546 +** count on this object is decremented. When it reaches 0, the destructor
 1.10547 +** is invoked and the FuncDestructor structure freed.
 1.10548 +*/
 1.10549 +struct FuncDestructor {
 1.10550 +  int nRef;
 1.10551 +  void (*xDestroy)(void *);
 1.10552 +  void *pUserData;
 1.10553 +};
 1.10554 +
 1.10555 +/*
 1.10556 +** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
 1.10557 +** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  There
 1.10558 +** are assert() statements in the code to verify this.
 1.10559 +*/
 1.10560 +#define SQLITE_FUNC_ENCMASK  0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
 1.10561 +#define SQLITE_FUNC_LIKE     0x004 /* Candidate for the LIKE optimization */
 1.10562 +#define SQLITE_FUNC_CASE     0x008 /* Case-sensitive LIKE-type function */
 1.10563 +#define SQLITE_FUNC_EPHEM    0x010 /* Ephemeral.  Delete with VDBE */
 1.10564 +#define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */
 1.10565 +#define SQLITE_FUNC_LENGTH   0x040 /* Built-in length() function */
 1.10566 +#define SQLITE_FUNC_TYPEOF   0x080 /* Built-in typeof() function */
 1.10567 +#define SQLITE_FUNC_COUNT    0x100 /* Built-in count(*) aggregate */
 1.10568 +#define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */
 1.10569 +#define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */
 1.10570 +#define SQLITE_FUNC_CONSTANT 0x800 /* Constant inputs give a constant output */
 1.10571 +
 1.10572 +/*
 1.10573 +** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
 1.10574 +** used to create the initializers for the FuncDef structures.
 1.10575 +**
 1.10576 +**   FUNCTION(zName, nArg, iArg, bNC, xFunc)
 1.10577 +**     Used to create a scalar function definition of a function zName 
 1.10578 +**     implemented by C function xFunc that accepts nArg arguments. The
 1.10579 +**     value passed as iArg is cast to a (void*) and made available
 1.10580 +**     as the user-data (sqlite3_user_data()) for the function. If 
 1.10581 +**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
 1.10582 +**
 1.10583 +**   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
 1.10584 +**     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
 1.10585 +**
 1.10586 +**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
 1.10587 +**     Used to create an aggregate function definition implemented by
 1.10588 +**     the C functions xStep and xFinal. The first four parameters
 1.10589 +**     are interpreted in the same way as the first 4 parameters to
 1.10590 +**     FUNCTION().
 1.10591 +**
 1.10592 +**   LIKEFUNC(zName, nArg, pArg, flags)
 1.10593 +**     Used to create a scalar function definition of a function zName 
 1.10594 +**     that accepts nArg arguments and is implemented by a call to C 
 1.10595 +**     function likeFunc. Argument pArg is cast to a (void *) and made
 1.10596 +**     available as the function user-data (sqlite3_user_data()). The
 1.10597 +**     FuncDef.flags variable is set to the value passed as the flags
 1.10598 +**     parameter.
 1.10599 +*/
 1.10600 +#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
 1.10601 +  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
 1.10602 +   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
 1.10603 +#define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
 1.10604 +  {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
 1.10605 +   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
 1.10606 +#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
 1.10607 +  {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
 1.10608 +   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
 1.10609 +#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
 1.10610 +  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
 1.10611 +   pArg, 0, xFunc, 0, 0, #zName, 0, 0}
 1.10612 +#define LIKEFUNC(zName, nArg, arg, flags) \
 1.10613 +  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
 1.10614 +   (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
 1.10615 +#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
 1.10616 +  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
 1.10617 +   SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
 1.10618 +
 1.10619 +/*
 1.10620 +** All current savepoints are stored in a linked list starting at
 1.10621 +** sqlite3.pSavepoint. The first element in the list is the most recently
 1.10622 +** opened savepoint. Savepoints are added to the list by the vdbe
 1.10623 +** OP_Savepoint instruction.
 1.10624 +*/
 1.10625 +struct Savepoint {
 1.10626 +  char *zName;                        /* Savepoint name (nul-terminated) */
 1.10627 +  i64 nDeferredCons;                  /* Number of deferred fk violations */
 1.10628 +  i64 nDeferredImmCons;               /* Number of deferred imm fk. */
 1.10629 +  Savepoint *pNext;                   /* Parent savepoint (if any) */
 1.10630 +};
 1.10631 +
 1.10632 +/*
 1.10633 +** The following are used as the second parameter to sqlite3Savepoint(),
 1.10634 +** and as the P1 argument to the OP_Savepoint instruction.
 1.10635 +*/
 1.10636 +#define SAVEPOINT_BEGIN      0
 1.10637 +#define SAVEPOINT_RELEASE    1
 1.10638 +#define SAVEPOINT_ROLLBACK   2
 1.10639 +
 1.10640 +
 1.10641 +/*
 1.10642 +** Each SQLite module (virtual table definition) is defined by an
 1.10643 +** instance of the following structure, stored in the sqlite3.aModule
 1.10644 +** hash table.
 1.10645 +*/
 1.10646 +struct Module {
 1.10647 +  const sqlite3_module *pModule;       /* Callback pointers */
 1.10648 +  const char *zName;                   /* Name passed to create_module() */
 1.10649 +  void *pAux;                          /* pAux passed to create_module() */
 1.10650 +  void (*xDestroy)(void *);            /* Module destructor function */
 1.10651 +};
 1.10652 +
 1.10653 +/*
 1.10654 +** information about each column of an SQL table is held in an instance
 1.10655 +** of this structure.
 1.10656 +*/
 1.10657 +struct Column {
 1.10658 +  char *zName;     /* Name of this column */
 1.10659 +  Expr *pDflt;     /* Default value of this column */
 1.10660 +  char *zDflt;     /* Original text of the default value */
 1.10661 +  char *zType;     /* Data type for this column */
 1.10662 +  char *zColl;     /* Collating sequence.  If NULL, use the default */
 1.10663 +  u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
 1.10664 +  char affinity;   /* One of the SQLITE_AFF_... values */
 1.10665 +  u8 szEst;        /* Estimated size of this column.  INT==1 */
 1.10666 +  u8 colFlags;     /* Boolean properties.  See COLFLAG_ defines below */
 1.10667 +};
 1.10668 +
 1.10669 +/* Allowed values for Column.colFlags:
 1.10670 +*/
 1.10671 +#define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
 1.10672 +#define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
 1.10673 +
 1.10674 +/*
 1.10675 +** A "Collating Sequence" is defined by an instance of the following
 1.10676 +** structure. Conceptually, a collating sequence consists of a name and
 1.10677 +** a comparison routine that defines the order of that sequence.
 1.10678 +**
 1.10679 +** If CollSeq.xCmp is NULL, it means that the
 1.10680 +** collating sequence is undefined.  Indices built on an undefined
 1.10681 +** collating sequence may not be read or written.
 1.10682 +*/
 1.10683 +struct CollSeq {
 1.10684 +  char *zName;          /* Name of the collating sequence, UTF-8 encoded */
 1.10685 +  u8 enc;               /* Text encoding handled by xCmp() */
 1.10686 +  void *pUser;          /* First argument to xCmp() */
 1.10687 +  int (*xCmp)(void*,int, const void*, int, const void*);
 1.10688 +  void (*xDel)(void*);  /* Destructor for pUser */
 1.10689 +};
 1.10690 +
 1.10691 +/*
 1.10692 +** A sort order can be either ASC or DESC.
 1.10693 +*/
 1.10694 +#define SQLITE_SO_ASC       0  /* Sort in ascending order */
 1.10695 +#define SQLITE_SO_DESC      1  /* Sort in ascending order */
 1.10696 +
 1.10697 +/*
 1.10698 +** Column affinity types.
 1.10699 +**
 1.10700 +** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
 1.10701 +** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
 1.10702 +** the speed a little by numbering the values consecutively.  
 1.10703 +**
 1.10704 +** But rather than start with 0 or 1, we begin with 'a'.  That way,
 1.10705 +** when multiple affinity types are concatenated into a string and
 1.10706 +** used as the P4 operand, they will be more readable.
 1.10707 +**
 1.10708 +** Note also that the numeric types are grouped together so that testing
 1.10709 +** for a numeric type is a single comparison.
 1.10710 +*/
 1.10711 +#define SQLITE_AFF_TEXT     'a'
 1.10712 +#define SQLITE_AFF_NONE     'b'
 1.10713 +#define SQLITE_AFF_NUMERIC  'c'
 1.10714 +#define SQLITE_AFF_INTEGER  'd'
 1.10715 +#define SQLITE_AFF_REAL     'e'
 1.10716 +
 1.10717 +#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
 1.10718 +
 1.10719 +/*
 1.10720 +** The SQLITE_AFF_MASK values masks off the significant bits of an
 1.10721 +** affinity value. 
 1.10722 +*/
 1.10723 +#define SQLITE_AFF_MASK     0x67
 1.10724 +
 1.10725 +/*
 1.10726 +** Additional bit values that can be ORed with an affinity without
 1.10727 +** changing the affinity.
 1.10728 +**
 1.10729 +** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
 1.10730 +** It causes an assert() to fire if either operand to a comparison
 1.10731 +** operator is NULL.  It is added to certain comparison operators to
 1.10732 +** prove that the operands are always NOT NULL.
 1.10733 +*/
 1.10734 +#define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
 1.10735 +#define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
 1.10736 +#define SQLITE_NULLEQ       0x80  /* NULL=NULL */
 1.10737 +#define SQLITE_NOTNULL      0x88  /* Assert that operands are never NULL */
 1.10738 +
 1.10739 +/*
 1.10740 +** An object of this type is created for each virtual table present in
 1.10741 +** the database schema. 
 1.10742 +**
 1.10743 +** If the database schema is shared, then there is one instance of this
 1.10744 +** structure for each database connection (sqlite3*) that uses the shared
 1.10745 +** schema. This is because each database connection requires its own unique
 1.10746 +** instance of the sqlite3_vtab* handle used to access the virtual table 
 1.10747 +** implementation. sqlite3_vtab* handles can not be shared between 
 1.10748 +** database connections, even when the rest of the in-memory database 
 1.10749 +** schema is shared, as the implementation often stores the database
 1.10750 +** connection handle passed to it via the xConnect() or xCreate() method
 1.10751 +** during initialization internally. This database connection handle may
 1.10752 +** then be used by the virtual table implementation to access real tables 
 1.10753 +** within the database. So that they appear as part of the callers 
 1.10754 +** transaction, these accesses need to be made via the same database 
 1.10755 +** connection as that used to execute SQL operations on the virtual table.
 1.10756 +**
 1.10757 +** All VTable objects that correspond to a single table in a shared
 1.10758 +** database schema are initially stored in a linked-list pointed to by
 1.10759 +** the Table.pVTable member variable of the corresponding Table object.
 1.10760 +** When an sqlite3_prepare() operation is required to access the virtual
 1.10761 +** table, it searches the list for the VTable that corresponds to the
 1.10762 +** database connection doing the preparing so as to use the correct
 1.10763 +** sqlite3_vtab* handle in the compiled query.
 1.10764 +**
 1.10765 +** When an in-memory Table object is deleted (for example when the
 1.10766 +** schema is being reloaded for some reason), the VTable objects are not 
 1.10767 +** deleted and the sqlite3_vtab* handles are not xDisconnect()ed 
 1.10768 +** immediately. Instead, they are moved from the Table.pVTable list to
 1.10769 +** another linked list headed by the sqlite3.pDisconnect member of the
 1.10770 +** corresponding sqlite3 structure. They are then deleted/xDisconnected 
 1.10771 +** next time a statement is prepared using said sqlite3*. This is done
 1.10772 +** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
 1.10773 +** Refer to comments above function sqlite3VtabUnlockList() for an
 1.10774 +** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
 1.10775 +** list without holding the corresponding sqlite3.mutex mutex.
 1.10776 +**
 1.10777 +** The memory for objects of this type is always allocated by 
 1.10778 +** sqlite3DbMalloc(), using the connection handle stored in VTable.db as 
 1.10779 +** the first argument.
 1.10780 +*/
 1.10781 +struct VTable {
 1.10782 +  sqlite3 *db;              /* Database connection associated with this table */
 1.10783 +  Module *pMod;             /* Pointer to module implementation */
 1.10784 +  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
 1.10785 +  int nRef;                 /* Number of pointers to this structure */
 1.10786 +  u8 bConstraint;           /* True if constraints are supported */
 1.10787 +  int iSavepoint;           /* Depth of the SAVEPOINT stack */
 1.10788 +  VTable *pNext;            /* Next in linked list (see above) */
 1.10789 +};
 1.10790 +
 1.10791 +/*
 1.10792 +** Each SQL table is represented in memory by an instance of the
 1.10793 +** following structure.
 1.10794 +**
 1.10795 +** Table.zName is the name of the table.  The case of the original
 1.10796 +** CREATE TABLE statement is stored, but case is not significant for
 1.10797 +** comparisons.
 1.10798 +**
 1.10799 +** Table.nCol is the number of columns in this table.  Table.aCol is a
 1.10800 +** pointer to an array of Column structures, one for each column.
 1.10801 +**
 1.10802 +** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
 1.10803 +** the column that is that key.   Otherwise Table.iPKey is negative.  Note
 1.10804 +** that the datatype of the PRIMARY KEY must be INTEGER for this field to
 1.10805 +** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
 1.10806 +** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
 1.10807 +** is generated for each row of the table.  TF_HasPrimaryKey is set if
 1.10808 +** the table has any PRIMARY KEY, INTEGER or otherwise.
 1.10809 +**
 1.10810 +** Table.tnum is the page number for the root BTree page of the table in the
 1.10811 +** database file.  If Table.iDb is the index of the database table backend
 1.10812 +** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
 1.10813 +** holds temporary tables and indices.  If TF_Ephemeral is set
 1.10814 +** then the table is stored in a file that is automatically deleted
 1.10815 +** when the VDBE cursor to the table is closed.  In this case Table.tnum 
 1.10816 +** refers VDBE cursor number that holds the table open, not to the root
 1.10817 +** page number.  Transient tables are used to hold the results of a
 1.10818 +** sub-query that appears instead of a real table name in the FROM clause 
 1.10819 +** of a SELECT statement.
 1.10820 +*/
 1.10821 +struct Table {
 1.10822 +  char *zName;         /* Name of the table or view */
 1.10823 +  Column *aCol;        /* Information about each column */
 1.10824 +  Index *pIndex;       /* List of SQL indexes on this table. */
 1.10825 +  Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
 1.10826 +  FKey *pFKey;         /* Linked list of all foreign keys in this table */
 1.10827 +  char *zColAff;       /* String defining the affinity of each column */
 1.10828 +#ifndef SQLITE_OMIT_CHECK
 1.10829 +  ExprList *pCheck;    /* All CHECK constraints */
 1.10830 +#endif
 1.10831 +  tRowcnt nRowEst;     /* Estimated rows in table - from sqlite_stat1 table */
 1.10832 +  int tnum;            /* Root BTree node for this table (see note above) */
 1.10833 +  i16 iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
 1.10834 +  i16 nCol;            /* Number of columns in this table */
 1.10835 +  u16 nRef;            /* Number of pointers to this Table */
 1.10836 +  LogEst szTabRow;     /* Estimated size of each table row in bytes */
 1.10837 +  u8 tabFlags;         /* Mask of TF_* values */
 1.10838 +  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
 1.10839 +#ifndef SQLITE_OMIT_ALTERTABLE
 1.10840 +  int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
 1.10841 +#endif
 1.10842 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.10843 +  int nModuleArg;      /* Number of arguments to the module */
 1.10844 +  char **azModuleArg;  /* Text of all module args. [0] is module name */
 1.10845 +  VTable *pVTable;     /* List of VTable objects. */
 1.10846 +#endif
 1.10847 +  Trigger *pTrigger;   /* List of triggers stored in pSchema */
 1.10848 +  Schema *pSchema;     /* Schema that contains this table */
 1.10849 +  Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
 1.10850 +};
 1.10851 +
 1.10852 +/*
 1.10853 +** Allowed values for Table.tabFlags.
 1.10854 +*/
 1.10855 +#define TF_Readonly        0x01    /* Read-only system table */
 1.10856 +#define TF_Ephemeral       0x02    /* An ephemeral table */
 1.10857 +#define TF_HasPrimaryKey   0x04    /* Table has a primary key */
 1.10858 +#define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
 1.10859 +#define TF_Virtual         0x10    /* Is a virtual table */
 1.10860 +#define TF_WithoutRowid    0x20    /* No rowid used. PRIMARY KEY is the key */
 1.10861 +
 1.10862 +
 1.10863 +/*
 1.10864 +** Test to see whether or not a table is a virtual table.  This is
 1.10865 +** done as a macro so that it will be optimized out when virtual
 1.10866 +** table support is omitted from the build.
 1.10867 +*/
 1.10868 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.10869 +#  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
 1.10870 +#  define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
 1.10871 +#else
 1.10872 +#  define IsVirtual(X)      0
 1.10873 +#  define IsHiddenColumn(X) 0
 1.10874 +#endif
 1.10875 +
 1.10876 +/* Does the table have a rowid */
 1.10877 +#define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)
 1.10878 +
 1.10879 +/*
 1.10880 +** Each foreign key constraint is an instance of the following structure.
 1.10881 +**
 1.10882 +** A foreign key is associated with two tables.  The "from" table is
 1.10883 +** the table that contains the REFERENCES clause that creates the foreign
 1.10884 +** key.  The "to" table is the table that is named in the REFERENCES clause.
 1.10885 +** Consider this example:
 1.10886 +**
 1.10887 +**     CREATE TABLE ex1(
 1.10888 +**       a INTEGER PRIMARY KEY,
 1.10889 +**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
 1.10890 +**     );
 1.10891 +**
 1.10892 +** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
 1.10893 +** Equivalent names:
 1.10894 +**
 1.10895 +**     from-table == child-table
 1.10896 +**       to-table == parent-table
 1.10897 +**
 1.10898 +** Each REFERENCES clause generates an instance of the following structure
 1.10899 +** which is attached to the from-table.  The to-table need not exist when
 1.10900 +** the from-table is created.  The existence of the to-table is not checked.
 1.10901 +**
 1.10902 +** The list of all parents for child Table X is held at X.pFKey.
 1.10903 +**
 1.10904 +** A list of all children for a table named Z (which might not even exist)
 1.10905 +** is held in Schema.fkeyHash with a hash key of Z.
 1.10906 +*/
 1.10907 +struct FKey {
 1.10908 +  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
 1.10909 +  FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */
 1.10910 +  char *zTo;        /* Name of table that the key points to (aka: Parent) */
 1.10911 +  FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */
 1.10912 +  FKey *pPrevTo;    /* Previous with the same zTo */
 1.10913 +  int nCol;         /* Number of columns in this key */
 1.10914 +  /* EV: R-30323-21917 */
 1.10915 +  u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */
 1.10916 +  u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */
 1.10917 +  Trigger *apTrigger[2];/* Triggers for aAction[] actions */
 1.10918 +  struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */
 1.10919 +    int iFrom;            /* Index of column in pFrom */
 1.10920 +    char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */
 1.10921 +  } aCol[1];            /* One entry for each of nCol columns */
 1.10922 +};
 1.10923 +
 1.10924 +/*
 1.10925 +** SQLite supports many different ways to resolve a constraint
 1.10926 +** error.  ROLLBACK processing means that a constraint violation
 1.10927 +** causes the operation in process to fail and for the current transaction
 1.10928 +** to be rolled back.  ABORT processing means the operation in process
 1.10929 +** fails and any prior changes from that one operation are backed out,
 1.10930 +** but the transaction is not rolled back.  FAIL processing means that
 1.10931 +** the operation in progress stops and returns an error code.  But prior
 1.10932 +** changes due to the same operation are not backed out and no rollback
 1.10933 +** occurs.  IGNORE means that the particular row that caused the constraint
 1.10934 +** error is not inserted or updated.  Processing continues and no error
 1.10935 +** is returned.  REPLACE means that preexisting database rows that caused
 1.10936 +** a UNIQUE constraint violation are removed so that the new insert or
 1.10937 +** update can proceed.  Processing continues and no error is reported.
 1.10938 +**
 1.10939 +** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
 1.10940 +** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
 1.10941 +** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
 1.10942 +** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
 1.10943 +** referenced table row is propagated into the row that holds the
 1.10944 +** foreign key.
 1.10945 +** 
 1.10946 +** The following symbolic values are used to record which type
 1.10947 +** of action to take.
 1.10948 +*/
 1.10949 +#define OE_None     0   /* There is no constraint to check */
 1.10950 +#define OE_Rollback 1   /* Fail the operation and rollback the transaction */
 1.10951 +#define OE_Abort    2   /* Back out changes but do no rollback transaction */
 1.10952 +#define OE_Fail     3   /* Stop the operation but leave all prior changes */
 1.10953 +#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
 1.10954 +#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
 1.10955 +
 1.10956 +#define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
 1.10957 +#define OE_SetNull  7   /* Set the foreign key value to NULL */
 1.10958 +#define OE_SetDflt  8   /* Set the foreign key value to its default */
 1.10959 +#define OE_Cascade  9   /* Cascade the changes */
 1.10960 +
 1.10961 +#define OE_Default  10  /* Do whatever the default action is */
 1.10962 +
 1.10963 +
 1.10964 +/*
 1.10965 +** An instance of the following structure is passed as the first
 1.10966 +** argument to sqlite3VdbeKeyCompare and is used to control the 
 1.10967 +** comparison of the two index keys.
 1.10968 +**
 1.10969 +** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
 1.10970 +** are nField slots for the columns of an index then one extra slot
 1.10971 +** for the rowid at the end.
 1.10972 +*/
 1.10973 +struct KeyInfo {
 1.10974 +  u32 nRef;           /* Number of references to this KeyInfo object */
 1.10975 +  u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
 1.10976 +  u16 nField;         /* Number of key columns in the index */
 1.10977 +  u16 nXField;        /* Number of columns beyond the key columns */
 1.10978 +  sqlite3 *db;        /* The database connection */
 1.10979 +  u8 *aSortOrder;     /* Sort order for each column. */
 1.10980 +  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
 1.10981 +};
 1.10982 +
 1.10983 +/*
 1.10984 +** An instance of the following structure holds information about a
 1.10985 +** single index record that has already been parsed out into individual
 1.10986 +** values.
 1.10987 +**
 1.10988 +** A record is an object that contains one or more fields of data.
 1.10989 +** Records are used to store the content of a table row and to store
 1.10990 +** the key of an index.  A blob encoding of a record is created by
 1.10991 +** the OP_MakeRecord opcode of the VDBE and is disassembled by the
 1.10992 +** OP_Column opcode.
 1.10993 +**
 1.10994 +** This structure holds a record that has already been disassembled
 1.10995 +** into its constituent fields.
 1.10996 +**
 1.10997 +** The r1 and r2 member variables are only used by the optimized comparison
 1.10998 +** functions vdbeRecordCompareInt() and vdbeRecordCompareString().
 1.10999 +*/
 1.11000 +struct UnpackedRecord {
 1.11001 +  KeyInfo *pKeyInfo;  /* Collation and sort-order information */
 1.11002 +  u16 nField;         /* Number of entries in apMem[] */
 1.11003 +  i8 default_rc;      /* Comparison result if keys are equal */
 1.11004 +  Mem *aMem;          /* Values */
 1.11005 +  int r1;             /* Value to return if (lhs > rhs) */
 1.11006 +  int r2;             /* Value to return if (rhs < lhs) */
 1.11007 +};
 1.11008 +
 1.11009 +
 1.11010 +/*
 1.11011 +** Each SQL index is represented in memory by an
 1.11012 +** instance of the following structure.
 1.11013 +**
 1.11014 +** The columns of the table that are to be indexed are described
 1.11015 +** by the aiColumn[] field of this structure.  For example, suppose
 1.11016 +** we have the following table and index:
 1.11017 +**
 1.11018 +**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
 1.11019 +**     CREATE INDEX Ex2 ON Ex1(c3,c1);
 1.11020 +**
 1.11021 +** In the Table structure describing Ex1, nCol==3 because there are
 1.11022 +** three columns in the table.  In the Index structure describing
 1.11023 +** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
 1.11024 +** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
 1.11025 +** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
 1.11026 +** The second column to be indexed (c1) has an index of 0 in
 1.11027 +** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
 1.11028 +**
 1.11029 +** The Index.onError field determines whether or not the indexed columns
 1.11030 +** must be unique and what to do if they are not.  When Index.onError=OE_None,
 1.11031 +** it means this is not a unique index.  Otherwise it is a unique index
 1.11032 +** and the value of Index.onError indicate the which conflict resolution 
 1.11033 +** algorithm to employ whenever an attempt is made to insert a non-unique
 1.11034 +** element.
 1.11035 +*/
 1.11036 +struct Index {
 1.11037 +  char *zName;             /* Name of this index */
 1.11038 +  i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */
 1.11039 +  tRowcnt *aiRowEst;       /* From ANALYZE: Est. rows selected by each column */
 1.11040 +  Table *pTable;           /* The SQL table being indexed */
 1.11041 +  char *zColAff;           /* String defining the affinity of each column */
 1.11042 +  Index *pNext;            /* The next index associated with the same table */
 1.11043 +  Schema *pSchema;         /* Schema containing this index */
 1.11044 +  u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
 1.11045 +  char **azColl;           /* Array of collation sequence names for index */
 1.11046 +  Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
 1.11047 +  KeyInfo *pKeyInfo;       /* A KeyInfo object suitable for this index */
 1.11048 +  int tnum;                /* DB Page containing root of this index */
 1.11049 +  LogEst szIdxRow;         /* Estimated average row size in bytes */
 1.11050 +  u16 nKeyCol;             /* Number of columns forming the key */
 1.11051 +  u16 nColumn;             /* Number of columns stored in the index */
 1.11052 +  u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
 1.11053 +  unsigned autoIndex:2;    /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
 1.11054 +  unsigned bUnordered:1;   /* Use this index for == or IN queries only */
 1.11055 +  unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
 1.11056 +  unsigned isResized:1;    /* True if resizeIndexObject() has been called */
 1.11057 +  unsigned isCovering:1;   /* True if this is a covering index */
 1.11058 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.11059 +  int nSample;             /* Number of elements in aSample[] */
 1.11060 +  int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
 1.11061 +  tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
 1.11062 +  IndexSample *aSample;    /* Samples of the left-most key */
 1.11063 +#endif
 1.11064 +};
 1.11065 +
 1.11066 +/*
 1.11067 +** Each sample stored in the sqlite_stat3 table is represented in memory 
 1.11068 +** using a structure of this type.  See documentation at the top of the
 1.11069 +** analyze.c source file for additional information.
 1.11070 +*/
 1.11071 +struct IndexSample {
 1.11072 +  void *p;          /* Pointer to sampled record */
 1.11073 +  int n;            /* Size of record in bytes */
 1.11074 +  tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
 1.11075 +  tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */
 1.11076 +  tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */
 1.11077 +};
 1.11078 +
 1.11079 +/*
 1.11080 +** Each token coming out of the lexer is an instance of
 1.11081 +** this structure.  Tokens are also used as part of an expression.
 1.11082 +**
 1.11083 +** Note if Token.z==0 then Token.dyn and Token.n are undefined and
 1.11084 +** may contain random values.  Do not make any assumptions about Token.dyn
 1.11085 +** and Token.n when Token.z==0.
 1.11086 +*/
 1.11087 +struct Token {
 1.11088 +  const char *z;     /* Text of the token.  Not NULL-terminated! */
 1.11089 +  unsigned int n;    /* Number of characters in this token */
 1.11090 +};
 1.11091 +
 1.11092 +/*
 1.11093 +** An instance of this structure contains information needed to generate
 1.11094 +** code for a SELECT that contains aggregate functions.
 1.11095 +**
 1.11096 +** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
 1.11097 +** pointer to this structure.  The Expr.iColumn field is the index in
 1.11098 +** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
 1.11099 +** code for that node.
 1.11100 +**
 1.11101 +** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
 1.11102 +** original Select structure that describes the SELECT statement.  These
 1.11103 +** fields do not need to be freed when deallocating the AggInfo structure.
 1.11104 +*/
 1.11105 +struct AggInfo {
 1.11106 +  u8 directMode;          /* Direct rendering mode means take data directly
 1.11107 +                          ** from source tables rather than from accumulators */
 1.11108 +  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
 1.11109 +                          ** than the source table */
 1.11110 +  int sortingIdx;         /* Cursor number of the sorting index */
 1.11111 +  int sortingIdxPTab;     /* Cursor number of pseudo-table */
 1.11112 +  int nSortingColumn;     /* Number of columns in the sorting index */
 1.11113 +  int mnReg, mxReg;       /* Range of registers allocated for aCol and aFunc */
 1.11114 +  ExprList *pGroupBy;     /* The group by clause */
 1.11115 +  struct AggInfo_col {    /* For each column used in source tables */
 1.11116 +    Table *pTab;             /* Source table */
 1.11117 +    int iTable;              /* Cursor number of the source table */
 1.11118 +    int iColumn;             /* Column number within the source table */
 1.11119 +    int iSorterColumn;       /* Column number in the sorting index */
 1.11120 +    int iMem;                /* Memory location that acts as accumulator */
 1.11121 +    Expr *pExpr;             /* The original expression */
 1.11122 +  } *aCol;
 1.11123 +  int nColumn;            /* Number of used entries in aCol[] */
 1.11124 +  int nAccumulator;       /* Number of columns that show through to the output.
 1.11125 +                          ** Additional columns are used only as parameters to
 1.11126 +                          ** aggregate functions */
 1.11127 +  struct AggInfo_func {   /* For each aggregate function */
 1.11128 +    Expr *pExpr;             /* Expression encoding the function */
 1.11129 +    FuncDef *pFunc;          /* The aggregate function implementation */
 1.11130 +    int iMem;                /* Memory location that acts as accumulator */
 1.11131 +    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
 1.11132 +  } *aFunc;
 1.11133 +  int nFunc;              /* Number of entries in aFunc[] */
 1.11134 +};
 1.11135 +
 1.11136 +/*
 1.11137 +** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
 1.11138 +** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
 1.11139 +** than 32767 we have to make it 32-bit.  16-bit is preferred because
 1.11140 +** it uses less memory in the Expr object, which is a big memory user
 1.11141 +** in systems with lots of prepared statements.  And few applications
 1.11142 +** need more than about 10 or 20 variables.  But some extreme users want
 1.11143 +** to have prepared statements with over 32767 variables, and for them
 1.11144 +** the option is available (at compile-time).
 1.11145 +*/
 1.11146 +#if SQLITE_MAX_VARIABLE_NUMBER<=32767
 1.11147 +typedef i16 ynVar;
 1.11148 +#else
 1.11149 +typedef int ynVar;
 1.11150 +#endif
 1.11151 +
 1.11152 +/*
 1.11153 +** Each node of an expression in the parse tree is an instance
 1.11154 +** of this structure.
 1.11155 +**
 1.11156 +** Expr.op is the opcode. The integer parser token codes are reused
 1.11157 +** as opcodes here. For example, the parser defines TK_GE to be an integer
 1.11158 +** code representing the ">=" operator. This same integer code is reused
 1.11159 +** to represent the greater-than-or-equal-to operator in the expression
 1.11160 +** tree.
 1.11161 +**
 1.11162 +** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
 1.11163 +** or TK_STRING), then Expr.token contains the text of the SQL literal. If
 1.11164 +** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
 1.11165 +** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
 1.11166 +** then Expr.token contains the name of the function.
 1.11167 +**
 1.11168 +** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
 1.11169 +** binary operator. Either or both may be NULL.
 1.11170 +**
 1.11171 +** Expr.x.pList is a list of arguments if the expression is an SQL function,
 1.11172 +** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
 1.11173 +** Expr.x.pSelect is used if the expression is a sub-select or an expression of
 1.11174 +** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
 1.11175 +** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
 1.11176 +** valid.
 1.11177 +**
 1.11178 +** An expression of the form ID or ID.ID refers to a column in a table.
 1.11179 +** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
 1.11180 +** the integer cursor number of a VDBE cursor pointing to that table and
 1.11181 +** Expr.iColumn is the column number for the specific column.  If the
 1.11182 +** expression is used as a result in an aggregate SELECT, then the
 1.11183 +** value is also stored in the Expr.iAgg column in the aggregate so that
 1.11184 +** it can be accessed after all aggregates are computed.
 1.11185 +**
 1.11186 +** If the expression is an unbound variable marker (a question mark 
 1.11187 +** character '?' in the original SQL) then the Expr.iTable holds the index 
 1.11188 +** number for that variable.
 1.11189 +**
 1.11190 +** If the expression is a subquery then Expr.iColumn holds an integer
 1.11191 +** register number containing the result of the subquery.  If the
 1.11192 +** subquery gives a constant result, then iTable is -1.  If the subquery
 1.11193 +** gives a different answer at different times during statement processing
 1.11194 +** then iTable is the address of a subroutine that computes the subquery.
 1.11195 +**
 1.11196 +** If the Expr is of type OP_Column, and the table it is selecting from
 1.11197 +** is a disk table or the "old.*" pseudo-table, then pTab points to the
 1.11198 +** corresponding table definition.
 1.11199 +**
 1.11200 +** ALLOCATION NOTES:
 1.11201 +**
 1.11202 +** Expr objects can use a lot of memory space in database schema.  To
 1.11203 +** help reduce memory requirements, sometimes an Expr object will be
 1.11204 +** truncated.  And to reduce the number of memory allocations, sometimes
 1.11205 +** two or more Expr objects will be stored in a single memory allocation,
 1.11206 +** together with Expr.zToken strings.
 1.11207 +**
 1.11208 +** If the EP_Reduced and EP_TokenOnly flags are set when
 1.11209 +** an Expr object is truncated.  When EP_Reduced is set, then all
 1.11210 +** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
 1.11211 +** are contained within the same memory allocation.  Note, however, that
 1.11212 +** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
 1.11213 +** allocated, regardless of whether or not EP_Reduced is set.
 1.11214 +*/
 1.11215 +struct Expr {
 1.11216 +  u8 op;                 /* Operation performed by this node */
 1.11217 +  char affinity;         /* The affinity of the column or 0 if not a column */
 1.11218 +  u32 flags;             /* Various flags.  EP_* See below */
 1.11219 +  union {
 1.11220 +    char *zToken;          /* Token value. Zero terminated and dequoted */
 1.11221 +    int iValue;            /* Non-negative integer value if EP_IntValue */
 1.11222 +  } u;
 1.11223 +
 1.11224 +  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
 1.11225 +  ** space is allocated for the fields below this point. An attempt to
 1.11226 +  ** access them will result in a segfault or malfunction. 
 1.11227 +  *********************************************************************/
 1.11228 +
 1.11229 +  Expr *pLeft;           /* Left subnode */
 1.11230 +  Expr *pRight;          /* Right subnode */
 1.11231 +  union {
 1.11232 +    ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
 1.11233 +    Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
 1.11234 +  } x;
 1.11235 +
 1.11236 +  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
 1.11237 +  ** space is allocated for the fields below this point. An attempt to
 1.11238 +  ** access them will result in a segfault or malfunction.
 1.11239 +  *********************************************************************/
 1.11240 +
 1.11241 +#if SQLITE_MAX_EXPR_DEPTH>0
 1.11242 +  int nHeight;           /* Height of the tree headed by this node */
 1.11243 +#endif
 1.11244 +  int iTable;            /* TK_COLUMN: cursor number of table holding column
 1.11245 +                         ** TK_REGISTER: register number
 1.11246 +                         ** TK_TRIGGER: 1 -> new, 0 -> old
 1.11247 +                         ** EP_Unlikely:  1000 times likelihood */
 1.11248 +  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
 1.11249 +                         ** TK_VARIABLE: variable number (always >= 1). */
 1.11250 +  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
 1.11251 +  i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
 1.11252 +  u8 op2;                /* TK_REGISTER: original value of Expr.op
 1.11253 +                         ** TK_COLUMN: the value of p5 for OP_Column
 1.11254 +                         ** TK_AGG_FUNCTION: nesting depth */
 1.11255 +  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
 1.11256 +  Table *pTab;           /* Table for TK_COLUMN expressions. */
 1.11257 +};
 1.11258 +
 1.11259 +/*
 1.11260 +** The following are the meanings of bits in the Expr.flags field.
 1.11261 +*/
 1.11262 +#define EP_FromJoin  0x000001 /* Originated in ON or USING clause of a join */
 1.11263 +#define EP_Agg       0x000002 /* Contains one or more aggregate functions */
 1.11264 +#define EP_Resolved  0x000004 /* IDs have been resolved to COLUMNs */
 1.11265 +#define EP_Error     0x000008 /* Expression contains one or more errors */
 1.11266 +#define EP_Distinct  0x000010 /* Aggregate function with DISTINCT keyword */
 1.11267 +#define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
 1.11268 +#define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
 1.11269 +#define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
 1.11270 +#define EP_Collate   0x000100 /* Tree contains a TK_COLLATE opeartor */
 1.11271 +      /* unused      0x000200 */
 1.11272 +#define EP_IntValue  0x000400 /* Integer value contained in u.iValue */
 1.11273 +#define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
 1.11274 +#define EP_Skip      0x001000 /* COLLATE, AS, or UNLIKELY */
 1.11275 +#define EP_Reduced   0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
 1.11276 +#define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
 1.11277 +#define EP_Static    0x008000 /* Held in memory not obtained from malloc() */
 1.11278 +#define EP_MemToken  0x010000 /* Need to sqlite3DbFree() Expr.zToken */
 1.11279 +#define EP_NoReduce  0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
 1.11280 +#define EP_Unlikely  0x040000 /* unlikely() or likelihood() function */
 1.11281 +#define EP_Constant  0x080000 /* Node is a constant */
 1.11282 +
 1.11283 +/*
 1.11284 +** These macros can be used to test, set, or clear bits in the 
 1.11285 +** Expr.flags field.
 1.11286 +*/
 1.11287 +#define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
 1.11288 +#define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
 1.11289 +#define ExprSetProperty(E,P)     (E)->flags|=(P)
 1.11290 +#define ExprClearProperty(E,P)   (E)->flags&=~(P)
 1.11291 +
 1.11292 +/* The ExprSetVVAProperty() macro is used for Verification, Validation,
 1.11293 +** and Accreditation only.  It works like ExprSetProperty() during VVA
 1.11294 +** processes but is a no-op for delivery.
 1.11295 +*/
 1.11296 +#ifdef SQLITE_DEBUG
 1.11297 +# define ExprSetVVAProperty(E,P)  (E)->flags|=(P)
 1.11298 +#else
 1.11299 +# define ExprSetVVAProperty(E,P)
 1.11300 +#endif
 1.11301 +
 1.11302 +/*
 1.11303 +** Macros to determine the number of bytes required by a normal Expr 
 1.11304 +** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
 1.11305 +** and an Expr struct with the EP_TokenOnly flag set.
 1.11306 +*/
 1.11307 +#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
 1.11308 +#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
 1.11309 +#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
 1.11310 +
 1.11311 +/*
 1.11312 +** Flags passed to the sqlite3ExprDup() function. See the header comment 
 1.11313 +** above sqlite3ExprDup() for details.
 1.11314 +*/
 1.11315 +#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
 1.11316 +
 1.11317 +/*
 1.11318 +** A list of expressions.  Each expression may optionally have a
 1.11319 +** name.  An expr/name combination can be used in several ways, such
 1.11320 +** as the list of "expr AS ID" fields following a "SELECT" or in the
 1.11321 +** list of "ID = expr" items in an UPDATE.  A list of expressions can
 1.11322 +** also be used as the argument to a function, in which case the a.zName
 1.11323 +** field is not used.
 1.11324 +**
 1.11325 +** By default the Expr.zSpan field holds a human-readable description of
 1.11326 +** the expression that is used in the generation of error messages and
 1.11327 +** column labels.  In this case, Expr.zSpan is typically the text of a
 1.11328 +** column expression as it exists in a SELECT statement.  However, if
 1.11329 +** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
 1.11330 +** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
 1.11331 +** form is used for name resolution with nested FROM clauses.
 1.11332 +*/
 1.11333 +struct ExprList {
 1.11334 +  int nExpr;             /* Number of expressions on the list */
 1.11335 +  int iECursor;          /* VDBE Cursor associated with this ExprList */
 1.11336 +  struct ExprList_item { /* For each expression in the list */
 1.11337 +    Expr *pExpr;            /* The list of expressions */
 1.11338 +    char *zName;            /* Token associated with this expression */
 1.11339 +    char *zSpan;            /* Original text of the expression */
 1.11340 +    u8 sortOrder;           /* 1 for DESC or 0 for ASC */
 1.11341 +    unsigned done :1;       /* A flag to indicate when processing is finished */
 1.11342 +    unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
 1.11343 +    unsigned reusable :1;   /* Constant expression is reusable */
 1.11344 +    union {
 1.11345 +      struct {
 1.11346 +        u16 iOrderByCol;      /* For ORDER BY, column number in result set */
 1.11347 +        u16 iAlias;           /* Index into Parse.aAlias[] for zName */
 1.11348 +      } x;
 1.11349 +      int iConstExprReg;      /* Register in which Expr value is cached */
 1.11350 +    } u;
 1.11351 +  } *a;                  /* Alloc a power of two greater or equal to nExpr */
 1.11352 +};
 1.11353 +
 1.11354 +/*
 1.11355 +** An instance of this structure is used by the parser to record both
 1.11356 +** the parse tree for an expression and the span of input text for an
 1.11357 +** expression.
 1.11358 +*/
 1.11359 +struct ExprSpan {
 1.11360 +  Expr *pExpr;          /* The expression parse tree */
 1.11361 +  const char *zStart;   /* First character of input text */
 1.11362 +  const char *zEnd;     /* One character past the end of input text */
 1.11363 +};
 1.11364 +
 1.11365 +/*
 1.11366 +** An instance of this structure can hold a simple list of identifiers,
 1.11367 +** such as the list "a,b,c" in the following statements:
 1.11368 +**
 1.11369 +**      INSERT INTO t(a,b,c) VALUES ...;
 1.11370 +**      CREATE INDEX idx ON t(a,b,c);
 1.11371 +**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
 1.11372 +**
 1.11373 +** The IdList.a.idx field is used when the IdList represents the list of
 1.11374 +** column names after a table name in an INSERT statement.  In the statement
 1.11375 +**
 1.11376 +**     INSERT INTO t(a,b,c) ...
 1.11377 +**
 1.11378 +** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
 1.11379 +*/
 1.11380 +struct IdList {
 1.11381 +  struct IdList_item {
 1.11382 +    char *zName;      /* Name of the identifier */
 1.11383 +    int idx;          /* Index in some Table.aCol[] of a column named zName */
 1.11384 +  } *a;
 1.11385 +  int nId;         /* Number of identifiers on the list */
 1.11386 +};
 1.11387 +
 1.11388 +/*
 1.11389 +** The bitmask datatype defined below is used for various optimizations.
 1.11390 +**
 1.11391 +** Changing this from a 64-bit to a 32-bit type limits the number of
 1.11392 +** tables in a join to 32 instead of 64.  But it also reduces the size
 1.11393 +** of the library by 738 bytes on ix86.
 1.11394 +*/
 1.11395 +typedef u64 Bitmask;
 1.11396 +
 1.11397 +/*
 1.11398 +** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
 1.11399 +*/
 1.11400 +#define BMS  ((int)(sizeof(Bitmask)*8))
 1.11401 +
 1.11402 +/*
 1.11403 +** A bit in a Bitmask
 1.11404 +*/
 1.11405 +#define MASKBIT(n)   (((Bitmask)1)<<(n))
 1.11406 +#define MASKBIT32(n) (((unsigned int)1)<<(n))
 1.11407 +
 1.11408 +/*
 1.11409 +** The following structure describes the FROM clause of a SELECT statement.
 1.11410 +** Each table or subquery in the FROM clause is a separate element of
 1.11411 +** the SrcList.a[] array.
 1.11412 +**
 1.11413 +** With the addition of multiple database support, the following structure
 1.11414 +** can also be used to describe a particular table such as the table that
 1.11415 +** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
 1.11416 +** such a table must be a simple name: ID.  But in SQLite, the table can
 1.11417 +** now be identified by a database name, a dot, then the table name: ID.ID.
 1.11418 +**
 1.11419 +** The jointype starts out showing the join type between the current table
 1.11420 +** and the next table on the list.  The parser builds the list this way.
 1.11421 +** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
 1.11422 +** jointype expresses the join between the table and the previous table.
 1.11423 +**
 1.11424 +** In the colUsed field, the high-order bit (bit 63) is set if the table
 1.11425 +** contains more than 63 columns and the 64-th or later column is used.
 1.11426 +*/
 1.11427 +struct SrcList {
 1.11428 +  int nSrc;        /* Number of tables or subqueries in the FROM clause */
 1.11429 +  u32 nAlloc;      /* Number of entries allocated in a[] below */
 1.11430 +  struct SrcList_item {
 1.11431 +    Schema *pSchema;  /* Schema to which this item is fixed */
 1.11432 +    char *zDatabase;  /* Name of database holding this table */
 1.11433 +    char *zName;      /* Name of the table */
 1.11434 +    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
 1.11435 +    Table *pTab;      /* An SQL table corresponding to zName */
 1.11436 +    Select *pSelect;  /* A SELECT statement used in place of a table name */
 1.11437 +    int addrFillSub;  /* Address of subroutine to manifest a subquery */
 1.11438 +    int regReturn;    /* Register holding return address of addrFillSub */
 1.11439 +    int regResult;    /* Registers holding results of a co-routine */
 1.11440 +    u8 jointype;      /* Type of join between this able and the previous */
 1.11441 +    unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
 1.11442 +    unsigned isCorrelated :1;  /* True if sub-query is correlated */
 1.11443 +    unsigned viaCoroutine :1;  /* Implemented as a co-routine */
 1.11444 +    unsigned isRecursive :1;   /* True for recursive reference in WITH */
 1.11445 +#ifndef SQLITE_OMIT_EXPLAIN
 1.11446 +    u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
 1.11447 +#endif
 1.11448 +    int iCursor;      /* The VDBE cursor number used to access this table */
 1.11449 +    Expr *pOn;        /* The ON clause of a join */
 1.11450 +    IdList *pUsing;   /* The USING clause of a join */
 1.11451 +    Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
 1.11452 +    char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
 1.11453 +    Index *pIndex;    /* Index structure corresponding to zIndex, if any */
 1.11454 +  } a[1];             /* One entry for each identifier on the list */
 1.11455 +};
 1.11456 +
 1.11457 +/*
 1.11458 +** Permitted values of the SrcList.a.jointype field
 1.11459 +*/
 1.11460 +#define JT_INNER     0x0001    /* Any kind of inner or cross join */
 1.11461 +#define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
 1.11462 +#define JT_NATURAL   0x0004    /* True for a "natural" join */
 1.11463 +#define JT_LEFT      0x0008    /* Left outer join */
 1.11464 +#define JT_RIGHT     0x0010    /* Right outer join */
 1.11465 +#define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
 1.11466 +#define JT_ERROR     0x0040    /* unknown or unsupported join type */
 1.11467 +
 1.11468 +
 1.11469 +/*
 1.11470 +** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
 1.11471 +** and the WhereInfo.wctrlFlags member.
 1.11472 +*/
 1.11473 +#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
 1.11474 +#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
 1.11475 +#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
 1.11476 +#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
 1.11477 +#define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
 1.11478 +#define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
 1.11479 +#define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
 1.11480 +#define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
 1.11481 +#define WHERE_AND_ONLY         0x0080 /* Don't use indices for OR terms */
 1.11482 +#define WHERE_GROUPBY          0x0100 /* pOrderBy is really a GROUP BY */
 1.11483 +#define WHERE_DISTINCTBY       0x0200 /* pOrderby is really a DISTINCT clause */
 1.11484 +#define WHERE_WANT_DISTINCT    0x0400 /* All output needs to be distinct */
 1.11485 +
 1.11486 +/* Allowed return values from sqlite3WhereIsDistinct()
 1.11487 +*/
 1.11488 +#define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
 1.11489 +#define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
 1.11490 +#define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
 1.11491 +#define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
 1.11492 +
 1.11493 +/*
 1.11494 +** A NameContext defines a context in which to resolve table and column
 1.11495 +** names.  The context consists of a list of tables (the pSrcList) field and
 1.11496 +** a list of named expression (pEList).  The named expression list may
 1.11497 +** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
 1.11498 +** to the table being operated on by INSERT, UPDATE, or DELETE.  The
 1.11499 +** pEList corresponds to the result set of a SELECT and is NULL for
 1.11500 +** other statements.
 1.11501 +**
 1.11502 +** NameContexts can be nested.  When resolving names, the inner-most 
 1.11503 +** context is searched first.  If no match is found, the next outer
 1.11504 +** context is checked.  If there is still no match, the next context
 1.11505 +** is checked.  This process continues until either a match is found
 1.11506 +** or all contexts are check.  When a match is found, the nRef member of
 1.11507 +** the context containing the match is incremented. 
 1.11508 +**
 1.11509 +** Each subquery gets a new NameContext.  The pNext field points to the
 1.11510 +** NameContext in the parent query.  Thus the process of scanning the
 1.11511 +** NameContext list corresponds to searching through successively outer
 1.11512 +** subqueries looking for a match.
 1.11513 +*/
 1.11514 +struct NameContext {
 1.11515 +  Parse *pParse;       /* The parser */
 1.11516 +  SrcList *pSrcList;   /* One or more tables used to resolve names */
 1.11517 +  ExprList *pEList;    /* Optional list of result-set columns */
 1.11518 +  AggInfo *pAggInfo;   /* Information about aggregates at this level */
 1.11519 +  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
 1.11520 +  int nRef;            /* Number of names resolved by this context */
 1.11521 +  int nErr;            /* Number of errors encountered while resolving names */
 1.11522 +  u8 ncFlags;          /* Zero or more NC_* flags defined below */
 1.11523 +};
 1.11524 +
 1.11525 +/*
 1.11526 +** Allowed values for the NameContext, ncFlags field.
 1.11527 +*/
 1.11528 +#define NC_AllowAgg  0x01    /* Aggregate functions are allowed here */
 1.11529 +#define NC_HasAgg    0x02    /* One or more aggregate functions seen */
 1.11530 +#define NC_IsCheck   0x04    /* True if resolving names in a CHECK constraint */
 1.11531 +#define NC_InAggFunc 0x08    /* True if analyzing arguments to an agg func */
 1.11532 +#define NC_PartIdx   0x10    /* True if resolving a partial index WHERE */
 1.11533 +
 1.11534 +/*
 1.11535 +** An instance of the following structure contains all information
 1.11536 +** needed to generate code for a single SELECT statement.
 1.11537 +**
 1.11538 +** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
 1.11539 +** If there is a LIMIT clause, the parser sets nLimit to the value of the
 1.11540 +** limit and nOffset to the value of the offset (or 0 if there is not
 1.11541 +** offset).  But later on, nLimit and nOffset become the memory locations
 1.11542 +** in the VDBE that record the limit and offset counters.
 1.11543 +**
 1.11544 +** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
 1.11545 +** These addresses must be stored so that we can go back and fill in
 1.11546 +** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
 1.11547 +** the number of columns in P2 can be computed at the same time
 1.11548 +** as the OP_OpenEphm instruction is coded because not
 1.11549 +** enough information about the compound query is known at that point.
 1.11550 +** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
 1.11551 +** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
 1.11552 +** sequences for the ORDER BY clause.
 1.11553 +*/
 1.11554 +struct Select {
 1.11555 +  ExprList *pEList;      /* The fields of the result */
 1.11556 +  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
 1.11557 +  u16 selFlags;          /* Various SF_* values */
 1.11558 +  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
 1.11559 +  int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
 1.11560 +  u64 nSelectRow;        /* Estimated number of result rows */
 1.11561 +  SrcList *pSrc;         /* The FROM clause */
 1.11562 +  Expr *pWhere;          /* The WHERE clause */
 1.11563 +  ExprList *pGroupBy;    /* The GROUP BY clause */
 1.11564 +  Expr *pHaving;         /* The HAVING clause */
 1.11565 +  ExprList *pOrderBy;    /* The ORDER BY clause */
 1.11566 +  Select *pPrior;        /* Prior select in a compound select statement */
 1.11567 +  Select *pNext;         /* Next select to the left in a compound */
 1.11568 +  Expr *pLimit;          /* LIMIT expression. NULL means not used. */
 1.11569 +  Expr *pOffset;         /* OFFSET expression. NULL means not used. */
 1.11570 +  With *pWith;           /* WITH clause attached to this select. Or NULL. */
 1.11571 +};
 1.11572 +
 1.11573 +/*
 1.11574 +** Allowed values for Select.selFlags.  The "SF" prefix stands for
 1.11575 +** "Select Flag".
 1.11576 +*/
 1.11577 +#define SF_Distinct        0x0001  /* Output should be DISTINCT */
 1.11578 +#define SF_Resolved        0x0002  /* Identifiers have been resolved */
 1.11579 +#define SF_Aggregate       0x0004  /* Contains aggregate functions */
 1.11580 +#define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
 1.11581 +#define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
 1.11582 +#define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
 1.11583 +#define SF_UseSorter       0x0040  /* Sort using a sorter */
 1.11584 +#define SF_Values          0x0080  /* Synthesized from VALUES clause */
 1.11585 +#define SF_Materialize     0x0100  /* NOT USED */
 1.11586 +#define SF_NestedFrom      0x0200  /* Part of a parenthesized FROM clause */
 1.11587 +#define SF_MaybeConvert    0x0400  /* Need convertCompoundSelectToSubquery() */
 1.11588 +#define SF_Recursive       0x0800  /* The recursive part of a recursive CTE */
 1.11589 +#define SF_Compound        0x1000  /* Part of a compound query */
 1.11590 +
 1.11591 +
 1.11592 +/*
 1.11593 +** The results of a SELECT can be distributed in several ways, as defined
 1.11594 +** by one of the following macros.  The "SRT" prefix means "SELECT Result
 1.11595 +** Type".
 1.11596 +**
 1.11597 +**     SRT_Union       Store results as a key in a temporary index 
 1.11598 +**                     identified by pDest->iSDParm.
 1.11599 +**
 1.11600 +**     SRT_Except      Remove results from the temporary index pDest->iSDParm.
 1.11601 +**
 1.11602 +**     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
 1.11603 +**                     set is not empty.
 1.11604 +**
 1.11605 +**     SRT_Discard     Throw the results away.  This is used by SELECT
 1.11606 +**                     statements within triggers whose only purpose is
 1.11607 +**                     the side-effects of functions.
 1.11608 +**
 1.11609 +** All of the above are free to ignore their ORDER BY clause. Those that
 1.11610 +** follow must honor the ORDER BY clause.
 1.11611 +**
 1.11612 +**     SRT_Output      Generate a row of output (using the OP_ResultRow
 1.11613 +**                     opcode) for each row in the result set.
 1.11614 +**
 1.11615 +**     SRT_Mem         Only valid if the result is a single column.
 1.11616 +**                     Store the first column of the first result row
 1.11617 +**                     in register pDest->iSDParm then abandon the rest
 1.11618 +**                     of the query.  This destination implies "LIMIT 1".
 1.11619 +**
 1.11620 +**     SRT_Set         The result must be a single column.  Store each
 1.11621 +**                     row of result as the key in table pDest->iSDParm. 
 1.11622 +**                     Apply the affinity pDest->affSdst before storing
 1.11623 +**                     results.  Used to implement "IN (SELECT ...)".
 1.11624 +**
 1.11625 +**     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
 1.11626 +**                     the result there. The cursor is left open after
 1.11627 +**                     returning.  This is like SRT_Table except that
 1.11628 +**                     this destination uses OP_OpenEphemeral to create
 1.11629 +**                     the table first.
 1.11630 +**
 1.11631 +**     SRT_Coroutine   Generate a co-routine that returns a new row of
 1.11632 +**                     results each time it is invoked.  The entry point
 1.11633 +**                     of the co-routine is stored in register pDest->iSDParm
 1.11634 +**                     and the result row is stored in pDest->nDest registers
 1.11635 +**                     starting with pDest->iSdst.
 1.11636 +**
 1.11637 +**     SRT_Table       Store results in temporary table pDest->iSDParm.
 1.11638 +**                     This is like SRT_EphemTab except that the table
 1.11639 +**                     is assumed to already be open.
 1.11640 +**
 1.11641 +**     SRT_DistTable   Store results in a temporary table pDest->iSDParm.
 1.11642 +**                     But also use temporary table pDest->iSDParm+1 as
 1.11643 +**                     a record of all prior results and ignore any duplicate
 1.11644 +**                     rows.  Name means:  "Distinct Table".
 1.11645 +**
 1.11646 +**     SRT_Queue       Store results in priority queue pDest->iSDParm (really
 1.11647 +**                     an index).  Append a sequence number so that all entries
 1.11648 +**                     are distinct.
 1.11649 +**
 1.11650 +**     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if
 1.11651 +**                     the same record has never been stored before.  The
 1.11652 +**                     index at pDest->iSDParm+1 hold all prior stores.
 1.11653 +*/
 1.11654 +#define SRT_Union        1  /* Store result as keys in an index */
 1.11655 +#define SRT_Except       2  /* Remove result from a UNION index */
 1.11656 +#define SRT_Exists       3  /* Store 1 if the result is not empty */
 1.11657 +#define SRT_Discard      4  /* Do not save the results anywhere */
 1.11658 +
 1.11659 +/* The ORDER BY clause is ignored for all of the above */
 1.11660 +#define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
 1.11661 +
 1.11662 +#define SRT_Output       5  /* Output each row of result */
 1.11663 +#define SRT_Mem          6  /* Store result in a memory cell */
 1.11664 +#define SRT_Set          7  /* Store results as keys in an index */
 1.11665 +#define SRT_EphemTab     8  /* Create transient tab and store like SRT_Table */
 1.11666 +#define SRT_Coroutine    9  /* Generate a single row of result */
 1.11667 +#define SRT_Table       10  /* Store result as data with an automatic rowid */
 1.11668 +#define SRT_DistTable   11  /* Like SRT_Table, but unique results only */
 1.11669 +#define SRT_Queue       12  /* Store result in an queue */
 1.11670 +#define SRT_DistQueue   13  /* Like SRT_Queue, but unique results only */
 1.11671 +
 1.11672 +/*
 1.11673 +** An instance of this object describes where to put of the results of
 1.11674 +** a SELECT statement.
 1.11675 +*/
 1.11676 +struct SelectDest {
 1.11677 +  u8 eDest;            /* How to dispose of the results.  On of SRT_* above. */
 1.11678 +  char affSdst;        /* Affinity used when eDest==SRT_Set */
 1.11679 +  int iSDParm;         /* A parameter used by the eDest disposal method */
 1.11680 +  int iSdst;           /* Base register where results are written */
 1.11681 +  int nSdst;           /* Number of registers allocated */
 1.11682 +  ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */
 1.11683 +};
 1.11684 +
 1.11685 +/*
 1.11686 +** During code generation of statements that do inserts into AUTOINCREMENT 
 1.11687 +** tables, the following information is attached to the Table.u.autoInc.p
 1.11688 +** pointer of each autoincrement table to record some side information that
 1.11689 +** the code generator needs.  We have to keep per-table autoincrement
 1.11690 +** information in case inserts are down within triggers.  Triggers do not
 1.11691 +** normally coordinate their activities, but we do need to coordinate the
 1.11692 +** loading and saving of autoincrement information.
 1.11693 +*/
 1.11694 +struct AutoincInfo {
 1.11695 +  AutoincInfo *pNext;   /* Next info block in a list of them all */
 1.11696 +  Table *pTab;          /* Table this info block refers to */
 1.11697 +  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
 1.11698 +  int regCtr;           /* Memory register holding the rowid counter */
 1.11699 +};
 1.11700 +
 1.11701 +/*
 1.11702 +** Size of the column cache
 1.11703 +*/
 1.11704 +#ifndef SQLITE_N_COLCACHE
 1.11705 +# define SQLITE_N_COLCACHE 10
 1.11706 +#endif
 1.11707 +
 1.11708 +/*
 1.11709 +** At least one instance of the following structure is created for each 
 1.11710 +** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
 1.11711 +** statement. All such objects are stored in the linked list headed at
 1.11712 +** Parse.pTriggerPrg and deleted once statement compilation has been
 1.11713 +** completed.
 1.11714 +**
 1.11715 +** A Vdbe sub-program that implements the body and WHEN clause of trigger
 1.11716 +** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
 1.11717 +** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
 1.11718 +** The Parse.pTriggerPrg list never contains two entries with the same
 1.11719 +** values for both pTrigger and orconf.
 1.11720 +**
 1.11721 +** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
 1.11722 +** accessed (or set to 0 for triggers fired as a result of INSERT 
 1.11723 +** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
 1.11724 +** a mask of new.* columns used by the program.
 1.11725 +*/
 1.11726 +struct TriggerPrg {
 1.11727 +  Trigger *pTrigger;      /* Trigger this program was coded from */
 1.11728 +  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
 1.11729 +  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
 1.11730 +  int orconf;             /* Default ON CONFLICT policy */
 1.11731 +  u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
 1.11732 +};
 1.11733 +
 1.11734 +/*
 1.11735 +** The yDbMask datatype for the bitmask of all attached databases.
 1.11736 +*/
 1.11737 +#if SQLITE_MAX_ATTACHED>30
 1.11738 +  typedef sqlite3_uint64 yDbMask;
 1.11739 +#else
 1.11740 +  typedef unsigned int yDbMask;
 1.11741 +#endif
 1.11742 +
 1.11743 +/*
 1.11744 +** An SQL parser context.  A copy of this structure is passed through
 1.11745 +** the parser and down into all the parser action routine in order to
 1.11746 +** carry around information that is global to the entire parse.
 1.11747 +**
 1.11748 +** The structure is divided into two parts.  When the parser and code
 1.11749 +** generate call themselves recursively, the first part of the structure
 1.11750 +** is constant but the second part is reset at the beginning and end of
 1.11751 +** each recursion.
 1.11752 +**
 1.11753 +** The nTableLock and aTableLock variables are only used if the shared-cache 
 1.11754 +** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
 1.11755 +** used to store the set of table-locks required by the statement being
 1.11756 +** compiled. Function sqlite3TableLock() is used to add entries to the
 1.11757 +** list.
 1.11758 +*/
 1.11759 +struct Parse {
 1.11760 +  sqlite3 *db;         /* The main database structure */
 1.11761 +  char *zErrMsg;       /* An error message */
 1.11762 +  Vdbe *pVdbe;         /* An engine for executing database bytecode */
 1.11763 +  int rc;              /* Return code from execution */
 1.11764 +  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
 1.11765 +  u8 checkSchema;      /* Causes schema cookie check after an error */
 1.11766 +  u8 nested;           /* Number of nested calls to the parser/code generator */
 1.11767 +  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
 1.11768 +  u8 nColCache;        /* Number of entries in aColCache[] */
 1.11769 +  u8 iColCache;        /* Next entry in aColCache[] to replace */
 1.11770 +  u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
 1.11771 +  u8 mayAbort;         /* True if statement may throw an ABORT exception */
 1.11772 +  u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
 1.11773 +  u8 okConstFactor;    /* OK to factor out constants */
 1.11774 +  int aTempReg[8];     /* Holding area for temporary registers */
 1.11775 +  int nRangeReg;       /* Size of the temporary register block */
 1.11776 +  int iRangeReg;       /* First register in temporary register block */
 1.11777 +  int nErr;            /* Number of errors seen */
 1.11778 +  int nTab;            /* Number of previously allocated VDBE cursors */
 1.11779 +  int nMem;            /* Number of memory cells used so far */
 1.11780 +  int nSet;            /* Number of sets used so far */
 1.11781 +  int nOnce;           /* Number of OP_Once instructions so far */
 1.11782 +  int nOpAlloc;        /* Number of slots allocated for Vdbe.aOp[] */
 1.11783 +  int iFixedOp;        /* Never back out opcodes iFixedOp-1 or earlier */
 1.11784 +  int ckBase;          /* Base register of data during check constraints */
 1.11785 +  int iPartIdxTab;     /* Table corresponding to a partial index */
 1.11786 +  int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
 1.11787 +  int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
 1.11788 +  int nLabel;          /* Number of labels used */
 1.11789 +  int *aLabel;         /* Space to hold the labels */
 1.11790 +  struct yColCache {
 1.11791 +    int iTable;           /* Table cursor number */
 1.11792 +    i16 iColumn;          /* Table column number */
 1.11793 +    u8 tempReg;           /* iReg is a temp register that needs to be freed */
 1.11794 +    int iLevel;           /* Nesting level */
 1.11795 +    int iReg;             /* Reg with value of this column. 0 means none. */
 1.11796 +    int lru;              /* Least recently used entry has the smallest value */
 1.11797 +  } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
 1.11798 +  ExprList *pConstExpr;/* Constant expressions */
 1.11799 +  Token constraintName;/* Name of the constraint currently being parsed */
 1.11800 +  yDbMask writeMask;   /* Start a write transaction on these databases */
 1.11801 +  yDbMask cookieMask;  /* Bitmask of schema verified databases */
 1.11802 +  int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
 1.11803 +  int regRowid;        /* Register holding rowid of CREATE TABLE entry */
 1.11804 +  int regRoot;         /* Register holding root page number for new objects */
 1.11805 +  int nMaxArg;         /* Max args passed to user function by sub-program */
 1.11806 +#ifndef SQLITE_OMIT_SHARED_CACHE
 1.11807 +  int nTableLock;        /* Number of locks in aTableLock */
 1.11808 +  TableLock *aTableLock; /* Required table locks for shared-cache mode */
 1.11809 +#endif
 1.11810 +  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
 1.11811 +
 1.11812 +  /* Information used while coding trigger programs. */
 1.11813 +  Parse *pToplevel;    /* Parse structure for main program (or NULL) */
 1.11814 +  Table *pTriggerTab;  /* Table triggers are being coded for */
 1.11815 +  int addrCrTab;       /* Address of OP_CreateTable opcode on CREATE TABLE */
 1.11816 +  int addrSkipPK;      /* Address of instruction to skip PRIMARY KEY index */
 1.11817 +  u32 nQueryLoop;      /* Est number of iterations of a query (10*log2(N)) */
 1.11818 +  u32 oldmask;         /* Mask of old.* columns referenced */
 1.11819 +  u32 newmask;         /* Mask of new.* columns referenced */
 1.11820 +  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
 1.11821 +  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
 1.11822 +  u8 disableTriggers;  /* True to disable triggers */
 1.11823 +
 1.11824 +  /************************************************************************
 1.11825 +  ** Above is constant between recursions.  Below is reset before and after
 1.11826 +  ** each recursion.  The boundary between these two regions is determined
 1.11827 +  ** using offsetof(Parse,nVar) so the nVar field must be the first field
 1.11828 +  ** in the recursive region.
 1.11829 +  ************************************************************************/
 1.11830 +
 1.11831 +  int nVar;                 /* Number of '?' variables seen in the SQL so far */
 1.11832 +  int nzVar;                /* Number of available slots in azVar[] */
 1.11833 +  u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */
 1.11834 +  u8 bFreeWith;             /* True if pWith should be freed with parser */
 1.11835 +  u8 explain;               /* True if the EXPLAIN flag is found on the query */
 1.11836 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.11837 +  u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
 1.11838 +  int nVtabLock;            /* Number of virtual tables to lock */
 1.11839 +#endif
 1.11840 +  int nAlias;               /* Number of aliased result set columns */
 1.11841 +  int nHeight;              /* Expression tree height of current sub-select */
 1.11842 +#ifndef SQLITE_OMIT_EXPLAIN
 1.11843 +  int iSelectId;            /* ID of current select for EXPLAIN output */
 1.11844 +  int iNextSelectId;        /* Next available select ID for EXPLAIN output */
 1.11845 +#endif
 1.11846 +  char **azVar;             /* Pointers to names of parameters */
 1.11847 +  Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
 1.11848 +  const char *zTail;        /* All SQL text past the last semicolon parsed */
 1.11849 +  Table *pNewTable;         /* A table being constructed by CREATE TABLE */
 1.11850 +  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
 1.11851 +  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
 1.11852 +  Token sNameToken;         /* Token with unqualified schema object name */
 1.11853 +  Token sLastToken;         /* The last token parsed */
 1.11854 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.11855 +  Token sArg;               /* Complete text of a module argument */
 1.11856 +  Table **apVtabLock;       /* Pointer to virtual tables needing locking */
 1.11857 +#endif
 1.11858 +  Table *pZombieTab;        /* List of Table objects to delete after code gen */
 1.11859 +  TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
 1.11860 +  With *pWith;              /* Current WITH clause, or NULL */
 1.11861 +};
 1.11862 +
 1.11863 +/*
 1.11864 +** Return true if currently inside an sqlite3_declare_vtab() call.
 1.11865 +*/
 1.11866 +#ifdef SQLITE_OMIT_VIRTUALTABLE
 1.11867 +  #define IN_DECLARE_VTAB 0
 1.11868 +#else
 1.11869 +  #define IN_DECLARE_VTAB (pParse->declareVtab)
 1.11870 +#endif
 1.11871 +
 1.11872 +/*
 1.11873 +** An instance of the following structure can be declared on a stack and used
 1.11874 +** to save the Parse.zAuthContext value so that it can be restored later.
 1.11875 +*/
 1.11876 +struct AuthContext {
 1.11877 +  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
 1.11878 +  Parse *pParse;              /* The Parse structure */
 1.11879 +};
 1.11880 +
 1.11881 +/*
 1.11882 +** Bitfield flags for P5 value in various opcodes.
 1.11883 +*/
 1.11884 +#define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
 1.11885 +#define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
 1.11886 +#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
 1.11887 +#define OPFLAG_APPEND        0x08    /* This is likely to be an append */
 1.11888 +#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
 1.11889 +#define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
 1.11890 +#define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
 1.11891 +#define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
 1.11892 +#define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
 1.11893 +#define OPFLAG_P2ISREG       0x02    /* P2 to OP_Open** is a register number */
 1.11894 +#define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
 1.11895 +
 1.11896 +/*
 1.11897 + * Each trigger present in the database schema is stored as an instance of
 1.11898 + * struct Trigger. 
 1.11899 + *
 1.11900 + * Pointers to instances of struct Trigger are stored in two ways.
 1.11901 + * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
 1.11902 + *    database). This allows Trigger structures to be retrieved by name.
 1.11903 + * 2. All triggers associated with a single table form a linked list, using the
 1.11904 + *    pNext member of struct Trigger. A pointer to the first element of the
 1.11905 + *    linked list is stored as the "pTrigger" member of the associated
 1.11906 + *    struct Table.
 1.11907 + *
 1.11908 + * The "step_list" member points to the first element of a linked list
 1.11909 + * containing the SQL statements specified as the trigger program.
 1.11910 + */
 1.11911 +struct Trigger {
 1.11912 +  char *zName;            /* The name of the trigger                        */
 1.11913 +  char *table;            /* The table or view to which the trigger applies */
 1.11914 +  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
 1.11915 +  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
 1.11916 +  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
 1.11917 +  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
 1.11918 +                             the <column-list> is stored here */
 1.11919 +  Schema *pSchema;        /* Schema containing the trigger */
 1.11920 +  Schema *pTabSchema;     /* Schema containing the table */
 1.11921 +  TriggerStep *step_list; /* Link list of trigger program steps             */
 1.11922 +  Trigger *pNext;         /* Next trigger associated with the table */
 1.11923 +};
 1.11924 +
 1.11925 +/*
 1.11926 +** A trigger is either a BEFORE or an AFTER trigger.  The following constants
 1.11927 +** determine which. 
 1.11928 +**
 1.11929 +** If there are multiple triggers, you might of some BEFORE and some AFTER.
 1.11930 +** In that cases, the constants below can be ORed together.
 1.11931 +*/
 1.11932 +#define TRIGGER_BEFORE  1
 1.11933 +#define TRIGGER_AFTER   2
 1.11934 +
 1.11935 +/*
 1.11936 + * An instance of struct TriggerStep is used to store a single SQL statement
 1.11937 + * that is a part of a trigger-program. 
 1.11938 + *
 1.11939 + * Instances of struct TriggerStep are stored in a singly linked list (linked
 1.11940 + * using the "pNext" member) referenced by the "step_list" member of the 
 1.11941 + * associated struct Trigger instance. The first element of the linked list is
 1.11942 + * the first step of the trigger-program.
 1.11943 + * 
 1.11944 + * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
 1.11945 + * "SELECT" statement. The meanings of the other members is determined by the 
 1.11946 + * value of "op" as follows:
 1.11947 + *
 1.11948 + * (op == TK_INSERT)
 1.11949 + * orconf    -> stores the ON CONFLICT algorithm
 1.11950 + * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
 1.11951 + *              this stores a pointer to the SELECT statement. Otherwise NULL.
 1.11952 + * target    -> A token holding the quoted name of the table to insert into.
 1.11953 + * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
 1.11954 + *              this stores values to be inserted. Otherwise NULL.
 1.11955 + * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
 1.11956 + *              statement, then this stores the column-names to be
 1.11957 + *              inserted into.
 1.11958 + *
 1.11959 + * (op == TK_DELETE)
 1.11960 + * target    -> A token holding the quoted name of the table to delete from.
 1.11961 + * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
 1.11962 + *              Otherwise NULL.
 1.11963 + * 
 1.11964 + * (op == TK_UPDATE)
 1.11965 + * target    -> A token holding the quoted name of the table to update rows of.
 1.11966 + * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
 1.11967 + *              Otherwise NULL.
 1.11968 + * pExprList -> A list of the columns to update and the expressions to update
 1.11969 + *              them to. See sqlite3Update() documentation of "pChanges"
 1.11970 + *              argument.
 1.11971 + * 
 1.11972 + */
 1.11973 +struct TriggerStep {
 1.11974 +  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
 1.11975 +  u8 orconf;           /* OE_Rollback etc. */
 1.11976 +  Trigger *pTrig;      /* The trigger that this step is a part of */
 1.11977 +  Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
 1.11978 +  Token target;        /* Target table for DELETE, UPDATE, INSERT */
 1.11979 +  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
 1.11980 +  ExprList *pExprList; /* SET clause for UPDATE. */
 1.11981 +  IdList *pIdList;     /* Column names for INSERT */
 1.11982 +  TriggerStep *pNext;  /* Next in the link-list */
 1.11983 +  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
 1.11984 +};
 1.11985 +
 1.11986 +/*
 1.11987 +** The following structure contains information used by the sqliteFix...
 1.11988 +** routines as they walk the parse tree to make database references
 1.11989 +** explicit.  
 1.11990 +*/
 1.11991 +typedef struct DbFixer DbFixer;
 1.11992 +struct DbFixer {
 1.11993 +  Parse *pParse;      /* The parsing context.  Error messages written here */
 1.11994 +  Schema *pSchema;    /* Fix items to this schema */
 1.11995 +  int bVarOnly;       /* Check for variable references only */
 1.11996 +  const char *zDb;    /* Make sure all objects are contained in this database */
 1.11997 +  const char *zType;  /* Type of the container - used for error messages */
 1.11998 +  const Token *pName; /* Name of the container - used for error messages */
 1.11999 +};
 1.12000 +
 1.12001 +/*
 1.12002 +** An objected used to accumulate the text of a string where we
 1.12003 +** do not necessarily know how big the string will be in the end.
 1.12004 +*/
 1.12005 +struct StrAccum {
 1.12006 +  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
 1.12007 +  char *zBase;         /* A base allocation.  Not from malloc. */
 1.12008 +  char *zText;         /* The string collected so far */
 1.12009 +  int  nChar;          /* Length of the string so far */
 1.12010 +  int  nAlloc;         /* Amount of space allocated in zText */
 1.12011 +  int  mxAlloc;        /* Maximum allowed string length */
 1.12012 +  u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
 1.12013 +  u8   accError;       /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
 1.12014 +};
 1.12015 +#define STRACCUM_NOMEM   1
 1.12016 +#define STRACCUM_TOOBIG  2
 1.12017 +
 1.12018 +/*
 1.12019 +** A pointer to this structure is used to communicate information
 1.12020 +** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
 1.12021 +*/
 1.12022 +typedef struct {
 1.12023 +  sqlite3 *db;        /* The database being initialized */
 1.12024 +  char **pzErrMsg;    /* Error message stored here */
 1.12025 +  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
 1.12026 +  int rc;             /* Result code stored here */
 1.12027 +} InitData;
 1.12028 +
 1.12029 +/*
 1.12030 +** Structure containing global configuration data for the SQLite library.
 1.12031 +**
 1.12032 +** This structure also contains some state information.
 1.12033 +*/
 1.12034 +struct Sqlite3Config {
 1.12035 +  int bMemstat;                     /* True to enable memory status */
 1.12036 +  int bCoreMutex;                   /* True to enable core mutexing */
 1.12037 +  int bFullMutex;                   /* True to enable full mutexing */
 1.12038 +  int bOpenUri;                     /* True to interpret filenames as URIs */
 1.12039 +  int bUseCis;                      /* Use covering indices for full-scans */
 1.12040 +  int mxStrlen;                     /* Maximum string length */
 1.12041 +  int neverCorrupt;                 /* Database is always well-formed */
 1.12042 +  int szLookaside;                  /* Default lookaside buffer size */
 1.12043 +  int nLookaside;                   /* Default lookaside buffer count */
 1.12044 +  sqlite3_mem_methods m;            /* Low-level memory allocation interface */
 1.12045 +  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
 1.12046 +  sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
 1.12047 +  void *pHeap;                      /* Heap storage space */
 1.12048 +  int nHeap;                        /* Size of pHeap[] */
 1.12049 +  int mnReq, mxReq;                 /* Min and max heap requests sizes */
 1.12050 +  sqlite3_int64 szMmap;             /* mmap() space per open file */
 1.12051 +  sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
 1.12052 +  void *pScratch;                   /* Scratch memory */
 1.12053 +  int szScratch;                    /* Size of each scratch buffer */
 1.12054 +  int nScratch;                     /* Number of scratch buffers */
 1.12055 +  void *pPage;                      /* Page cache memory */
 1.12056 +  int szPage;                       /* Size of each page in pPage[] */
 1.12057 +  int nPage;                        /* Number of pages in pPage[] */
 1.12058 +  int mxParserStack;                /* maximum depth of the parser stack */
 1.12059 +  int sharedCacheEnabled;           /* true if shared-cache mode enabled */
 1.12060 +  /* The above might be initialized to non-zero.  The following need to always
 1.12061 +  ** initially be zero, however. */
 1.12062 +  int isInit;                       /* True after initialization has finished */
 1.12063 +  int inProgress;                   /* True while initialization in progress */
 1.12064 +  int isMutexInit;                  /* True after mutexes are initialized */
 1.12065 +  int isMallocInit;                 /* True after malloc is initialized */
 1.12066 +  int isPCacheInit;                 /* True after malloc is initialized */
 1.12067 +  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
 1.12068 +  int nRefInitMutex;                /* Number of users of pInitMutex */
 1.12069 +  void (*xLog)(void*,int,const char*); /* Function for logging */
 1.12070 +  void *pLogArg;                       /* First argument to xLog() */
 1.12071 +  int bLocaltimeFault;              /* True to fail localtime() calls */
 1.12072 +#ifdef SQLITE_ENABLE_SQLLOG
 1.12073 +  void(*xSqllog)(void*,sqlite3*,const char*, int);
 1.12074 +  void *pSqllogArg;
 1.12075 +#endif
 1.12076 +#ifdef SQLITE_VDBE_COVERAGE
 1.12077 +  /* The following callback (if not NULL) is invoked on every VDBE branch
 1.12078 +  ** operation.  Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
 1.12079 +  */
 1.12080 +  void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx);  /* Callback */
 1.12081 +  void *pVdbeBranchArg;                                     /* 1st argument */
 1.12082 +#endif
 1.12083 +};
 1.12084 +
 1.12085 +/*
 1.12086 +** This macro is used inside of assert() statements to indicate that
 1.12087 +** the assert is only valid on a well-formed database.  Instead of:
 1.12088 +**
 1.12089 +**     assert( X );
 1.12090 +**
 1.12091 +** One writes:
 1.12092 +**
 1.12093 +**     assert( X || CORRUPT_DB );
 1.12094 +**
 1.12095 +** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate
 1.12096 +** that the database is definitely corrupt, only that it might be corrupt.
 1.12097 +** For most test cases, CORRUPT_DB is set to false using a special
 1.12098 +** sqlite3_test_control().  This enables assert() statements to prove
 1.12099 +** things that are always true for well-formed databases.
 1.12100 +*/
 1.12101 +#define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)
 1.12102 +
 1.12103 +/*
 1.12104 +** Context pointer passed down through the tree-walk.
 1.12105 +*/
 1.12106 +struct Walker {
 1.12107 +  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
 1.12108 +  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
 1.12109 +  void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
 1.12110 +  Parse *pParse;                            /* Parser context.  */
 1.12111 +  int walkerDepth;                          /* Number of subqueries */
 1.12112 +  union {                                   /* Extra data for callback */
 1.12113 +    NameContext *pNC;                          /* Naming context */
 1.12114 +    int i;                                     /* Integer value */
 1.12115 +    SrcList *pSrcList;                         /* FROM clause */
 1.12116 +    struct SrcCount *pSrcCount;                /* Counting column references */
 1.12117 +  } u;
 1.12118 +};
 1.12119 +
 1.12120 +/* Forward declarations */
 1.12121 +SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
 1.12122 +SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
 1.12123 +SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
 1.12124 +SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
 1.12125 +SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
 1.12126 +
 1.12127 +/*
 1.12128 +** Return code from the parse-tree walking primitives and their
 1.12129 +** callbacks.
 1.12130 +*/
 1.12131 +#define WRC_Continue    0   /* Continue down into children */
 1.12132 +#define WRC_Prune       1   /* Omit children but continue walking siblings */
 1.12133 +#define WRC_Abort       2   /* Abandon the tree walk */
 1.12134 +
 1.12135 +/*
 1.12136 +** An instance of this structure represents a set of one or more CTEs
 1.12137 +** (common table expressions) created by a single WITH clause.
 1.12138 +*/
 1.12139 +struct With {
 1.12140 +  int nCte;                       /* Number of CTEs in the WITH clause */
 1.12141 +  With *pOuter;                   /* Containing WITH clause, or NULL */
 1.12142 +  struct Cte {                    /* For each CTE in the WITH clause.... */
 1.12143 +    char *zName;                    /* Name of this CTE */
 1.12144 +    ExprList *pCols;                /* List of explicit column names, or NULL */
 1.12145 +    Select *pSelect;                /* The definition of this CTE */
 1.12146 +    const char *zErr;               /* Error message for circular references */
 1.12147 +  } a[1];
 1.12148 +};
 1.12149 +
 1.12150 +/*
 1.12151 +** Assuming zIn points to the first byte of a UTF-8 character,
 1.12152 +** advance zIn to point to the first byte of the next UTF-8 character.
 1.12153 +*/
 1.12154 +#define SQLITE_SKIP_UTF8(zIn) {                        \
 1.12155 +  if( (*(zIn++))>=0xc0 ){                              \
 1.12156 +    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
 1.12157 +  }                                                    \
 1.12158 +}
 1.12159 +
 1.12160 +/*
 1.12161 +** The SQLITE_*_BKPT macros are substitutes for the error codes with
 1.12162 +** the same name but without the _BKPT suffix.  These macros invoke
 1.12163 +** routines that report the line-number on which the error originated
 1.12164 +** using sqlite3_log().  The routines also provide a convenient place
 1.12165 +** to set a debugger breakpoint.
 1.12166 +*/
 1.12167 +SQLITE_PRIVATE int sqlite3CorruptError(int);
 1.12168 +SQLITE_PRIVATE int sqlite3MisuseError(int);
 1.12169 +SQLITE_PRIVATE int sqlite3CantopenError(int);
 1.12170 +#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
 1.12171 +#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
 1.12172 +#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
 1.12173 +
 1.12174 +
 1.12175 +/*
 1.12176 +** FTS4 is really an extension for FTS3.  It is enabled using the
 1.12177 +** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
 1.12178 +** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
 1.12179 +*/
 1.12180 +#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
 1.12181 +# define SQLITE_ENABLE_FTS3
 1.12182 +#endif
 1.12183 +
 1.12184 +/*
 1.12185 +** The ctype.h header is needed for non-ASCII systems.  It is also
 1.12186 +** needed by FTS3 when FTS3 is included in the amalgamation.
 1.12187 +*/
 1.12188 +#if !defined(SQLITE_ASCII) || \
 1.12189 +    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
 1.12190 +# include <ctype.h>
 1.12191 +#endif
 1.12192 +
 1.12193 +/*
 1.12194 +** The following macros mimic the standard library functions toupper(),
 1.12195 +** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
 1.12196 +** sqlite versions only work for ASCII characters, regardless of locale.
 1.12197 +*/
 1.12198 +#ifdef SQLITE_ASCII
 1.12199 +# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
 1.12200 +# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
 1.12201 +# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
 1.12202 +# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
 1.12203 +# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
 1.12204 +# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
 1.12205 +# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
 1.12206 +#else
 1.12207 +# define sqlite3Toupper(x)   toupper((unsigned char)(x))
 1.12208 +# define sqlite3Isspace(x)   isspace((unsigned char)(x))
 1.12209 +# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
 1.12210 +# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
 1.12211 +# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
 1.12212 +# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
 1.12213 +# define sqlite3Tolower(x)   tolower((unsigned char)(x))
 1.12214 +#endif
 1.12215 +
 1.12216 +/*
 1.12217 +** Internal function prototypes
 1.12218 +*/
 1.12219 +#define sqlite3StrICmp sqlite3_stricmp
 1.12220 +SQLITE_PRIVATE int sqlite3Strlen30(const char*);
 1.12221 +#define sqlite3StrNICmp sqlite3_strnicmp
 1.12222 +
 1.12223 +SQLITE_PRIVATE int sqlite3MallocInit(void);
 1.12224 +SQLITE_PRIVATE void sqlite3MallocEnd(void);
 1.12225 +SQLITE_PRIVATE void *sqlite3Malloc(int);
 1.12226 +SQLITE_PRIVATE void *sqlite3MallocZero(int);
 1.12227 +SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
 1.12228 +SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
 1.12229 +SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
 1.12230 +SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
 1.12231 +SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
 1.12232 +SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
 1.12233 +SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
 1.12234 +SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
 1.12235 +SQLITE_PRIVATE int sqlite3MallocSize(void*);
 1.12236 +SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
 1.12237 +SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
 1.12238 +SQLITE_PRIVATE void sqlite3ScratchFree(void*);
 1.12239 +SQLITE_PRIVATE void *sqlite3PageMalloc(int);
 1.12240 +SQLITE_PRIVATE void sqlite3PageFree(void*);
 1.12241 +SQLITE_PRIVATE void sqlite3MemSetDefault(void);
 1.12242 +SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
 1.12243 +SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
 1.12244 +
 1.12245 +/*
 1.12246 +** On systems with ample stack space and that support alloca(), make
 1.12247 +** use of alloca() to obtain space for large automatic objects.  By default,
 1.12248 +** obtain space from malloc().
 1.12249 +**
 1.12250 +** The alloca() routine never returns NULL.  This will cause code paths
 1.12251 +** that deal with sqlite3StackAlloc() failures to be unreachable.
 1.12252 +*/
 1.12253 +#ifdef SQLITE_USE_ALLOCA
 1.12254 +# define sqlite3StackAllocRaw(D,N)   alloca(N)
 1.12255 +# define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
 1.12256 +# define sqlite3StackFree(D,P)       
 1.12257 +#else
 1.12258 +# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
 1.12259 +# define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
 1.12260 +# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
 1.12261 +#endif
 1.12262 +
 1.12263 +#ifdef SQLITE_ENABLE_MEMSYS3
 1.12264 +SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
 1.12265 +#endif
 1.12266 +#ifdef SQLITE_ENABLE_MEMSYS5
 1.12267 +SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
 1.12268 +#endif
 1.12269 +
 1.12270 +
 1.12271 +#ifndef SQLITE_MUTEX_OMIT
 1.12272 +SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
 1.12273 +SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
 1.12274 +SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
 1.12275 +SQLITE_PRIVATE   int sqlite3MutexInit(void);
 1.12276 +SQLITE_PRIVATE   int sqlite3MutexEnd(void);
 1.12277 +#endif
 1.12278 +
 1.12279 +SQLITE_PRIVATE int sqlite3StatusValue(int);
 1.12280 +SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
 1.12281 +SQLITE_PRIVATE void sqlite3StatusSet(int, int);
 1.12282 +
 1.12283 +#ifndef SQLITE_OMIT_FLOATING_POINT
 1.12284 +SQLITE_PRIVATE   int sqlite3IsNaN(double);
 1.12285 +#else
 1.12286 +# define sqlite3IsNaN(X)  0
 1.12287 +#endif
 1.12288 +
 1.12289 +/*
 1.12290 +** An instance of the following structure holds information about SQL
 1.12291 +** functions arguments that are the parameters to the printf() function.
 1.12292 +*/
 1.12293 +struct PrintfArguments {
 1.12294 +  int nArg;                /* Total number of arguments */
 1.12295 +  int nUsed;               /* Number of arguments used so far */
 1.12296 +  sqlite3_value **apArg;   /* The argument values */
 1.12297 +};
 1.12298 +
 1.12299 +#define SQLITE_PRINTF_INTERNAL 0x01
 1.12300 +#define SQLITE_PRINTF_SQLFUNC  0x02
 1.12301 +SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, u32, const char*, va_list);
 1.12302 +SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, u32, const char*, ...);
 1.12303 +SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
 1.12304 +SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
 1.12305 +SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
 1.12306 +#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
 1.12307 +SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
 1.12308 +#endif
 1.12309 +#if defined(SQLITE_TEST)
 1.12310 +SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
 1.12311 +#endif
 1.12312 +
 1.12313 +/* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
 1.12314 +#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
 1.12315 +SQLITE_PRIVATE   void sqlite3ExplainBegin(Vdbe*);
 1.12316 +SQLITE_PRIVATE   void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
 1.12317 +SQLITE_PRIVATE   void sqlite3ExplainNL(Vdbe*);
 1.12318 +SQLITE_PRIVATE   void sqlite3ExplainPush(Vdbe*);
 1.12319 +SQLITE_PRIVATE   void sqlite3ExplainPop(Vdbe*);
 1.12320 +SQLITE_PRIVATE   void sqlite3ExplainFinish(Vdbe*);
 1.12321 +SQLITE_PRIVATE   void sqlite3ExplainSelect(Vdbe*, Select*);
 1.12322 +SQLITE_PRIVATE   void sqlite3ExplainExpr(Vdbe*, Expr*);
 1.12323 +SQLITE_PRIVATE   void sqlite3ExplainExprList(Vdbe*, ExprList*);
 1.12324 +SQLITE_PRIVATE   const char *sqlite3VdbeExplanation(Vdbe*);
 1.12325 +#else
 1.12326 +# define sqlite3ExplainBegin(X)
 1.12327 +# define sqlite3ExplainSelect(A,B)
 1.12328 +# define sqlite3ExplainExpr(A,B)
 1.12329 +# define sqlite3ExplainExprList(A,B)
 1.12330 +# define sqlite3ExplainFinish(X)
 1.12331 +# define sqlite3VdbeExplanation(X) 0
 1.12332 +#endif
 1.12333 +
 1.12334 +
 1.12335 +SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
 1.12336 +SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
 1.12337 +SQLITE_PRIVATE int sqlite3Dequote(char*);
 1.12338 +SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
 1.12339 +SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
 1.12340 +SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
 1.12341 +SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
 1.12342 +SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
 1.12343 +SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
 1.12344 +SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
 1.12345 +SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
 1.12346 +SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
 1.12347 +SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
 1.12348 +SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
 1.12349 +SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
 1.12350 +SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
 1.12351 +SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
 1.12352 +SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
 1.12353 +SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
 1.12354 +SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
 1.12355 +SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
 1.12356 +SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
 1.12357 +SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
 1.12358 +SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
 1.12359 +SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
 1.12360 +SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
 1.12361 +SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
 1.12362 +SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
 1.12363 +SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
 1.12364 +SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
 1.12365 +SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
 1.12366 +SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
 1.12367 +SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
 1.12368 +SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
 1.12369 +SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
 1.12370 +SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
 1.12371 +SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
 1.12372 +SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
 1.12373 +SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
 1.12374 +SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
 1.12375 +SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
 1.12376 +SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
 1.12377 +SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
 1.12378 +SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
 1.12379 +SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
 1.12380 +                    sqlite3_vfs**,char**,char **);
 1.12381 +SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
 1.12382 +SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
 1.12383 +
 1.12384 +SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
 1.12385 +SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
 1.12386 +SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
 1.12387 +SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
 1.12388 +SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
 1.12389 +SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
 1.12390 +SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
 1.12391 +
 1.12392 +SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
 1.12393 +SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
 1.12394 +SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
 1.12395 +SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
 1.12396 +SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
 1.12397 +
 1.12398 +SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
 1.12399 +
 1.12400 +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
 1.12401 +SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
 1.12402 +#else
 1.12403 +# define sqlite3ViewGetColumnNames(A,B) 0
 1.12404 +#endif
 1.12405 +
 1.12406 +SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
 1.12407 +SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
 1.12408 +SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
 1.12409 +#ifndef SQLITE_OMIT_AUTOINCREMENT
 1.12410 +SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
 1.12411 +SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
 1.12412 +#else
 1.12413 +# define sqlite3AutoincrementBegin(X)
 1.12414 +# define sqlite3AutoincrementEnd(X)
 1.12415 +#endif
 1.12416 +SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
 1.12417 +SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
 1.12418 +SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
 1.12419 +SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
 1.12420 +SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
 1.12421 +SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
 1.12422 +SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
 1.12423 +                                      Token*, Select*, Expr*, IdList*);
 1.12424 +SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
 1.12425 +SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
 1.12426 +SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
 1.12427 +SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
 1.12428 +SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
 1.12429 +SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
 1.12430 +SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
 1.12431 +SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
 1.12432 +                          Expr*, int, int);
 1.12433 +SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
 1.12434 +SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
 1.12435 +SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
 1.12436 +                         Expr*,ExprList*,u16,Expr*,Expr*);
 1.12437 +SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
 1.12438 +SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
 1.12439 +SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
 1.12440 +SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
 1.12441 +#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
 1.12442 +SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
 1.12443 +#endif
 1.12444 +SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
 1.12445 +SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
 1.12446 +SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
 1.12447 +SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
 1.12448 +SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
 1.12449 +SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
 1.12450 +SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
 1.12451 +SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
 1.12452 +SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
 1.12453 +SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
 1.12454 +SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
 1.12455 +SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
 1.12456 +SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
 1.12457 +SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
 1.12458 +SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
 1.12459 +SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
 1.12460 +SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
 1.12461 +SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
 1.12462 +SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
 1.12463 +SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
 1.12464 +SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
 1.12465 +SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
 1.12466 +SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
 1.12467 +SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
 1.12468 +SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
 1.12469 +SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, u8);
 1.12470 +#define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
 1.12471 +#define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
 1.12472 +SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
 1.12473 +SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
 1.12474 +SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
 1.12475 +SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
 1.12476 +SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
 1.12477 +SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
 1.12478 +SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
 1.12479 +SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
 1.12480 +SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
 1.12481 +SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
 1.12482 +SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
 1.12483 +SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
 1.12484 +SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
 1.12485 +SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
 1.12486 +SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
 1.12487 +SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
 1.12488 +SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
 1.12489 +SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
 1.12490 +SQLITE_PRIVATE void sqlite3PrngSaveState(void);
 1.12491 +SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
 1.12492 +SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
 1.12493 +SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
 1.12494 +SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
 1.12495 +SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
 1.12496 +SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
 1.12497 +SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
 1.12498 +SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
 1.12499 +SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
 1.12500 +SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
 1.12501 +SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
 1.12502 +SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
 1.12503 +SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
 1.12504 +SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
 1.12505 +SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
 1.12506 +SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
 1.12507 +SQLITE_PRIVATE int sqlite3IsRowid(const char*);
 1.12508 +SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8);
 1.12509 +SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*);
 1.12510 +SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
 1.12511 +SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
 1.12512 +                                     u8,u8,int,int*);
 1.12513 +SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
 1.12514 +SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int, u8*, int*, int*);
 1.12515 +SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
 1.12516 +SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
 1.12517 +SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
 1.12518 +SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
 1.12519 +SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
 1.12520 +SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
 1.12521 +SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
 1.12522 +SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
 1.12523 +SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
 1.12524 +SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
 1.12525 +SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
 1.12526 +SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
 1.12527 +SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
 1.12528 +SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
 1.12529 +SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
 1.12530 +SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
 1.12531 +SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
 1.12532 +SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
 1.12533 +SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
 1.12534 +
 1.12535 +#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
 1.12536 +SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
 1.12537 +#endif
 1.12538 +
 1.12539 +#ifndef SQLITE_OMIT_TRIGGER
 1.12540 +SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
 1.12541 +                           Expr*,int, int);
 1.12542 +SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
 1.12543 +SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
 1.12544 +SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
 1.12545 +SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
 1.12546 +SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
 1.12547 +SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
 1.12548 +                            int, int, int);
 1.12549 +SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
 1.12550 +  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
 1.12551 +SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
 1.12552 +SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
 1.12553 +SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
 1.12554 +                                        Select*,u8);
 1.12555 +SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
 1.12556 +SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
 1.12557 +SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
 1.12558 +SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
 1.12559 +SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
 1.12560 +# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
 1.12561 +#else
 1.12562 +# define sqlite3TriggersExist(B,C,D,E,F) 0
 1.12563 +# define sqlite3DeleteTrigger(A,B)
 1.12564 +# define sqlite3DropTriggerPtr(A,B)
 1.12565 +# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
 1.12566 +# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
 1.12567 +# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
 1.12568 +# define sqlite3TriggerList(X, Y) 0
 1.12569 +# define sqlite3ParseToplevel(p) p
 1.12570 +# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
 1.12571 +#endif
 1.12572 +
 1.12573 +SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
 1.12574 +SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
 1.12575 +SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
 1.12576 +#ifndef SQLITE_OMIT_AUTHORIZATION
 1.12577 +SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
 1.12578 +SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
 1.12579 +SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
 1.12580 +SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
 1.12581 +SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
 1.12582 +#else
 1.12583 +# define sqlite3AuthRead(a,b,c,d)
 1.12584 +# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
 1.12585 +# define sqlite3AuthContextPush(a,b,c)
 1.12586 +# define sqlite3AuthContextPop(a)  ((void)(a))
 1.12587 +#endif
 1.12588 +SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
 1.12589 +SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
 1.12590 +SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
 1.12591 +SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
 1.12592 +SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
 1.12593 +SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
 1.12594 +SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
 1.12595 +SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
 1.12596 +SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
 1.12597 +SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
 1.12598 +SQLITE_PRIVATE int sqlite3Atoi(const char*);
 1.12599 +SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
 1.12600 +SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
 1.12601 +SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
 1.12602 +SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
 1.12603 +SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
 1.12604 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.12605 +SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
 1.12606 +#endif
 1.12607 +SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
 1.12608 +
 1.12609 +/*
 1.12610 +** Routines to read and write variable-length integers.  These used to
 1.12611 +** be defined locally, but now we use the varint routines in the util.c
 1.12612 +** file.  Code should use the MACRO forms below, as the Varint32 versions
 1.12613 +** are coded to assume the single byte case is already handled (which 
 1.12614 +** the MACRO form does).
 1.12615 +*/
 1.12616 +SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
 1.12617 +SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
 1.12618 +SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
 1.12619 +SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
 1.12620 +SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
 1.12621 +
 1.12622 +/*
 1.12623 +** The header of a record consists of a sequence variable-length integers.
 1.12624 +** These integers are almost always small and are encoded as a single byte.
 1.12625 +** The following macros take advantage this fact to provide a fast encode
 1.12626 +** and decode of the integers in a record header.  It is faster for the common
 1.12627 +** case where the integer is a single byte.  It is a little slower when the
 1.12628 +** integer is two or more bytes.  But overall it is faster.
 1.12629 +**
 1.12630 +** The following expressions are equivalent:
 1.12631 +**
 1.12632 +**     x = sqlite3GetVarint32( A, &B );
 1.12633 +**     x = sqlite3PutVarint32( A, B );
 1.12634 +**
 1.12635 +**     x = getVarint32( A, B );
 1.12636 +**     x = putVarint32( A, B );
 1.12637 +**
 1.12638 +*/
 1.12639 +#define getVarint32(A,B)  \
 1.12640 +  (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
 1.12641 +#define putVarint32(A,B)  \
 1.12642 +  (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
 1.12643 +  sqlite3PutVarint32((A),(B)))
 1.12644 +#define getVarint    sqlite3GetVarint
 1.12645 +#define putVarint    sqlite3PutVarint
 1.12646 +
 1.12647 +
 1.12648 +SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
 1.12649 +SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
 1.12650 +SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
 1.12651 +SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
 1.12652 +SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
 1.12653 +SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
 1.12654 +SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
 1.12655 +SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
 1.12656 +SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
 1.12657 +SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
 1.12658 +
 1.12659 +#if defined(SQLITE_TEST) 
 1.12660 +SQLITE_PRIVATE const char *sqlite3ErrName(int);
 1.12661 +#endif
 1.12662 +
 1.12663 +SQLITE_PRIVATE const char *sqlite3ErrStr(int);
 1.12664 +SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
 1.12665 +SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
 1.12666 +SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
 1.12667 +SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
 1.12668 +SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, Token*);
 1.12669 +SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
 1.12670 +SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
 1.12671 +SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
 1.12672 +SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
 1.12673 +SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
 1.12674 +SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
 1.12675 +SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
 1.12676 +SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
 1.12677 +SQLITE_PRIVATE int sqlite3AbsInt32(int);
 1.12678 +#ifdef SQLITE_ENABLE_8_3_NAMES
 1.12679 +SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
 1.12680 +#else
 1.12681 +# define sqlite3FileSuffix3(X,Y)
 1.12682 +#endif
 1.12683 +SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
 1.12684 +
 1.12685 +SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
 1.12686 +SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
 1.12687 +SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
 1.12688 +                        void(*)(void*));
 1.12689 +SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
 1.12690 +SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
 1.12691 +SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
 1.12692 +SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
 1.12693 +SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
 1.12694 +SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
 1.12695 +#ifndef SQLITE_AMALGAMATION
 1.12696 +SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
 1.12697 +SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
 1.12698 +SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
 1.12699 +SQLITE_PRIVATE const Token sqlite3IntTokens[];
 1.12700 +SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
 1.12701 +SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
 1.12702 +#ifndef SQLITE_OMIT_WSD
 1.12703 +SQLITE_PRIVATE int sqlite3PendingByte;
 1.12704 +#endif
 1.12705 +#endif
 1.12706 +SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
 1.12707 +SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
 1.12708 +SQLITE_PRIVATE void sqlite3AlterFunctions(void);
 1.12709 +SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
 1.12710 +SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
 1.12711 +SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
 1.12712 +SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
 1.12713 +SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
 1.12714 +SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
 1.12715 +SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
 1.12716 +SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
 1.12717 +SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
 1.12718 +SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
 1.12719 +SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
 1.12720 +SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
 1.12721 +SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
 1.12722 +SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
 1.12723 +SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
 1.12724 +SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
 1.12725 +SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
 1.12726 +SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
 1.12727 +SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
 1.12728 +SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
 1.12729 +SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
 1.12730 +SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
 1.12731 +SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
 1.12732 +SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
 1.12733 +SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
 1.12734 +SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
 1.12735 +SQLITE_PRIVATE void sqlite3SchemaClear(void *);
 1.12736 +SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
 1.12737 +SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
 1.12738 +SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
 1.12739 +SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
 1.12740 +SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
 1.12741 +SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
 1.12742 +#ifdef SQLITE_DEBUG
 1.12743 +SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
 1.12744 +#endif
 1.12745 +SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
 1.12746 +  void (*)(sqlite3_context*,int,sqlite3_value **),
 1.12747 +  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
 1.12748 +  FuncDestructor *pDestructor
 1.12749 +);
 1.12750 +SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
 1.12751 +SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
 1.12752 +
 1.12753 +SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
 1.12754 +SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
 1.12755 +SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
 1.12756 +SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
 1.12757 +SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
 1.12758 +SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
 1.12759 +SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
 1.12760 +SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
 1.12761 +
 1.12762 +SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
 1.12763 +SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
 1.12764 +
 1.12765 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.12766 +SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
 1.12767 +SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
 1.12768 +SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
 1.12769 +#endif
 1.12770 +
 1.12771 +/*
 1.12772 +** The interface to the LEMON-generated parser
 1.12773 +*/
 1.12774 +SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
 1.12775 +SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
 1.12776 +SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
 1.12777 +#ifdef YYTRACKMAXSTACKDEPTH
 1.12778 +SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
 1.12779 +#endif
 1.12780 +
 1.12781 +SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
 1.12782 +#ifndef SQLITE_OMIT_LOAD_EXTENSION
 1.12783 +SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
 1.12784 +#else
 1.12785 +# define sqlite3CloseExtensions(X)
 1.12786 +#endif
 1.12787 +
 1.12788 +#ifndef SQLITE_OMIT_SHARED_CACHE
 1.12789 +SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
 1.12790 +#else
 1.12791 +  #define sqlite3TableLock(v,w,x,y,z)
 1.12792 +#endif
 1.12793 +
 1.12794 +#ifdef SQLITE_TEST
 1.12795 +SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
 1.12796 +#endif
 1.12797 +
 1.12798 +#ifdef SQLITE_OMIT_VIRTUALTABLE
 1.12799 +#  define sqlite3VtabClear(Y)
 1.12800 +#  define sqlite3VtabSync(X,Y) SQLITE_OK
 1.12801 +#  define sqlite3VtabRollback(X)
 1.12802 +#  define sqlite3VtabCommit(X)
 1.12803 +#  define sqlite3VtabInSync(db) 0
 1.12804 +#  define sqlite3VtabLock(X) 
 1.12805 +#  define sqlite3VtabUnlock(X)
 1.12806 +#  define sqlite3VtabUnlockList(X)
 1.12807 +#  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
 1.12808 +#  define sqlite3GetVTable(X,Y)  ((VTable*)0)
 1.12809 +#else
 1.12810 +SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
 1.12811 +SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
 1.12812 +SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, Vdbe*);
 1.12813 +SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
 1.12814 +SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
 1.12815 +SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
 1.12816 +SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
 1.12817 +SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
 1.12818 +SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
 1.12819 +SQLITE_PRIVATE    void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
 1.12820 +SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
 1.12821 +#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
 1.12822 +#endif
 1.12823 +SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
 1.12824 +SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
 1.12825 +SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
 1.12826 +SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
 1.12827 +SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
 1.12828 +SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
 1.12829 +SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
 1.12830 +SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
 1.12831 +SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
 1.12832 +SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
 1.12833 +SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
 1.12834 +SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
 1.12835 +SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
 1.12836 +SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
 1.12837 +SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
 1.12838 +SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
 1.12839 +SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
 1.12840 +SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
 1.12841 +SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
 1.12842 +SQLITE_PRIVATE const char *sqlite3JournalModename(int);
 1.12843 +#ifndef SQLITE_OMIT_WAL
 1.12844 +SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
 1.12845 +SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
 1.12846 +#endif
 1.12847 +#ifndef SQLITE_OMIT_CTE
 1.12848 +SQLITE_PRIVATE   With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
 1.12849 +SQLITE_PRIVATE   void sqlite3WithDelete(sqlite3*,With*);
 1.12850 +SQLITE_PRIVATE   void sqlite3WithPush(Parse*, With*, u8);
 1.12851 +#else
 1.12852 +#define sqlite3WithPush(x,y,z)
 1.12853 +#define sqlite3WithDelete(x,y)
 1.12854 +#endif
 1.12855 +
 1.12856 +/* Declarations for functions in fkey.c. All of these are replaced by
 1.12857 +** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
 1.12858 +** key functionality is available. If OMIT_TRIGGER is defined but
 1.12859 +** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
 1.12860 +** this case foreign keys are parsed, but no other functionality is 
 1.12861 +** provided (enforcement of FK constraints requires the triggers sub-system).
 1.12862 +*/
 1.12863 +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
 1.12864 +SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
 1.12865 +SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
 1.12866 +SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
 1.12867 +SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
 1.12868 +SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
 1.12869 +SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
 1.12870 +#else
 1.12871 +  #define sqlite3FkActions(a,b,c,d,e,f)
 1.12872 +  #define sqlite3FkCheck(a,b,c,d,e,f)
 1.12873 +  #define sqlite3FkDropTable(a,b,c)
 1.12874 +  #define sqlite3FkOldmask(a,b)         0
 1.12875 +  #define sqlite3FkRequired(a,b,c,d)    0
 1.12876 +#endif
 1.12877 +#ifndef SQLITE_OMIT_FOREIGN_KEY
 1.12878 +SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
 1.12879 +SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
 1.12880 +#else
 1.12881 +  #define sqlite3FkDelete(a,b)
 1.12882 +  #define sqlite3FkLocateIndex(a,b,c,d,e)
 1.12883 +#endif
 1.12884 +
 1.12885 +
 1.12886 +/*
 1.12887 +** Available fault injectors.  Should be numbered beginning with 0.
 1.12888 +*/
 1.12889 +#define SQLITE_FAULTINJECTOR_MALLOC     0
 1.12890 +#define SQLITE_FAULTINJECTOR_COUNT      1
 1.12891 +
 1.12892 +/*
 1.12893 +** The interface to the code in fault.c used for identifying "benign"
 1.12894 +** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
 1.12895 +** is not defined.
 1.12896 +*/
 1.12897 +#ifndef SQLITE_OMIT_BUILTIN_TEST
 1.12898 +SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
 1.12899 +SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
 1.12900 +#else
 1.12901 +  #define sqlite3BeginBenignMalloc()
 1.12902 +  #define sqlite3EndBenignMalloc()
 1.12903 +#endif
 1.12904 +
 1.12905 +#define IN_INDEX_ROWID           1
 1.12906 +#define IN_INDEX_EPH             2
 1.12907 +#define IN_INDEX_INDEX_ASC       3
 1.12908 +#define IN_INDEX_INDEX_DESC      4
 1.12909 +SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
 1.12910 +
 1.12911 +#ifdef SQLITE_ENABLE_ATOMIC_WRITE
 1.12912 +SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
 1.12913 +SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
 1.12914 +SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
 1.12915 +SQLITE_PRIVATE   int sqlite3JournalExists(sqlite3_file *p);
 1.12916 +#else
 1.12917 +  #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
 1.12918 +  #define sqlite3JournalExists(p) 1
 1.12919 +#endif
 1.12920 +
 1.12921 +SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
 1.12922 +SQLITE_PRIVATE int sqlite3MemJournalSize(void);
 1.12923 +SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
 1.12924 +
 1.12925 +#if SQLITE_MAX_EXPR_DEPTH>0
 1.12926 +SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
 1.12927 +SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
 1.12928 +SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
 1.12929 +#else
 1.12930 +  #define sqlite3ExprSetHeight(x,y)
 1.12931 +  #define sqlite3SelectExprHeight(x) 0
 1.12932 +  #define sqlite3ExprCheckHeight(x,y)
 1.12933 +#endif
 1.12934 +
 1.12935 +SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
 1.12936 +SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
 1.12937 +
 1.12938 +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
 1.12939 +SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
 1.12940 +SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
 1.12941 +SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
 1.12942 +#else
 1.12943 +  #define sqlite3ConnectionBlocked(x,y)
 1.12944 +  #define sqlite3ConnectionUnlocked(x)
 1.12945 +  #define sqlite3ConnectionClosed(x)
 1.12946 +#endif
 1.12947 +
 1.12948 +#ifdef SQLITE_DEBUG
 1.12949 +SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
 1.12950 +#endif
 1.12951 +
 1.12952 +/*
 1.12953 +** If the SQLITE_ENABLE IOTRACE exists then the global variable
 1.12954 +** sqlite3IoTrace is a pointer to a printf-like routine used to
 1.12955 +** print I/O tracing messages. 
 1.12956 +*/
 1.12957 +#ifdef SQLITE_ENABLE_IOTRACE
 1.12958 +# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
 1.12959 +SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
 1.12960 +SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
 1.12961 +#else
 1.12962 +# define IOTRACE(A)
 1.12963 +# define sqlite3VdbeIOTraceSql(X)
 1.12964 +#endif
 1.12965 +
 1.12966 +/*
 1.12967 +** These routines are available for the mem2.c debugging memory allocator
 1.12968 +** only.  They are used to verify that different "types" of memory
 1.12969 +** allocations are properly tracked by the system.
 1.12970 +**
 1.12971 +** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
 1.12972 +** the MEMTYPE_* macros defined below.  The type must be a bitmask with
 1.12973 +** a single bit set.
 1.12974 +**
 1.12975 +** sqlite3MemdebugHasType() returns true if any of the bits in its second
 1.12976 +** argument match the type set by the previous sqlite3MemdebugSetType().
 1.12977 +** sqlite3MemdebugHasType() is intended for use inside assert() statements.
 1.12978 +**
 1.12979 +** sqlite3MemdebugNoType() returns true if none of the bits in its second
 1.12980 +** argument match the type set by the previous sqlite3MemdebugSetType().
 1.12981 +**
 1.12982 +** Perhaps the most important point is the difference between MEMTYPE_HEAP
 1.12983 +** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
 1.12984 +** it might have been allocated by lookaside, except the allocation was
 1.12985 +** too large or lookaside was already full.  It is important to verify
 1.12986 +** that allocations that might have been satisfied by lookaside are not
 1.12987 +** passed back to non-lookaside free() routines.  Asserts such as the
 1.12988 +** example above are placed on the non-lookaside free() routines to verify
 1.12989 +** this constraint. 
 1.12990 +**
 1.12991 +** All of this is no-op for a production build.  It only comes into
 1.12992 +** play when the SQLITE_MEMDEBUG compile-time option is used.
 1.12993 +*/
 1.12994 +#ifdef SQLITE_MEMDEBUG
 1.12995 +SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
 1.12996 +SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
 1.12997 +SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
 1.12998 +#else
 1.12999 +# define sqlite3MemdebugSetType(X,Y)  /* no-op */
 1.13000 +# define sqlite3MemdebugHasType(X,Y)  1
 1.13001 +# define sqlite3MemdebugNoType(X,Y)   1
 1.13002 +#endif
 1.13003 +#define MEMTYPE_HEAP       0x01  /* General heap allocations */
 1.13004 +#define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
 1.13005 +#define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
 1.13006 +#define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
 1.13007 +#define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
 1.13008 +
 1.13009 +#endif /* _SQLITEINT_H_ */
 1.13010 +
 1.13011 +/************** End of sqliteInt.h *******************************************/
 1.13012 +/************** Begin file global.c ******************************************/
 1.13013 +/*
 1.13014 +** 2008 June 13
 1.13015 +**
 1.13016 +** The author disclaims copyright to this source code.  In place of
 1.13017 +** a legal notice, here is a blessing:
 1.13018 +**
 1.13019 +**    May you do good and not evil.
 1.13020 +**    May you find forgiveness for yourself and forgive others.
 1.13021 +**    May you share freely, never taking more than you give.
 1.13022 +**
 1.13023 +*************************************************************************
 1.13024 +**
 1.13025 +** This file contains definitions of global variables and contants.
 1.13026 +*/
 1.13027 +
 1.13028 +/* An array to map all upper-case characters into their corresponding
 1.13029 +** lower-case character. 
 1.13030 +**
 1.13031 +** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
 1.13032 +** handle case conversions for the UTF character set since the tables
 1.13033 +** involved are nearly as big or bigger than SQLite itself.
 1.13034 +*/
 1.13035 +SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
 1.13036 +#ifdef SQLITE_ASCII
 1.13037 +      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
 1.13038 +     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
 1.13039 +     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
 1.13040 +     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
 1.13041 +    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
 1.13042 +    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
 1.13043 +    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
 1.13044 +    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
 1.13045 +    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
 1.13046 +    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
 1.13047 +    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
 1.13048 +    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
 1.13049 +    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
 1.13050 +    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
 1.13051 +    252,253,254,255
 1.13052 +#endif
 1.13053 +#ifdef SQLITE_EBCDIC
 1.13054 +      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
 1.13055 +     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
 1.13056 +     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
 1.13057 +     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
 1.13058 +     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
 1.13059 +     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
 1.13060 +     96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
 1.13061 +    112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
 1.13062 +    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
 1.13063 +    144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
 1.13064 +    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
 1.13065 +    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
 1.13066 +    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
 1.13067 +    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
 1.13068 +    224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
 1.13069 +    239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
 1.13070 +#endif
 1.13071 +};
 1.13072 +
 1.13073 +/*
 1.13074 +** The following 256 byte lookup table is used to support SQLites built-in
 1.13075 +** equivalents to the following standard library functions:
 1.13076 +**
 1.13077 +**   isspace()                        0x01
 1.13078 +**   isalpha()                        0x02
 1.13079 +**   isdigit()                        0x04
 1.13080 +**   isalnum()                        0x06
 1.13081 +**   isxdigit()                       0x08
 1.13082 +**   toupper()                        0x20
 1.13083 +**   SQLite identifier character      0x40
 1.13084 +**
 1.13085 +** Bit 0x20 is set if the mapped character requires translation to upper
 1.13086 +** case. i.e. if the character is a lower-case ASCII character.
 1.13087 +** If x is a lower-case ASCII character, then its upper-case equivalent
 1.13088 +** is (x - 0x20). Therefore toupper() can be implemented as:
 1.13089 +**
 1.13090 +**   (x & ~(map[x]&0x20))
 1.13091 +**
 1.13092 +** Standard function tolower() is implemented using the sqlite3UpperToLower[]
 1.13093 +** array. tolower() is used more often than toupper() by SQLite.
 1.13094 +**
 1.13095 +** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
 1.13096 +** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
 1.13097 +** non-ASCII UTF character. Hence the test for whether or not a character is
 1.13098 +** part of an identifier is 0x46.
 1.13099 +**
 1.13100 +** SQLite's versions are identical to the standard versions assuming a
 1.13101 +** locale of "C". They are implemented as macros in sqliteInt.h.
 1.13102 +*/
 1.13103 +#ifdef SQLITE_ASCII
 1.13104 +SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
 1.13105 +  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
 1.13106 +  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
 1.13107 +  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
 1.13108 +  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
 1.13109 +  0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
 1.13110 +  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
 1.13111 +  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
 1.13112 +  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
 1.13113 +
 1.13114 +  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
 1.13115 +  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
 1.13116 +  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
 1.13117 +  0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
 1.13118 +  0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
 1.13119 +  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
 1.13120 +  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
 1.13121 +  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
 1.13122 +
 1.13123 +  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
 1.13124 +  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
 1.13125 +  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
 1.13126 +  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
 1.13127 +  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
 1.13128 +  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
 1.13129 +  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
 1.13130 +  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
 1.13131 +
 1.13132 +  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
 1.13133 +  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
 1.13134 +  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
 1.13135 +  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
 1.13136 +  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
 1.13137 +  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
 1.13138 +  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
 1.13139 +  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
 1.13140 +};
 1.13141 +#endif
 1.13142 +
 1.13143 +#ifndef SQLITE_USE_URI
 1.13144 +# define  SQLITE_USE_URI 0
 1.13145 +#endif
 1.13146 +
 1.13147 +#ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
 1.13148 +# define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
 1.13149 +#endif
 1.13150 +
 1.13151 +/*
 1.13152 +** The following singleton contains the global configuration for
 1.13153 +** the SQLite library.
 1.13154 +*/
 1.13155 +SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
 1.13156 +   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
 1.13157 +   1,                         /* bCoreMutex */
 1.13158 +   SQLITE_THREADSAFE==1,      /* bFullMutex */
 1.13159 +   SQLITE_USE_URI,            /* bOpenUri */
 1.13160 +   SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
 1.13161 +   0x7ffffffe,                /* mxStrlen */
 1.13162 +   0,                         /* neverCorrupt */
 1.13163 +   128,                       /* szLookaside */
 1.13164 +   500,                       /* nLookaside */
 1.13165 +   {0,0,0,0,0,0,0,0},         /* m */
 1.13166 +   {0,0,0,0,0,0,0,0,0},       /* mutex */
 1.13167 +   {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
 1.13168 +   (void*)0,                  /* pHeap */
 1.13169 +   0,                         /* nHeap */
 1.13170 +   0, 0,                      /* mnHeap, mxHeap */
 1.13171 +   SQLITE_DEFAULT_MMAP_SIZE,  /* szMmap */
 1.13172 +   SQLITE_MAX_MMAP_SIZE,      /* mxMmap */
 1.13173 +   (void*)0,                  /* pScratch */
 1.13174 +   0,                         /* szScratch */
 1.13175 +   0,                         /* nScratch */
 1.13176 +   (void*)0,                  /* pPage */
 1.13177 +   0,                         /* szPage */
 1.13178 +   0,                         /* nPage */
 1.13179 +   0,                         /* mxParserStack */
 1.13180 +   0,                         /* sharedCacheEnabled */
 1.13181 +   /* All the rest should always be initialized to zero */
 1.13182 +   0,                         /* isInit */
 1.13183 +   0,                         /* inProgress */
 1.13184 +   0,                         /* isMutexInit */
 1.13185 +   0,                         /* isMallocInit */
 1.13186 +   0,                         /* isPCacheInit */
 1.13187 +   0,                         /* pInitMutex */
 1.13188 +   0,                         /* nRefInitMutex */
 1.13189 +   0,                         /* xLog */
 1.13190 +   0,                         /* pLogArg */
 1.13191 +   0,                         /* bLocaltimeFault */
 1.13192 +#ifdef SQLITE_ENABLE_SQLLOG
 1.13193 +   0,                         /* xSqllog */
 1.13194 +   0                          /* pSqllogArg */
 1.13195 +#endif
 1.13196 +};
 1.13197 +
 1.13198 +/*
 1.13199 +** Hash table for global functions - functions common to all
 1.13200 +** database connections.  After initialization, this table is
 1.13201 +** read-only.
 1.13202 +*/
 1.13203 +SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
 1.13204 +
 1.13205 +/*
 1.13206 +** Constant tokens for values 0 and 1.
 1.13207 +*/
 1.13208 +SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
 1.13209 +   { "0", 1 },
 1.13210 +   { "1", 1 }
 1.13211 +};
 1.13212 +
 1.13213 +
 1.13214 +/*
 1.13215 +** The value of the "pending" byte must be 0x40000000 (1 byte past the
 1.13216 +** 1-gibabyte boundary) in a compatible database.  SQLite never uses
 1.13217 +** the database page that contains the pending byte.  It never attempts
 1.13218 +** to read or write that page.  The pending byte page is set assign
 1.13219 +** for use by the VFS layers as space for managing file locks.
 1.13220 +**
 1.13221 +** During testing, it is often desirable to move the pending byte to
 1.13222 +** a different position in the file.  This allows code that has to
 1.13223 +** deal with the pending byte to run on files that are much smaller
 1.13224 +** than 1 GiB.  The sqlite3_test_control() interface can be used to
 1.13225 +** move the pending byte.
 1.13226 +**
 1.13227 +** IMPORTANT:  Changing the pending byte to any value other than
 1.13228 +** 0x40000000 results in an incompatible database file format!
 1.13229 +** Changing the pending byte during operating results in undefined
 1.13230 +** and dileterious behavior.
 1.13231 +*/
 1.13232 +#ifndef SQLITE_OMIT_WSD
 1.13233 +SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
 1.13234 +#endif
 1.13235 +
 1.13236 +/*
 1.13237 +** Properties of opcodes.  The OPFLG_INITIALIZER macro is
 1.13238 +** created by mkopcodeh.awk during compilation.  Data is obtained
 1.13239 +** from the comments following the "case OP_xxxx:" statements in
 1.13240 +** the vdbe.c file.  
 1.13241 +*/
 1.13242 +SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
 1.13243 +
 1.13244 +/************** End of global.c **********************************************/
 1.13245 +/************** Begin file ctime.c *******************************************/
 1.13246 +/*
 1.13247 +** 2010 February 23
 1.13248 +**
 1.13249 +** The author disclaims copyright to this source code.  In place of
 1.13250 +** a legal notice, here is a blessing:
 1.13251 +**
 1.13252 +**    May you do good and not evil.
 1.13253 +**    May you find forgiveness for yourself and forgive others.
 1.13254 +**    May you share freely, never taking more than you give.
 1.13255 +**
 1.13256 +*************************************************************************
 1.13257 +**
 1.13258 +** This file implements routines used to report what compile-time options
 1.13259 +** SQLite was built with.
 1.13260 +*/
 1.13261 +
 1.13262 +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
 1.13263 +
 1.13264 +
 1.13265 +/*
 1.13266 +** An array of names of all compile-time options.  This array should 
 1.13267 +** be sorted A-Z.
 1.13268 +**
 1.13269 +** This array looks large, but in a typical installation actually uses
 1.13270 +** only a handful of compile-time options, so most times this array is usually
 1.13271 +** rather short and uses little memory space.
 1.13272 +*/
 1.13273 +static const char * const azCompileOpt[] = {
 1.13274 +
 1.13275 +/* These macros are provided to "stringify" the value of the define
 1.13276 +** for those options in which the value is meaningful. */
 1.13277 +#define CTIMEOPT_VAL_(opt) #opt
 1.13278 +#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
 1.13279 +
 1.13280 +#ifdef SQLITE_32BIT_ROWID
 1.13281 +  "32BIT_ROWID",
 1.13282 +#endif
 1.13283 +#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
 1.13284 +  "4_BYTE_ALIGNED_MALLOC",
 1.13285 +#endif
 1.13286 +#ifdef SQLITE_CASE_SENSITIVE_LIKE
 1.13287 +  "CASE_SENSITIVE_LIKE",
 1.13288 +#endif
 1.13289 +#ifdef SQLITE_CHECK_PAGES
 1.13290 +  "CHECK_PAGES",
 1.13291 +#endif
 1.13292 +#ifdef SQLITE_COVERAGE_TEST
 1.13293 +  "COVERAGE_TEST",
 1.13294 +#endif
 1.13295 +#ifdef SQLITE_DEBUG
 1.13296 +  "DEBUG",
 1.13297 +#endif
 1.13298 +#ifdef SQLITE_DEFAULT_LOCKING_MODE
 1.13299 +  "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
 1.13300 +#endif
 1.13301 +#if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
 1.13302 +  "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
 1.13303 +#endif
 1.13304 +#ifdef SQLITE_DISABLE_DIRSYNC
 1.13305 +  "DISABLE_DIRSYNC",
 1.13306 +#endif
 1.13307 +#ifdef SQLITE_DISABLE_LFS
 1.13308 +  "DISABLE_LFS",
 1.13309 +#endif
 1.13310 +#ifdef SQLITE_ENABLE_ATOMIC_WRITE
 1.13311 +  "ENABLE_ATOMIC_WRITE",
 1.13312 +#endif
 1.13313 +#ifdef SQLITE_ENABLE_CEROD
 1.13314 +  "ENABLE_CEROD",
 1.13315 +#endif
 1.13316 +#ifdef SQLITE_ENABLE_COLUMN_METADATA
 1.13317 +  "ENABLE_COLUMN_METADATA",
 1.13318 +#endif
 1.13319 +#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
 1.13320 +  "ENABLE_EXPENSIVE_ASSERT",
 1.13321 +#endif
 1.13322 +#ifdef SQLITE_ENABLE_FTS1
 1.13323 +  "ENABLE_FTS1",
 1.13324 +#endif
 1.13325 +#ifdef SQLITE_ENABLE_FTS2
 1.13326 +  "ENABLE_FTS2",
 1.13327 +#endif
 1.13328 +#ifdef SQLITE_ENABLE_FTS3
 1.13329 +  "ENABLE_FTS3",
 1.13330 +#endif
 1.13331 +#ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
 1.13332 +  "ENABLE_FTS3_PARENTHESIS",
 1.13333 +#endif
 1.13334 +#ifdef SQLITE_ENABLE_FTS4
 1.13335 +  "ENABLE_FTS4",
 1.13336 +#endif
 1.13337 +#ifdef SQLITE_ENABLE_ICU
 1.13338 +  "ENABLE_ICU",
 1.13339 +#endif
 1.13340 +#ifdef SQLITE_ENABLE_IOTRACE
 1.13341 +  "ENABLE_IOTRACE",
 1.13342 +#endif
 1.13343 +#ifdef SQLITE_ENABLE_LOAD_EXTENSION
 1.13344 +  "ENABLE_LOAD_EXTENSION",
 1.13345 +#endif
 1.13346 +#ifdef SQLITE_ENABLE_LOCKING_STYLE
 1.13347 +  "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
 1.13348 +#endif
 1.13349 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
 1.13350 +  "ENABLE_MEMORY_MANAGEMENT",
 1.13351 +#endif
 1.13352 +#ifdef SQLITE_ENABLE_MEMSYS3
 1.13353 +  "ENABLE_MEMSYS3",
 1.13354 +#endif
 1.13355 +#ifdef SQLITE_ENABLE_MEMSYS5
 1.13356 +  "ENABLE_MEMSYS5",
 1.13357 +#endif
 1.13358 +#ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
 1.13359 +  "ENABLE_OVERSIZE_CELL_CHECK",
 1.13360 +#endif
 1.13361 +#ifdef SQLITE_ENABLE_RTREE
 1.13362 +  "ENABLE_RTREE",
 1.13363 +#endif
 1.13364 +#if defined(SQLITE_ENABLE_STAT4)
 1.13365 +  "ENABLE_STAT4",
 1.13366 +#elif defined(SQLITE_ENABLE_STAT3)
 1.13367 +  "ENABLE_STAT3",
 1.13368 +#endif
 1.13369 +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
 1.13370 +  "ENABLE_UNLOCK_NOTIFY",
 1.13371 +#endif
 1.13372 +#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
 1.13373 +  "ENABLE_UPDATE_DELETE_LIMIT",
 1.13374 +#endif
 1.13375 +#ifdef SQLITE_HAS_CODEC
 1.13376 +  "HAS_CODEC",
 1.13377 +#endif
 1.13378 +#ifdef SQLITE_HAVE_ISNAN
 1.13379 +  "HAVE_ISNAN",
 1.13380 +#endif
 1.13381 +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
 1.13382 +  "HOMEGROWN_RECURSIVE_MUTEX",
 1.13383 +#endif
 1.13384 +#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
 1.13385 +  "IGNORE_AFP_LOCK_ERRORS",
 1.13386 +#endif
 1.13387 +#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
 1.13388 +  "IGNORE_FLOCK_LOCK_ERRORS",
 1.13389 +#endif
 1.13390 +#ifdef SQLITE_INT64_TYPE
 1.13391 +  "INT64_TYPE",
 1.13392 +#endif
 1.13393 +#ifdef SQLITE_LOCK_TRACE
 1.13394 +  "LOCK_TRACE",
 1.13395 +#endif
 1.13396 +#if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
 1.13397 +  "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
 1.13398 +#endif
 1.13399 +#ifdef SQLITE_MAX_SCHEMA_RETRY
 1.13400 +  "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
 1.13401 +#endif
 1.13402 +#ifdef SQLITE_MEMDEBUG
 1.13403 +  "MEMDEBUG",
 1.13404 +#endif
 1.13405 +#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
 1.13406 +  "MIXED_ENDIAN_64BIT_FLOAT",
 1.13407 +#endif
 1.13408 +#ifdef SQLITE_NO_SYNC
 1.13409 +  "NO_SYNC",
 1.13410 +#endif
 1.13411 +#ifdef SQLITE_OMIT_ALTERTABLE
 1.13412 +  "OMIT_ALTERTABLE",
 1.13413 +#endif
 1.13414 +#ifdef SQLITE_OMIT_ANALYZE
 1.13415 +  "OMIT_ANALYZE",
 1.13416 +#endif
 1.13417 +#ifdef SQLITE_OMIT_ATTACH
 1.13418 +  "OMIT_ATTACH",
 1.13419 +#endif
 1.13420 +#ifdef SQLITE_OMIT_AUTHORIZATION
 1.13421 +  "OMIT_AUTHORIZATION",
 1.13422 +#endif
 1.13423 +#ifdef SQLITE_OMIT_AUTOINCREMENT
 1.13424 +  "OMIT_AUTOINCREMENT",
 1.13425 +#endif
 1.13426 +#ifdef SQLITE_OMIT_AUTOINIT
 1.13427 +  "OMIT_AUTOINIT",
 1.13428 +#endif
 1.13429 +#ifdef SQLITE_OMIT_AUTOMATIC_INDEX
 1.13430 +  "OMIT_AUTOMATIC_INDEX",
 1.13431 +#endif
 1.13432 +#ifdef SQLITE_OMIT_AUTORESET
 1.13433 +  "OMIT_AUTORESET",
 1.13434 +#endif
 1.13435 +#ifdef SQLITE_OMIT_AUTOVACUUM
 1.13436 +  "OMIT_AUTOVACUUM",
 1.13437 +#endif
 1.13438 +#ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
 1.13439 +  "OMIT_BETWEEN_OPTIMIZATION",
 1.13440 +#endif
 1.13441 +#ifdef SQLITE_OMIT_BLOB_LITERAL
 1.13442 +  "OMIT_BLOB_LITERAL",
 1.13443 +#endif
 1.13444 +#ifdef SQLITE_OMIT_BTREECOUNT
 1.13445 +  "OMIT_BTREECOUNT",
 1.13446 +#endif
 1.13447 +#ifdef SQLITE_OMIT_BUILTIN_TEST
 1.13448 +  "OMIT_BUILTIN_TEST",
 1.13449 +#endif
 1.13450 +#ifdef SQLITE_OMIT_CAST
 1.13451 +  "OMIT_CAST",
 1.13452 +#endif
 1.13453 +#ifdef SQLITE_OMIT_CHECK
 1.13454 +  "OMIT_CHECK",
 1.13455 +#endif
 1.13456 +#ifdef SQLITE_OMIT_COMPLETE
 1.13457 +  "OMIT_COMPLETE",
 1.13458 +#endif
 1.13459 +#ifdef SQLITE_OMIT_COMPOUND_SELECT
 1.13460 +  "OMIT_COMPOUND_SELECT",
 1.13461 +#endif
 1.13462 +#ifdef SQLITE_OMIT_CTE
 1.13463 +  "OMIT_CTE",
 1.13464 +#endif
 1.13465 +#ifdef SQLITE_OMIT_DATETIME_FUNCS
 1.13466 +  "OMIT_DATETIME_FUNCS",
 1.13467 +#endif
 1.13468 +#ifdef SQLITE_OMIT_DECLTYPE
 1.13469 +  "OMIT_DECLTYPE",
 1.13470 +#endif
 1.13471 +#ifdef SQLITE_OMIT_DEPRECATED
 1.13472 +  "OMIT_DEPRECATED",
 1.13473 +#endif
 1.13474 +#ifdef SQLITE_OMIT_DISKIO
 1.13475 +  "OMIT_DISKIO",
 1.13476 +#endif
 1.13477 +#ifdef SQLITE_OMIT_EXPLAIN
 1.13478 +  "OMIT_EXPLAIN",
 1.13479 +#endif
 1.13480 +#ifdef SQLITE_OMIT_FLAG_PRAGMAS
 1.13481 +  "OMIT_FLAG_PRAGMAS",
 1.13482 +#endif
 1.13483 +#ifdef SQLITE_OMIT_FLOATING_POINT
 1.13484 +  "OMIT_FLOATING_POINT",
 1.13485 +#endif
 1.13486 +#ifdef SQLITE_OMIT_FOREIGN_KEY
 1.13487 +  "OMIT_FOREIGN_KEY",
 1.13488 +#endif
 1.13489 +#ifdef SQLITE_OMIT_GET_TABLE
 1.13490 +  "OMIT_GET_TABLE",
 1.13491 +#endif
 1.13492 +#ifdef SQLITE_OMIT_INCRBLOB
 1.13493 +  "OMIT_INCRBLOB",
 1.13494 +#endif
 1.13495 +#ifdef SQLITE_OMIT_INTEGRITY_CHECK
 1.13496 +  "OMIT_INTEGRITY_CHECK",
 1.13497 +#endif
 1.13498 +#ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
 1.13499 +  "OMIT_LIKE_OPTIMIZATION",
 1.13500 +#endif
 1.13501 +#ifdef SQLITE_OMIT_LOAD_EXTENSION
 1.13502 +  "OMIT_LOAD_EXTENSION",
 1.13503 +#endif
 1.13504 +#ifdef SQLITE_OMIT_LOCALTIME
 1.13505 +  "OMIT_LOCALTIME",
 1.13506 +#endif
 1.13507 +#ifdef SQLITE_OMIT_LOOKASIDE
 1.13508 +  "OMIT_LOOKASIDE",
 1.13509 +#endif
 1.13510 +#ifdef SQLITE_OMIT_MEMORYDB
 1.13511 +  "OMIT_MEMORYDB",
 1.13512 +#endif
 1.13513 +#ifdef SQLITE_OMIT_OR_OPTIMIZATION
 1.13514 +  "OMIT_OR_OPTIMIZATION",
 1.13515 +#endif
 1.13516 +#ifdef SQLITE_OMIT_PAGER_PRAGMAS
 1.13517 +  "OMIT_PAGER_PRAGMAS",
 1.13518 +#endif
 1.13519 +#ifdef SQLITE_OMIT_PRAGMA
 1.13520 +  "OMIT_PRAGMA",
 1.13521 +#endif
 1.13522 +#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
 1.13523 +  "OMIT_PROGRESS_CALLBACK",
 1.13524 +#endif
 1.13525 +#ifdef SQLITE_OMIT_QUICKBALANCE
 1.13526 +  "OMIT_QUICKBALANCE",
 1.13527 +#endif
 1.13528 +#ifdef SQLITE_OMIT_REINDEX
 1.13529 +  "OMIT_REINDEX",
 1.13530 +#endif
 1.13531 +#ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
 1.13532 +  "OMIT_SCHEMA_PRAGMAS",
 1.13533 +#endif
 1.13534 +#ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
 1.13535 +  "OMIT_SCHEMA_VERSION_PRAGMAS",
 1.13536 +#endif
 1.13537 +#ifdef SQLITE_OMIT_SHARED_CACHE
 1.13538 +  "OMIT_SHARED_CACHE",
 1.13539 +#endif
 1.13540 +#ifdef SQLITE_OMIT_SUBQUERY
 1.13541 +  "OMIT_SUBQUERY",
 1.13542 +#endif
 1.13543 +#ifdef SQLITE_OMIT_TCL_VARIABLE
 1.13544 +  "OMIT_TCL_VARIABLE",
 1.13545 +#endif
 1.13546 +#ifdef SQLITE_OMIT_TEMPDB
 1.13547 +  "OMIT_TEMPDB",
 1.13548 +#endif
 1.13549 +#ifdef SQLITE_OMIT_TRACE
 1.13550 +  "OMIT_TRACE",
 1.13551 +#endif
 1.13552 +#ifdef SQLITE_OMIT_TRIGGER
 1.13553 +  "OMIT_TRIGGER",
 1.13554 +#endif
 1.13555 +#ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
 1.13556 +  "OMIT_TRUNCATE_OPTIMIZATION",
 1.13557 +#endif
 1.13558 +#ifdef SQLITE_OMIT_UTF16
 1.13559 +  "OMIT_UTF16",
 1.13560 +#endif
 1.13561 +#ifdef SQLITE_OMIT_VACUUM
 1.13562 +  "OMIT_VACUUM",
 1.13563 +#endif
 1.13564 +#ifdef SQLITE_OMIT_VIEW
 1.13565 +  "OMIT_VIEW",
 1.13566 +#endif
 1.13567 +#ifdef SQLITE_OMIT_VIRTUALTABLE
 1.13568 +  "OMIT_VIRTUALTABLE",
 1.13569 +#endif
 1.13570 +#ifdef SQLITE_OMIT_WAL
 1.13571 +  "OMIT_WAL",
 1.13572 +#endif
 1.13573 +#ifdef SQLITE_OMIT_WSD
 1.13574 +  "OMIT_WSD",
 1.13575 +#endif
 1.13576 +#ifdef SQLITE_OMIT_XFER_OPT
 1.13577 +  "OMIT_XFER_OPT",
 1.13578 +#endif
 1.13579 +#ifdef SQLITE_PERFORMANCE_TRACE
 1.13580 +  "PERFORMANCE_TRACE",
 1.13581 +#endif
 1.13582 +#ifdef SQLITE_PROXY_DEBUG
 1.13583 +  "PROXY_DEBUG",
 1.13584 +#endif
 1.13585 +#ifdef SQLITE_RTREE_INT_ONLY
 1.13586 +  "RTREE_INT_ONLY",
 1.13587 +#endif
 1.13588 +#ifdef SQLITE_SECURE_DELETE
 1.13589 +  "SECURE_DELETE",
 1.13590 +#endif
 1.13591 +#ifdef SQLITE_SMALL_STACK
 1.13592 +  "SMALL_STACK",
 1.13593 +#endif
 1.13594 +#ifdef SQLITE_SOUNDEX
 1.13595 +  "SOUNDEX",
 1.13596 +#endif
 1.13597 +#ifdef SQLITE_SYSTEM_MALLOC
 1.13598 +  "SYSTEM_MALLOC",
 1.13599 +#endif
 1.13600 +#ifdef SQLITE_TCL
 1.13601 +  "TCL",
 1.13602 +#endif
 1.13603 +#if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
 1.13604 +  "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
 1.13605 +#endif
 1.13606 +#ifdef SQLITE_TEST
 1.13607 +  "TEST",
 1.13608 +#endif
 1.13609 +#if defined(SQLITE_THREADSAFE)
 1.13610 +  "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
 1.13611 +#endif
 1.13612 +#ifdef SQLITE_USE_ALLOCA
 1.13613 +  "USE_ALLOCA",
 1.13614 +#endif
 1.13615 +#ifdef SQLITE_WIN32_MALLOC
 1.13616 +  "WIN32_MALLOC",
 1.13617 +#endif
 1.13618 +#ifdef SQLITE_ZERO_MALLOC
 1.13619 +  "ZERO_MALLOC"
 1.13620 +#endif
 1.13621 +};
 1.13622 +
 1.13623 +/*
 1.13624 +** Given the name of a compile-time option, return true if that option
 1.13625 +** was used and false if not.
 1.13626 +**
 1.13627 +** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
 1.13628 +** is not required for a match.
 1.13629 +*/
 1.13630 +SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
 1.13631 +  int i, n;
 1.13632 +  if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
 1.13633 +  n = sqlite3Strlen30(zOptName);
 1.13634 +
 1.13635 +  /* Since ArraySize(azCompileOpt) is normally in single digits, a
 1.13636 +  ** linear search is adequate.  No need for a binary search. */
 1.13637 +  for(i=0; i<ArraySize(azCompileOpt); i++){
 1.13638 +    if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
 1.13639 +     && sqlite3CtypeMap[(unsigned char)azCompileOpt[i][n]]==0
 1.13640 +    ){
 1.13641 +      return 1;
 1.13642 +    }
 1.13643 +  }
 1.13644 +  return 0;
 1.13645 +}
 1.13646 +
 1.13647 +/*
 1.13648 +** Return the N-th compile-time option string.  If N is out of range,
 1.13649 +** return a NULL pointer.
 1.13650 +*/
 1.13651 +SQLITE_API const char *sqlite3_compileoption_get(int N){
 1.13652 +  if( N>=0 && N<ArraySize(azCompileOpt) ){
 1.13653 +    return azCompileOpt[N];
 1.13654 +  }
 1.13655 +  return 0;
 1.13656 +}
 1.13657 +
 1.13658 +#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
 1.13659 +
 1.13660 +/************** End of ctime.c ***********************************************/
 1.13661 +/************** Begin file status.c ******************************************/
 1.13662 +/*
 1.13663 +** 2008 June 18
 1.13664 +**
 1.13665 +** The author disclaims copyright to this source code.  In place of
 1.13666 +** a legal notice, here is a blessing:
 1.13667 +**
 1.13668 +**    May you do good and not evil.
 1.13669 +**    May you find forgiveness for yourself and forgive others.
 1.13670 +**    May you share freely, never taking more than you give.
 1.13671 +**
 1.13672 +*************************************************************************
 1.13673 +**
 1.13674 +** This module implements the sqlite3_status() interface and related
 1.13675 +** functionality.
 1.13676 +*/
 1.13677 +/************** Include vdbeInt.h in the middle of status.c ******************/
 1.13678 +/************** Begin file vdbeInt.h *****************************************/
 1.13679 +/*
 1.13680 +** 2003 September 6
 1.13681 +**
 1.13682 +** The author disclaims copyright to this source code.  In place of
 1.13683 +** a legal notice, here is a blessing:
 1.13684 +**
 1.13685 +**    May you do good and not evil.
 1.13686 +**    May you find forgiveness for yourself and forgive others.
 1.13687 +**    May you share freely, never taking more than you give.
 1.13688 +**
 1.13689 +*************************************************************************
 1.13690 +** This is the header file for information that is private to the
 1.13691 +** VDBE.  This information used to all be at the top of the single
 1.13692 +** source code file "vdbe.c".  When that file became too big (over
 1.13693 +** 6000 lines long) it was split up into several smaller files and
 1.13694 +** this header information was factored out.
 1.13695 +*/
 1.13696 +#ifndef _VDBEINT_H_
 1.13697 +#define _VDBEINT_H_
 1.13698 +
 1.13699 +/*
 1.13700 +** The maximum number of times that a statement will try to reparse
 1.13701 +** itself before giving up and returning SQLITE_SCHEMA.
 1.13702 +*/
 1.13703 +#ifndef SQLITE_MAX_SCHEMA_RETRY
 1.13704 +# define SQLITE_MAX_SCHEMA_RETRY 50
 1.13705 +#endif
 1.13706 +
 1.13707 +/*
 1.13708 +** SQL is translated into a sequence of instructions to be
 1.13709 +** executed by a virtual machine.  Each instruction is an instance
 1.13710 +** of the following structure.
 1.13711 +*/
 1.13712 +typedef struct VdbeOp Op;
 1.13713 +
 1.13714 +/*
 1.13715 +** Boolean values
 1.13716 +*/
 1.13717 +typedef unsigned Bool;
 1.13718 +
 1.13719 +/* Opaque type used by code in vdbesort.c */
 1.13720 +typedef struct VdbeSorter VdbeSorter;
 1.13721 +
 1.13722 +/* Opaque type used by the explainer */
 1.13723 +typedef struct Explain Explain;
 1.13724 +
 1.13725 +/* Elements of the linked list at Vdbe.pAuxData */
 1.13726 +typedef struct AuxData AuxData;
 1.13727 +
 1.13728 +/*
 1.13729 +** A cursor is a pointer into a single BTree within a database file.
 1.13730 +** The cursor can seek to a BTree entry with a particular key, or
 1.13731 +** loop over all entries of the Btree.  You can also insert new BTree
 1.13732 +** entries or retrieve the key or data from the entry that the cursor
 1.13733 +** is currently pointing to.
 1.13734 +**
 1.13735 +** Cursors can also point to virtual tables, sorters, or "pseudo-tables".
 1.13736 +** A pseudo-table is a single-row table implemented by registers.
 1.13737 +** 
 1.13738 +** Every cursor that the virtual machine has open is represented by an
 1.13739 +** instance of the following structure.
 1.13740 +*/
 1.13741 +struct VdbeCursor {
 1.13742 +  BtCursor *pCursor;    /* The cursor structure of the backend */
 1.13743 +  Btree *pBt;           /* Separate file holding temporary table */
 1.13744 +  KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
 1.13745 +  int seekResult;       /* Result of previous sqlite3BtreeMoveto() */
 1.13746 +  int pseudoTableReg;   /* Register holding pseudotable content. */
 1.13747 +  i16 nField;           /* Number of fields in the header */
 1.13748 +  u16 nHdrParsed;       /* Number of header fields parsed so far */
 1.13749 +  i8 iDb;               /* Index of cursor database in db->aDb[] (or -1) */
 1.13750 +  u8 nullRow;           /* True if pointing to a row with no data */
 1.13751 +  u8 rowidIsValid;      /* True if lastRowid is valid */
 1.13752 +  u8 deferredMoveto;    /* A call to sqlite3BtreeMoveto() is needed */
 1.13753 +  Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
 1.13754 +  Bool isTable:1;       /* True if a table requiring integer keys */
 1.13755 +  Bool isOrdered:1;     /* True if the underlying table is BTREE_UNORDERED */
 1.13756 +  sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
 1.13757 +  i64 seqCount;         /* Sequence counter */
 1.13758 +  i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
 1.13759 +  i64 lastRowid;        /* Rowid being deleted by OP_Delete */
 1.13760 +  VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
 1.13761 +
 1.13762 +  /* Cached information about the header for the data record that the
 1.13763 +  ** cursor is currently pointing to.  Only valid if cacheStatus matches
 1.13764 +  ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
 1.13765 +  ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
 1.13766 +  ** the cache is out of date.
 1.13767 +  **
 1.13768 +  ** aRow might point to (ephemeral) data for the current row, or it might
 1.13769 +  ** be NULL.
 1.13770 +  */
 1.13771 +  u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
 1.13772 +  u32 payloadSize;      /* Total number of bytes in the record */
 1.13773 +  u32 szRow;            /* Byte available in aRow */
 1.13774 +  u32 iHdrOffset;       /* Offset to next unparsed byte of the header */
 1.13775 +  const u8 *aRow;       /* Data for the current row, if all on one page */
 1.13776 +  u32 aType[1];         /* Type values for all entries in the record */
 1.13777 +  /* 2*nField extra array elements allocated for aType[], beyond the one
 1.13778 +  ** static element declared in the structure.  nField total array slots for
 1.13779 +  ** aType[] and nField+1 array slots for aOffset[] */
 1.13780 +};
 1.13781 +typedef struct VdbeCursor VdbeCursor;
 1.13782 +
 1.13783 +/*
 1.13784 +** When a sub-program is executed (OP_Program), a structure of this type
 1.13785 +** is allocated to store the current value of the program counter, as
 1.13786 +** well as the current memory cell array and various other frame specific
 1.13787 +** values stored in the Vdbe struct. When the sub-program is finished, 
 1.13788 +** these values are copied back to the Vdbe from the VdbeFrame structure,
 1.13789 +** restoring the state of the VM to as it was before the sub-program
 1.13790 +** began executing.
 1.13791 +**
 1.13792 +** The memory for a VdbeFrame object is allocated and managed by a memory
 1.13793 +** cell in the parent (calling) frame. When the memory cell is deleted or
 1.13794 +** overwritten, the VdbeFrame object is not freed immediately. Instead, it
 1.13795 +** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
 1.13796 +** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
 1.13797 +** this instead of deleting the VdbeFrame immediately is to avoid recursive
 1.13798 +** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
 1.13799 +** child frame are released.
 1.13800 +**
 1.13801 +** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
 1.13802 +** set to NULL if the currently executing frame is the main program.
 1.13803 +*/
 1.13804 +typedef struct VdbeFrame VdbeFrame;
 1.13805 +struct VdbeFrame {
 1.13806 +  Vdbe *v;                /* VM this frame belongs to */
 1.13807 +  VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
 1.13808 +  Op *aOp;                /* Program instructions for parent frame */
 1.13809 +  Mem *aMem;              /* Array of memory cells for parent frame */
 1.13810 +  u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
 1.13811 +  VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
 1.13812 +  void *token;            /* Copy of SubProgram.token */
 1.13813 +  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
 1.13814 +  int nCursor;            /* Number of entries in apCsr */
 1.13815 +  int pc;                 /* Program Counter in parent (calling) frame */
 1.13816 +  int nOp;                /* Size of aOp array */
 1.13817 +  int nMem;               /* Number of entries in aMem */
 1.13818 +  int nOnceFlag;          /* Number of entries in aOnceFlag */
 1.13819 +  int nChildMem;          /* Number of memory cells for child frame */
 1.13820 +  int nChildCsr;          /* Number of cursors for child frame */
 1.13821 +  int nChange;            /* Statement changes (Vdbe.nChanges)     */
 1.13822 +};
 1.13823 +
 1.13824 +#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
 1.13825 +
 1.13826 +/*
 1.13827 +** A value for VdbeCursor.cacheValid that means the cache is always invalid.
 1.13828 +*/
 1.13829 +#define CACHE_STALE 0
 1.13830 +
 1.13831 +/*
 1.13832 +** Internally, the vdbe manipulates nearly all SQL values as Mem
 1.13833 +** structures. Each Mem struct may cache multiple representations (string,
 1.13834 +** integer etc.) of the same value.
 1.13835 +*/
 1.13836 +struct Mem {
 1.13837 +  sqlite3 *db;        /* The associated database connection */
 1.13838 +  char *z;            /* String or BLOB value */
 1.13839 +  double r;           /* Real value */
 1.13840 +  union {
 1.13841 +    i64 i;              /* Integer value used when MEM_Int is set in flags */
 1.13842 +    int nZero;          /* Used when bit MEM_Zero is set in flags */
 1.13843 +    FuncDef *pDef;      /* Used only when flags==MEM_Agg */
 1.13844 +    RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
 1.13845 +    VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
 1.13846 +  } u;
 1.13847 +  int n;              /* Number of characters in string value, excluding '\0' */
 1.13848 +  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
 1.13849 +  u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
 1.13850 +#ifdef SQLITE_DEBUG
 1.13851 +  Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
 1.13852 +  void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
 1.13853 +#endif
 1.13854 +  void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
 1.13855 +  char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
 1.13856 +};
 1.13857 +
 1.13858 +/* One or more of the following flags are set to indicate the validOK
 1.13859 +** representations of the value stored in the Mem struct.
 1.13860 +**
 1.13861 +** If the MEM_Null flag is set, then the value is an SQL NULL value.
 1.13862 +** No other flags may be set in this case.
 1.13863 +**
 1.13864 +** If the MEM_Str flag is set then Mem.z points at a string representation.
 1.13865 +** Usually this is encoded in the same unicode encoding as the main
 1.13866 +** database (see below for exceptions). If the MEM_Term flag is also
 1.13867 +** set, then the string is nul terminated. The MEM_Int and MEM_Real 
 1.13868 +** flags may coexist with the MEM_Str flag.
 1.13869 +*/
 1.13870 +#define MEM_Null      0x0001   /* Value is NULL */
 1.13871 +#define MEM_Str       0x0002   /* Value is a string */
 1.13872 +#define MEM_Int       0x0004   /* Value is an integer */
 1.13873 +#define MEM_Real      0x0008   /* Value is a real number */
 1.13874 +#define MEM_Blob      0x0010   /* Value is a BLOB */
 1.13875 +#define MEM_AffMask   0x001f   /* Mask of affinity bits */
 1.13876 +#define MEM_RowSet    0x0020   /* Value is a RowSet object */
 1.13877 +#define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
 1.13878 +#define MEM_Undefined 0x0080   /* Value is undefined */
 1.13879 +#define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
 1.13880 +#define MEM_TypeMask  0x01ff   /* Mask of type bits */
 1.13881 +
 1.13882 +
 1.13883 +/* Whenever Mem contains a valid string or blob representation, one of
 1.13884 +** the following flags must be set to determine the memory management
 1.13885 +** policy for Mem.z.  The MEM_Term flag tells us whether or not the
 1.13886 +** string is \000 or \u0000 terminated
 1.13887 +*/
 1.13888 +#define MEM_Term      0x0200   /* String rep is nul terminated */
 1.13889 +#define MEM_Dyn       0x0400   /* Need to call Mem.xDel() on Mem.z */
 1.13890 +#define MEM_Static    0x0800   /* Mem.z points to a static string */
 1.13891 +#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
 1.13892 +#define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
 1.13893 +#define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
 1.13894 +#ifdef SQLITE_OMIT_INCRBLOB
 1.13895 +  #undef MEM_Zero
 1.13896 +  #define MEM_Zero 0x0000
 1.13897 +#endif
 1.13898 +
 1.13899 +/*
 1.13900 +** Clear any existing type flags from a Mem and replace them with f
 1.13901 +*/
 1.13902 +#define MemSetTypeFlag(p, f) \
 1.13903 +   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
 1.13904 +
 1.13905 +/*
 1.13906 +** Return true if a memory cell is not marked as invalid.  This macro
 1.13907 +** is for use inside assert() statements only.
 1.13908 +*/
 1.13909 +#ifdef SQLITE_DEBUG
 1.13910 +#define memIsValid(M)  ((M)->flags & MEM_Undefined)==0
 1.13911 +#endif
 1.13912 +
 1.13913 +/*
 1.13914 +** Each auxilliary data pointer stored by a user defined function 
 1.13915 +** implementation calling sqlite3_set_auxdata() is stored in an instance
 1.13916 +** of this structure. All such structures associated with a single VM
 1.13917 +** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
 1.13918 +** when the VM is halted (if not before).
 1.13919 +*/
 1.13920 +struct AuxData {
 1.13921 +  int iOp;                        /* Instruction number of OP_Function opcode */
 1.13922 +  int iArg;                       /* Index of function argument. */
 1.13923 +  void *pAux;                     /* Aux data pointer */
 1.13924 +  void (*xDelete)(void *);        /* Destructor for the aux data */
 1.13925 +  AuxData *pNext;                 /* Next element in list */
 1.13926 +};
 1.13927 +
 1.13928 +/*
 1.13929 +** The "context" argument for a installable function.  A pointer to an
 1.13930 +** instance of this structure is the first argument to the routines used
 1.13931 +** implement the SQL functions.
 1.13932 +**
 1.13933 +** There is a typedef for this structure in sqlite.h.  So all routines,
 1.13934 +** even the public interface to SQLite, can use a pointer to this structure.
 1.13935 +** But this file is the only place where the internal details of this
 1.13936 +** structure are known.
 1.13937 +**
 1.13938 +** This structure is defined inside of vdbeInt.h because it uses substructures
 1.13939 +** (Mem) which are only defined there.
 1.13940 +*/
 1.13941 +struct sqlite3_context {
 1.13942 +  FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
 1.13943 +  Mem s;                /* The return value is stored here */
 1.13944 +  Mem *pMem;            /* Memory cell used to store aggregate context */
 1.13945 +  CollSeq *pColl;       /* Collating sequence */
 1.13946 +  Vdbe *pVdbe;          /* The VM that owns this context */
 1.13947 +  int iOp;              /* Instruction number of OP_Function */
 1.13948 +  int isError;          /* Error code returned by the function. */
 1.13949 +  u8 skipFlag;          /* Skip skip accumulator loading if true */
 1.13950 +  u8 fErrorOrAux;       /* isError!=0 or pVdbe->pAuxData modified */
 1.13951 +};
 1.13952 +
 1.13953 +/*
 1.13954 +** An Explain object accumulates indented output which is helpful
 1.13955 +** in describing recursive data structures.
 1.13956 +*/
 1.13957 +struct Explain {
 1.13958 +  Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
 1.13959 +  StrAccum str;      /* The string being accumulated */
 1.13960 +  int nIndent;       /* Number of elements in aIndent */
 1.13961 +  u16 aIndent[100];  /* Levels of indentation */
 1.13962 +  char zBase[100];   /* Initial space */
 1.13963 +};
 1.13964 +
 1.13965 +/* A bitfield type for use inside of structures.  Always follow with :N where
 1.13966 +** N is the number of bits.
 1.13967 +*/
 1.13968 +typedef unsigned bft;  /* Bit Field Type */
 1.13969 +
 1.13970 +/*
 1.13971 +** An instance of the virtual machine.  This structure contains the complete
 1.13972 +** state of the virtual machine.
 1.13973 +**
 1.13974 +** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
 1.13975 +** is really a pointer to an instance of this structure.
 1.13976 +**
 1.13977 +** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
 1.13978 +** any virtual table method invocations made by the vdbe program. It is
 1.13979 +** set to 2 for xDestroy method calls and 1 for all other methods. This
 1.13980 +** variable is used for two purposes: to allow xDestroy methods to execute
 1.13981 +** "DROP TABLE" statements and to prevent some nasty side effects of
 1.13982 +** malloc failure when SQLite is invoked recursively by a virtual table 
 1.13983 +** method function.
 1.13984 +*/
 1.13985 +struct Vdbe {
 1.13986 +  sqlite3 *db;            /* The database connection that owns this statement */
 1.13987 +  Op *aOp;                /* Space to hold the virtual machine's program */
 1.13988 +  Mem *aMem;              /* The memory locations */
 1.13989 +  Mem **apArg;            /* Arguments to currently executing user function */
 1.13990 +  Mem *aColName;          /* Column names to return */
 1.13991 +  Mem *pResultSet;        /* Pointer to an array of results */
 1.13992 +  Parse *pParse;          /* Parsing context used to create this Vdbe */
 1.13993 +  int nMem;               /* Number of memory locations currently allocated */
 1.13994 +  int nOp;                /* Number of instructions in the program */
 1.13995 +  int nCursor;            /* Number of slots in apCsr[] */
 1.13996 +  u32 magic;              /* Magic number for sanity checking */
 1.13997 +  char *zErrMsg;          /* Error message written here */
 1.13998 +  Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
 1.13999 +  VdbeCursor **apCsr;     /* One element of this array for each open cursor */
 1.14000 +  Mem *aVar;              /* Values for the OP_Variable opcode. */
 1.14001 +  char **azVar;           /* Name of variables */
 1.14002 +  ynVar nVar;             /* Number of entries in aVar[] */
 1.14003 +  ynVar nzVar;            /* Number of entries in azVar[] */
 1.14004 +  u32 cacheCtr;           /* VdbeCursor row cache generation counter */
 1.14005 +  int pc;                 /* The program counter */
 1.14006 +  int rc;                 /* Value to return */
 1.14007 +  u16 nResColumn;         /* Number of columns in one row of the result set */
 1.14008 +  u8 errorAction;         /* Recovery action to do in case of an error */
 1.14009 +  u8 minWriteFileFormat;  /* Minimum file format for writable database files */
 1.14010 +  bft explain:2;          /* True if EXPLAIN present on SQL command */
 1.14011 +  bft inVtabMethod:2;     /* See comments above */
 1.14012 +  bft changeCntOn:1;      /* True to update the change-counter */
 1.14013 +  bft expired:1;          /* True if the VM needs to be recompiled */
 1.14014 +  bft runOnlyOnce:1;      /* Automatically expire on reset */
 1.14015 +  bft usesStmtJournal:1;  /* True if uses a statement journal */
 1.14016 +  bft readOnly:1;         /* True for statements that do not write */
 1.14017 +  bft bIsReader:1;        /* True for statements that read */
 1.14018 +  bft isPrepareV2:1;      /* True if prepared with prepare_v2() */
 1.14019 +  bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
 1.14020 +  int nChange;            /* Number of db changes made since last reset */
 1.14021 +  yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
 1.14022 +  yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
 1.14023 +  int iStatement;         /* Statement number (or 0 if has not opened stmt) */
 1.14024 +  u32 aCounter[5];        /* Counters used by sqlite3_stmt_status() */
 1.14025 +#ifndef SQLITE_OMIT_TRACE
 1.14026 +  i64 startTime;          /* Time when query started - used for profiling */
 1.14027 +#endif
 1.14028 +  i64 iCurrentTime;       /* Value of julianday('now') for this statement */
 1.14029 +  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
 1.14030 +  i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
 1.14031 +  i64 nStmtDefImmCons;    /* Number of def. imm constraints when stmt started */
 1.14032 +  char *zSql;             /* Text of the SQL statement that generated this */
 1.14033 +  void *pFree;            /* Free this when deleting the vdbe */
 1.14034 +#ifdef SQLITE_ENABLE_TREE_EXPLAIN
 1.14035 +  Explain *pExplain;      /* The explainer */
 1.14036 +  char *zExplain;         /* Explanation of data structures */
 1.14037 +#endif
 1.14038 +  VdbeFrame *pFrame;      /* Parent frame */
 1.14039 +  VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
 1.14040 +  int nFrame;             /* Number of frames in pFrame list */
 1.14041 +  u32 expmask;            /* Binding to these vars invalidates VM */
 1.14042 +  SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
 1.14043 +  int nOnceFlag;          /* Size of array aOnceFlag[] */
 1.14044 +  u8 *aOnceFlag;          /* Flags for OP_Once */
 1.14045 +  AuxData *pAuxData;      /* Linked list of auxdata allocations */
 1.14046 +};
 1.14047 +
 1.14048 +/*
 1.14049 +** The following are allowed values for Vdbe.magic
 1.14050 +*/
 1.14051 +#define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
 1.14052 +#define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
 1.14053 +#define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
 1.14054 +#define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
 1.14055 +
 1.14056 +/*
 1.14057 +** Function prototypes
 1.14058 +*/
 1.14059 +SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
 1.14060 +void sqliteVdbePopStack(Vdbe*,int);
 1.14061 +SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
 1.14062 +#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
 1.14063 +SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
 1.14064 +#endif
 1.14065 +SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
 1.14066 +SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
 1.14067 +SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
 1.14068 +SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
 1.14069 +SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
 1.14070 +
 1.14071 +int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
 1.14072 +SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,const UnpackedRecord*,int*);
 1.14073 +SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
 1.14074 +SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
 1.14075 +SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
 1.14076 +SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
 1.14077 +SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
 1.14078 +SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
 1.14079 +SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
 1.14080 +SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
 1.14081 +SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
 1.14082 +SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
 1.14083 +SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
 1.14084 +SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
 1.14085 +SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
 1.14086 +#ifdef SQLITE_OMIT_FLOATING_POINT
 1.14087 +# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
 1.14088 +#else
 1.14089 +SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
 1.14090 +#endif
 1.14091 +SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
 1.14092 +SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
 1.14093 +SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
 1.14094 +SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
 1.14095 +SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
 1.14096 +SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
 1.14097 +SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
 1.14098 +SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
 1.14099 +SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
 1.14100 +SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
 1.14101 +SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
 1.14102 +SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
 1.14103 +SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
 1.14104 +SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
 1.14105 +#define VdbeMemDynamic(X)  \
 1.14106 +  (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
 1.14107 +#define VdbeMemRelease(X)  \
 1.14108 +  if( VdbeMemDynamic(X) ) sqlite3VdbeMemReleaseExternal(X);
 1.14109 +SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
 1.14110 +SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
 1.14111 +SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
 1.14112 +SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
 1.14113 +SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
 1.14114 +SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
 1.14115 +SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
 1.14116 +
 1.14117 +SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
 1.14118 +SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
 1.14119 +SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
 1.14120 +SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
 1.14121 +SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *);
 1.14122 +SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *);
 1.14123 +SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
 1.14124 +
 1.14125 +#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
 1.14126 +SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
 1.14127 +SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
 1.14128 +#else
 1.14129 +# define sqlite3VdbeEnter(X)
 1.14130 +# define sqlite3VdbeLeave(X)
 1.14131 +#endif
 1.14132 +
 1.14133 +#ifdef SQLITE_DEBUG
 1.14134 +SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
 1.14135 +SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
 1.14136 +#endif
 1.14137 +
 1.14138 +#ifndef SQLITE_OMIT_FOREIGN_KEY
 1.14139 +SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
 1.14140 +#else
 1.14141 +# define sqlite3VdbeCheckFk(p,i) 0
 1.14142 +#endif
 1.14143 +
 1.14144 +SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
 1.14145 +#ifdef SQLITE_DEBUG
 1.14146 +SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
 1.14147 +SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
 1.14148 +#endif
 1.14149 +SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
 1.14150 +
 1.14151 +#ifndef SQLITE_OMIT_INCRBLOB
 1.14152 +SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
 1.14153 +  #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
 1.14154 +#else
 1.14155 +  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
 1.14156 +  #define ExpandBlob(P) SQLITE_OK
 1.14157 +#endif
 1.14158 +
 1.14159 +#endif /* !defined(_VDBEINT_H_) */
 1.14160 +
 1.14161 +/************** End of vdbeInt.h *********************************************/
 1.14162 +/************** Continuing where we left off in status.c *********************/
 1.14163 +
 1.14164 +/*
 1.14165 +** Variables in which to record status information.
 1.14166 +*/
 1.14167 +typedef struct sqlite3StatType sqlite3StatType;
 1.14168 +static SQLITE_WSD struct sqlite3StatType {
 1.14169 +  int nowValue[10];         /* Current value */
 1.14170 +  int mxValue[10];          /* Maximum value */
 1.14171 +} sqlite3Stat = { {0,}, {0,} };
 1.14172 +
 1.14173 +
 1.14174 +/* The "wsdStat" macro will resolve to the status information
 1.14175 +** state vector.  If writable static data is unsupported on the target,
 1.14176 +** we have to locate the state vector at run-time.  In the more common
 1.14177 +** case where writable static data is supported, wsdStat can refer directly
 1.14178 +** to the "sqlite3Stat" state vector declared above.
 1.14179 +*/
 1.14180 +#ifdef SQLITE_OMIT_WSD
 1.14181 +# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
 1.14182 +# define wsdStat x[0]
 1.14183 +#else
 1.14184 +# define wsdStatInit
 1.14185 +# define wsdStat sqlite3Stat
 1.14186 +#endif
 1.14187 +
 1.14188 +/*
 1.14189 +** Return the current value of a status parameter.
 1.14190 +*/
 1.14191 +SQLITE_PRIVATE int sqlite3StatusValue(int op){
 1.14192 +  wsdStatInit;
 1.14193 +  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
 1.14194 +  return wsdStat.nowValue[op];
 1.14195 +}
 1.14196 +
 1.14197 +/*
 1.14198 +** Add N to the value of a status record.  It is assumed that the
 1.14199 +** caller holds appropriate locks.
 1.14200 +*/
 1.14201 +SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
 1.14202 +  wsdStatInit;
 1.14203 +  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
 1.14204 +  wsdStat.nowValue[op] += N;
 1.14205 +  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
 1.14206 +    wsdStat.mxValue[op] = wsdStat.nowValue[op];
 1.14207 +  }
 1.14208 +}
 1.14209 +
 1.14210 +/*
 1.14211 +** Set the value of a status to X.
 1.14212 +*/
 1.14213 +SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
 1.14214 +  wsdStatInit;
 1.14215 +  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
 1.14216 +  wsdStat.nowValue[op] = X;
 1.14217 +  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
 1.14218 +    wsdStat.mxValue[op] = wsdStat.nowValue[op];
 1.14219 +  }
 1.14220 +}
 1.14221 +
 1.14222 +/*
 1.14223 +** Query status information.
 1.14224 +**
 1.14225 +** This implementation assumes that reading or writing an aligned
 1.14226 +** 32-bit integer is an atomic operation.  If that assumption is not true,
 1.14227 +** then this routine is not threadsafe.
 1.14228 +*/
 1.14229 +SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
 1.14230 +  wsdStatInit;
 1.14231 +  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
 1.14232 +    return SQLITE_MISUSE_BKPT;
 1.14233 +  }
 1.14234 +  *pCurrent = wsdStat.nowValue[op];
 1.14235 +  *pHighwater = wsdStat.mxValue[op];
 1.14236 +  if( resetFlag ){
 1.14237 +    wsdStat.mxValue[op] = wsdStat.nowValue[op];
 1.14238 +  }
 1.14239 +  return SQLITE_OK;
 1.14240 +}
 1.14241 +
 1.14242 +/*
 1.14243 +** Query status information for a single database connection
 1.14244 +*/
 1.14245 +SQLITE_API int sqlite3_db_status(
 1.14246 +  sqlite3 *db,          /* The database connection whose status is desired */
 1.14247 +  int op,               /* Status verb */
 1.14248 +  int *pCurrent,        /* Write current value here */
 1.14249 +  int *pHighwater,      /* Write high-water mark here */
 1.14250 +  int resetFlag         /* Reset high-water mark if true */
 1.14251 +){
 1.14252 +  int rc = SQLITE_OK;   /* Return code */
 1.14253 +  sqlite3_mutex_enter(db->mutex);
 1.14254 +  switch( op ){
 1.14255 +    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
 1.14256 +      *pCurrent = db->lookaside.nOut;
 1.14257 +      *pHighwater = db->lookaside.mxOut;
 1.14258 +      if( resetFlag ){
 1.14259 +        db->lookaside.mxOut = db->lookaside.nOut;
 1.14260 +      }
 1.14261 +      break;
 1.14262 +    }
 1.14263 +
 1.14264 +    case SQLITE_DBSTATUS_LOOKASIDE_HIT:
 1.14265 +    case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
 1.14266 +    case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
 1.14267 +      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
 1.14268 +      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
 1.14269 +      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
 1.14270 +      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
 1.14271 +      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
 1.14272 +      *pCurrent = 0;
 1.14273 +      *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
 1.14274 +      if( resetFlag ){
 1.14275 +        db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
 1.14276 +      }
 1.14277 +      break;
 1.14278 +    }
 1.14279 +
 1.14280 +    /* 
 1.14281 +    ** Return an approximation for the amount of memory currently used
 1.14282 +    ** by all pagers associated with the given database connection.  The
 1.14283 +    ** highwater mark is meaningless and is returned as zero.
 1.14284 +    */
 1.14285 +    case SQLITE_DBSTATUS_CACHE_USED: {
 1.14286 +      int totalUsed = 0;
 1.14287 +      int i;
 1.14288 +      sqlite3BtreeEnterAll(db);
 1.14289 +      for(i=0; i<db->nDb; i++){
 1.14290 +        Btree *pBt = db->aDb[i].pBt;
 1.14291 +        if( pBt ){
 1.14292 +          Pager *pPager = sqlite3BtreePager(pBt);
 1.14293 +          totalUsed += sqlite3PagerMemUsed(pPager);
 1.14294 +        }
 1.14295 +      }
 1.14296 +      sqlite3BtreeLeaveAll(db);
 1.14297 +      *pCurrent = totalUsed;
 1.14298 +      *pHighwater = 0;
 1.14299 +      break;
 1.14300 +    }
 1.14301 +
 1.14302 +    /*
 1.14303 +    ** *pCurrent gets an accurate estimate of the amount of memory used
 1.14304 +    ** to store the schema for all databases (main, temp, and any ATTACHed
 1.14305 +    ** databases.  *pHighwater is set to zero.
 1.14306 +    */
 1.14307 +    case SQLITE_DBSTATUS_SCHEMA_USED: {
 1.14308 +      int i;                      /* Used to iterate through schemas */
 1.14309 +      int nByte = 0;              /* Used to accumulate return value */
 1.14310 +
 1.14311 +      sqlite3BtreeEnterAll(db);
 1.14312 +      db->pnBytesFreed = &nByte;
 1.14313 +      for(i=0; i<db->nDb; i++){
 1.14314 +        Schema *pSchema = db->aDb[i].pSchema;
 1.14315 +        if( ALWAYS(pSchema!=0) ){
 1.14316 +          HashElem *p;
 1.14317 +
 1.14318 +          nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
 1.14319 +              pSchema->tblHash.count 
 1.14320 +            + pSchema->trigHash.count
 1.14321 +            + pSchema->idxHash.count
 1.14322 +            + pSchema->fkeyHash.count
 1.14323 +          );
 1.14324 +          nByte += sqlite3MallocSize(pSchema->tblHash.ht);
 1.14325 +          nByte += sqlite3MallocSize(pSchema->trigHash.ht);
 1.14326 +          nByte += sqlite3MallocSize(pSchema->idxHash.ht);
 1.14327 +          nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
 1.14328 +
 1.14329 +          for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
 1.14330 +            sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
 1.14331 +          }
 1.14332 +          for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
 1.14333 +            sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
 1.14334 +          }
 1.14335 +        }
 1.14336 +      }
 1.14337 +      db->pnBytesFreed = 0;
 1.14338 +      sqlite3BtreeLeaveAll(db);
 1.14339 +
 1.14340 +      *pHighwater = 0;
 1.14341 +      *pCurrent = nByte;
 1.14342 +      break;
 1.14343 +    }
 1.14344 +
 1.14345 +    /*
 1.14346 +    ** *pCurrent gets an accurate estimate of the amount of memory used
 1.14347 +    ** to store all prepared statements.
 1.14348 +    ** *pHighwater is set to zero.
 1.14349 +    */
 1.14350 +    case SQLITE_DBSTATUS_STMT_USED: {
 1.14351 +      struct Vdbe *pVdbe;         /* Used to iterate through VMs */
 1.14352 +      int nByte = 0;              /* Used to accumulate return value */
 1.14353 +
 1.14354 +      db->pnBytesFreed = &nByte;
 1.14355 +      for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
 1.14356 +        sqlite3VdbeClearObject(db, pVdbe);
 1.14357 +        sqlite3DbFree(db, pVdbe);
 1.14358 +      }
 1.14359 +      db->pnBytesFreed = 0;
 1.14360 +
 1.14361 +      *pHighwater = 0;
 1.14362 +      *pCurrent = nByte;
 1.14363 +
 1.14364 +      break;
 1.14365 +    }
 1.14366 +
 1.14367 +    /*
 1.14368 +    ** Set *pCurrent to the total cache hits or misses encountered by all
 1.14369 +    ** pagers the database handle is connected to. *pHighwater is always set 
 1.14370 +    ** to zero.
 1.14371 +    */
 1.14372 +    case SQLITE_DBSTATUS_CACHE_HIT:
 1.14373 +    case SQLITE_DBSTATUS_CACHE_MISS:
 1.14374 +    case SQLITE_DBSTATUS_CACHE_WRITE:{
 1.14375 +      int i;
 1.14376 +      int nRet = 0;
 1.14377 +      assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
 1.14378 +      assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
 1.14379 +
 1.14380 +      for(i=0; i<db->nDb; i++){
 1.14381 +        if( db->aDb[i].pBt ){
 1.14382 +          Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
 1.14383 +          sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
 1.14384 +        }
 1.14385 +      }
 1.14386 +      *pHighwater = 0;
 1.14387 +      *pCurrent = nRet;
 1.14388 +      break;
 1.14389 +    }
 1.14390 +
 1.14391 +    /* Set *pCurrent to non-zero if there are unresolved deferred foreign
 1.14392 +    ** key constraints.  Set *pCurrent to zero if all foreign key constraints
 1.14393 +    ** have been satisfied.  The *pHighwater is always set to zero.
 1.14394 +    */
 1.14395 +    case SQLITE_DBSTATUS_DEFERRED_FKS: {
 1.14396 +      *pHighwater = 0;
 1.14397 +      *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
 1.14398 +      break;
 1.14399 +    }
 1.14400 +
 1.14401 +    default: {
 1.14402 +      rc = SQLITE_ERROR;
 1.14403 +    }
 1.14404 +  }
 1.14405 +  sqlite3_mutex_leave(db->mutex);
 1.14406 +  return rc;
 1.14407 +}
 1.14408 +
 1.14409 +/************** End of status.c **********************************************/
 1.14410 +/************** Begin file date.c ********************************************/
 1.14411 +/*
 1.14412 +** 2003 October 31
 1.14413 +**
 1.14414 +** The author disclaims copyright to this source code.  In place of
 1.14415 +** a legal notice, here is a blessing:
 1.14416 +**
 1.14417 +**    May you do good and not evil.
 1.14418 +**    May you find forgiveness for yourself and forgive others.
 1.14419 +**    May you share freely, never taking more than you give.
 1.14420 +**
 1.14421 +*************************************************************************
 1.14422 +** This file contains the C functions that implement date and time
 1.14423 +** functions for SQLite.  
 1.14424 +**
 1.14425 +** There is only one exported symbol in this file - the function
 1.14426 +** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
 1.14427 +** All other code has file scope.
 1.14428 +**
 1.14429 +** SQLite processes all times and dates as Julian Day numbers.  The
 1.14430 +** dates and times are stored as the number of days since noon
 1.14431 +** in Greenwich on November 24, 4714 B.C. according to the Gregorian
 1.14432 +** calendar system. 
 1.14433 +**
 1.14434 +** 1970-01-01 00:00:00 is JD 2440587.5
 1.14435 +** 2000-01-01 00:00:00 is JD 2451544.5
 1.14436 +**
 1.14437 +** This implemention requires years to be expressed as a 4-digit number
 1.14438 +** which means that only dates between 0000-01-01 and 9999-12-31 can
 1.14439 +** be represented, even though julian day numbers allow a much wider
 1.14440 +** range of dates.
 1.14441 +**
 1.14442 +** The Gregorian calendar system is used for all dates and times,
 1.14443 +** even those that predate the Gregorian calendar.  Historians usually
 1.14444 +** use the Julian calendar for dates prior to 1582-10-15 and for some
 1.14445 +** dates afterwards, depending on locale.  Beware of this difference.
 1.14446 +**
 1.14447 +** The conversion algorithms are implemented based on descriptions
 1.14448 +** in the following text:
 1.14449 +**
 1.14450 +**      Jean Meeus
 1.14451 +**      Astronomical Algorithms, 2nd Edition, 1998
 1.14452 +**      ISBM 0-943396-61-1
 1.14453 +**      Willmann-Bell, Inc
 1.14454 +**      Richmond, Virginia (USA)
 1.14455 +*/
 1.14456 +/* #include <stdlib.h> */
 1.14457 +/* #include <assert.h> */
 1.14458 +#include <time.h>
 1.14459 +
 1.14460 +#ifndef SQLITE_OMIT_DATETIME_FUNCS
 1.14461 +
 1.14462 +
 1.14463 +/*
 1.14464 +** A structure for holding a single date and time.
 1.14465 +*/
 1.14466 +typedef struct DateTime DateTime;
 1.14467 +struct DateTime {
 1.14468 +  sqlite3_int64 iJD; /* The julian day number times 86400000 */
 1.14469 +  int Y, M, D;       /* Year, month, and day */
 1.14470 +  int h, m;          /* Hour and minutes */
 1.14471 +  int tz;            /* Timezone offset in minutes */
 1.14472 +  double s;          /* Seconds */
 1.14473 +  char validYMD;     /* True (1) if Y,M,D are valid */
 1.14474 +  char validHMS;     /* True (1) if h,m,s are valid */
 1.14475 +  char validJD;      /* True (1) if iJD is valid */
 1.14476 +  char validTZ;      /* True (1) if tz is valid */
 1.14477 +};
 1.14478 +
 1.14479 +
 1.14480 +/*
 1.14481 +** Convert zDate into one or more integers.  Additional arguments
 1.14482 +** come in groups of 5 as follows:
 1.14483 +**
 1.14484 +**       N       number of digits in the integer
 1.14485 +**       min     minimum allowed value of the integer
 1.14486 +**       max     maximum allowed value of the integer
 1.14487 +**       nextC   first character after the integer
 1.14488 +**       pVal    where to write the integers value.
 1.14489 +**
 1.14490 +** Conversions continue until one with nextC==0 is encountered.
 1.14491 +** The function returns the number of successful conversions.
 1.14492 +*/
 1.14493 +static int getDigits(const char *zDate, ...){
 1.14494 +  va_list ap;
 1.14495 +  int val;
 1.14496 +  int N;
 1.14497 +  int min;
 1.14498 +  int max;
 1.14499 +  int nextC;
 1.14500 +  int *pVal;
 1.14501 +  int cnt = 0;
 1.14502 +  va_start(ap, zDate);
 1.14503 +  do{
 1.14504 +    N = va_arg(ap, int);
 1.14505 +    min = va_arg(ap, int);
 1.14506 +    max = va_arg(ap, int);
 1.14507 +    nextC = va_arg(ap, int);
 1.14508 +    pVal = va_arg(ap, int*);
 1.14509 +    val = 0;
 1.14510 +    while( N-- ){
 1.14511 +      if( !sqlite3Isdigit(*zDate) ){
 1.14512 +        goto end_getDigits;
 1.14513 +      }
 1.14514 +      val = val*10 + *zDate - '0';
 1.14515 +      zDate++;
 1.14516 +    }
 1.14517 +    if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
 1.14518 +      goto end_getDigits;
 1.14519 +    }
 1.14520 +    *pVal = val;
 1.14521 +    zDate++;
 1.14522 +    cnt++;
 1.14523 +  }while( nextC );
 1.14524 +end_getDigits:
 1.14525 +  va_end(ap);
 1.14526 +  return cnt;
 1.14527 +}
 1.14528 +
 1.14529 +/*
 1.14530 +** Parse a timezone extension on the end of a date-time.
 1.14531 +** The extension is of the form:
 1.14532 +**
 1.14533 +**        (+/-)HH:MM
 1.14534 +**
 1.14535 +** Or the "zulu" notation:
 1.14536 +**
 1.14537 +**        Z
 1.14538 +**
 1.14539 +** If the parse is successful, write the number of minutes
 1.14540 +** of change in p->tz and return 0.  If a parser error occurs,
 1.14541 +** return non-zero.
 1.14542 +**
 1.14543 +** A missing specifier is not considered an error.
 1.14544 +*/
 1.14545 +static int parseTimezone(const char *zDate, DateTime *p){
 1.14546 +  int sgn = 0;
 1.14547 +  int nHr, nMn;
 1.14548 +  int c;
 1.14549 +  while( sqlite3Isspace(*zDate) ){ zDate++; }
 1.14550 +  p->tz = 0;
 1.14551 +  c = *zDate;
 1.14552 +  if( c=='-' ){
 1.14553 +    sgn = -1;
 1.14554 +  }else if( c=='+' ){
 1.14555 +    sgn = +1;
 1.14556 +  }else if( c=='Z' || c=='z' ){
 1.14557 +    zDate++;
 1.14558 +    goto zulu_time;
 1.14559 +  }else{
 1.14560 +    return c!=0;
 1.14561 +  }
 1.14562 +  zDate++;
 1.14563 +  if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
 1.14564 +    return 1;
 1.14565 +  }
 1.14566 +  zDate += 5;
 1.14567 +  p->tz = sgn*(nMn + nHr*60);
 1.14568 +zulu_time:
 1.14569 +  while( sqlite3Isspace(*zDate) ){ zDate++; }
 1.14570 +  return *zDate!=0;
 1.14571 +}
 1.14572 +
 1.14573 +/*
 1.14574 +** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
 1.14575 +** The HH, MM, and SS must each be exactly 2 digits.  The
 1.14576 +** fractional seconds FFFF can be one or more digits.
 1.14577 +**
 1.14578 +** Return 1 if there is a parsing error and 0 on success.
 1.14579 +*/
 1.14580 +static int parseHhMmSs(const char *zDate, DateTime *p){
 1.14581 +  int h, m, s;
 1.14582 +  double ms = 0.0;
 1.14583 +  if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
 1.14584 +    return 1;
 1.14585 +  }
 1.14586 +  zDate += 5;
 1.14587 +  if( *zDate==':' ){
 1.14588 +    zDate++;
 1.14589 +    if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
 1.14590 +      return 1;
 1.14591 +    }
 1.14592 +    zDate += 2;
 1.14593 +    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
 1.14594 +      double rScale = 1.0;
 1.14595 +      zDate++;
 1.14596 +      while( sqlite3Isdigit(*zDate) ){
 1.14597 +        ms = ms*10.0 + *zDate - '0';
 1.14598 +        rScale *= 10.0;
 1.14599 +        zDate++;
 1.14600 +      }
 1.14601 +      ms /= rScale;
 1.14602 +    }
 1.14603 +  }else{
 1.14604 +    s = 0;
 1.14605 +  }
 1.14606 +  p->validJD = 0;
 1.14607 +  p->validHMS = 1;
 1.14608 +  p->h = h;
 1.14609 +  p->m = m;
 1.14610 +  p->s = s + ms;
 1.14611 +  if( parseTimezone(zDate, p) ) return 1;
 1.14612 +  p->validTZ = (p->tz!=0)?1:0;
 1.14613 +  return 0;
 1.14614 +}
 1.14615 +
 1.14616 +/*
 1.14617 +** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
 1.14618 +** that the YYYY-MM-DD is according to the Gregorian calendar.
 1.14619 +**
 1.14620 +** Reference:  Meeus page 61
 1.14621 +*/
 1.14622 +static void computeJD(DateTime *p){
 1.14623 +  int Y, M, D, A, B, X1, X2;
 1.14624 +
 1.14625 +  if( p->validJD ) return;
 1.14626 +  if( p->validYMD ){
 1.14627 +    Y = p->Y;
 1.14628 +    M = p->M;
 1.14629 +    D = p->D;
 1.14630 +  }else{
 1.14631 +    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
 1.14632 +    M = 1;
 1.14633 +    D = 1;
 1.14634 +  }
 1.14635 +  if( M<=2 ){
 1.14636 +    Y--;
 1.14637 +    M += 12;
 1.14638 +  }
 1.14639 +  A = Y/100;
 1.14640 +  B = 2 - A + (A/4);
 1.14641 +  X1 = 36525*(Y+4716)/100;
 1.14642 +  X2 = 306001*(M+1)/10000;
 1.14643 +  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
 1.14644 +  p->validJD = 1;
 1.14645 +  if( p->validHMS ){
 1.14646 +    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
 1.14647 +    if( p->validTZ ){
 1.14648 +      p->iJD -= p->tz*60000;
 1.14649 +      p->validYMD = 0;
 1.14650 +      p->validHMS = 0;
 1.14651 +      p->validTZ = 0;
 1.14652 +    }
 1.14653 +  }
 1.14654 +}
 1.14655 +
 1.14656 +/*
 1.14657 +** Parse dates of the form
 1.14658 +**
 1.14659 +**     YYYY-MM-DD HH:MM:SS.FFF
 1.14660 +**     YYYY-MM-DD HH:MM:SS
 1.14661 +**     YYYY-MM-DD HH:MM
 1.14662 +**     YYYY-MM-DD
 1.14663 +**
 1.14664 +** Write the result into the DateTime structure and return 0
 1.14665 +** on success and 1 if the input string is not a well-formed
 1.14666 +** date.
 1.14667 +*/
 1.14668 +static int parseYyyyMmDd(const char *zDate, DateTime *p){
 1.14669 +  int Y, M, D, neg;
 1.14670 +
 1.14671 +  if( zDate[0]=='-' ){
 1.14672 +    zDate++;
 1.14673 +    neg = 1;
 1.14674 +  }else{
 1.14675 +    neg = 0;
 1.14676 +  }
 1.14677 +  if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
 1.14678 +    return 1;
 1.14679 +  }
 1.14680 +  zDate += 10;
 1.14681 +  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
 1.14682 +  if( parseHhMmSs(zDate, p)==0 ){
 1.14683 +    /* We got the time */
 1.14684 +  }else if( *zDate==0 ){
 1.14685 +    p->validHMS = 0;
 1.14686 +  }else{
 1.14687 +    return 1;
 1.14688 +  }
 1.14689 +  p->validJD = 0;
 1.14690 +  p->validYMD = 1;
 1.14691 +  p->Y = neg ? -Y : Y;
 1.14692 +  p->M = M;
 1.14693 +  p->D = D;
 1.14694 +  if( p->validTZ ){
 1.14695 +    computeJD(p);
 1.14696 +  }
 1.14697 +  return 0;
 1.14698 +}
 1.14699 +
 1.14700 +/*
 1.14701 +** Set the time to the current time reported by the VFS.
 1.14702 +**
 1.14703 +** Return the number of errors.
 1.14704 +*/
 1.14705 +static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
 1.14706 +  p->iJD = sqlite3StmtCurrentTime(context);
 1.14707 +  if( p->iJD>0 ){
 1.14708 +    p->validJD = 1;
 1.14709 +    return 0;
 1.14710 +  }else{
 1.14711 +    return 1;
 1.14712 +  }
 1.14713 +}
 1.14714 +
 1.14715 +/*
 1.14716 +** Attempt to parse the given string into a Julian Day Number.  Return
 1.14717 +** the number of errors.
 1.14718 +**
 1.14719 +** The following are acceptable forms for the input string:
 1.14720 +**
 1.14721 +**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
 1.14722 +**      DDDD.DD 
 1.14723 +**      now
 1.14724 +**
 1.14725 +** In the first form, the +/-HH:MM is always optional.  The fractional
 1.14726 +** seconds extension (the ".FFF") is optional.  The seconds portion
 1.14727 +** (":SS.FFF") is option.  The year and date can be omitted as long
 1.14728 +** as there is a time string.  The time string can be omitted as long
 1.14729 +** as there is a year and date.
 1.14730 +*/
 1.14731 +static int parseDateOrTime(
 1.14732 +  sqlite3_context *context, 
 1.14733 +  const char *zDate, 
 1.14734 +  DateTime *p
 1.14735 +){
 1.14736 +  double r;
 1.14737 +  if( parseYyyyMmDd(zDate,p)==0 ){
 1.14738 +    return 0;
 1.14739 +  }else if( parseHhMmSs(zDate, p)==0 ){
 1.14740 +    return 0;
 1.14741 +  }else if( sqlite3StrICmp(zDate,"now")==0){
 1.14742 +    return setDateTimeToCurrent(context, p);
 1.14743 +  }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
 1.14744 +    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
 1.14745 +    p->validJD = 1;
 1.14746 +    return 0;
 1.14747 +  }
 1.14748 +  return 1;
 1.14749 +}
 1.14750 +
 1.14751 +/*
 1.14752 +** Compute the Year, Month, and Day from the julian day number.
 1.14753 +*/
 1.14754 +static void computeYMD(DateTime *p){
 1.14755 +  int Z, A, B, C, D, E, X1;
 1.14756 +  if( p->validYMD ) return;
 1.14757 +  if( !p->validJD ){
 1.14758 +    p->Y = 2000;
 1.14759 +    p->M = 1;
 1.14760 +    p->D = 1;
 1.14761 +  }else{
 1.14762 +    Z = (int)((p->iJD + 43200000)/86400000);
 1.14763 +    A = (int)((Z - 1867216.25)/36524.25);
 1.14764 +    A = Z + 1 + A - (A/4);
 1.14765 +    B = A + 1524;
 1.14766 +    C = (int)((B - 122.1)/365.25);
 1.14767 +    D = (36525*C)/100;
 1.14768 +    E = (int)((B-D)/30.6001);
 1.14769 +    X1 = (int)(30.6001*E);
 1.14770 +    p->D = B - D - X1;
 1.14771 +    p->M = E<14 ? E-1 : E-13;
 1.14772 +    p->Y = p->M>2 ? C - 4716 : C - 4715;
 1.14773 +  }
 1.14774 +  p->validYMD = 1;
 1.14775 +}
 1.14776 +
 1.14777 +/*
 1.14778 +** Compute the Hour, Minute, and Seconds from the julian day number.
 1.14779 +*/
 1.14780 +static void computeHMS(DateTime *p){
 1.14781 +  int s;
 1.14782 +  if( p->validHMS ) return;
 1.14783 +  computeJD(p);
 1.14784 +  s = (int)((p->iJD + 43200000) % 86400000);
 1.14785 +  p->s = s/1000.0;
 1.14786 +  s = (int)p->s;
 1.14787 +  p->s -= s;
 1.14788 +  p->h = s/3600;
 1.14789 +  s -= p->h*3600;
 1.14790 +  p->m = s/60;
 1.14791 +  p->s += s - p->m*60;
 1.14792 +  p->validHMS = 1;
 1.14793 +}
 1.14794 +
 1.14795 +/*
 1.14796 +** Compute both YMD and HMS
 1.14797 +*/
 1.14798 +static void computeYMD_HMS(DateTime *p){
 1.14799 +  computeYMD(p);
 1.14800 +  computeHMS(p);
 1.14801 +}
 1.14802 +
 1.14803 +/*
 1.14804 +** Clear the YMD and HMS and the TZ
 1.14805 +*/
 1.14806 +static void clearYMD_HMS_TZ(DateTime *p){
 1.14807 +  p->validYMD = 0;
 1.14808 +  p->validHMS = 0;
 1.14809 +  p->validTZ = 0;
 1.14810 +}
 1.14811 +
 1.14812 +/*
 1.14813 +** On recent Windows platforms, the localtime_s() function is available
 1.14814 +** as part of the "Secure CRT". It is essentially equivalent to 
 1.14815 +** localtime_r() available under most POSIX platforms, except that the 
 1.14816 +** order of the parameters is reversed.
 1.14817 +**
 1.14818 +** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
 1.14819 +**
 1.14820 +** If the user has not indicated to use localtime_r() or localtime_s()
 1.14821 +** already, check for an MSVC build environment that provides 
 1.14822 +** localtime_s().
 1.14823 +*/
 1.14824 +#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
 1.14825 +     defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
 1.14826 +#define HAVE_LOCALTIME_S 1
 1.14827 +#endif
 1.14828 +
 1.14829 +#ifndef SQLITE_OMIT_LOCALTIME
 1.14830 +/*
 1.14831 +** The following routine implements the rough equivalent of localtime_r()
 1.14832 +** using whatever operating-system specific localtime facility that
 1.14833 +** is available.  This routine returns 0 on success and
 1.14834 +** non-zero on any kind of error.
 1.14835 +**
 1.14836 +** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
 1.14837 +** routine will always fail.
 1.14838 +**
 1.14839 +** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
 1.14840 +** library function localtime_r() is used to assist in the calculation of
 1.14841 +** local time.
 1.14842 +*/
 1.14843 +static int osLocaltime(time_t *t, struct tm *pTm){
 1.14844 +  int rc;
 1.14845 +#if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
 1.14846 +      && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
 1.14847 +  struct tm *pX;
 1.14848 +#if SQLITE_THREADSAFE>0
 1.14849 +  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
 1.14850 +#endif
 1.14851 +  sqlite3_mutex_enter(mutex);
 1.14852 +  pX = localtime(t);
 1.14853 +#ifndef SQLITE_OMIT_BUILTIN_TEST
 1.14854 +  if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
 1.14855 +#endif
 1.14856 +  if( pX ) *pTm = *pX;
 1.14857 +  sqlite3_mutex_leave(mutex);
 1.14858 +  rc = pX==0;
 1.14859 +#else
 1.14860 +#ifndef SQLITE_OMIT_BUILTIN_TEST
 1.14861 +  if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
 1.14862 +#endif
 1.14863 +#if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
 1.14864 +  rc = localtime_r(t, pTm)==0;
 1.14865 +#else
 1.14866 +  rc = localtime_s(pTm, t);
 1.14867 +#endif /* HAVE_LOCALTIME_R */
 1.14868 +#endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
 1.14869 +  return rc;
 1.14870 +}
 1.14871 +#endif /* SQLITE_OMIT_LOCALTIME */
 1.14872 +
 1.14873 +
 1.14874 +#ifndef SQLITE_OMIT_LOCALTIME
 1.14875 +/*
 1.14876 +** Compute the difference (in milliseconds) between localtime and UTC
 1.14877 +** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
 1.14878 +** return this value and set *pRc to SQLITE_OK. 
 1.14879 +**
 1.14880 +** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
 1.14881 +** is undefined in this case.
 1.14882 +*/
 1.14883 +static sqlite3_int64 localtimeOffset(
 1.14884 +  DateTime *p,                    /* Date at which to calculate offset */
 1.14885 +  sqlite3_context *pCtx,          /* Write error here if one occurs */
 1.14886 +  int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
 1.14887 +){
 1.14888 +  DateTime x, y;
 1.14889 +  time_t t;
 1.14890 +  struct tm sLocal;
 1.14891 +
 1.14892 +  /* Initialize the contents of sLocal to avoid a compiler warning. */
 1.14893 +  memset(&sLocal, 0, sizeof(sLocal));
 1.14894 +
 1.14895 +  x = *p;
 1.14896 +  computeYMD_HMS(&x);
 1.14897 +  if( x.Y<1971 || x.Y>=2038 ){
 1.14898 +    /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
 1.14899 +    ** works for years between 1970 and 2037. For dates outside this range,
 1.14900 +    ** SQLite attempts to map the year into an equivalent year within this
 1.14901 +    ** range, do the calculation, then map the year back.
 1.14902 +    */
 1.14903 +    x.Y = 2000;
 1.14904 +    x.M = 1;
 1.14905 +    x.D = 1;
 1.14906 +    x.h = 0;
 1.14907 +    x.m = 0;
 1.14908 +    x.s = 0.0;
 1.14909 +  } else {
 1.14910 +    int s = (int)(x.s + 0.5);
 1.14911 +    x.s = s;
 1.14912 +  }
 1.14913 +  x.tz = 0;
 1.14914 +  x.validJD = 0;
 1.14915 +  computeJD(&x);
 1.14916 +  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
 1.14917 +  if( osLocaltime(&t, &sLocal) ){
 1.14918 +    sqlite3_result_error(pCtx, "local time unavailable", -1);
 1.14919 +    *pRc = SQLITE_ERROR;
 1.14920 +    return 0;
 1.14921 +  }
 1.14922 +  y.Y = sLocal.tm_year + 1900;
 1.14923 +  y.M = sLocal.tm_mon + 1;
 1.14924 +  y.D = sLocal.tm_mday;
 1.14925 +  y.h = sLocal.tm_hour;
 1.14926 +  y.m = sLocal.tm_min;
 1.14927 +  y.s = sLocal.tm_sec;
 1.14928 +  y.validYMD = 1;
 1.14929 +  y.validHMS = 1;
 1.14930 +  y.validJD = 0;
 1.14931 +  y.validTZ = 0;
 1.14932 +  computeJD(&y);
 1.14933 +  *pRc = SQLITE_OK;
 1.14934 +  return y.iJD - x.iJD;
 1.14935 +}
 1.14936 +#endif /* SQLITE_OMIT_LOCALTIME */
 1.14937 +
 1.14938 +/*
 1.14939 +** Process a modifier to a date-time stamp.  The modifiers are
 1.14940 +** as follows:
 1.14941 +**
 1.14942 +**     NNN days
 1.14943 +**     NNN hours
 1.14944 +**     NNN minutes
 1.14945 +**     NNN.NNNN seconds
 1.14946 +**     NNN months
 1.14947 +**     NNN years
 1.14948 +**     start of month
 1.14949 +**     start of year
 1.14950 +**     start of week
 1.14951 +**     start of day
 1.14952 +**     weekday N
 1.14953 +**     unixepoch
 1.14954 +**     localtime
 1.14955 +**     utc
 1.14956 +**
 1.14957 +** Return 0 on success and 1 if there is any kind of error. If the error
 1.14958 +** is in a system call (i.e. localtime()), then an error message is written
 1.14959 +** to context pCtx. If the error is an unrecognized modifier, no error is
 1.14960 +** written to pCtx.
 1.14961 +*/
 1.14962 +static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
 1.14963 +  int rc = 1;
 1.14964 +  int n;
 1.14965 +  double r;
 1.14966 +  char *z, zBuf[30];
 1.14967 +  z = zBuf;
 1.14968 +  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
 1.14969 +    z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
 1.14970 +  }
 1.14971 +  z[n] = 0;
 1.14972 +  switch( z[0] ){
 1.14973 +#ifndef SQLITE_OMIT_LOCALTIME
 1.14974 +    case 'l': {
 1.14975 +      /*    localtime
 1.14976 +      **
 1.14977 +      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
 1.14978 +      ** show local time.
 1.14979 +      */
 1.14980 +      if( strcmp(z, "localtime")==0 ){
 1.14981 +        computeJD(p);
 1.14982 +        p->iJD += localtimeOffset(p, pCtx, &rc);
 1.14983 +        clearYMD_HMS_TZ(p);
 1.14984 +      }
 1.14985 +      break;
 1.14986 +    }
 1.14987 +#endif
 1.14988 +    case 'u': {
 1.14989 +      /*
 1.14990 +      **    unixepoch
 1.14991 +      **
 1.14992 +      ** Treat the current value of p->iJD as the number of
 1.14993 +      ** seconds since 1970.  Convert to a real julian day number.
 1.14994 +      */
 1.14995 +      if( strcmp(z, "unixepoch")==0 && p->validJD ){
 1.14996 +        p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
 1.14997 +        clearYMD_HMS_TZ(p);
 1.14998 +        rc = 0;
 1.14999 +      }
 1.15000 +#ifndef SQLITE_OMIT_LOCALTIME
 1.15001 +      else if( strcmp(z, "utc")==0 ){
 1.15002 +        sqlite3_int64 c1;
 1.15003 +        computeJD(p);
 1.15004 +        c1 = localtimeOffset(p, pCtx, &rc);
 1.15005 +        if( rc==SQLITE_OK ){
 1.15006 +          p->iJD -= c1;
 1.15007 +          clearYMD_HMS_TZ(p);
 1.15008 +          p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
 1.15009 +        }
 1.15010 +      }
 1.15011 +#endif
 1.15012 +      break;
 1.15013 +    }
 1.15014 +    case 'w': {
 1.15015 +      /*
 1.15016 +      **    weekday N
 1.15017 +      **
 1.15018 +      ** Move the date to the same time on the next occurrence of
 1.15019 +      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
 1.15020 +      ** date is already on the appropriate weekday, this is a no-op.
 1.15021 +      */
 1.15022 +      if( strncmp(z, "weekday ", 8)==0
 1.15023 +               && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
 1.15024 +               && (n=(int)r)==r && n>=0 && r<7 ){
 1.15025 +        sqlite3_int64 Z;
 1.15026 +        computeYMD_HMS(p);
 1.15027 +        p->validTZ = 0;
 1.15028 +        p->validJD = 0;
 1.15029 +        computeJD(p);
 1.15030 +        Z = ((p->iJD + 129600000)/86400000) % 7;
 1.15031 +        if( Z>n ) Z -= 7;
 1.15032 +        p->iJD += (n - Z)*86400000;
 1.15033 +        clearYMD_HMS_TZ(p);
 1.15034 +        rc = 0;
 1.15035 +      }
 1.15036 +      break;
 1.15037 +    }
 1.15038 +    case 's': {
 1.15039 +      /*
 1.15040 +      **    start of TTTTT
 1.15041 +      **
 1.15042 +      ** Move the date backwards to the beginning of the current day,
 1.15043 +      ** or month or year.
 1.15044 +      */
 1.15045 +      if( strncmp(z, "start of ", 9)!=0 ) break;
 1.15046 +      z += 9;
 1.15047 +      computeYMD(p);
 1.15048 +      p->validHMS = 1;
 1.15049 +      p->h = p->m = 0;
 1.15050 +      p->s = 0.0;
 1.15051 +      p->validTZ = 0;
 1.15052 +      p->validJD = 0;
 1.15053 +      if( strcmp(z,"month")==0 ){
 1.15054 +        p->D = 1;
 1.15055 +        rc = 0;
 1.15056 +      }else if( strcmp(z,"year")==0 ){
 1.15057 +        computeYMD(p);
 1.15058 +        p->M = 1;
 1.15059 +        p->D = 1;
 1.15060 +        rc = 0;
 1.15061 +      }else if( strcmp(z,"day")==0 ){
 1.15062 +        rc = 0;
 1.15063 +      }
 1.15064 +      break;
 1.15065 +    }
 1.15066 +    case '+':
 1.15067 +    case '-':
 1.15068 +    case '0':
 1.15069 +    case '1':
 1.15070 +    case '2':
 1.15071 +    case '3':
 1.15072 +    case '4':
 1.15073 +    case '5':
 1.15074 +    case '6':
 1.15075 +    case '7':
 1.15076 +    case '8':
 1.15077 +    case '9': {
 1.15078 +      double rRounder;
 1.15079 +      for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
 1.15080 +      if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
 1.15081 +        rc = 1;
 1.15082 +        break;
 1.15083 +      }
 1.15084 +      if( z[n]==':' ){
 1.15085 +        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
 1.15086 +        ** specified number of hours, minutes, seconds, and fractional seconds
 1.15087 +        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
 1.15088 +        ** omitted.
 1.15089 +        */
 1.15090 +        const char *z2 = z;
 1.15091 +        DateTime tx;
 1.15092 +        sqlite3_int64 day;
 1.15093 +        if( !sqlite3Isdigit(*z2) ) z2++;
 1.15094 +        memset(&tx, 0, sizeof(tx));
 1.15095 +        if( parseHhMmSs(z2, &tx) ) break;
 1.15096 +        computeJD(&tx);
 1.15097 +        tx.iJD -= 43200000;
 1.15098 +        day = tx.iJD/86400000;
 1.15099 +        tx.iJD -= day*86400000;
 1.15100 +        if( z[0]=='-' ) tx.iJD = -tx.iJD;
 1.15101 +        computeJD(p);
 1.15102 +        clearYMD_HMS_TZ(p);
 1.15103 +        p->iJD += tx.iJD;
 1.15104 +        rc = 0;
 1.15105 +        break;
 1.15106 +      }
 1.15107 +      z += n;
 1.15108 +      while( sqlite3Isspace(*z) ) z++;
 1.15109 +      n = sqlite3Strlen30(z);
 1.15110 +      if( n>10 || n<3 ) break;
 1.15111 +      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
 1.15112 +      computeJD(p);
 1.15113 +      rc = 0;
 1.15114 +      rRounder = r<0 ? -0.5 : +0.5;
 1.15115 +      if( n==3 && strcmp(z,"day")==0 ){
 1.15116 +        p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
 1.15117 +      }else if( n==4 && strcmp(z,"hour")==0 ){
 1.15118 +        p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
 1.15119 +      }else if( n==6 && strcmp(z,"minute")==0 ){
 1.15120 +        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
 1.15121 +      }else if( n==6 && strcmp(z,"second")==0 ){
 1.15122 +        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
 1.15123 +      }else if( n==5 && strcmp(z,"month")==0 ){
 1.15124 +        int x, y;
 1.15125 +        computeYMD_HMS(p);
 1.15126 +        p->M += (int)r;
 1.15127 +        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
 1.15128 +        p->Y += x;
 1.15129 +        p->M -= x*12;
 1.15130 +        p->validJD = 0;
 1.15131 +        computeJD(p);
 1.15132 +        y = (int)r;
 1.15133 +        if( y!=r ){
 1.15134 +          p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
 1.15135 +        }
 1.15136 +      }else if( n==4 && strcmp(z,"year")==0 ){
 1.15137 +        int y = (int)r;
 1.15138 +        computeYMD_HMS(p);
 1.15139 +        p->Y += y;
 1.15140 +        p->validJD = 0;
 1.15141 +        computeJD(p);
 1.15142 +        if( y!=r ){
 1.15143 +          p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
 1.15144 +        }
 1.15145 +      }else{
 1.15146 +        rc = 1;
 1.15147 +      }
 1.15148 +      clearYMD_HMS_TZ(p);
 1.15149 +      break;
 1.15150 +    }
 1.15151 +    default: {
 1.15152 +      break;
 1.15153 +    }
 1.15154 +  }
 1.15155 +  return rc;
 1.15156 +}
 1.15157 +
 1.15158 +/*
 1.15159 +** Process time function arguments.  argv[0] is a date-time stamp.
 1.15160 +** argv[1] and following are modifiers.  Parse them all and write
 1.15161 +** the resulting time into the DateTime structure p.  Return 0
 1.15162 +** on success and 1 if there are any errors.
 1.15163 +**
 1.15164 +** If there are zero parameters (if even argv[0] is undefined)
 1.15165 +** then assume a default value of "now" for argv[0].
 1.15166 +*/
 1.15167 +static int isDate(
 1.15168 +  sqlite3_context *context, 
 1.15169 +  int argc, 
 1.15170 +  sqlite3_value **argv, 
 1.15171 +  DateTime *p
 1.15172 +){
 1.15173 +  int i;
 1.15174 +  const unsigned char *z;
 1.15175 +  int eType;
 1.15176 +  memset(p, 0, sizeof(*p));
 1.15177 +  if( argc==0 ){
 1.15178 +    return setDateTimeToCurrent(context, p);
 1.15179 +  }
 1.15180 +  if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
 1.15181 +                   || eType==SQLITE_INTEGER ){
 1.15182 +    p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
 1.15183 +    p->validJD = 1;
 1.15184 +  }else{
 1.15185 +    z = sqlite3_value_text(argv[0]);
 1.15186 +    if( !z || parseDateOrTime(context, (char*)z, p) ){
 1.15187 +      return 1;
 1.15188 +    }
 1.15189 +  }
 1.15190 +  for(i=1; i<argc; i++){
 1.15191 +    z = sqlite3_value_text(argv[i]);
 1.15192 +    if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
 1.15193 +  }
 1.15194 +  return 0;
 1.15195 +}
 1.15196 +
 1.15197 +
 1.15198 +/*
 1.15199 +** The following routines implement the various date and time functions
 1.15200 +** of SQLite.
 1.15201 +*/
 1.15202 +
 1.15203 +/*
 1.15204 +**    julianday( TIMESTRING, MOD, MOD, ...)
 1.15205 +**
 1.15206 +** Return the julian day number of the date specified in the arguments
 1.15207 +*/
 1.15208 +static void juliandayFunc(
 1.15209 +  sqlite3_context *context,
 1.15210 +  int argc,
 1.15211 +  sqlite3_value **argv
 1.15212 +){
 1.15213 +  DateTime x;
 1.15214 +  if( isDate(context, argc, argv, &x)==0 ){
 1.15215 +    computeJD(&x);
 1.15216 +    sqlite3_result_double(context, x.iJD/86400000.0);
 1.15217 +  }
 1.15218 +}
 1.15219 +
 1.15220 +/*
 1.15221 +**    datetime( TIMESTRING, MOD, MOD, ...)
 1.15222 +**
 1.15223 +** Return YYYY-MM-DD HH:MM:SS
 1.15224 +*/
 1.15225 +static void datetimeFunc(
 1.15226 +  sqlite3_context *context,
 1.15227 +  int argc,
 1.15228 +  sqlite3_value **argv
 1.15229 +){
 1.15230 +  DateTime x;
 1.15231 +  if( isDate(context, argc, argv, &x)==0 ){
 1.15232 +    char zBuf[100];
 1.15233 +    computeYMD_HMS(&x);
 1.15234 +    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
 1.15235 +                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
 1.15236 +    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
 1.15237 +  }
 1.15238 +}
 1.15239 +
 1.15240 +/*
 1.15241 +**    time( TIMESTRING, MOD, MOD, ...)
 1.15242 +**
 1.15243 +** Return HH:MM:SS
 1.15244 +*/
 1.15245 +static void timeFunc(
 1.15246 +  sqlite3_context *context,
 1.15247 +  int argc,
 1.15248 +  sqlite3_value **argv
 1.15249 +){
 1.15250 +  DateTime x;
 1.15251 +  if( isDate(context, argc, argv, &x)==0 ){
 1.15252 +    char zBuf[100];
 1.15253 +    computeHMS(&x);
 1.15254 +    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
 1.15255 +    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
 1.15256 +  }
 1.15257 +}
 1.15258 +
 1.15259 +/*
 1.15260 +**    date( TIMESTRING, MOD, MOD, ...)
 1.15261 +**
 1.15262 +** Return YYYY-MM-DD
 1.15263 +*/
 1.15264 +static void dateFunc(
 1.15265 +  sqlite3_context *context,
 1.15266 +  int argc,
 1.15267 +  sqlite3_value **argv
 1.15268 +){
 1.15269 +  DateTime x;
 1.15270 +  if( isDate(context, argc, argv, &x)==0 ){
 1.15271 +    char zBuf[100];
 1.15272 +    computeYMD(&x);
 1.15273 +    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
 1.15274 +    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
 1.15275 +  }
 1.15276 +}
 1.15277 +
 1.15278 +/*
 1.15279 +**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
 1.15280 +**
 1.15281 +** Return a string described by FORMAT.  Conversions as follows:
 1.15282 +**
 1.15283 +**   %d  day of month
 1.15284 +**   %f  ** fractional seconds  SS.SSS
 1.15285 +**   %H  hour 00-24
 1.15286 +**   %j  day of year 000-366
 1.15287 +**   %J  ** Julian day number
 1.15288 +**   %m  month 01-12
 1.15289 +**   %M  minute 00-59
 1.15290 +**   %s  seconds since 1970-01-01
 1.15291 +**   %S  seconds 00-59
 1.15292 +**   %w  day of week 0-6  sunday==0
 1.15293 +**   %W  week of year 00-53
 1.15294 +**   %Y  year 0000-9999
 1.15295 +**   %%  %
 1.15296 +*/
 1.15297 +static void strftimeFunc(
 1.15298 +  sqlite3_context *context,
 1.15299 +  int argc,
 1.15300 +  sqlite3_value **argv
 1.15301 +){
 1.15302 +  DateTime x;
 1.15303 +  u64 n;
 1.15304 +  size_t i,j;
 1.15305 +  char *z;
 1.15306 +  sqlite3 *db;
 1.15307 +  const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
 1.15308 +  char zBuf[100];
 1.15309 +  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
 1.15310 +  db = sqlite3_context_db_handle(context);
 1.15311 +  for(i=0, n=1; zFmt[i]; i++, n++){
 1.15312 +    if( zFmt[i]=='%' ){
 1.15313 +      switch( zFmt[i+1] ){
 1.15314 +        case 'd':
 1.15315 +        case 'H':
 1.15316 +        case 'm':
 1.15317 +        case 'M':
 1.15318 +        case 'S':
 1.15319 +        case 'W':
 1.15320 +          n++;
 1.15321 +          /* fall thru */
 1.15322 +        case 'w':
 1.15323 +        case '%':
 1.15324 +          break;
 1.15325 +        case 'f':
 1.15326 +          n += 8;
 1.15327 +          break;
 1.15328 +        case 'j':
 1.15329 +          n += 3;
 1.15330 +          break;
 1.15331 +        case 'Y':
 1.15332 +          n += 8;
 1.15333 +          break;
 1.15334 +        case 's':
 1.15335 +        case 'J':
 1.15336 +          n += 50;
 1.15337 +          break;
 1.15338 +        default:
 1.15339 +          return;  /* ERROR.  return a NULL */
 1.15340 +      }
 1.15341 +      i++;
 1.15342 +    }
 1.15343 +  }
 1.15344 +  testcase( n==sizeof(zBuf)-1 );
 1.15345 +  testcase( n==sizeof(zBuf) );
 1.15346 +  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
 1.15347 +  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
 1.15348 +  if( n<sizeof(zBuf) ){
 1.15349 +    z = zBuf;
 1.15350 +  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
 1.15351 +    sqlite3_result_error_toobig(context);
 1.15352 +    return;
 1.15353 +  }else{
 1.15354 +    z = sqlite3DbMallocRaw(db, (int)n);
 1.15355 +    if( z==0 ){
 1.15356 +      sqlite3_result_error_nomem(context);
 1.15357 +      return;
 1.15358 +    }
 1.15359 +  }
 1.15360 +  computeJD(&x);
 1.15361 +  computeYMD_HMS(&x);
 1.15362 +  for(i=j=0; zFmt[i]; i++){
 1.15363 +    if( zFmt[i]!='%' ){
 1.15364 +      z[j++] = zFmt[i];
 1.15365 +    }else{
 1.15366 +      i++;
 1.15367 +      switch( zFmt[i] ){
 1.15368 +        case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
 1.15369 +        case 'f': {
 1.15370 +          double s = x.s;
 1.15371 +          if( s>59.999 ) s = 59.999;
 1.15372 +          sqlite3_snprintf(7, &z[j],"%06.3f", s);
 1.15373 +          j += sqlite3Strlen30(&z[j]);
 1.15374 +          break;
 1.15375 +        }
 1.15376 +        case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
 1.15377 +        case 'W': /* Fall thru */
 1.15378 +        case 'j': {
 1.15379 +          int nDay;             /* Number of days since 1st day of year */
 1.15380 +          DateTime y = x;
 1.15381 +          y.validJD = 0;
 1.15382 +          y.M = 1;
 1.15383 +          y.D = 1;
 1.15384 +          computeJD(&y);
 1.15385 +          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
 1.15386 +          if( zFmt[i]=='W' ){
 1.15387 +            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
 1.15388 +            wd = (int)(((x.iJD+43200000)/86400000)%7);
 1.15389 +            sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
 1.15390 +            j += 2;
 1.15391 +          }else{
 1.15392 +            sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
 1.15393 +            j += 3;
 1.15394 +          }
 1.15395 +          break;
 1.15396 +        }
 1.15397 +        case 'J': {
 1.15398 +          sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
 1.15399 +          j+=sqlite3Strlen30(&z[j]);
 1.15400 +          break;
 1.15401 +        }
 1.15402 +        case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
 1.15403 +        case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
 1.15404 +        case 's': {
 1.15405 +          sqlite3_snprintf(30,&z[j],"%lld",
 1.15406 +                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
 1.15407 +          j += sqlite3Strlen30(&z[j]);
 1.15408 +          break;
 1.15409 +        }
 1.15410 +        case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
 1.15411 +        case 'w': {
 1.15412 +          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
 1.15413 +          break;
 1.15414 +        }
 1.15415 +        case 'Y': {
 1.15416 +          sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
 1.15417 +          break;
 1.15418 +        }
 1.15419 +        default:   z[j++] = '%'; break;
 1.15420 +      }
 1.15421 +    }
 1.15422 +  }
 1.15423 +  z[j] = 0;
 1.15424 +  sqlite3_result_text(context, z, -1,
 1.15425 +                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
 1.15426 +}
 1.15427 +
 1.15428 +/*
 1.15429 +** current_time()
 1.15430 +**
 1.15431 +** This function returns the same value as time('now').
 1.15432 +*/
 1.15433 +static void ctimeFunc(
 1.15434 +  sqlite3_context *context,
 1.15435 +  int NotUsed,
 1.15436 +  sqlite3_value **NotUsed2
 1.15437 +){
 1.15438 +  UNUSED_PARAMETER2(NotUsed, NotUsed2);
 1.15439 +  timeFunc(context, 0, 0);
 1.15440 +}
 1.15441 +
 1.15442 +/*
 1.15443 +** current_date()
 1.15444 +**
 1.15445 +** This function returns the same value as date('now').
 1.15446 +*/
 1.15447 +static void cdateFunc(
 1.15448 +  sqlite3_context *context,
 1.15449 +  int NotUsed,
 1.15450 +  sqlite3_value **NotUsed2
 1.15451 +){
 1.15452 +  UNUSED_PARAMETER2(NotUsed, NotUsed2);
 1.15453 +  dateFunc(context, 0, 0);
 1.15454 +}
 1.15455 +
 1.15456 +/*
 1.15457 +** current_timestamp()
 1.15458 +**
 1.15459 +** This function returns the same value as datetime('now').
 1.15460 +*/
 1.15461 +static void ctimestampFunc(
 1.15462 +  sqlite3_context *context,
 1.15463 +  int NotUsed,
 1.15464 +  sqlite3_value **NotUsed2
 1.15465 +){
 1.15466 +  UNUSED_PARAMETER2(NotUsed, NotUsed2);
 1.15467 +  datetimeFunc(context, 0, 0);
 1.15468 +}
 1.15469 +#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
 1.15470 +
 1.15471 +#ifdef SQLITE_OMIT_DATETIME_FUNCS
 1.15472 +/*
 1.15473 +** If the library is compiled to omit the full-scale date and time
 1.15474 +** handling (to get a smaller binary), the following minimal version
 1.15475 +** of the functions current_time(), current_date() and current_timestamp()
 1.15476 +** are included instead. This is to support column declarations that
 1.15477 +** include "DEFAULT CURRENT_TIME" etc.
 1.15478 +**
 1.15479 +** This function uses the C-library functions time(), gmtime()
 1.15480 +** and strftime(). The format string to pass to strftime() is supplied
 1.15481 +** as the user-data for the function.
 1.15482 +*/
 1.15483 +static void currentTimeFunc(
 1.15484 +  sqlite3_context *context,
 1.15485 +  int argc,
 1.15486 +  sqlite3_value **argv
 1.15487 +){
 1.15488 +  time_t t;
 1.15489 +  char *zFormat = (char *)sqlite3_user_data(context);
 1.15490 +  sqlite3 *db;
 1.15491 +  sqlite3_int64 iT;
 1.15492 +  struct tm *pTm;
 1.15493 +  struct tm sNow;
 1.15494 +  char zBuf[20];
 1.15495 +
 1.15496 +  UNUSED_PARAMETER(argc);
 1.15497 +  UNUSED_PARAMETER(argv);
 1.15498 +
 1.15499 +  iT = sqlite3StmtCurrentTime(context);
 1.15500 +  if( iT<=0 ) return;
 1.15501 +  t = iT/1000 - 10000*(sqlite3_int64)21086676;
 1.15502 +#ifdef HAVE_GMTIME_R
 1.15503 +  pTm = gmtime_r(&t, &sNow);
 1.15504 +#else
 1.15505 +  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
 1.15506 +  pTm = gmtime(&t);
 1.15507 +  if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
 1.15508 +  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
 1.15509 +#endif
 1.15510 +  if( pTm ){
 1.15511 +    strftime(zBuf, 20, zFormat, &sNow);
 1.15512 +    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
 1.15513 +  }
 1.15514 +}
 1.15515 +#endif
 1.15516 +
 1.15517 +/*
 1.15518 +** This function registered all of the above C functions as SQL
 1.15519 +** functions.  This should be the only routine in this file with
 1.15520 +** external linkage.
 1.15521 +*/
 1.15522 +SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
 1.15523 +  static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
 1.15524 +#ifndef SQLITE_OMIT_DATETIME_FUNCS
 1.15525 +    FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
 1.15526 +    FUNCTION(date,             -1, 0, 0, dateFunc      ),
 1.15527 +    FUNCTION(time,             -1, 0, 0, timeFunc      ),
 1.15528 +    FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
 1.15529 +    FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
 1.15530 +    FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
 1.15531 +    FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
 1.15532 +    FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
 1.15533 +#else
 1.15534 +    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
 1.15535 +    STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
 1.15536 +    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
 1.15537 +#endif
 1.15538 +  };
 1.15539 +  int i;
 1.15540 +  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
 1.15541 +  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
 1.15542 +
 1.15543 +  for(i=0; i<ArraySize(aDateTimeFuncs); i++){
 1.15544 +    sqlite3FuncDefInsert(pHash, &aFunc[i]);
 1.15545 +  }
 1.15546 +}
 1.15547 +
 1.15548 +/************** End of date.c ************************************************/
 1.15549 +/************** Begin file os.c **********************************************/
 1.15550 +/*
 1.15551 +** 2005 November 29
 1.15552 +**
 1.15553 +** The author disclaims copyright to this source code.  In place of
 1.15554 +** a legal notice, here is a blessing:
 1.15555 +**
 1.15556 +**    May you do good and not evil.
 1.15557 +**    May you find forgiveness for yourself and forgive others.
 1.15558 +**    May you share freely, never taking more than you give.
 1.15559 +**
 1.15560 +******************************************************************************
 1.15561 +**
 1.15562 +** This file contains OS interface code that is common to all
 1.15563 +** architectures.
 1.15564 +*/
 1.15565 +#define _SQLITE_OS_C_ 1
 1.15566 +#undef _SQLITE_OS_C_
 1.15567 +
 1.15568 +/*
 1.15569 +** The default SQLite sqlite3_vfs implementations do not allocate
 1.15570 +** memory (actually, os_unix.c allocates a small amount of memory
 1.15571 +** from within OsOpen()), but some third-party implementations may.
 1.15572 +** So we test the effects of a malloc() failing and the sqlite3OsXXX()
 1.15573 +** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
 1.15574 +**
 1.15575 +** The following functions are instrumented for malloc() failure 
 1.15576 +** testing:
 1.15577 +**
 1.15578 +**     sqlite3OsRead()
 1.15579 +**     sqlite3OsWrite()
 1.15580 +**     sqlite3OsSync()
 1.15581 +**     sqlite3OsFileSize()
 1.15582 +**     sqlite3OsLock()
 1.15583 +**     sqlite3OsCheckReservedLock()
 1.15584 +**     sqlite3OsFileControl()
 1.15585 +**     sqlite3OsShmMap()
 1.15586 +**     sqlite3OsOpen()
 1.15587 +**     sqlite3OsDelete()
 1.15588 +**     sqlite3OsAccess()
 1.15589 +**     sqlite3OsFullPathname()
 1.15590 +**
 1.15591 +*/
 1.15592 +#if defined(SQLITE_TEST)
 1.15593 +SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
 1.15594 +  #define DO_OS_MALLOC_TEST(x)                                       \
 1.15595 +  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
 1.15596 +    void *pTstAlloc = sqlite3Malloc(10);                             \
 1.15597 +    if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
 1.15598 +    sqlite3_free(pTstAlloc);                                         \
 1.15599 +  }
 1.15600 +#else
 1.15601 +  #define DO_OS_MALLOC_TEST(x)
 1.15602 +#endif
 1.15603 +
 1.15604 +/*
 1.15605 +** The following routines are convenience wrappers around methods
 1.15606 +** of the sqlite3_file object.  This is mostly just syntactic sugar. All
 1.15607 +** of this would be completely automatic if SQLite were coded using
 1.15608 +** C++ instead of plain old C.
 1.15609 +*/
 1.15610 +SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
 1.15611 +  int rc = SQLITE_OK;
 1.15612 +  if( pId->pMethods ){
 1.15613 +    rc = pId->pMethods->xClose(pId);
 1.15614 +    pId->pMethods = 0;
 1.15615 +  }
 1.15616 +  return rc;
 1.15617 +}
 1.15618 +SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
 1.15619 +  DO_OS_MALLOC_TEST(id);
 1.15620 +  return id->pMethods->xRead(id, pBuf, amt, offset);
 1.15621 +}
 1.15622 +SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
 1.15623 +  DO_OS_MALLOC_TEST(id);
 1.15624 +  return id->pMethods->xWrite(id, pBuf, amt, offset);
 1.15625 +}
 1.15626 +SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
 1.15627 +  return id->pMethods->xTruncate(id, size);
 1.15628 +}
 1.15629 +SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
 1.15630 +  DO_OS_MALLOC_TEST(id);
 1.15631 +  return id->pMethods->xSync(id, flags);
 1.15632 +}
 1.15633 +SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
 1.15634 +  DO_OS_MALLOC_TEST(id);
 1.15635 +  return id->pMethods->xFileSize(id, pSize);
 1.15636 +}
 1.15637 +SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
 1.15638 +  DO_OS_MALLOC_TEST(id);
 1.15639 +  return id->pMethods->xLock(id, lockType);
 1.15640 +}
 1.15641 +SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
 1.15642 +  return id->pMethods->xUnlock(id, lockType);
 1.15643 +}
 1.15644 +SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
 1.15645 +  DO_OS_MALLOC_TEST(id);
 1.15646 +  return id->pMethods->xCheckReservedLock(id, pResOut);
 1.15647 +}
 1.15648 +
 1.15649 +/*
 1.15650 +** Use sqlite3OsFileControl() when we are doing something that might fail
 1.15651 +** and we need to know about the failures.  Use sqlite3OsFileControlHint()
 1.15652 +** when simply tossing information over the wall to the VFS and we do not
 1.15653 +** really care if the VFS receives and understands the information since it
 1.15654 +** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
 1.15655 +** routine has no return value since the return value would be meaningless.
 1.15656 +*/
 1.15657 +SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
 1.15658 +#ifdef SQLITE_TEST
 1.15659 +  if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
 1.15660 +    /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
 1.15661 +    ** is using a regular VFS, it is called after the corresponding 
 1.15662 +    ** transaction has been committed. Injecting a fault at this point 
 1.15663 +    ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
 1.15664 +    ** but the transaction is committed anyway.
 1.15665 +    **
 1.15666 +    ** The core must call OsFileControl() though, not OsFileControlHint(),
 1.15667 +    ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
 1.15668 +    ** means the commit really has failed and an error should be returned
 1.15669 +    ** to the user.  */
 1.15670 +    DO_OS_MALLOC_TEST(id);
 1.15671 +  }
 1.15672 +#endif
 1.15673 +  return id->pMethods->xFileControl(id, op, pArg);
 1.15674 +}
 1.15675 +SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
 1.15676 +  (void)id->pMethods->xFileControl(id, op, pArg);
 1.15677 +}
 1.15678 +
 1.15679 +SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
 1.15680 +  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
 1.15681 +  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
 1.15682 +}
 1.15683 +SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
 1.15684 +  return id->pMethods->xDeviceCharacteristics(id);
 1.15685 +}
 1.15686 +SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
 1.15687 +  return id->pMethods->xShmLock(id, offset, n, flags);
 1.15688 +}
 1.15689 +SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
 1.15690 +  id->pMethods->xShmBarrier(id);
 1.15691 +}
 1.15692 +SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
 1.15693 +  return id->pMethods->xShmUnmap(id, deleteFlag);
 1.15694 +}
 1.15695 +SQLITE_PRIVATE int sqlite3OsShmMap(
 1.15696 +  sqlite3_file *id,               /* Database file handle */
 1.15697 +  int iPage,
 1.15698 +  int pgsz,
 1.15699 +  int bExtend,                    /* True to extend file if necessary */
 1.15700 +  void volatile **pp              /* OUT: Pointer to mapping */
 1.15701 +){
 1.15702 +  DO_OS_MALLOC_TEST(id);
 1.15703 +  return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
 1.15704 +}
 1.15705 +
 1.15706 +#if SQLITE_MAX_MMAP_SIZE>0
 1.15707 +/* The real implementation of xFetch and xUnfetch */
 1.15708 +SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
 1.15709 +  DO_OS_MALLOC_TEST(id);
 1.15710 +  return id->pMethods->xFetch(id, iOff, iAmt, pp);
 1.15711 +}
 1.15712 +SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
 1.15713 +  return id->pMethods->xUnfetch(id, iOff, p);
 1.15714 +}
 1.15715 +#else
 1.15716 +/* No-op stubs to use when memory-mapped I/O is disabled */
 1.15717 +SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
 1.15718 +  *pp = 0;
 1.15719 +  return SQLITE_OK;
 1.15720 +}
 1.15721 +SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
 1.15722 +  return SQLITE_OK;
 1.15723 +}
 1.15724 +#endif
 1.15725 +
 1.15726 +/*
 1.15727 +** The next group of routines are convenience wrappers around the
 1.15728 +** VFS methods.
 1.15729 +*/
 1.15730 +SQLITE_PRIVATE int sqlite3OsOpen(
 1.15731 +  sqlite3_vfs *pVfs, 
 1.15732 +  const char *zPath, 
 1.15733 +  sqlite3_file *pFile, 
 1.15734 +  int flags, 
 1.15735 +  int *pFlagsOut
 1.15736 +){
 1.15737 +  int rc;
 1.15738 +  DO_OS_MALLOC_TEST(0);
 1.15739 +  /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
 1.15740 +  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
 1.15741 +  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
 1.15742 +  ** reaching the VFS. */
 1.15743 +  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
 1.15744 +  assert( rc==SQLITE_OK || pFile->pMethods==0 );
 1.15745 +  return rc;
 1.15746 +}
 1.15747 +SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
 1.15748 +  DO_OS_MALLOC_TEST(0);
 1.15749 +  assert( dirSync==0 || dirSync==1 );
 1.15750 +  return pVfs->xDelete(pVfs, zPath, dirSync);
 1.15751 +}
 1.15752 +SQLITE_PRIVATE int sqlite3OsAccess(
 1.15753 +  sqlite3_vfs *pVfs, 
 1.15754 +  const char *zPath, 
 1.15755 +  int flags, 
 1.15756 +  int *pResOut
 1.15757 +){
 1.15758 +  DO_OS_MALLOC_TEST(0);
 1.15759 +  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
 1.15760 +}
 1.15761 +SQLITE_PRIVATE int sqlite3OsFullPathname(
 1.15762 +  sqlite3_vfs *pVfs, 
 1.15763 +  const char *zPath, 
 1.15764 +  int nPathOut, 
 1.15765 +  char *zPathOut
 1.15766 +){
 1.15767 +  DO_OS_MALLOC_TEST(0);
 1.15768 +  zPathOut[0] = 0;
 1.15769 +  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
 1.15770 +}
 1.15771 +#ifndef SQLITE_OMIT_LOAD_EXTENSION
 1.15772 +SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
 1.15773 +  return pVfs->xDlOpen(pVfs, zPath);
 1.15774 +}
 1.15775 +SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
 1.15776 +  pVfs->xDlError(pVfs, nByte, zBufOut);
 1.15777 +}
 1.15778 +SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
 1.15779 +  return pVfs->xDlSym(pVfs, pHdle, zSym);
 1.15780 +}
 1.15781 +SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
 1.15782 +  pVfs->xDlClose(pVfs, pHandle);
 1.15783 +}
 1.15784 +#endif /* SQLITE_OMIT_LOAD_EXTENSION */
 1.15785 +SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
 1.15786 +  return pVfs->xRandomness(pVfs, nByte, zBufOut);
 1.15787 +}
 1.15788 +SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
 1.15789 +  return pVfs->xSleep(pVfs, nMicro);
 1.15790 +}
 1.15791 +SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
 1.15792 +  int rc;
 1.15793 +  /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
 1.15794 +  ** method to get the current date and time if that method is available
 1.15795 +  ** (if iVersion is 2 or greater and the function pointer is not NULL) and
 1.15796 +  ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
 1.15797 +  ** unavailable.
 1.15798 +  */
 1.15799 +  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
 1.15800 +    rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
 1.15801 +  }else{
 1.15802 +    double r;
 1.15803 +    rc = pVfs->xCurrentTime(pVfs, &r);
 1.15804 +    *pTimeOut = (sqlite3_int64)(r*86400000.0);
 1.15805 +  }
 1.15806 +  return rc;
 1.15807 +}
 1.15808 +
 1.15809 +SQLITE_PRIVATE int sqlite3OsOpenMalloc(
 1.15810 +  sqlite3_vfs *pVfs, 
 1.15811 +  const char *zFile, 
 1.15812 +  sqlite3_file **ppFile, 
 1.15813 +  int flags,
 1.15814 +  int *pOutFlags
 1.15815 +){
 1.15816 +  int rc = SQLITE_NOMEM;
 1.15817 +  sqlite3_file *pFile;
 1.15818 +  pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
 1.15819 +  if( pFile ){
 1.15820 +    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
 1.15821 +    if( rc!=SQLITE_OK ){
 1.15822 +      sqlite3_free(pFile);
 1.15823 +    }else{
 1.15824 +      *ppFile = pFile;
 1.15825 +    }
 1.15826 +  }
 1.15827 +  return rc;
 1.15828 +}
 1.15829 +SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
 1.15830 +  int rc = SQLITE_OK;
 1.15831 +  assert( pFile );
 1.15832 +  rc = sqlite3OsClose(pFile);
 1.15833 +  sqlite3_free(pFile);
 1.15834 +  return rc;
 1.15835 +}
 1.15836 +
 1.15837 +/*
 1.15838 +** This function is a wrapper around the OS specific implementation of
 1.15839 +** sqlite3_os_init(). The purpose of the wrapper is to provide the
 1.15840 +** ability to simulate a malloc failure, so that the handling of an
 1.15841 +** error in sqlite3_os_init() by the upper layers can be tested.
 1.15842 +*/
 1.15843 +SQLITE_PRIVATE int sqlite3OsInit(void){
 1.15844 +  void *p = sqlite3_malloc(10);
 1.15845 +  if( p==0 ) return SQLITE_NOMEM;
 1.15846 +  sqlite3_free(p);
 1.15847 +  return sqlite3_os_init();
 1.15848 +}
 1.15849 +
 1.15850 +/*
 1.15851 +** The list of all registered VFS implementations.
 1.15852 +*/
 1.15853 +static sqlite3_vfs * SQLITE_WSD vfsList = 0;
 1.15854 +#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
 1.15855 +
 1.15856 +/*
 1.15857 +** Locate a VFS by name.  If no name is given, simply return the
 1.15858 +** first VFS on the list.
 1.15859 +*/
 1.15860 +SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
 1.15861 +  sqlite3_vfs *pVfs = 0;
 1.15862 +#if SQLITE_THREADSAFE
 1.15863 +  sqlite3_mutex *mutex;
 1.15864 +#endif
 1.15865 +#ifndef SQLITE_OMIT_AUTOINIT
 1.15866 +  int rc = sqlite3_initialize();
 1.15867 +  if( rc ) return 0;
 1.15868 +#endif
 1.15869 +#if SQLITE_THREADSAFE
 1.15870 +  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
 1.15871 +#endif
 1.15872 +  sqlite3_mutex_enter(mutex);
 1.15873 +  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
 1.15874 +    if( zVfs==0 ) break;
 1.15875 +    if( strcmp(zVfs, pVfs->zName)==0 ) break;
 1.15876 +  }
 1.15877 +  sqlite3_mutex_leave(mutex);
 1.15878 +  return pVfs;
 1.15879 +}
 1.15880 +
 1.15881 +/*
 1.15882 +** Unlink a VFS from the linked list
 1.15883 +*/
 1.15884 +static void vfsUnlink(sqlite3_vfs *pVfs){
 1.15885 +  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
 1.15886 +  if( pVfs==0 ){
 1.15887 +    /* No-op */
 1.15888 +  }else if( vfsList==pVfs ){
 1.15889 +    vfsList = pVfs->pNext;
 1.15890 +  }else if( vfsList ){
 1.15891 +    sqlite3_vfs *p = vfsList;
 1.15892 +    while( p->pNext && p->pNext!=pVfs ){
 1.15893 +      p = p->pNext;
 1.15894 +    }
 1.15895 +    if( p->pNext==pVfs ){
 1.15896 +      p->pNext = pVfs->pNext;
 1.15897 +    }
 1.15898 +  }
 1.15899 +}
 1.15900 +
 1.15901 +/*
 1.15902 +** Register a VFS with the system.  It is harmless to register the same
 1.15903 +** VFS multiple times.  The new VFS becomes the default if makeDflt is
 1.15904 +** true.
 1.15905 +*/
 1.15906 +SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
 1.15907 +  MUTEX_LOGIC(sqlite3_mutex *mutex;)
 1.15908 +#ifndef SQLITE_OMIT_AUTOINIT
 1.15909 +  int rc = sqlite3_initialize();
 1.15910 +  if( rc ) return rc;
 1.15911 +#endif
 1.15912 +  MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
 1.15913 +  sqlite3_mutex_enter(mutex);
 1.15914 +  vfsUnlink(pVfs);
 1.15915 +  if( makeDflt || vfsList==0 ){
 1.15916 +    pVfs->pNext = vfsList;
 1.15917 +    vfsList = pVfs;
 1.15918 +  }else{
 1.15919 +    pVfs->pNext = vfsList->pNext;
 1.15920 +    vfsList->pNext = pVfs;
 1.15921 +  }
 1.15922 +  assert(vfsList);
 1.15923 +  sqlite3_mutex_leave(mutex);
 1.15924 +  return SQLITE_OK;
 1.15925 +}
 1.15926 +
 1.15927 +/*
 1.15928 +** Unregister a VFS so that it is no longer accessible.
 1.15929 +*/
 1.15930 +SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
 1.15931 +#if SQLITE_THREADSAFE
 1.15932 +  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
 1.15933 +#endif
 1.15934 +  sqlite3_mutex_enter(mutex);
 1.15935 +  vfsUnlink(pVfs);
 1.15936 +  sqlite3_mutex_leave(mutex);
 1.15937 +  return SQLITE_OK;
 1.15938 +}
 1.15939 +
 1.15940 +/************** End of os.c **************************************************/
 1.15941 +/************** Begin file fault.c *******************************************/
 1.15942 +/*
 1.15943 +** 2008 Jan 22
 1.15944 +**
 1.15945 +** The author disclaims copyright to this source code.  In place of
 1.15946 +** a legal notice, here is a blessing:
 1.15947 +**
 1.15948 +**    May you do good and not evil.
 1.15949 +**    May you find forgiveness for yourself and forgive others.
 1.15950 +**    May you share freely, never taking more than you give.
 1.15951 +**
 1.15952 +*************************************************************************
 1.15953 +**
 1.15954 +** This file contains code to support the concept of "benign" 
 1.15955 +** malloc failures (when the xMalloc() or xRealloc() method of the
 1.15956 +** sqlite3_mem_methods structure fails to allocate a block of memory
 1.15957 +** and returns 0). 
 1.15958 +**
 1.15959 +** Most malloc failures are non-benign. After they occur, SQLite
 1.15960 +** abandons the current operation and returns an error code (usually
 1.15961 +** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
 1.15962 +** fatal. For example, if a malloc fails while resizing a hash table, this 
 1.15963 +** is completely recoverable simply by not carrying out the resize. The 
 1.15964 +** hash table will continue to function normally.  So a malloc failure 
 1.15965 +** during a hash table resize is a benign fault.
 1.15966 +*/
 1.15967 +
 1.15968 +
 1.15969 +#ifndef SQLITE_OMIT_BUILTIN_TEST
 1.15970 +
 1.15971 +/*
 1.15972 +** Global variables.
 1.15973 +*/
 1.15974 +typedef struct BenignMallocHooks BenignMallocHooks;
 1.15975 +static SQLITE_WSD struct BenignMallocHooks {
 1.15976 +  void (*xBenignBegin)(void);
 1.15977 +  void (*xBenignEnd)(void);
 1.15978 +} sqlite3Hooks = { 0, 0 };
 1.15979 +
 1.15980 +/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
 1.15981 +** structure.  If writable static data is unsupported on the target,
 1.15982 +** we have to locate the state vector at run-time.  In the more common
 1.15983 +** case where writable static data is supported, wsdHooks can refer directly
 1.15984 +** to the "sqlite3Hooks" state vector declared above.
 1.15985 +*/
 1.15986 +#ifdef SQLITE_OMIT_WSD
 1.15987 +# define wsdHooksInit \
 1.15988 +  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
 1.15989 +# define wsdHooks x[0]
 1.15990 +#else
 1.15991 +# define wsdHooksInit
 1.15992 +# define wsdHooks sqlite3Hooks
 1.15993 +#endif
 1.15994 +
 1.15995 +
 1.15996 +/*
 1.15997 +** Register hooks to call when sqlite3BeginBenignMalloc() and
 1.15998 +** sqlite3EndBenignMalloc() are called, respectively.
 1.15999 +*/
 1.16000 +SQLITE_PRIVATE void sqlite3BenignMallocHooks(
 1.16001 +  void (*xBenignBegin)(void),
 1.16002 +  void (*xBenignEnd)(void)
 1.16003 +){
 1.16004 +  wsdHooksInit;
 1.16005 +  wsdHooks.xBenignBegin = xBenignBegin;
 1.16006 +  wsdHooks.xBenignEnd = xBenignEnd;
 1.16007 +}
 1.16008 +
 1.16009 +/*
 1.16010 +** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
 1.16011 +** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
 1.16012 +** indicates that subsequent malloc failures are non-benign.
 1.16013 +*/
 1.16014 +SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
 1.16015 +  wsdHooksInit;
 1.16016 +  if( wsdHooks.xBenignBegin ){
 1.16017 +    wsdHooks.xBenignBegin();
 1.16018 +  }
 1.16019 +}
 1.16020 +SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
 1.16021 +  wsdHooksInit;
 1.16022 +  if( wsdHooks.xBenignEnd ){
 1.16023 +    wsdHooks.xBenignEnd();
 1.16024 +  }
 1.16025 +}
 1.16026 +
 1.16027 +#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
 1.16028 +
 1.16029 +/************** End of fault.c ***********************************************/
 1.16030 +/************** Begin file mem0.c ********************************************/
 1.16031 +/*
 1.16032 +** 2008 October 28
 1.16033 +**
 1.16034 +** The author disclaims copyright to this source code.  In place of
 1.16035 +** a legal notice, here is a blessing:
 1.16036 +**
 1.16037 +**    May you do good and not evil.
 1.16038 +**    May you find forgiveness for yourself and forgive others.
 1.16039 +**    May you share freely, never taking more than you give.
 1.16040 +**
 1.16041 +*************************************************************************
 1.16042 +**
 1.16043 +** This file contains a no-op memory allocation drivers for use when
 1.16044 +** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
 1.16045 +** here always fail.  SQLite will not operate with these drivers.  These
 1.16046 +** are merely placeholders.  Real drivers must be substituted using
 1.16047 +** sqlite3_config() before SQLite will operate.
 1.16048 +*/
 1.16049 +
 1.16050 +/*
 1.16051 +** This version of the memory allocator is the default.  It is
 1.16052 +** used when no other memory allocator is specified using compile-time
 1.16053 +** macros.
 1.16054 +*/
 1.16055 +#ifdef SQLITE_ZERO_MALLOC
 1.16056 +
 1.16057 +/*
 1.16058 +** No-op versions of all memory allocation routines
 1.16059 +*/
 1.16060 +static void *sqlite3MemMalloc(int nByte){ return 0; }
 1.16061 +static void sqlite3MemFree(void *pPrior){ return; }
 1.16062 +static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
 1.16063 +static int sqlite3MemSize(void *pPrior){ return 0; }
 1.16064 +static int sqlite3MemRoundup(int n){ return n; }
 1.16065 +static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
 1.16066 +static void sqlite3MemShutdown(void *NotUsed){ return; }
 1.16067 +
 1.16068 +/*
 1.16069 +** This routine is the only routine in this file with external linkage.
 1.16070 +**
 1.16071 +** Populate the low-level memory allocation function pointers in
 1.16072 +** sqlite3GlobalConfig.m with pointers to the routines in this file.
 1.16073 +*/
 1.16074 +SQLITE_PRIVATE void sqlite3MemSetDefault(void){
 1.16075 +  static const sqlite3_mem_methods defaultMethods = {
 1.16076 +     sqlite3MemMalloc,
 1.16077 +     sqlite3MemFree,
 1.16078 +     sqlite3MemRealloc,
 1.16079 +     sqlite3MemSize,
 1.16080 +     sqlite3MemRoundup,
 1.16081 +     sqlite3MemInit,
 1.16082 +     sqlite3MemShutdown,
 1.16083 +     0
 1.16084 +  };
 1.16085 +  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
 1.16086 +}
 1.16087 +
 1.16088 +#endif /* SQLITE_ZERO_MALLOC */
 1.16089 +
 1.16090 +/************** End of mem0.c ************************************************/
 1.16091 +/************** Begin file mem1.c ********************************************/
 1.16092 +/*
 1.16093 +** 2007 August 14
 1.16094 +**
 1.16095 +** The author disclaims copyright to this source code.  In place of
 1.16096 +** a legal notice, here is a blessing:
 1.16097 +**
 1.16098 +**    May you do good and not evil.
 1.16099 +**    May you find forgiveness for yourself and forgive others.
 1.16100 +**    May you share freely, never taking more than you give.
 1.16101 +**
 1.16102 +*************************************************************************
 1.16103 +**
 1.16104 +** This file contains low-level memory allocation drivers for when
 1.16105 +** SQLite will use the standard C-library malloc/realloc/free interface
 1.16106 +** to obtain the memory it needs.
 1.16107 +**
 1.16108 +** This file contains implementations of the low-level memory allocation
 1.16109 +** routines specified in the sqlite3_mem_methods object.  The content of
 1.16110 +** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
 1.16111 +** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
 1.16112 +** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
 1.16113 +** default configuration is to use memory allocation routines in this
 1.16114 +** file.
 1.16115 +**
 1.16116 +** C-preprocessor macro summary:
 1.16117 +**
 1.16118 +**    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
 1.16119 +**                                the malloc_usable_size() interface exists
 1.16120 +**                                on the target platform.  Or, this symbol
 1.16121 +**                                can be set manually, if desired.
 1.16122 +**                                If an equivalent interface exists by
 1.16123 +**                                a different name, using a separate -D
 1.16124 +**                                option to rename it.
 1.16125 +**
 1.16126 +**    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
 1.16127 +**                                memory allocator.  Set this symbol to enable
 1.16128 +**                                building on older macs.
 1.16129 +**
 1.16130 +**    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
 1.16131 +**                                _msize() on windows systems.  This might
 1.16132 +**                                be necessary when compiling for Delphi,
 1.16133 +**                                for example.
 1.16134 +*/
 1.16135 +
 1.16136 +/*
 1.16137 +** This version of the memory allocator is the default.  It is
 1.16138 +** used when no other memory allocator is specified using compile-time
 1.16139 +** macros.
 1.16140 +*/
 1.16141 +#ifdef SQLITE_SYSTEM_MALLOC
 1.16142 +#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
 1.16143 +
 1.16144 +/*
 1.16145 +** Use the zone allocator available on apple products unless the
 1.16146 +** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
 1.16147 +*/
 1.16148 +#include <sys/sysctl.h>
 1.16149 +#include <malloc/malloc.h>
 1.16150 +#include <libkern/OSAtomic.h>
 1.16151 +static malloc_zone_t* _sqliteZone_;
 1.16152 +#define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
 1.16153 +#define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
 1.16154 +#define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
 1.16155 +#define SQLITE_MALLOCSIZE(x) \
 1.16156 +        (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
 1.16157 +
 1.16158 +#else /* if not __APPLE__ */
 1.16159 +
 1.16160 +/*
 1.16161 +** Use standard C library malloc and free on non-Apple systems.  
 1.16162 +** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
 1.16163 +*/
 1.16164 +#define SQLITE_MALLOC(x)             malloc(x)
 1.16165 +#define SQLITE_FREE(x)               free(x)
 1.16166 +#define SQLITE_REALLOC(x,y)          realloc((x),(y))
 1.16167 +
 1.16168 +/*
 1.16169 +** The malloc.h header file is needed for malloc_usable_size() function
 1.16170 +** on some systems (e.g. Linux).
 1.16171 +*/
 1.16172 +#if defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE)
 1.16173 +#  define SQLITE_USE_MALLOC_H
 1.16174 +#  define SQLITE_USE_MALLOC_USABLE_SIZE
 1.16175 +/*
 1.16176 +** The MSVCRT has malloc_usable_size(), but it is called _msize().  The
 1.16177 +** use of _msize() is automatic, but can be disabled by compiling with
 1.16178 +** -DSQLITE_WITHOUT_MSIZE.  Using the _msize() function also requires
 1.16179 +** the malloc.h header file.
 1.16180 +*/
 1.16181 +#elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
 1.16182 +#  define SQLITE_USE_MALLOC_H
 1.16183 +#  define SQLITE_USE_MSIZE
 1.16184 +#endif
 1.16185 +
 1.16186 +/*
 1.16187 +** Include the malloc.h header file, if necessary.  Also set define macro
 1.16188 +** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
 1.16189 +** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
 1.16190 +** The memory size function can always be overridden manually by defining
 1.16191 +** the macro SQLITE_MALLOCSIZE to the desired function name.
 1.16192 +*/
 1.16193 +#if defined(SQLITE_USE_MALLOC_H)
 1.16194 +#  include <malloc.h>
 1.16195 +#  if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
 1.16196 +#    if !defined(SQLITE_MALLOCSIZE)
 1.16197 +#      define SQLITE_MALLOCSIZE(x)   malloc_usable_size(x)
 1.16198 +#    endif
 1.16199 +#  elif defined(SQLITE_USE_MSIZE)
 1.16200 +#    if !defined(SQLITE_MALLOCSIZE)
 1.16201 +#      define SQLITE_MALLOCSIZE      _msize
 1.16202 +#    endif
 1.16203 +#  endif
 1.16204 +#endif /* defined(SQLITE_USE_MALLOC_H) */
 1.16205 +
 1.16206 +#endif /* __APPLE__ or not __APPLE__ */
 1.16207 +
 1.16208 +/*
 1.16209 +** Like malloc(), but remember the size of the allocation
 1.16210 +** so that we can find it later using sqlite3MemSize().
 1.16211 +**
 1.16212 +** For this low-level routine, we are guaranteed that nByte>0 because
 1.16213 +** cases of nByte<=0 will be intercepted and dealt with by higher level
 1.16214 +** routines.
 1.16215 +*/
 1.16216 +static void *sqlite3MemMalloc(int nByte){
 1.16217 +#ifdef SQLITE_MALLOCSIZE
 1.16218 +  void *p = SQLITE_MALLOC( nByte );
 1.16219 +  if( p==0 ){
 1.16220 +    testcase( sqlite3GlobalConfig.xLog!=0 );
 1.16221 +    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
 1.16222 +  }
 1.16223 +  return p;
 1.16224 +#else
 1.16225 +  sqlite3_int64 *p;
 1.16226 +  assert( nByte>0 );
 1.16227 +  nByte = ROUND8(nByte);
 1.16228 +  p = SQLITE_MALLOC( nByte+8 );
 1.16229 +  if( p ){
 1.16230 +    p[0] = nByte;
 1.16231 +    p++;
 1.16232 +  }else{
 1.16233 +    testcase( sqlite3GlobalConfig.xLog!=0 );
 1.16234 +    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
 1.16235 +  }
 1.16236 +  return (void *)p;
 1.16237 +#endif
 1.16238 +}
 1.16239 +
 1.16240 +/*
 1.16241 +** Like free() but works for allocations obtained from sqlite3MemMalloc()
 1.16242 +** or sqlite3MemRealloc().
 1.16243 +**
 1.16244 +** For this low-level routine, we already know that pPrior!=0 since
 1.16245 +** cases where pPrior==0 will have been intecepted and dealt with
 1.16246 +** by higher-level routines.
 1.16247 +*/
 1.16248 +static void sqlite3MemFree(void *pPrior){
 1.16249 +#ifdef SQLITE_MALLOCSIZE
 1.16250 +  SQLITE_FREE(pPrior);
 1.16251 +#else
 1.16252 +  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
 1.16253 +  assert( pPrior!=0 );
 1.16254 +  p--;
 1.16255 +  SQLITE_FREE(p);
 1.16256 +#endif
 1.16257 +}
 1.16258 +
 1.16259 +/*
 1.16260 +** Report the allocated size of a prior return from xMalloc()
 1.16261 +** or xRealloc().
 1.16262 +*/
 1.16263 +static int sqlite3MemSize(void *pPrior){
 1.16264 +#ifdef SQLITE_MALLOCSIZE
 1.16265 +  return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
 1.16266 +#else
 1.16267 +  sqlite3_int64 *p;
 1.16268 +  if( pPrior==0 ) return 0;
 1.16269 +  p = (sqlite3_int64*)pPrior;
 1.16270 +  p--;
 1.16271 +  return (int)p[0];
 1.16272 +#endif
 1.16273 +}
 1.16274 +
 1.16275 +/*
 1.16276 +** Like realloc().  Resize an allocation previously obtained from
 1.16277 +** sqlite3MemMalloc().
 1.16278 +**
 1.16279 +** For this low-level interface, we know that pPrior!=0.  Cases where
 1.16280 +** pPrior==0 while have been intercepted by higher-level routine and
 1.16281 +** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
 1.16282 +** cases where nByte<=0 will have been intercepted by higher-level
 1.16283 +** routines and redirected to xFree.
 1.16284 +*/
 1.16285 +static void *sqlite3MemRealloc(void *pPrior, int nByte){
 1.16286 +#ifdef SQLITE_MALLOCSIZE
 1.16287 +  void *p = SQLITE_REALLOC(pPrior, nByte);
 1.16288 +  if( p==0 ){
 1.16289 +    testcase( sqlite3GlobalConfig.xLog!=0 );
 1.16290 +    sqlite3_log(SQLITE_NOMEM,
 1.16291 +      "failed memory resize %u to %u bytes",
 1.16292 +      SQLITE_MALLOCSIZE(pPrior), nByte);
 1.16293 +  }
 1.16294 +  return p;
 1.16295 +#else
 1.16296 +  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
 1.16297 +  assert( pPrior!=0 && nByte>0 );
 1.16298 +  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
 1.16299 +  p--;
 1.16300 +  p = SQLITE_REALLOC(p, nByte+8 );
 1.16301 +  if( p ){
 1.16302 +    p[0] = nByte;
 1.16303 +    p++;
 1.16304 +  }else{
 1.16305 +    testcase( sqlite3GlobalConfig.xLog!=0 );
 1.16306 +    sqlite3_log(SQLITE_NOMEM,
 1.16307 +      "failed memory resize %u to %u bytes",
 1.16308 +      sqlite3MemSize(pPrior), nByte);
 1.16309 +  }
 1.16310 +  return (void*)p;
 1.16311 +#endif
 1.16312 +}
 1.16313 +
 1.16314 +/*
 1.16315 +** Round up a request size to the next valid allocation size.
 1.16316 +*/
 1.16317 +static int sqlite3MemRoundup(int n){
 1.16318 +  return ROUND8(n);
 1.16319 +}
 1.16320 +
 1.16321 +/*
 1.16322 +** Initialize this module.
 1.16323 +*/
 1.16324 +static int sqlite3MemInit(void *NotUsed){
 1.16325 +#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
 1.16326 +  int cpuCount;
 1.16327 +  size_t len;
 1.16328 +  if( _sqliteZone_ ){
 1.16329 +    return SQLITE_OK;
 1.16330 +  }
 1.16331 +  len = sizeof(cpuCount);
 1.16332 +  /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
 1.16333 +  sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
 1.16334 +  if( cpuCount>1 ){
 1.16335 +    /* defer MT decisions to system malloc */
 1.16336 +    _sqliteZone_ = malloc_default_zone();
 1.16337 +  }else{
 1.16338 +    /* only 1 core, use our own zone to contention over global locks, 
 1.16339 +    ** e.g. we have our own dedicated locks */
 1.16340 +    bool success;
 1.16341 +    malloc_zone_t* newzone = malloc_create_zone(4096, 0);
 1.16342 +    malloc_set_zone_name(newzone, "Sqlite_Heap");
 1.16343 +    do{
 1.16344 +      success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone, 
 1.16345 +                                 (void * volatile *)&_sqliteZone_);
 1.16346 +    }while(!_sqliteZone_);
 1.16347 +    if( !success ){
 1.16348 +      /* somebody registered a zone first */
 1.16349 +      malloc_destroy_zone(newzone);
 1.16350 +    }
 1.16351 +  }
 1.16352 +#endif
 1.16353 +  UNUSED_PARAMETER(NotUsed);
 1.16354 +  return SQLITE_OK;
 1.16355 +}
 1.16356 +
 1.16357 +/*
 1.16358 +** Deinitialize this module.
 1.16359 +*/
 1.16360 +static void sqlite3MemShutdown(void *NotUsed){
 1.16361 +  UNUSED_PARAMETER(NotUsed);
 1.16362 +  return;
 1.16363 +}
 1.16364 +
 1.16365 +/*
 1.16366 +** This routine is the only routine in this file with external linkage.
 1.16367 +**
 1.16368 +** Populate the low-level memory allocation function pointers in
 1.16369 +** sqlite3GlobalConfig.m with pointers to the routines in this file.
 1.16370 +*/
 1.16371 +SQLITE_PRIVATE void sqlite3MemSetDefault(void){
 1.16372 +  static const sqlite3_mem_methods defaultMethods = {
 1.16373 +     sqlite3MemMalloc,
 1.16374 +     sqlite3MemFree,
 1.16375 +     sqlite3MemRealloc,
 1.16376 +     sqlite3MemSize,
 1.16377 +     sqlite3MemRoundup,
 1.16378 +     sqlite3MemInit,
 1.16379 +     sqlite3MemShutdown,
 1.16380 +     0
 1.16381 +  };
 1.16382 +  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
 1.16383 +}
 1.16384 +
 1.16385 +#endif /* SQLITE_SYSTEM_MALLOC */
 1.16386 +
 1.16387 +/************** End of mem1.c ************************************************/
 1.16388 +/************** Begin file mem2.c ********************************************/
 1.16389 +/*
 1.16390 +** 2007 August 15
 1.16391 +**
 1.16392 +** The author disclaims copyright to this source code.  In place of
 1.16393 +** a legal notice, here is a blessing:
 1.16394 +**
 1.16395 +**    May you do good and not evil.
 1.16396 +**    May you find forgiveness for yourself and forgive others.
 1.16397 +**    May you share freely, never taking more than you give.
 1.16398 +**
 1.16399 +*************************************************************************
 1.16400 +**
 1.16401 +** This file contains low-level memory allocation drivers for when
 1.16402 +** SQLite will use the standard C-library malloc/realloc/free interface
 1.16403 +** to obtain the memory it needs while adding lots of additional debugging
 1.16404 +** information to each allocation in order to help detect and fix memory
 1.16405 +** leaks and memory usage errors.
 1.16406 +**
 1.16407 +** This file contains implementations of the low-level memory allocation
 1.16408 +** routines specified in the sqlite3_mem_methods object.
 1.16409 +*/
 1.16410 +
 1.16411 +/*
 1.16412 +** This version of the memory allocator is used only if the
 1.16413 +** SQLITE_MEMDEBUG macro is defined
 1.16414 +*/
 1.16415 +#ifdef SQLITE_MEMDEBUG
 1.16416 +
 1.16417 +/*
 1.16418 +** The backtrace functionality is only available with GLIBC
 1.16419 +*/
 1.16420 +#ifdef __GLIBC__
 1.16421 +  extern int backtrace(void**,int);
 1.16422 +  extern void backtrace_symbols_fd(void*const*,int,int);
 1.16423 +#else
 1.16424 +# define backtrace(A,B) 1
 1.16425 +# define backtrace_symbols_fd(A,B,C)
 1.16426 +#endif
 1.16427 +/* #include <stdio.h> */
 1.16428 +
 1.16429 +/*
 1.16430 +** Each memory allocation looks like this:
 1.16431 +**
 1.16432 +**  ------------------------------------------------------------------------
 1.16433 +**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
 1.16434 +**  ------------------------------------------------------------------------
 1.16435 +**
 1.16436 +** The application code sees only a pointer to the allocation.  We have
 1.16437 +** to back up from the allocation pointer to find the MemBlockHdr.  The
 1.16438 +** MemBlockHdr tells us the size of the allocation and the number of
 1.16439 +** backtrace pointers.  There is also a guard word at the end of the
 1.16440 +** MemBlockHdr.
 1.16441 +*/
 1.16442 +struct MemBlockHdr {
 1.16443 +  i64 iSize;                          /* Size of this allocation */
 1.16444 +  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
 1.16445 +  char nBacktrace;                    /* Number of backtraces on this alloc */
 1.16446 +  char nBacktraceSlots;               /* Available backtrace slots */
 1.16447 +  u8 nTitle;                          /* Bytes of title; includes '\0' */
 1.16448 +  u8 eType;                           /* Allocation type code */
 1.16449 +  int iForeGuard;                     /* Guard word for sanity */
 1.16450 +};
 1.16451 +
 1.16452 +/*
 1.16453 +** Guard words
 1.16454 +*/
 1.16455 +#define FOREGUARD 0x80F5E153
 1.16456 +#define REARGUARD 0xE4676B53
 1.16457 +
 1.16458 +/*
 1.16459 +** Number of malloc size increments to track.
 1.16460 +*/
 1.16461 +#define NCSIZE  1000
 1.16462 +
 1.16463 +/*
 1.16464 +** All of the static variables used by this module are collected
 1.16465 +** into a single structure named "mem".  This is to keep the
 1.16466 +** static variables organized and to reduce namespace pollution
 1.16467 +** when this module is combined with other in the amalgamation.
 1.16468 +*/
 1.16469 +static struct {
 1.16470 +  
 1.16471 +  /*
 1.16472 +  ** Mutex to control access to the memory allocation subsystem.
 1.16473 +  */
 1.16474 +  sqlite3_mutex *mutex;
 1.16475 +
 1.16476 +  /*
 1.16477 +  ** Head and tail of a linked list of all outstanding allocations
 1.16478 +  */
 1.16479 +  struct MemBlockHdr *pFirst;
 1.16480 +  struct MemBlockHdr *pLast;
 1.16481 +  
 1.16482 +  /*
 1.16483 +  ** The number of levels of backtrace to save in new allocations.
 1.16484 +  */
 1.16485 +  int nBacktrace;
 1.16486 +  void (*xBacktrace)(int, int, void **);
 1.16487 +
 1.16488 +  /*
 1.16489 +  ** Title text to insert in front of each block
 1.16490 +  */
 1.16491 +  int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
 1.16492 +  char zTitle[100];  /* The title text */
 1.16493 +
 1.16494 +  /* 
 1.16495 +  ** sqlite3MallocDisallow() increments the following counter.
 1.16496 +  ** sqlite3MallocAllow() decrements it.
 1.16497 +  */
 1.16498 +  int disallow; /* Do not allow memory allocation */
 1.16499 +
 1.16500 +  /*
 1.16501 +  ** Gather statistics on the sizes of memory allocations.
 1.16502 +  ** nAlloc[i] is the number of allocation attempts of i*8
 1.16503 +  ** bytes.  i==NCSIZE is the number of allocation attempts for
 1.16504 +  ** sizes more than NCSIZE*8 bytes.
 1.16505 +  */
 1.16506 +  int nAlloc[NCSIZE];      /* Total number of allocations */
 1.16507 +  int nCurrent[NCSIZE];    /* Current number of allocations */
 1.16508 +  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
 1.16509 +
 1.16510 +} mem;
 1.16511 +
 1.16512 +
 1.16513 +/*
 1.16514 +** Adjust memory usage statistics
 1.16515 +*/
 1.16516 +static void adjustStats(int iSize, int increment){
 1.16517 +  int i = ROUND8(iSize)/8;
 1.16518 +  if( i>NCSIZE-1 ){
 1.16519 +    i = NCSIZE - 1;
 1.16520 +  }
 1.16521 +  if( increment>0 ){
 1.16522 +    mem.nAlloc[i]++;
 1.16523 +    mem.nCurrent[i]++;
 1.16524 +    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
 1.16525 +      mem.mxCurrent[i] = mem.nCurrent[i];
 1.16526 +    }
 1.16527 +  }else{
 1.16528 +    mem.nCurrent[i]--;
 1.16529 +    assert( mem.nCurrent[i]>=0 );
 1.16530 +  }
 1.16531 +}
 1.16532 +
 1.16533 +/*
 1.16534 +** Given an allocation, find the MemBlockHdr for that allocation.
 1.16535 +**
 1.16536 +** This routine checks the guards at either end of the allocation and
 1.16537 +** if they are incorrect it asserts.
 1.16538 +*/
 1.16539 +static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
 1.16540 +  struct MemBlockHdr *p;
 1.16541 +  int *pInt;
 1.16542 +  u8 *pU8;
 1.16543 +  int nReserve;
 1.16544 +
 1.16545 +  p = (struct MemBlockHdr*)pAllocation;
 1.16546 +  p--;
 1.16547 +  assert( p->iForeGuard==(int)FOREGUARD );
 1.16548 +  nReserve = ROUND8(p->iSize);
 1.16549 +  pInt = (int*)pAllocation;
 1.16550 +  pU8 = (u8*)pAllocation;
 1.16551 +  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
 1.16552 +  /* This checks any of the "extra" bytes allocated due
 1.16553 +  ** to rounding up to an 8 byte boundary to ensure 
 1.16554 +  ** they haven't been overwritten.
 1.16555 +  */
 1.16556 +  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
 1.16557 +  return p;
 1.16558 +}
 1.16559 +
 1.16560 +/*
 1.16561 +** Return the number of bytes currently allocated at address p.
 1.16562 +*/
 1.16563 +static int sqlite3MemSize(void *p){
 1.16564 +  struct MemBlockHdr *pHdr;
 1.16565 +  if( !p ){
 1.16566 +    return 0;
 1.16567 +  }
 1.16568 +  pHdr = sqlite3MemsysGetHeader(p);
 1.16569 +  return (int)pHdr->iSize;
 1.16570 +}
 1.16571 +
 1.16572 +/*
 1.16573 +** Initialize the memory allocation subsystem.
 1.16574 +*/
 1.16575 +static int sqlite3MemInit(void *NotUsed){
 1.16576 +  UNUSED_PARAMETER(NotUsed);
 1.16577 +  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
 1.16578 +  if( !sqlite3GlobalConfig.bMemstat ){
 1.16579 +    /* If memory status is enabled, then the malloc.c wrapper will already
 1.16580 +    ** hold the STATIC_MEM mutex when the routines here are invoked. */
 1.16581 +    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
 1.16582 +  }
 1.16583 +  return SQLITE_OK;
 1.16584 +}
 1.16585 +
 1.16586 +/*
 1.16587 +** Deinitialize the memory allocation subsystem.
 1.16588 +*/
 1.16589 +static void sqlite3MemShutdown(void *NotUsed){
 1.16590 +  UNUSED_PARAMETER(NotUsed);
 1.16591 +  mem.mutex = 0;
 1.16592 +}
 1.16593 +
 1.16594 +/*
 1.16595 +** Round up a request size to the next valid allocation size.
 1.16596 +*/
 1.16597 +static int sqlite3MemRoundup(int n){
 1.16598 +  return ROUND8(n);
 1.16599 +}
 1.16600 +
 1.16601 +/*
 1.16602 +** Fill a buffer with pseudo-random bytes.  This is used to preset
 1.16603 +** the content of a new memory allocation to unpredictable values and
 1.16604 +** to clear the content of a freed allocation to unpredictable values.
 1.16605 +*/
 1.16606 +static void randomFill(char *pBuf, int nByte){
 1.16607 +  unsigned int x, y, r;
 1.16608 +  x = SQLITE_PTR_TO_INT(pBuf);
 1.16609 +  y = nByte | 1;
 1.16610 +  while( nByte >= 4 ){
 1.16611 +    x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
 1.16612 +    y = y*1103515245 + 12345;
 1.16613 +    r = x ^ y;
 1.16614 +    *(int*)pBuf = r;
 1.16615 +    pBuf += 4;
 1.16616 +    nByte -= 4;
 1.16617 +  }
 1.16618 +  while( nByte-- > 0 ){
 1.16619 +    x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
 1.16620 +    y = y*1103515245 + 12345;
 1.16621 +    r = x ^ y;
 1.16622 +    *(pBuf++) = r & 0xff;
 1.16623 +  }
 1.16624 +}
 1.16625 +
 1.16626 +/*
 1.16627 +** Allocate nByte bytes of memory.
 1.16628 +*/
 1.16629 +static void *sqlite3MemMalloc(int nByte){
 1.16630 +  struct MemBlockHdr *pHdr;
 1.16631 +  void **pBt;
 1.16632 +  char *z;
 1.16633 +  int *pInt;
 1.16634 +  void *p = 0;
 1.16635 +  int totalSize;
 1.16636 +  int nReserve;
 1.16637 +  sqlite3_mutex_enter(mem.mutex);
 1.16638 +  assert( mem.disallow==0 );
 1.16639 +  nReserve = ROUND8(nByte);
 1.16640 +  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
 1.16641 +               mem.nBacktrace*sizeof(void*) + mem.nTitle;
 1.16642 +  p = malloc(totalSize);
 1.16643 +  if( p ){
 1.16644 +    z = p;
 1.16645 +    pBt = (void**)&z[mem.nTitle];
 1.16646 +    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
 1.16647 +    pHdr->pNext = 0;
 1.16648 +    pHdr->pPrev = mem.pLast;
 1.16649 +    if( mem.pLast ){
 1.16650 +      mem.pLast->pNext = pHdr;
 1.16651 +    }else{
 1.16652 +      mem.pFirst = pHdr;
 1.16653 +    }
 1.16654 +    mem.pLast = pHdr;
 1.16655 +    pHdr->iForeGuard = FOREGUARD;
 1.16656 +    pHdr->eType = MEMTYPE_HEAP;
 1.16657 +    pHdr->nBacktraceSlots = mem.nBacktrace;
 1.16658 +    pHdr->nTitle = mem.nTitle;
 1.16659 +    if( mem.nBacktrace ){
 1.16660 +      void *aAddr[40];
 1.16661 +      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
 1.16662 +      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
 1.16663 +      assert(pBt[0]);
 1.16664 +      if( mem.xBacktrace ){
 1.16665 +        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
 1.16666 +      }
 1.16667 +    }else{
 1.16668 +      pHdr->nBacktrace = 0;
 1.16669 +    }
 1.16670 +    if( mem.nTitle ){
 1.16671 +      memcpy(z, mem.zTitle, mem.nTitle);
 1.16672 +    }
 1.16673 +    pHdr->iSize = nByte;
 1.16674 +    adjustStats(nByte, +1);
 1.16675 +    pInt = (int*)&pHdr[1];
 1.16676 +    pInt[nReserve/sizeof(int)] = REARGUARD;
 1.16677 +    randomFill((char*)pInt, nByte);
 1.16678 +    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
 1.16679 +    p = (void*)pInt;
 1.16680 +  }
 1.16681 +  sqlite3_mutex_leave(mem.mutex);
 1.16682 +  return p; 
 1.16683 +}
 1.16684 +
 1.16685 +/*
 1.16686 +** Free memory.
 1.16687 +*/
 1.16688 +static void sqlite3MemFree(void *pPrior){
 1.16689 +  struct MemBlockHdr *pHdr;
 1.16690 +  void **pBt;
 1.16691 +  char *z;
 1.16692 +  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
 1.16693 +       || mem.mutex!=0 );
 1.16694 +  pHdr = sqlite3MemsysGetHeader(pPrior);
 1.16695 +  pBt = (void**)pHdr;
 1.16696 +  pBt -= pHdr->nBacktraceSlots;
 1.16697 +  sqlite3_mutex_enter(mem.mutex);
 1.16698 +  if( pHdr->pPrev ){
 1.16699 +    assert( pHdr->pPrev->pNext==pHdr );
 1.16700 +    pHdr->pPrev->pNext = pHdr->pNext;
 1.16701 +  }else{
 1.16702 +    assert( mem.pFirst==pHdr );
 1.16703 +    mem.pFirst = pHdr->pNext;
 1.16704 +  }
 1.16705 +  if( pHdr->pNext ){
 1.16706 +    assert( pHdr->pNext->pPrev==pHdr );
 1.16707 +    pHdr->pNext->pPrev = pHdr->pPrev;
 1.16708 +  }else{
 1.16709 +    assert( mem.pLast==pHdr );
 1.16710 +    mem.pLast = pHdr->pPrev;
 1.16711 +  }
 1.16712 +  z = (char*)pBt;
 1.16713 +  z -= pHdr->nTitle;
 1.16714 +  adjustStats((int)pHdr->iSize, -1);
 1.16715 +  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
 1.16716 +                (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
 1.16717 +  free(z);
 1.16718 +  sqlite3_mutex_leave(mem.mutex);  
 1.16719 +}
 1.16720 +
 1.16721 +/*
 1.16722 +** Change the size of an existing memory allocation.
 1.16723 +**
 1.16724 +** For this debugging implementation, we *always* make a copy of the
 1.16725 +** allocation into a new place in memory.  In this way, if the 
 1.16726 +** higher level code is using pointer to the old allocation, it is 
 1.16727 +** much more likely to break and we are much more liking to find
 1.16728 +** the error.
 1.16729 +*/
 1.16730 +static void *sqlite3MemRealloc(void *pPrior, int nByte){
 1.16731 +  struct MemBlockHdr *pOldHdr;
 1.16732 +  void *pNew;
 1.16733 +  assert( mem.disallow==0 );
 1.16734 +  assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
 1.16735 +  pOldHdr = sqlite3MemsysGetHeader(pPrior);
 1.16736 +  pNew = sqlite3MemMalloc(nByte);
 1.16737 +  if( pNew ){
 1.16738 +    memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
 1.16739 +    if( nByte>pOldHdr->iSize ){
 1.16740 +      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
 1.16741 +    }
 1.16742 +    sqlite3MemFree(pPrior);
 1.16743 +  }
 1.16744 +  return pNew;
 1.16745 +}
 1.16746 +
 1.16747 +/*
 1.16748 +** Populate the low-level memory allocation function pointers in
 1.16749 +** sqlite3GlobalConfig.m with pointers to the routines in this file.
 1.16750 +*/
 1.16751 +SQLITE_PRIVATE void sqlite3MemSetDefault(void){
 1.16752 +  static const sqlite3_mem_methods defaultMethods = {
 1.16753 +     sqlite3MemMalloc,
 1.16754 +     sqlite3MemFree,
 1.16755 +     sqlite3MemRealloc,
 1.16756 +     sqlite3MemSize,
 1.16757 +     sqlite3MemRoundup,
 1.16758 +     sqlite3MemInit,
 1.16759 +     sqlite3MemShutdown,
 1.16760 +     0
 1.16761 +  };
 1.16762 +  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
 1.16763 +}
 1.16764 +
 1.16765 +/*
 1.16766 +** Set the "type" of an allocation.
 1.16767 +*/
 1.16768 +SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
 1.16769 +  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
 1.16770 +    struct MemBlockHdr *pHdr;
 1.16771 +    pHdr = sqlite3MemsysGetHeader(p);
 1.16772 +    assert( pHdr->iForeGuard==FOREGUARD );
 1.16773 +    pHdr->eType = eType;
 1.16774 +  }
 1.16775 +}
 1.16776 +
 1.16777 +/*
 1.16778 +** Return TRUE if the mask of type in eType matches the type of the
 1.16779 +** allocation p.  Also return true if p==NULL.
 1.16780 +**
 1.16781 +** This routine is designed for use within an assert() statement, to
 1.16782 +** verify the type of an allocation.  For example:
 1.16783 +**
 1.16784 +**     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
 1.16785 +*/
 1.16786 +SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
 1.16787 +  int rc = 1;
 1.16788 +  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
 1.16789 +    struct MemBlockHdr *pHdr;
 1.16790 +    pHdr = sqlite3MemsysGetHeader(p);
 1.16791 +    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
 1.16792 +    if( (pHdr->eType&eType)==0 ){
 1.16793 +      rc = 0;
 1.16794 +    }
 1.16795 +  }
 1.16796 +  return rc;
 1.16797 +}
 1.16798 +
 1.16799 +/*
 1.16800 +** Return TRUE if the mask of type in eType matches no bits of the type of the
 1.16801 +** allocation p.  Also return true if p==NULL.
 1.16802 +**
 1.16803 +** This routine is designed for use within an assert() statement, to
 1.16804 +** verify the type of an allocation.  For example:
 1.16805 +**
 1.16806 +**     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
 1.16807 +*/
 1.16808 +SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
 1.16809 +  int rc = 1;
 1.16810 +  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
 1.16811 +    struct MemBlockHdr *pHdr;
 1.16812 +    pHdr = sqlite3MemsysGetHeader(p);
 1.16813 +    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
 1.16814 +    if( (pHdr->eType&eType)!=0 ){
 1.16815 +      rc = 0;
 1.16816 +    }
 1.16817 +  }
 1.16818 +  return rc;
 1.16819 +}
 1.16820 +
 1.16821 +/*
 1.16822 +** Set the number of backtrace levels kept for each allocation.
 1.16823 +** A value of zero turns off backtracing.  The number is always rounded
 1.16824 +** up to a multiple of 2.
 1.16825 +*/
 1.16826 +SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
 1.16827 +  if( depth<0 ){ depth = 0; }
 1.16828 +  if( depth>20 ){ depth = 20; }
 1.16829 +  depth = (depth+1)&0xfe;
 1.16830 +  mem.nBacktrace = depth;
 1.16831 +}
 1.16832 +
 1.16833 +SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
 1.16834 +  mem.xBacktrace = xBacktrace;
 1.16835 +}
 1.16836 +
 1.16837 +/*
 1.16838 +** Set the title string for subsequent allocations.
 1.16839 +*/
 1.16840 +SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
 1.16841 +  unsigned int n = sqlite3Strlen30(zTitle) + 1;
 1.16842 +  sqlite3_mutex_enter(mem.mutex);
 1.16843 +  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
 1.16844 +  memcpy(mem.zTitle, zTitle, n);
 1.16845 +  mem.zTitle[n] = 0;
 1.16846 +  mem.nTitle = ROUND8(n);
 1.16847 +  sqlite3_mutex_leave(mem.mutex);
 1.16848 +}
 1.16849 +
 1.16850 +SQLITE_PRIVATE void sqlite3MemdebugSync(){
 1.16851 +  struct MemBlockHdr *pHdr;
 1.16852 +  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
 1.16853 +    void **pBt = (void**)pHdr;
 1.16854 +    pBt -= pHdr->nBacktraceSlots;
 1.16855 +    mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
 1.16856 +  }
 1.16857 +}
 1.16858 +
 1.16859 +/*
 1.16860 +** Open the file indicated and write a log of all unfreed memory 
 1.16861 +** allocations into that log.
 1.16862 +*/
 1.16863 +SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
 1.16864 +  FILE *out;
 1.16865 +  struct MemBlockHdr *pHdr;
 1.16866 +  void **pBt;
 1.16867 +  int i;
 1.16868 +  out = fopen(zFilename, "w");
 1.16869 +  if( out==0 ){
 1.16870 +    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
 1.16871 +                    zFilename);
 1.16872 +    return;
 1.16873 +  }
 1.16874 +  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
 1.16875 +    char *z = (char*)pHdr;
 1.16876 +    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
 1.16877 +    fprintf(out, "**** %lld bytes at %p from %s ****\n", 
 1.16878 +            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
 1.16879 +    if( pHdr->nBacktrace ){
 1.16880 +      fflush(out);
 1.16881 +      pBt = (void**)pHdr;
 1.16882 +      pBt -= pHdr->nBacktraceSlots;
 1.16883 +      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
 1.16884 +      fprintf(out, "\n");
 1.16885 +    }
 1.16886 +  }
 1.16887 +  fprintf(out, "COUNTS:\n");
 1.16888 +  for(i=0; i<NCSIZE-1; i++){
 1.16889 +    if( mem.nAlloc[i] ){
 1.16890 +      fprintf(out, "   %5d: %10d %10d %10d\n", 
 1.16891 +            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
 1.16892 +    }
 1.16893 +  }
 1.16894 +  if( mem.nAlloc[NCSIZE-1] ){
 1.16895 +    fprintf(out, "   %5d: %10d %10d %10d\n",
 1.16896 +             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
 1.16897 +             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
 1.16898 +  }
 1.16899 +  fclose(out);
 1.16900 +}
 1.16901 +
 1.16902 +/*
 1.16903 +** Return the number of times sqlite3MemMalloc() has been called.
 1.16904 +*/
 1.16905 +SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
 1.16906 +  int i;
 1.16907 +  int nTotal = 0;
 1.16908 +  for(i=0; i<NCSIZE; i++){
 1.16909 +    nTotal += mem.nAlloc[i];
 1.16910 +  }
 1.16911 +  return nTotal;
 1.16912 +}
 1.16913 +
 1.16914 +
 1.16915 +#endif /* SQLITE_MEMDEBUG */
 1.16916 +
 1.16917 +/************** End of mem2.c ************************************************/
 1.16918 +/************** Begin file mem3.c ********************************************/
 1.16919 +/*
 1.16920 +** 2007 October 14
 1.16921 +**
 1.16922 +** The author disclaims copyright to this source code.  In place of
 1.16923 +** a legal notice, here is a blessing:
 1.16924 +**
 1.16925 +**    May you do good and not evil.
 1.16926 +**    May you find forgiveness for yourself and forgive others.
 1.16927 +**    May you share freely, never taking more than you give.
 1.16928 +**
 1.16929 +*************************************************************************
 1.16930 +** This file contains the C functions that implement a memory
 1.16931 +** allocation subsystem for use by SQLite. 
 1.16932 +**
 1.16933 +** This version of the memory allocation subsystem omits all
 1.16934 +** use of malloc(). The SQLite user supplies a block of memory
 1.16935 +** before calling sqlite3_initialize() from which allocations
 1.16936 +** are made and returned by the xMalloc() and xRealloc() 
 1.16937 +** implementations. Once sqlite3_initialize() has been called,
 1.16938 +** the amount of memory available to SQLite is fixed and cannot
 1.16939 +** be changed.
 1.16940 +**
 1.16941 +** This version of the memory allocation subsystem is included
 1.16942 +** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
 1.16943 +*/
 1.16944 +
 1.16945 +/*
 1.16946 +** This version of the memory allocator is only built into the library
 1.16947 +** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
 1.16948 +** mean that the library will use a memory-pool by default, just that
 1.16949 +** it is available. The mempool allocator is activated by calling
 1.16950 +** sqlite3_config().
 1.16951 +*/
 1.16952 +#ifdef SQLITE_ENABLE_MEMSYS3
 1.16953 +
 1.16954 +/*
 1.16955 +** Maximum size (in Mem3Blocks) of a "small" chunk.
 1.16956 +*/
 1.16957 +#define MX_SMALL 10
 1.16958 +
 1.16959 +
 1.16960 +/*
 1.16961 +** Number of freelist hash slots
 1.16962 +*/
 1.16963 +#define N_HASH  61
 1.16964 +
 1.16965 +/*
 1.16966 +** A memory allocation (also called a "chunk") consists of two or 
 1.16967 +** more blocks where each block is 8 bytes.  The first 8 bytes are 
 1.16968 +** a header that is not returned to the user.
 1.16969 +**
 1.16970 +** A chunk is two or more blocks that is either checked out or
 1.16971 +** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
 1.16972 +** size of the allocation in blocks if the allocation is free.
 1.16973 +** The u.hdr.size4x&1 bit is true if the chunk is checked out and
 1.16974 +** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
 1.16975 +** is true if the previous chunk is checked out and false if the
 1.16976 +** previous chunk is free.  The u.hdr.prevSize field is the size of
 1.16977 +** the previous chunk in blocks if the previous chunk is on the
 1.16978 +** freelist. If the previous chunk is checked out, then
 1.16979 +** u.hdr.prevSize can be part of the data for that chunk and should
 1.16980 +** not be read or written.
 1.16981 +**
 1.16982 +** We often identify a chunk by its index in mem3.aPool[].  When
 1.16983 +** this is done, the chunk index refers to the second block of
 1.16984 +** the chunk.  In this way, the first chunk has an index of 1.
 1.16985 +** A chunk index of 0 means "no such chunk" and is the equivalent
 1.16986 +** of a NULL pointer.
 1.16987 +**
 1.16988 +** The second block of free chunks is of the form u.list.  The
 1.16989 +** two fields form a double-linked list of chunks of related sizes.
 1.16990 +** Pointers to the head of the list are stored in mem3.aiSmall[] 
 1.16991 +** for smaller chunks and mem3.aiHash[] for larger chunks.
 1.16992 +**
 1.16993 +** The second block of a chunk is user data if the chunk is checked 
 1.16994 +** out.  If a chunk is checked out, the user data may extend into
 1.16995 +** the u.hdr.prevSize value of the following chunk.
 1.16996 +*/
 1.16997 +typedef struct Mem3Block Mem3Block;
 1.16998 +struct Mem3Block {
 1.16999 +  union {
 1.17000 +    struct {
 1.17001 +      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
 1.17002 +      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
 1.17003 +    } hdr;
 1.17004 +    struct {
 1.17005 +      u32 next;       /* Index in mem3.aPool[] of next free chunk */
 1.17006 +      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
 1.17007 +    } list;
 1.17008 +  } u;
 1.17009 +};
 1.17010 +
 1.17011 +/*
 1.17012 +** All of the static variables used by this module are collected
 1.17013 +** into a single structure named "mem3".  This is to keep the
 1.17014 +** static variables organized and to reduce namespace pollution
 1.17015 +** when this module is combined with other in the amalgamation.
 1.17016 +*/
 1.17017 +static SQLITE_WSD struct Mem3Global {
 1.17018 +  /*
 1.17019 +  ** Memory available for allocation. nPool is the size of the array
 1.17020 +  ** (in Mem3Blocks) pointed to by aPool less 2.
 1.17021 +  */
 1.17022 +  u32 nPool;
 1.17023 +  Mem3Block *aPool;
 1.17024 +
 1.17025 +  /*
 1.17026 +  ** True if we are evaluating an out-of-memory callback.
 1.17027 +  */
 1.17028 +  int alarmBusy;
 1.17029 +  
 1.17030 +  /*
 1.17031 +  ** Mutex to control access to the memory allocation subsystem.
 1.17032 +  */
 1.17033 +  sqlite3_mutex *mutex;
 1.17034 +  
 1.17035 +  /*
 1.17036 +  ** The minimum amount of free space that we have seen.
 1.17037 +  */
 1.17038 +  u32 mnMaster;
 1.17039 +
 1.17040 +  /*
 1.17041 +  ** iMaster is the index of the master chunk.  Most new allocations
 1.17042 +  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
 1.17043 +  ** of the current master.  iMaster is 0 if there is not master chunk.
 1.17044 +  ** The master chunk is not in either the aiHash[] or aiSmall[].
 1.17045 +  */
 1.17046 +  u32 iMaster;
 1.17047 +  u32 szMaster;
 1.17048 +
 1.17049 +  /*
 1.17050 +  ** Array of lists of free blocks according to the block size 
 1.17051 +  ** for smaller chunks, or a hash on the block size for larger
 1.17052 +  ** chunks.
 1.17053 +  */
 1.17054 +  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
 1.17055 +  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
 1.17056 +} mem3 = { 97535575 };
 1.17057 +
 1.17058 +#define mem3 GLOBAL(struct Mem3Global, mem3)
 1.17059 +
 1.17060 +/*
 1.17061 +** Unlink the chunk at mem3.aPool[i] from list it is currently
 1.17062 +** on.  *pRoot is the list that i is a member of.
 1.17063 +*/
 1.17064 +static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
 1.17065 +  u32 next = mem3.aPool[i].u.list.next;
 1.17066 +  u32 prev = mem3.aPool[i].u.list.prev;
 1.17067 +  assert( sqlite3_mutex_held(mem3.mutex) );
 1.17068 +  if( prev==0 ){
 1.17069 +    *pRoot = next;
 1.17070 +  }else{
 1.17071 +    mem3.aPool[prev].u.list.next = next;
 1.17072 +  }
 1.17073 +  if( next ){
 1.17074 +    mem3.aPool[next].u.list.prev = prev;
 1.17075 +  }
 1.17076 +  mem3.aPool[i].u.list.next = 0;
 1.17077 +  mem3.aPool[i].u.list.prev = 0;
 1.17078 +}
 1.17079 +
 1.17080 +/*
 1.17081 +** Unlink the chunk at index i from 
 1.17082 +** whatever list is currently a member of.
 1.17083 +*/
 1.17084 +static void memsys3Unlink(u32 i){
 1.17085 +  u32 size, hash;
 1.17086 +  assert( sqlite3_mutex_held(mem3.mutex) );
 1.17087 +  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
 1.17088 +  assert( i>=1 );
 1.17089 +  size = mem3.aPool[i-1].u.hdr.size4x/4;
 1.17090 +  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
 1.17091 +  assert( size>=2 );
 1.17092 +  if( size <= MX_SMALL ){
 1.17093 +    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
 1.17094 +  }else{
 1.17095 +    hash = size % N_HASH;
 1.17096 +    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
 1.17097 +  }
 1.17098 +}
 1.17099 +
 1.17100 +/*
 1.17101 +** Link the chunk at mem3.aPool[i] so that is on the list rooted
 1.17102 +** at *pRoot.
 1.17103 +*/
 1.17104 +static void memsys3LinkIntoList(u32 i, u32 *pRoot){
 1.17105 +  assert( sqlite3_mutex_held(mem3.mutex) );
 1.17106 +  mem3.aPool[i].u.list.next = *pRoot;
 1.17107 +  mem3.aPool[i].u.list.prev = 0;
 1.17108 +  if( *pRoot ){
 1.17109 +    mem3.aPool[*pRoot].u.list.prev = i;
 1.17110 +  }
 1.17111 +  *pRoot = i;
 1.17112 +}
 1.17113 +
 1.17114 +/*
 1.17115 +** Link the chunk at index i into either the appropriate
 1.17116 +** small chunk list, or into the large chunk hash table.
 1.17117 +*/
 1.17118 +static void memsys3Link(u32 i){
 1.17119 +  u32 size, hash;
 1.17120 +  assert( sqlite3_mutex_held(mem3.mutex) );
 1.17121 +  assert( i>=1 );
 1.17122 +  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
 1.17123 +  size = mem3.aPool[i-1].u.hdr.size4x/4;
 1.17124 +  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
 1.17125 +  assert( size>=2 );
 1.17126 +  if( size <= MX_SMALL ){
 1.17127 +    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
 1.17128 +  }else{
 1.17129 +    hash = size % N_HASH;
 1.17130 +    memsys3LinkIntoList(i, &mem3.aiHash[hash]);
 1.17131 +  }
 1.17132 +}
 1.17133 +
 1.17134 +/*
 1.17135 +** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
 1.17136 +** will already be held (obtained by code in malloc.c) if
 1.17137 +** sqlite3GlobalConfig.bMemStat is true.
 1.17138 +*/
 1.17139 +static void memsys3Enter(void){
 1.17140 +  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
 1.17141 +    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
 1.17142 +  }
 1.17143 +  sqlite3_mutex_enter(mem3.mutex);
 1.17144 +}
 1.17145 +static void memsys3Leave(void){
 1.17146 +  sqlite3_mutex_leave(mem3.mutex);
 1.17147 +}
 1.17148 +
 1.17149 +/*
 1.17150 +** Called when we are unable to satisfy an allocation of nBytes.
 1.17151 +*/
 1.17152 +static void memsys3OutOfMemory(int nByte){
 1.17153 +  if( !mem3.alarmBusy ){
 1.17154 +    mem3.alarmBusy = 1;
 1.17155 +    assert( sqlite3_mutex_held(mem3.mutex) );
 1.17156 +    sqlite3_mutex_leave(mem3.mutex);
 1.17157 +    sqlite3_release_memory(nByte);
 1.17158 +    sqlite3_mutex_enter(mem3.mutex);
 1.17159 +    mem3.alarmBusy = 0;
 1.17160 +  }
 1.17161 +}
 1.17162 +
 1.17163 +
 1.17164 +/*
 1.17165 +** Chunk i is a free chunk that has been unlinked.  Adjust its 
 1.17166 +** size parameters for check-out and return a pointer to the 
 1.17167 +** user portion of the chunk.
 1.17168 +*/
 1.17169 +static void *memsys3Checkout(u32 i, u32 nBlock){
 1.17170 +  u32 x;
 1.17171 +  assert( sqlite3_mutex_held(mem3.mutex) );
 1.17172 +  assert( i>=1 );
 1.17173 +  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
 1.17174 +  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
 1.17175 +  x = mem3.aPool[i-1].u.hdr.size4x;
 1.17176 +  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
 1.17177 +  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
 1.17178 +  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
 1.17179 +  return &mem3.aPool[i];
 1.17180 +}
 1.17181 +
 1.17182 +/*
 1.17183 +** Carve a piece off of the end of the mem3.iMaster free chunk.
 1.17184 +** Return a pointer to the new allocation.  Or, if the master chunk
 1.17185 +** is not large enough, return 0.
 1.17186 +*/
 1.17187 +static void *memsys3FromMaster(u32 nBlock){
 1.17188 +  assert( sqlite3_mutex_held(mem3.mutex) );
 1.17189 +  assert( mem3.szMaster>=nBlock );
 1.17190 +  if( nBlock>=mem3.szMaster-1 ){
 1.17191 +    /* Use the entire master */
 1.17192 +    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
 1.17193 +    mem3.iMaster = 0;
 1.17194 +    mem3.szMaster = 0;
 1.17195 +    mem3.mnMaster = 0;
 1.17196 +    return p;
 1.17197 +  }else{
 1.17198 +    /* Split the master block.  Return the tail. */
 1.17199 +    u32 newi, x;
 1.17200 +    newi = mem3.iMaster + mem3.szMaster - nBlock;
 1.17201 +    assert( newi > mem3.iMaster+1 );
 1.17202 +    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
 1.17203 +    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
 1.17204 +    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
 1.17205 +    mem3.szMaster -= nBlock;
 1.17206 +    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
 1.17207 +    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
 1.17208 +    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
 1.17209 +    if( mem3.szMaster < mem3.mnMaster ){
 1.17210 +      mem3.mnMaster = mem3.szMaster;
 1.17211 +    }
 1.17212 +    return (void*)&mem3.aPool[newi];
 1.17213 +  }
 1.17214 +}
 1.17215 +
 1.17216 +/*
 1.17217 +** *pRoot is the head of a list of free chunks of the same size
 1.17218 +** or same size hash.  In other words, *pRoot is an entry in either
 1.17219 +** mem3.aiSmall[] or mem3.aiHash[].  
 1.17220 +**
 1.17221 +** This routine examines all entries on the given list and tries
 1.17222 +** to coalesce each entries with adjacent free chunks.  
 1.17223 +**
 1.17224 +** If it sees a chunk that is larger than mem3.iMaster, it replaces 
 1.17225 +** the current mem3.iMaster with the new larger chunk.  In order for
 1.17226 +** this mem3.iMaster replacement to work, the master chunk must be
 1.17227 +** linked into the hash tables.  That is not the normal state of
 1.17228 +** affairs, of course.  The calling routine must link the master
 1.17229 +** chunk before invoking this routine, then must unlink the (possibly
 1.17230 +** changed) master chunk once this routine has finished.
 1.17231 +*/
 1.17232 +static void memsys3Merge(u32 *pRoot){
 1.17233 +  u32 iNext, prev, size, i, x;
 1.17234 +
 1.17235 +  assert( sqlite3_mutex_held(mem3.mutex) );
 1.17236 +  for(i=*pRoot; i>0; i=iNext){
 1.17237 +    iNext = mem3.aPool[i].u.list.next;
 1.17238 +    size = mem3.aPool[i-1].u.hdr.size4x;
 1.17239 +    assert( (size&1)==0 );
 1.17240 +    if( (size&2)==0 ){
 1.17241 +      memsys3UnlinkFromList(i, pRoot);
 1.17242 +      assert( i > mem3.aPool[i-1].u.hdr.prevSize );
 1.17243 +      prev = i - mem3.aPool[i-1].u.hdr.prevSize;
 1.17244 +      if( prev==iNext ){
 1.17245 +        iNext = mem3.aPool[prev].u.list.next;
 1.17246 +      }
 1.17247 +      memsys3Unlink(prev);
 1.17248 +      size = i + size/4 - prev;
 1.17249 +      x = mem3.aPool[prev-1].u.hdr.size4x & 2;
 1.17250 +      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
 1.17251 +      mem3.aPool[prev+size-1].u.hdr.prevSize = size;
 1.17252 +      memsys3Link(prev);
 1.17253 +      i = prev;
 1.17254 +    }else{
 1.17255 +      size /= 4;
 1.17256 +    }
 1.17257 +    if( size>mem3.szMaster ){
 1.17258 +      mem3.iMaster = i;
 1.17259 +      mem3.szMaster = size;
 1.17260 +    }
 1.17261 +  }
 1.17262 +}
 1.17263 +
 1.17264 +/*
 1.17265 +** Return a block of memory of at least nBytes in size.
 1.17266 +** Return NULL if unable.
 1.17267 +**
 1.17268 +** This function assumes that the necessary mutexes, if any, are
 1.17269 +** already held by the caller. Hence "Unsafe".
 1.17270 +*/
 1.17271 +static void *memsys3MallocUnsafe(int nByte){
 1.17272 +  u32 i;
 1.17273 +  u32 nBlock;
 1.17274 +  u32 toFree;
 1.17275 +
 1.17276 +  assert( sqlite3_mutex_held(mem3.mutex) );
 1.17277 +  assert( sizeof(Mem3Block)==8 );
 1.17278 +  if( nByte<=12 ){
 1.17279 +    nBlock = 2;
 1.17280 +  }else{
 1.17281 +    nBlock = (nByte + 11)/8;
 1.17282 +  }
 1.17283 +  assert( nBlock>=2 );
 1.17284 +
 1.17285 +  /* STEP 1:
 1.17286 +  ** Look for an entry of the correct size in either the small
 1.17287 +  ** chunk table or in the large chunk hash table.  This is
 1.17288 +  ** successful most of the time (about 9 times out of 10).
 1.17289 +  */
 1.17290 +  if( nBlock <= MX_SMALL ){
 1.17291 +    i = mem3.aiSmall[nBlock-2];
 1.17292 +    if( i>0 ){
 1.17293 +      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
 1.17294 +      return memsys3Checkout(i, nBlock);
 1.17295 +    }
 1.17296 +  }else{
 1.17297 +    int hash = nBlock % N_HASH;
 1.17298 +    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
 1.17299 +      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
 1.17300 +        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
 1.17301 +        return memsys3Checkout(i, nBlock);
 1.17302 +      }
 1.17303 +    }
 1.17304 +  }
 1.17305 +
 1.17306 +  /* STEP 2:
 1.17307 +  ** Try to satisfy the allocation by carving a piece off of the end
 1.17308 +  ** of the master chunk.  This step usually works if step 1 fails.
 1.17309 +  */
 1.17310 +  if( mem3.szMaster>=nBlock ){
 1.17311 +    return memsys3FromMaster(nBlock);
 1.17312 +  }
 1.17313 +
 1.17314 +
 1.17315 +  /* STEP 3:  
 1.17316 +  ** Loop through the entire memory pool.  Coalesce adjacent free
 1.17317 +  ** chunks.  Recompute the master chunk as the largest free chunk.
 1.17318 +  ** Then try again to satisfy the allocation by carving a piece off
 1.17319 +  ** of the end of the master chunk.  This step happens very
 1.17320 +  ** rarely (we hope!)
 1.17321 +  */
 1.17322 +  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
 1.17323 +    memsys3OutOfMemory(toFree);
 1.17324 +    if( mem3.iMaster ){
 1.17325 +      memsys3Link(mem3.iMaster);
 1.17326 +      mem3.iMaster = 0;
 1.17327 +      mem3.szMaster = 0;
 1.17328 +    }
 1.17329 +    for(i=0; i<N_HASH; i++){
 1.17330 +      memsys3Merge(&mem3.aiHash[i]);
 1.17331 +    }
 1.17332 +    for(i=0; i<MX_SMALL-1; i++){
 1.17333 +      memsys3Merge(&mem3.aiSmall[i]);
 1.17334 +    }
 1.17335 +    if( mem3.szMaster ){
 1.17336 +      memsys3Unlink(mem3.iMaster);
 1.17337 +      if( mem3.szMaster>=nBlock ){
 1.17338 +        return memsys3FromMaster(nBlock);
 1.17339 +      }
 1.17340 +    }
 1.17341 +  }
 1.17342 +
 1.17343 +  /* If none of the above worked, then we fail. */
 1.17344 +  return 0;
 1.17345 +}
 1.17346 +
 1.17347 +/*
 1.17348 +** Free an outstanding memory allocation.
 1.17349 +**
 1.17350 +** This function assumes that the necessary mutexes, if any, are
 1.17351 +** already held by the caller. Hence "Unsafe".
 1.17352 +*/
 1.17353 +static void memsys3FreeUnsafe(void *pOld){
 1.17354 +  Mem3Block *p = (Mem3Block*)pOld;
 1.17355 +  int i;
 1.17356 +  u32 size, x;
 1.17357 +  assert( sqlite3_mutex_held(mem3.mutex) );
 1.17358 +  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
 1.17359 +  i = p - mem3.aPool;
 1.17360 +  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
 1.17361 +  size = mem3.aPool[i-1].u.hdr.size4x/4;
 1.17362 +  assert( i+size<=mem3.nPool+1 );
 1.17363 +  mem3.aPool[i-1].u.hdr.size4x &= ~1;
 1.17364 +  mem3.aPool[i+size-1].u.hdr.prevSize = size;
 1.17365 +  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
 1.17366 +  memsys3Link(i);
 1.17367 +
 1.17368 +  /* Try to expand the master using the newly freed chunk */
 1.17369 +  if( mem3.iMaster ){
 1.17370 +    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
 1.17371 +      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
 1.17372 +      mem3.iMaster -= size;
 1.17373 +      mem3.szMaster += size;
 1.17374 +      memsys3Unlink(mem3.iMaster);
 1.17375 +      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
 1.17376 +      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
 1.17377 +      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
 1.17378 +    }
 1.17379 +    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
 1.17380 +    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
 1.17381 +      memsys3Unlink(mem3.iMaster+mem3.szMaster);
 1.17382 +      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
 1.17383 +      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
 1.17384 +      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
 1.17385 +    }
 1.17386 +  }
 1.17387 +}
 1.17388 +
 1.17389 +/*
 1.17390 +** Return the size of an outstanding allocation, in bytes.  The
 1.17391 +** size returned omits the 8-byte header overhead.  This only
 1.17392 +** works for chunks that are currently checked out.
 1.17393 +*/
 1.17394 +static int memsys3Size(void *p){
 1.17395 +  Mem3Block *pBlock;
 1.17396 +  if( p==0 ) return 0;
 1.17397 +  pBlock = (Mem3Block*)p;
 1.17398 +  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
 1.17399 +  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
 1.17400 +}
 1.17401 +
 1.17402 +/*
 1.17403 +** Round up a request size to the next valid allocation size.
 1.17404 +*/
 1.17405 +static int memsys3Roundup(int n){
 1.17406 +  if( n<=12 ){
 1.17407 +    return 12;
 1.17408 +  }else{
 1.17409 +    return ((n+11)&~7) - 4;
 1.17410 +  }
 1.17411 +}
 1.17412 +
 1.17413 +/*
 1.17414 +** Allocate nBytes of memory.
 1.17415 +*/
 1.17416 +static void *memsys3Malloc(int nBytes){
 1.17417 +  sqlite3_int64 *p;
 1.17418 +  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
 1.17419 +  memsys3Enter();
 1.17420 +  p = memsys3MallocUnsafe(nBytes);
 1.17421 +  memsys3Leave();
 1.17422 +  return (void*)p; 
 1.17423 +}
 1.17424 +
 1.17425 +/*
 1.17426 +** Free memory.
 1.17427 +*/
 1.17428 +static void memsys3Free(void *pPrior){
 1.17429 +  assert( pPrior );
 1.17430 +  memsys3Enter();
 1.17431 +  memsys3FreeUnsafe(pPrior);
 1.17432 +  memsys3Leave();
 1.17433 +}
 1.17434 +
 1.17435 +/*
 1.17436 +** Change the size of an existing memory allocation
 1.17437 +*/
 1.17438 +static void *memsys3Realloc(void *pPrior, int nBytes){
 1.17439 +  int nOld;
 1.17440 +  void *p;
 1.17441 +  if( pPrior==0 ){
 1.17442 +    return sqlite3_malloc(nBytes);
 1.17443 +  }
 1.17444 +  if( nBytes<=0 ){
 1.17445 +    sqlite3_free(pPrior);
 1.17446 +    return 0;
 1.17447 +  }
 1.17448 +  nOld = memsys3Size(pPrior);
 1.17449 +  if( nBytes<=nOld && nBytes>=nOld-128 ){
 1.17450 +    return pPrior;
 1.17451 +  }
 1.17452 +  memsys3Enter();
 1.17453 +  p = memsys3MallocUnsafe(nBytes);
 1.17454 +  if( p ){
 1.17455 +    if( nOld<nBytes ){
 1.17456 +      memcpy(p, pPrior, nOld);
 1.17457 +    }else{
 1.17458 +      memcpy(p, pPrior, nBytes);
 1.17459 +    }
 1.17460 +    memsys3FreeUnsafe(pPrior);
 1.17461 +  }
 1.17462 +  memsys3Leave();
 1.17463 +  return p;
 1.17464 +}
 1.17465 +
 1.17466 +/*
 1.17467 +** Initialize this module.
 1.17468 +*/
 1.17469 +static int memsys3Init(void *NotUsed){
 1.17470 +  UNUSED_PARAMETER(NotUsed);
 1.17471 +  if( !sqlite3GlobalConfig.pHeap ){
 1.17472 +    return SQLITE_ERROR;
 1.17473 +  }
 1.17474 +
 1.17475 +  /* Store a pointer to the memory block in global structure mem3. */
 1.17476 +  assert( sizeof(Mem3Block)==8 );
 1.17477 +  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
 1.17478 +  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
 1.17479 +
 1.17480 +  /* Initialize the master block. */
 1.17481 +  mem3.szMaster = mem3.nPool;
 1.17482 +  mem3.mnMaster = mem3.szMaster;
 1.17483 +  mem3.iMaster = 1;
 1.17484 +  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
 1.17485 +  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
 1.17486 +  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
 1.17487 +
 1.17488 +  return SQLITE_OK;
 1.17489 +}
 1.17490 +
 1.17491 +/*
 1.17492 +** Deinitialize this module.
 1.17493 +*/
 1.17494 +static void memsys3Shutdown(void *NotUsed){
 1.17495 +  UNUSED_PARAMETER(NotUsed);
 1.17496 +  mem3.mutex = 0;
 1.17497 +  return;
 1.17498 +}
 1.17499 +
 1.17500 +
 1.17501 +
 1.17502 +/*
 1.17503 +** Open the file indicated and write a log of all unfreed memory 
 1.17504 +** allocations into that log.
 1.17505 +*/
 1.17506 +SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
 1.17507 +#ifdef SQLITE_DEBUG
 1.17508 +  FILE *out;
 1.17509 +  u32 i, j;
 1.17510 +  u32 size;
 1.17511 +  if( zFilename==0 || zFilename[0]==0 ){
 1.17512 +    out = stdout;
 1.17513 +  }else{
 1.17514 +    out = fopen(zFilename, "w");
 1.17515 +    if( out==0 ){
 1.17516 +      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
 1.17517 +                      zFilename);
 1.17518 +      return;
 1.17519 +    }
 1.17520 +  }
 1.17521 +  memsys3Enter();
 1.17522 +  fprintf(out, "CHUNKS:\n");
 1.17523 +  for(i=1; i<=mem3.nPool; i+=size/4){
 1.17524 +    size = mem3.aPool[i-1].u.hdr.size4x;
 1.17525 +    if( size/4<=1 ){
 1.17526 +      fprintf(out, "%p size error\n", &mem3.aPool[i]);
 1.17527 +      assert( 0 );
 1.17528 +      break;
 1.17529 +    }
 1.17530 +    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
 1.17531 +      fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
 1.17532 +      assert( 0 );
 1.17533 +      break;
 1.17534 +    }
 1.17535 +    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
 1.17536 +      fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
 1.17537 +      assert( 0 );
 1.17538 +      break;
 1.17539 +    }
 1.17540 +    if( size&1 ){
 1.17541 +      fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
 1.17542 +    }else{
 1.17543 +      fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
 1.17544 +                  i==mem3.iMaster ? " **master**" : "");
 1.17545 +    }
 1.17546 +  }
 1.17547 +  for(i=0; i<MX_SMALL-1; i++){
 1.17548 +    if( mem3.aiSmall[i]==0 ) continue;
 1.17549 +    fprintf(out, "small(%2d):", i);
 1.17550 +    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
 1.17551 +      fprintf(out, " %p(%d)", &mem3.aPool[j],
 1.17552 +              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
 1.17553 +    }
 1.17554 +    fprintf(out, "\n"); 
 1.17555 +  }
 1.17556 +  for(i=0; i<N_HASH; i++){
 1.17557 +    if( mem3.aiHash[i]==0 ) continue;
 1.17558 +    fprintf(out, "hash(%2d):", i);
 1.17559 +    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
 1.17560 +      fprintf(out, " %p(%d)", &mem3.aPool[j],
 1.17561 +              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
 1.17562 +    }
 1.17563 +    fprintf(out, "\n"); 
 1.17564 +  }
 1.17565 +  fprintf(out, "master=%d\n", mem3.iMaster);
 1.17566 +  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
 1.17567 +  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
 1.17568 +  sqlite3_mutex_leave(mem3.mutex);
 1.17569 +  if( out==stdout ){
 1.17570 +    fflush(stdout);
 1.17571 +  }else{
 1.17572 +    fclose(out);
 1.17573 +  }
 1.17574 +#else
 1.17575 +  UNUSED_PARAMETER(zFilename);
 1.17576 +#endif
 1.17577 +}
 1.17578 +
 1.17579 +/*
 1.17580 +** This routine is the only routine in this file with external 
 1.17581 +** linkage.
 1.17582 +**
 1.17583 +** Populate the low-level memory allocation function pointers in
 1.17584 +** sqlite3GlobalConfig.m with pointers to the routines in this file. The
 1.17585 +** arguments specify the block of memory to manage.
 1.17586 +**
 1.17587 +** This routine is only called by sqlite3_config(), and therefore
 1.17588 +** is not required to be threadsafe (it is not).
 1.17589 +*/
 1.17590 +SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
 1.17591 +  static const sqlite3_mem_methods mempoolMethods = {
 1.17592 +     memsys3Malloc,
 1.17593 +     memsys3Free,
 1.17594 +     memsys3Realloc,
 1.17595 +     memsys3Size,
 1.17596 +     memsys3Roundup,
 1.17597 +     memsys3Init,
 1.17598 +     memsys3Shutdown,
 1.17599 +     0
 1.17600 +  };
 1.17601 +  return &mempoolMethods;
 1.17602 +}
 1.17603 +
 1.17604 +#endif /* SQLITE_ENABLE_MEMSYS3 */
 1.17605 +
 1.17606 +/************** End of mem3.c ************************************************/
 1.17607 +/************** Begin file mem5.c ********************************************/
 1.17608 +/*
 1.17609 +** 2007 October 14
 1.17610 +**
 1.17611 +** The author disclaims copyright to this source code.  In place of
 1.17612 +** a legal notice, here is a blessing:
 1.17613 +**
 1.17614 +**    May you do good and not evil.
 1.17615 +**    May you find forgiveness for yourself and forgive others.
 1.17616 +**    May you share freely, never taking more than you give.
 1.17617 +**
 1.17618 +*************************************************************************
 1.17619 +** This file contains the C functions that implement a memory
 1.17620 +** allocation subsystem for use by SQLite. 
 1.17621 +**
 1.17622 +** This version of the memory allocation subsystem omits all
 1.17623 +** use of malloc(). The application gives SQLite a block of memory
 1.17624 +** before calling sqlite3_initialize() from which allocations
 1.17625 +** are made and returned by the xMalloc() and xRealloc() 
 1.17626 +** implementations. Once sqlite3_initialize() has been called,
 1.17627 +** the amount of memory available to SQLite is fixed and cannot
 1.17628 +** be changed.
 1.17629 +**
 1.17630 +** This version of the memory allocation subsystem is included
 1.17631 +** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
 1.17632 +**
 1.17633 +** This memory allocator uses the following algorithm:
 1.17634 +**
 1.17635 +**   1.  All memory allocations sizes are rounded up to a power of 2.
 1.17636 +**
 1.17637 +**   2.  If two adjacent free blocks are the halves of a larger block,
 1.17638 +**       then the two blocks are coalesed into the single larger block.
 1.17639 +**
 1.17640 +**   3.  New memory is allocated from the first available free block.
 1.17641 +**
 1.17642 +** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
 1.17643 +** Concerning Dynamic Storage Allocation". Journal of the Association for
 1.17644 +** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
 1.17645 +** 
 1.17646 +** Let n be the size of the largest allocation divided by the minimum
 1.17647 +** allocation size (after rounding all sizes up to a power of 2.)  Let M
 1.17648 +** be the maximum amount of memory ever outstanding at one time.  Let
 1.17649 +** N be the total amount of memory available for allocation.  Robson
 1.17650 +** proved that this memory allocator will never breakdown due to 
 1.17651 +** fragmentation as long as the following constraint holds:
 1.17652 +**
 1.17653 +**      N >=  M*(1 + log2(n)/2) - n + 1
 1.17654 +**
 1.17655 +** The sqlite3_status() logic tracks the maximum values of n and M so
 1.17656 +** that an application can, at any time, verify this constraint.
 1.17657 +*/
 1.17658 +
 1.17659 +/*
 1.17660 +** This version of the memory allocator is used only when 
 1.17661 +** SQLITE_ENABLE_MEMSYS5 is defined.
 1.17662 +*/
 1.17663 +#ifdef SQLITE_ENABLE_MEMSYS5
 1.17664 +
 1.17665 +/*
 1.17666 +** A minimum allocation is an instance of the following structure.
 1.17667 +** Larger allocations are an array of these structures where the
 1.17668 +** size of the array is a power of 2.
 1.17669 +**
 1.17670 +** The size of this object must be a power of two.  That fact is
 1.17671 +** verified in memsys5Init().
 1.17672 +*/
 1.17673 +typedef struct Mem5Link Mem5Link;
 1.17674 +struct Mem5Link {
 1.17675 +  int next;       /* Index of next free chunk */
 1.17676 +  int prev;       /* Index of previous free chunk */
 1.17677 +};
 1.17678 +
 1.17679 +/*
 1.17680 +** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
 1.17681 +** mem5.szAtom is always at least 8 and 32-bit integers are used,
 1.17682 +** it is not actually possible to reach this limit.
 1.17683 +*/
 1.17684 +#define LOGMAX 30
 1.17685 +
 1.17686 +/*
 1.17687 +** Masks used for mem5.aCtrl[] elements.
 1.17688 +*/
 1.17689 +#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
 1.17690 +#define CTRL_FREE     0x20    /* True if not checked out */
 1.17691 +
 1.17692 +/*
 1.17693 +** All of the static variables used by this module are collected
 1.17694 +** into a single structure named "mem5".  This is to keep the
 1.17695 +** static variables organized and to reduce namespace pollution
 1.17696 +** when this module is combined with other in the amalgamation.
 1.17697 +*/
 1.17698 +static SQLITE_WSD struct Mem5Global {
 1.17699 +  /*
 1.17700 +  ** Memory available for allocation
 1.17701 +  */
 1.17702 +  int szAtom;      /* Smallest possible allocation in bytes */
 1.17703 +  int nBlock;      /* Number of szAtom sized blocks in zPool */
 1.17704 +  u8 *zPool;       /* Memory available to be allocated */
 1.17705 +  
 1.17706 +  /*
 1.17707 +  ** Mutex to control access to the memory allocation subsystem.
 1.17708 +  */
 1.17709 +  sqlite3_mutex *mutex;
 1.17710 +
 1.17711 +  /*
 1.17712 +  ** Performance statistics
 1.17713 +  */
 1.17714 +  u64 nAlloc;         /* Total number of calls to malloc */
 1.17715 +  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
 1.17716 +  u64 totalExcess;    /* Total internal fragmentation */
 1.17717 +  u32 currentOut;     /* Current checkout, including internal fragmentation */
 1.17718 +  u32 currentCount;   /* Current number of distinct checkouts */
 1.17719 +  u32 maxOut;         /* Maximum instantaneous currentOut */
 1.17720 +  u32 maxCount;       /* Maximum instantaneous currentCount */
 1.17721 +  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
 1.17722 +  
 1.17723 +  /*
 1.17724 +  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
 1.17725 +  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
 1.17726 +  ** and so forth.
 1.17727 +  */
 1.17728 +  int aiFreelist[LOGMAX+1];
 1.17729 +
 1.17730 +  /*
 1.17731 +  ** Space for tracking which blocks are checked out and the size
 1.17732 +  ** of each block.  One byte per block.
 1.17733 +  */
 1.17734 +  u8 *aCtrl;
 1.17735 +
 1.17736 +} mem5;
 1.17737 +
 1.17738 +/*
 1.17739 +** Access the static variable through a macro for SQLITE_OMIT_WSD.
 1.17740 +*/
 1.17741 +#define mem5 GLOBAL(struct Mem5Global, mem5)
 1.17742 +
 1.17743 +/*
 1.17744 +** Assuming mem5.zPool is divided up into an array of Mem5Link
 1.17745 +** structures, return a pointer to the idx-th such link.
 1.17746 +*/
 1.17747 +#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
 1.17748 +
 1.17749 +/*
 1.17750 +** Unlink the chunk at mem5.aPool[i] from list it is currently
 1.17751 +** on.  It should be found on mem5.aiFreelist[iLogsize].
 1.17752 +*/
 1.17753 +static void memsys5Unlink(int i, int iLogsize){
 1.17754 +  int next, prev;
 1.17755 +  assert( i>=0 && i<mem5.nBlock );
 1.17756 +  assert( iLogsize>=0 && iLogsize<=LOGMAX );
 1.17757 +  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
 1.17758 +
 1.17759 +  next = MEM5LINK(i)->next;
 1.17760 +  prev = MEM5LINK(i)->prev;
 1.17761 +  if( prev<0 ){
 1.17762 +    mem5.aiFreelist[iLogsize] = next;
 1.17763 +  }else{
 1.17764 +    MEM5LINK(prev)->next = next;
 1.17765 +  }
 1.17766 +  if( next>=0 ){
 1.17767 +    MEM5LINK(next)->prev = prev;
 1.17768 +  }
 1.17769 +}
 1.17770 +
 1.17771 +/*
 1.17772 +** Link the chunk at mem5.aPool[i] so that is on the iLogsize
 1.17773 +** free list.
 1.17774 +*/
 1.17775 +static void memsys5Link(int i, int iLogsize){
 1.17776 +  int x;
 1.17777 +  assert( sqlite3_mutex_held(mem5.mutex) );
 1.17778 +  assert( i>=0 && i<mem5.nBlock );
 1.17779 +  assert( iLogsize>=0 && iLogsize<=LOGMAX );
 1.17780 +  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
 1.17781 +
 1.17782 +  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
 1.17783 +  MEM5LINK(i)->prev = -1;
 1.17784 +  if( x>=0 ){
 1.17785 +    assert( x<mem5.nBlock );
 1.17786 +    MEM5LINK(x)->prev = i;
 1.17787 +  }
 1.17788 +  mem5.aiFreelist[iLogsize] = i;
 1.17789 +}
 1.17790 +
 1.17791 +/*
 1.17792 +** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
 1.17793 +** will already be held (obtained by code in malloc.c) if
 1.17794 +** sqlite3GlobalConfig.bMemStat is true.
 1.17795 +*/
 1.17796 +static void memsys5Enter(void){
 1.17797 +  sqlite3_mutex_enter(mem5.mutex);
 1.17798 +}
 1.17799 +static void memsys5Leave(void){
 1.17800 +  sqlite3_mutex_leave(mem5.mutex);
 1.17801 +}
 1.17802 +
 1.17803 +/*
 1.17804 +** Return the size of an outstanding allocation, in bytes.  The
 1.17805 +** size returned omits the 8-byte header overhead.  This only
 1.17806 +** works for chunks that are currently checked out.
 1.17807 +*/
 1.17808 +static int memsys5Size(void *p){
 1.17809 +  int iSize = 0;
 1.17810 +  if( p ){
 1.17811 +    int i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
 1.17812 +    assert( i>=0 && i<mem5.nBlock );
 1.17813 +    iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
 1.17814 +  }
 1.17815 +  return iSize;
 1.17816 +}
 1.17817 +
 1.17818 +/*
 1.17819 +** Return a block of memory of at least nBytes in size.
 1.17820 +** Return NULL if unable.  Return NULL if nBytes==0.
 1.17821 +**
 1.17822 +** The caller guarantees that nByte is positive.
 1.17823 +**
 1.17824 +** The caller has obtained a mutex prior to invoking this
 1.17825 +** routine so there is never any chance that two or more
 1.17826 +** threads can be in this routine at the same time.
 1.17827 +*/
 1.17828 +static void *memsys5MallocUnsafe(int nByte){
 1.17829 +  int i;           /* Index of a mem5.aPool[] slot */
 1.17830 +  int iBin;        /* Index into mem5.aiFreelist[] */
 1.17831 +  int iFullSz;     /* Size of allocation rounded up to power of 2 */
 1.17832 +  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
 1.17833 +
 1.17834 +  /* nByte must be a positive */
 1.17835 +  assert( nByte>0 );
 1.17836 +
 1.17837 +  /* Keep track of the maximum allocation request.  Even unfulfilled
 1.17838 +  ** requests are counted */
 1.17839 +  if( (u32)nByte>mem5.maxRequest ){
 1.17840 +    mem5.maxRequest = nByte;
 1.17841 +  }
 1.17842 +
 1.17843 +  /* Abort if the requested allocation size is larger than the largest
 1.17844 +  ** power of two that we can represent using 32-bit signed integers.
 1.17845 +  */
 1.17846 +  if( nByte > 0x40000000 ){
 1.17847 +    return 0;
 1.17848 +  }
 1.17849 +
 1.17850 +  /* Round nByte up to the next valid power of two */
 1.17851 +  for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
 1.17852 +
 1.17853 +  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
 1.17854 +  ** block.  If not, then split a block of the next larger power of
 1.17855 +  ** two in order to create a new free block of size iLogsize.
 1.17856 +  */
 1.17857 +  for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
 1.17858 +  if( iBin>LOGMAX ){
 1.17859 +    testcase( sqlite3GlobalConfig.xLog!=0 );
 1.17860 +    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
 1.17861 +    return 0;
 1.17862 +  }
 1.17863 +  i = mem5.aiFreelist[iBin];
 1.17864 +  memsys5Unlink(i, iBin);
 1.17865 +  while( iBin>iLogsize ){
 1.17866 +    int newSize;
 1.17867 +
 1.17868 +    iBin--;
 1.17869 +    newSize = 1 << iBin;
 1.17870 +    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
 1.17871 +    memsys5Link(i+newSize, iBin);
 1.17872 +  }
 1.17873 +  mem5.aCtrl[i] = iLogsize;
 1.17874 +
 1.17875 +  /* Update allocator performance statistics. */
 1.17876 +  mem5.nAlloc++;
 1.17877 +  mem5.totalAlloc += iFullSz;
 1.17878 +  mem5.totalExcess += iFullSz - nByte;
 1.17879 +  mem5.currentCount++;
 1.17880 +  mem5.currentOut += iFullSz;
 1.17881 +  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
 1.17882 +  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
 1.17883 +
 1.17884 +#ifdef SQLITE_DEBUG
 1.17885 +  /* Make sure the allocated memory does not assume that it is set to zero
 1.17886 +  ** or retains a value from a previous allocation */
 1.17887 +  memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
 1.17888 +#endif
 1.17889 +
 1.17890 +  /* Return a pointer to the allocated memory. */
 1.17891 +  return (void*)&mem5.zPool[i*mem5.szAtom];
 1.17892 +}
 1.17893 +
 1.17894 +/*
 1.17895 +** Free an outstanding memory allocation.
 1.17896 +*/
 1.17897 +static void memsys5FreeUnsafe(void *pOld){
 1.17898 +  u32 size, iLogsize;
 1.17899 +  int iBlock;
 1.17900 +
 1.17901 +  /* Set iBlock to the index of the block pointed to by pOld in 
 1.17902 +  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
 1.17903 +  */
 1.17904 +  iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
 1.17905 +
 1.17906 +  /* Check that the pointer pOld points to a valid, non-free block. */
 1.17907 +  assert( iBlock>=0 && iBlock<mem5.nBlock );
 1.17908 +  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
 1.17909 +  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
 1.17910 +
 1.17911 +  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
 1.17912 +  size = 1<<iLogsize;
 1.17913 +  assert( iBlock+size-1<(u32)mem5.nBlock );
 1.17914 +
 1.17915 +  mem5.aCtrl[iBlock] |= CTRL_FREE;
 1.17916 +  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
 1.17917 +  assert( mem5.currentCount>0 );
 1.17918 +  assert( mem5.currentOut>=(size*mem5.szAtom) );
 1.17919 +  mem5.currentCount--;
 1.17920 +  mem5.currentOut -= size*mem5.szAtom;
 1.17921 +  assert( mem5.currentOut>0 || mem5.currentCount==0 );
 1.17922 +  assert( mem5.currentCount>0 || mem5.currentOut==0 );
 1.17923 +
 1.17924 +  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
 1.17925 +  while( ALWAYS(iLogsize<LOGMAX) ){
 1.17926 +    int iBuddy;
 1.17927 +    if( (iBlock>>iLogsize) & 1 ){
 1.17928 +      iBuddy = iBlock - size;
 1.17929 +    }else{
 1.17930 +      iBuddy = iBlock + size;
 1.17931 +    }
 1.17932 +    assert( iBuddy>=0 );
 1.17933 +    if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
 1.17934 +    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
 1.17935 +    memsys5Unlink(iBuddy, iLogsize);
 1.17936 +    iLogsize++;
 1.17937 +    if( iBuddy<iBlock ){
 1.17938 +      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
 1.17939 +      mem5.aCtrl[iBlock] = 0;
 1.17940 +      iBlock = iBuddy;
 1.17941 +    }else{
 1.17942 +      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
 1.17943 +      mem5.aCtrl[iBuddy] = 0;
 1.17944 +    }
 1.17945 +    size *= 2;
 1.17946 +  }
 1.17947 +
 1.17948 +#ifdef SQLITE_DEBUG
 1.17949 +  /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
 1.17950 +  ** not used after being freed */
 1.17951 +  memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
 1.17952 +#endif
 1.17953 +
 1.17954 +  memsys5Link(iBlock, iLogsize);
 1.17955 +}
 1.17956 +
 1.17957 +/*
 1.17958 +** Allocate nBytes of memory.
 1.17959 +*/
 1.17960 +static void *memsys5Malloc(int nBytes){
 1.17961 +  sqlite3_int64 *p = 0;
 1.17962 +  if( nBytes>0 ){
 1.17963 +    memsys5Enter();
 1.17964 +    p = memsys5MallocUnsafe(nBytes);
 1.17965 +    memsys5Leave();
 1.17966 +  }
 1.17967 +  return (void*)p; 
 1.17968 +}
 1.17969 +
 1.17970 +/*
 1.17971 +** Free memory.
 1.17972 +**
 1.17973 +** The outer layer memory allocator prevents this routine from
 1.17974 +** being called with pPrior==0.
 1.17975 +*/
 1.17976 +static void memsys5Free(void *pPrior){
 1.17977 +  assert( pPrior!=0 );
 1.17978 +  memsys5Enter();
 1.17979 +  memsys5FreeUnsafe(pPrior);
 1.17980 +  memsys5Leave();  
 1.17981 +}
 1.17982 +
 1.17983 +/*
 1.17984 +** Change the size of an existing memory allocation.
 1.17985 +**
 1.17986 +** The outer layer memory allocator prevents this routine from
 1.17987 +** being called with pPrior==0.  
 1.17988 +**
 1.17989 +** nBytes is always a value obtained from a prior call to
 1.17990 +** memsys5Round().  Hence nBytes is always a non-negative power
 1.17991 +** of two.  If nBytes==0 that means that an oversize allocation
 1.17992 +** (an allocation larger than 0x40000000) was requested and this
 1.17993 +** routine should return 0 without freeing pPrior.
 1.17994 +*/
 1.17995 +static void *memsys5Realloc(void *pPrior, int nBytes){
 1.17996 +  int nOld;
 1.17997 +  void *p;
 1.17998 +  assert( pPrior!=0 );
 1.17999 +  assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
 1.18000 +  assert( nBytes>=0 );
 1.18001 +  if( nBytes==0 ){
 1.18002 +    return 0;
 1.18003 +  }
 1.18004 +  nOld = memsys5Size(pPrior);
 1.18005 +  if( nBytes<=nOld ){
 1.18006 +    return pPrior;
 1.18007 +  }
 1.18008 +  memsys5Enter();
 1.18009 +  p = memsys5MallocUnsafe(nBytes);
 1.18010 +  if( p ){
 1.18011 +    memcpy(p, pPrior, nOld);
 1.18012 +    memsys5FreeUnsafe(pPrior);
 1.18013 +  }
 1.18014 +  memsys5Leave();
 1.18015 +  return p;
 1.18016 +}
 1.18017 +
 1.18018 +/*
 1.18019 +** Round up a request size to the next valid allocation size.  If
 1.18020 +** the allocation is too large to be handled by this allocation system,
 1.18021 +** return 0.
 1.18022 +**
 1.18023 +** All allocations must be a power of two and must be expressed by a
 1.18024 +** 32-bit signed integer.  Hence the largest allocation is 0x40000000
 1.18025 +** or 1073741824 bytes.
 1.18026 +*/
 1.18027 +static int memsys5Roundup(int n){
 1.18028 +  int iFullSz;
 1.18029 +  if( n > 0x40000000 ) return 0;
 1.18030 +  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
 1.18031 +  return iFullSz;
 1.18032 +}
 1.18033 +
 1.18034 +/*
 1.18035 +** Return the ceiling of the logarithm base 2 of iValue.
 1.18036 +**
 1.18037 +** Examples:   memsys5Log(1) -> 0
 1.18038 +**             memsys5Log(2) -> 1
 1.18039 +**             memsys5Log(4) -> 2
 1.18040 +**             memsys5Log(5) -> 3
 1.18041 +**             memsys5Log(8) -> 3
 1.18042 +**             memsys5Log(9) -> 4
 1.18043 +*/
 1.18044 +static int memsys5Log(int iValue){
 1.18045 +  int iLog;
 1.18046 +  for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
 1.18047 +  return iLog;
 1.18048 +}
 1.18049 +
 1.18050 +/*
 1.18051 +** Initialize the memory allocator.
 1.18052 +**
 1.18053 +** This routine is not threadsafe.  The caller must be holding a mutex
 1.18054 +** to prevent multiple threads from entering at the same time.
 1.18055 +*/
 1.18056 +static int memsys5Init(void *NotUsed){
 1.18057 +  int ii;            /* Loop counter */
 1.18058 +  int nByte;         /* Number of bytes of memory available to this allocator */
 1.18059 +  u8 *zByte;         /* Memory usable by this allocator */
 1.18060 +  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
 1.18061 +  int iOffset;       /* An offset into mem5.aCtrl[] */
 1.18062 +
 1.18063 +  UNUSED_PARAMETER(NotUsed);
 1.18064 +
 1.18065 +  /* For the purposes of this routine, disable the mutex */
 1.18066 +  mem5.mutex = 0;
 1.18067 +
 1.18068 +  /* The size of a Mem5Link object must be a power of two.  Verify that
 1.18069 +  ** this is case.
 1.18070 +  */
 1.18071 +  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
 1.18072 +
 1.18073 +  nByte = sqlite3GlobalConfig.nHeap;
 1.18074 +  zByte = (u8*)sqlite3GlobalConfig.pHeap;
 1.18075 +  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
 1.18076 +
 1.18077 +  /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
 1.18078 +  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
 1.18079 +  mem5.szAtom = (1<<nMinLog);
 1.18080 +  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
 1.18081 +    mem5.szAtom = mem5.szAtom << 1;
 1.18082 +  }
 1.18083 +
 1.18084 +  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
 1.18085 +  mem5.zPool = zByte;
 1.18086 +  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
 1.18087 +
 1.18088 +  for(ii=0; ii<=LOGMAX; ii++){
 1.18089 +    mem5.aiFreelist[ii] = -1;
 1.18090 +  }
 1.18091 +
 1.18092 +  iOffset = 0;
 1.18093 +  for(ii=LOGMAX; ii>=0; ii--){
 1.18094 +    int nAlloc = (1<<ii);
 1.18095 +    if( (iOffset+nAlloc)<=mem5.nBlock ){
 1.18096 +      mem5.aCtrl[iOffset] = ii | CTRL_FREE;
 1.18097 +      memsys5Link(iOffset, ii);
 1.18098 +      iOffset += nAlloc;
 1.18099 +    }
 1.18100 +    assert((iOffset+nAlloc)>mem5.nBlock);
 1.18101 +  }
 1.18102 +
 1.18103 +  /* If a mutex is required for normal operation, allocate one */
 1.18104 +  if( sqlite3GlobalConfig.bMemstat==0 ){
 1.18105 +    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
 1.18106 +  }
 1.18107 +
 1.18108 +  return SQLITE_OK;
 1.18109 +}
 1.18110 +
 1.18111 +/*
 1.18112 +** Deinitialize this module.
 1.18113 +*/
 1.18114 +static void memsys5Shutdown(void *NotUsed){
 1.18115 +  UNUSED_PARAMETER(NotUsed);
 1.18116 +  mem5.mutex = 0;
 1.18117 +  return;
 1.18118 +}
 1.18119 +
 1.18120 +#ifdef SQLITE_TEST
 1.18121 +/*
 1.18122 +** Open the file indicated and write a log of all unfreed memory 
 1.18123 +** allocations into that log.
 1.18124 +*/
 1.18125 +SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
 1.18126 +  FILE *out;
 1.18127 +  int i, j, n;
 1.18128 +  int nMinLog;
 1.18129 +
 1.18130 +  if( zFilename==0 || zFilename[0]==0 ){
 1.18131 +    out = stdout;
 1.18132 +  }else{
 1.18133 +    out = fopen(zFilename, "w");
 1.18134 +    if( out==0 ){
 1.18135 +      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
 1.18136 +                      zFilename);
 1.18137 +      return;
 1.18138 +    }
 1.18139 +  }
 1.18140 +  memsys5Enter();
 1.18141 +  nMinLog = memsys5Log(mem5.szAtom);
 1.18142 +  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
 1.18143 +    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
 1.18144 +    fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
 1.18145 +  }
 1.18146 +  fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
 1.18147 +  fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
 1.18148 +  fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
 1.18149 +  fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
 1.18150 +  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
 1.18151 +  fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
 1.18152 +  fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
 1.18153 +  fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
 1.18154 +  memsys5Leave();
 1.18155 +  if( out==stdout ){
 1.18156 +    fflush(stdout);
 1.18157 +  }else{
 1.18158 +    fclose(out);
 1.18159 +  }
 1.18160 +}
 1.18161 +#endif
 1.18162 +
 1.18163 +/*
 1.18164 +** This routine is the only routine in this file with external 
 1.18165 +** linkage. It returns a pointer to a static sqlite3_mem_methods
 1.18166 +** struct populated with the memsys5 methods.
 1.18167 +*/
 1.18168 +SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
 1.18169 +  static const sqlite3_mem_methods memsys5Methods = {
 1.18170 +     memsys5Malloc,
 1.18171 +     memsys5Free,
 1.18172 +     memsys5Realloc,
 1.18173 +     memsys5Size,
 1.18174 +     memsys5Roundup,
 1.18175 +     memsys5Init,
 1.18176 +     memsys5Shutdown,
 1.18177 +     0
 1.18178 +  };
 1.18179 +  return &memsys5Methods;
 1.18180 +}
 1.18181 +
 1.18182 +#endif /* SQLITE_ENABLE_MEMSYS5 */
 1.18183 +
 1.18184 +/************** End of mem5.c ************************************************/
 1.18185 +/************** Begin file mutex.c *******************************************/
 1.18186 +/*
 1.18187 +** 2007 August 14
 1.18188 +**
 1.18189 +** The author disclaims copyright to this source code.  In place of
 1.18190 +** a legal notice, here is a blessing:
 1.18191 +**
 1.18192 +**    May you do good and not evil.
 1.18193 +**    May you find forgiveness for yourself and forgive others.
 1.18194 +**    May you share freely, never taking more than you give.
 1.18195 +**
 1.18196 +*************************************************************************
 1.18197 +** This file contains the C functions that implement mutexes.
 1.18198 +**
 1.18199 +** This file contains code that is common across all mutex implementations.
 1.18200 +*/
 1.18201 +
 1.18202 +#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
 1.18203 +/*
 1.18204 +** For debugging purposes, record when the mutex subsystem is initialized
 1.18205 +** and uninitialized so that we can assert() if there is an attempt to
 1.18206 +** allocate a mutex while the system is uninitialized.
 1.18207 +*/
 1.18208 +static SQLITE_WSD int mutexIsInit = 0;
 1.18209 +#endif /* SQLITE_DEBUG */
 1.18210 +
 1.18211 +
 1.18212 +#ifndef SQLITE_MUTEX_OMIT
 1.18213 +/*
 1.18214 +** Initialize the mutex system.
 1.18215 +*/
 1.18216 +SQLITE_PRIVATE int sqlite3MutexInit(void){ 
 1.18217 +  int rc = SQLITE_OK;
 1.18218 +  if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
 1.18219 +    /* If the xMutexAlloc method has not been set, then the user did not
 1.18220 +    ** install a mutex implementation via sqlite3_config() prior to 
 1.18221 +    ** sqlite3_initialize() being called. This block copies pointers to
 1.18222 +    ** the default implementation into the sqlite3GlobalConfig structure.
 1.18223 +    */
 1.18224 +    sqlite3_mutex_methods const *pFrom;
 1.18225 +    sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
 1.18226 +
 1.18227 +    if( sqlite3GlobalConfig.bCoreMutex ){
 1.18228 +      pFrom = sqlite3DefaultMutex();
 1.18229 +    }else{
 1.18230 +      pFrom = sqlite3NoopMutex();
 1.18231 +    }
 1.18232 +    memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
 1.18233 +    memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
 1.18234 +           sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
 1.18235 +    pTo->xMutexAlloc = pFrom->xMutexAlloc;
 1.18236 +  }
 1.18237 +  rc = sqlite3GlobalConfig.mutex.xMutexInit();
 1.18238 +
 1.18239 +#ifdef SQLITE_DEBUG
 1.18240 +  GLOBAL(int, mutexIsInit) = 1;
 1.18241 +#endif
 1.18242 +
 1.18243 +  return rc;
 1.18244 +}
 1.18245 +
 1.18246 +/*
 1.18247 +** Shutdown the mutex system. This call frees resources allocated by
 1.18248 +** sqlite3MutexInit().
 1.18249 +*/
 1.18250 +SQLITE_PRIVATE int sqlite3MutexEnd(void){
 1.18251 +  int rc = SQLITE_OK;
 1.18252 +  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
 1.18253 +    rc = sqlite3GlobalConfig.mutex.xMutexEnd();
 1.18254 +  }
 1.18255 +
 1.18256 +#ifdef SQLITE_DEBUG
 1.18257 +  GLOBAL(int, mutexIsInit) = 0;
 1.18258 +#endif
 1.18259 +
 1.18260 +  return rc;
 1.18261 +}
 1.18262 +
 1.18263 +/*
 1.18264 +** Retrieve a pointer to a static mutex or allocate a new dynamic one.
 1.18265 +*/
 1.18266 +SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
 1.18267 +#ifndef SQLITE_OMIT_AUTOINIT
 1.18268 +  if( sqlite3_initialize() ) return 0;
 1.18269 +#endif
 1.18270 +  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
 1.18271 +}
 1.18272 +
 1.18273 +SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
 1.18274 +  if( !sqlite3GlobalConfig.bCoreMutex ){
 1.18275 +    return 0;
 1.18276 +  }
 1.18277 +  assert( GLOBAL(int, mutexIsInit) );
 1.18278 +  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
 1.18279 +}
 1.18280 +
 1.18281 +/*
 1.18282 +** Free a dynamic mutex.
 1.18283 +*/
 1.18284 +SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
 1.18285 +  if( p ){
 1.18286 +    sqlite3GlobalConfig.mutex.xMutexFree(p);
 1.18287 +  }
 1.18288 +}
 1.18289 +
 1.18290 +/*
 1.18291 +** Obtain the mutex p. If some other thread already has the mutex, block
 1.18292 +** until it can be obtained.
 1.18293 +*/
 1.18294 +SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
 1.18295 +  if( p ){
 1.18296 +    sqlite3GlobalConfig.mutex.xMutexEnter(p);
 1.18297 +  }
 1.18298 +}
 1.18299 +
 1.18300 +/*
 1.18301 +** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
 1.18302 +** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
 1.18303 +*/
 1.18304 +SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
 1.18305 +  int rc = SQLITE_OK;
 1.18306 +  if( p ){
 1.18307 +    return sqlite3GlobalConfig.mutex.xMutexTry(p);
 1.18308 +  }
 1.18309 +  return rc;
 1.18310 +}
 1.18311 +
 1.18312 +/*
 1.18313 +** The sqlite3_mutex_leave() routine exits a mutex that was previously
 1.18314 +** entered by the same thread.  The behavior is undefined if the mutex 
 1.18315 +** is not currently entered. If a NULL pointer is passed as an argument
 1.18316 +** this function is a no-op.
 1.18317 +*/
 1.18318 +SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
 1.18319 +  if( p ){
 1.18320 +    sqlite3GlobalConfig.mutex.xMutexLeave(p);
 1.18321 +  }
 1.18322 +}
 1.18323 +
 1.18324 +#ifndef NDEBUG
 1.18325 +/*
 1.18326 +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
 1.18327 +** intended for use inside assert() statements.
 1.18328 +*/
 1.18329 +SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
 1.18330 +  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
 1.18331 +}
 1.18332 +SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
 1.18333 +  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
 1.18334 +}
 1.18335 +#endif
 1.18336 +
 1.18337 +#endif /* !defined(SQLITE_MUTEX_OMIT) */
 1.18338 +
 1.18339 +/************** End of mutex.c ***********************************************/
 1.18340 +/************** Begin file mutex_noop.c **************************************/
 1.18341 +/*
 1.18342 +** 2008 October 07
 1.18343 +**
 1.18344 +** The author disclaims copyright to this source code.  In place of
 1.18345 +** a legal notice, here is a blessing:
 1.18346 +**
 1.18347 +**    May you do good and not evil.
 1.18348 +**    May you find forgiveness for yourself and forgive others.
 1.18349 +**    May you share freely, never taking more than you give.
 1.18350 +**
 1.18351 +*************************************************************************
 1.18352 +** This file contains the C functions that implement mutexes.
 1.18353 +**
 1.18354 +** This implementation in this file does not provide any mutual
 1.18355 +** exclusion and is thus suitable for use only in applications
 1.18356 +** that use SQLite in a single thread.  The routines defined
 1.18357 +** here are place-holders.  Applications can substitute working
 1.18358 +** mutex routines at start-time using the
 1.18359 +**
 1.18360 +**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
 1.18361 +**
 1.18362 +** interface.
 1.18363 +**
 1.18364 +** If compiled with SQLITE_DEBUG, then additional logic is inserted
 1.18365 +** that does error checking on mutexes to make sure they are being
 1.18366 +** called correctly.
 1.18367 +*/
 1.18368 +
 1.18369 +#ifndef SQLITE_MUTEX_OMIT
 1.18370 +
 1.18371 +#ifndef SQLITE_DEBUG
 1.18372 +/*
 1.18373 +** Stub routines for all mutex methods.
 1.18374 +**
 1.18375 +** This routines provide no mutual exclusion or error checking.
 1.18376 +*/
 1.18377 +static int noopMutexInit(void){ return SQLITE_OK; }
 1.18378 +static int noopMutexEnd(void){ return SQLITE_OK; }
 1.18379 +static sqlite3_mutex *noopMutexAlloc(int id){ 
 1.18380 +  UNUSED_PARAMETER(id);
 1.18381 +  return (sqlite3_mutex*)8; 
 1.18382 +}
 1.18383 +static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
 1.18384 +static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
 1.18385 +static int noopMutexTry(sqlite3_mutex *p){
 1.18386 +  UNUSED_PARAMETER(p);
 1.18387 +  return SQLITE_OK;
 1.18388 +}
 1.18389 +static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
 1.18390 +
 1.18391 +SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
 1.18392 +  static const sqlite3_mutex_methods sMutex = {
 1.18393 +    noopMutexInit,
 1.18394 +    noopMutexEnd,
 1.18395 +    noopMutexAlloc,
 1.18396 +    noopMutexFree,
 1.18397 +    noopMutexEnter,
 1.18398 +    noopMutexTry,
 1.18399 +    noopMutexLeave,
 1.18400 +
 1.18401 +    0,
 1.18402 +    0,
 1.18403 +  };
 1.18404 +
 1.18405 +  return &sMutex;
 1.18406 +}
 1.18407 +#endif /* !SQLITE_DEBUG */
 1.18408 +
 1.18409 +#ifdef SQLITE_DEBUG
 1.18410 +/*
 1.18411 +** In this implementation, error checking is provided for testing
 1.18412 +** and debugging purposes.  The mutexes still do not provide any
 1.18413 +** mutual exclusion.
 1.18414 +*/
 1.18415 +
 1.18416 +/*
 1.18417 +** The mutex object
 1.18418 +*/
 1.18419 +typedef struct sqlite3_debug_mutex {
 1.18420 +  int id;     /* The mutex type */
 1.18421 +  int cnt;    /* Number of entries without a matching leave */
 1.18422 +} sqlite3_debug_mutex;
 1.18423 +
 1.18424 +/*
 1.18425 +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
 1.18426 +** intended for use inside assert() statements.
 1.18427 +*/
 1.18428 +static int debugMutexHeld(sqlite3_mutex *pX){
 1.18429 +  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
 1.18430 +  return p==0 || p->cnt>0;
 1.18431 +}
 1.18432 +static int debugMutexNotheld(sqlite3_mutex *pX){
 1.18433 +  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
 1.18434 +  return p==0 || p->cnt==0;
 1.18435 +}
 1.18436 +
 1.18437 +/*
 1.18438 +** Initialize and deinitialize the mutex subsystem.
 1.18439 +*/
 1.18440 +static int debugMutexInit(void){ return SQLITE_OK; }
 1.18441 +static int debugMutexEnd(void){ return SQLITE_OK; }
 1.18442 +
 1.18443 +/*
 1.18444 +** The sqlite3_mutex_alloc() routine allocates a new
 1.18445 +** mutex and returns a pointer to it.  If it returns NULL
 1.18446 +** that means that a mutex could not be allocated. 
 1.18447 +*/
 1.18448 +static sqlite3_mutex *debugMutexAlloc(int id){
 1.18449 +  static sqlite3_debug_mutex aStatic[6];
 1.18450 +  sqlite3_debug_mutex *pNew = 0;
 1.18451 +  switch( id ){
 1.18452 +    case SQLITE_MUTEX_FAST:
 1.18453 +    case SQLITE_MUTEX_RECURSIVE: {
 1.18454 +      pNew = sqlite3Malloc(sizeof(*pNew));
 1.18455 +      if( pNew ){
 1.18456 +        pNew->id = id;
 1.18457 +        pNew->cnt = 0;
 1.18458 +      }
 1.18459 +      break;
 1.18460 +    }
 1.18461 +    default: {
 1.18462 +      assert( id-2 >= 0 );
 1.18463 +      assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
 1.18464 +      pNew = &aStatic[id-2];
 1.18465 +      pNew->id = id;
 1.18466 +      break;
 1.18467 +    }
 1.18468 +  }
 1.18469 +  return (sqlite3_mutex*)pNew;
 1.18470 +}
 1.18471 +
 1.18472 +/*
 1.18473 +** This routine deallocates a previously allocated mutex.
 1.18474 +*/
 1.18475 +static void debugMutexFree(sqlite3_mutex *pX){
 1.18476 +  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
 1.18477 +  assert( p->cnt==0 );
 1.18478 +  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
 1.18479 +  sqlite3_free(p);
 1.18480 +}
 1.18481 +
 1.18482 +/*
 1.18483 +** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
 1.18484 +** to enter a mutex.  If another thread is already within the mutex,
 1.18485 +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
 1.18486 +** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
 1.18487 +** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
 1.18488 +** be entered multiple times by the same thread.  In such cases the,
 1.18489 +** mutex must be exited an equal number of times before another thread
 1.18490 +** can enter.  If the same thread tries to enter any other kind of mutex
 1.18491 +** more than once, the behavior is undefined.
 1.18492 +*/
 1.18493 +static void debugMutexEnter(sqlite3_mutex *pX){
 1.18494 +  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
 1.18495 +  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
 1.18496 +  p->cnt++;
 1.18497 +}
 1.18498 +static int debugMutexTry(sqlite3_mutex *pX){
 1.18499 +  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
 1.18500 +  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
 1.18501 +  p->cnt++;
 1.18502 +  return SQLITE_OK;
 1.18503 +}
 1.18504 +
 1.18505 +/*
 1.18506 +** The sqlite3_mutex_leave() routine exits a mutex that was
 1.18507 +** previously entered by the same thread.  The behavior
 1.18508 +** is undefined if the mutex is not currently entered or
 1.18509 +** is not currently allocated.  SQLite will never do either.
 1.18510 +*/
 1.18511 +static void debugMutexLeave(sqlite3_mutex *pX){
 1.18512 +  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
 1.18513 +  assert( debugMutexHeld(pX) );
 1.18514 +  p->cnt--;
 1.18515 +  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
 1.18516 +}
 1.18517 +
 1.18518 +SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
 1.18519 +  static const sqlite3_mutex_methods sMutex = {
 1.18520 +    debugMutexInit,
 1.18521 +    debugMutexEnd,
 1.18522 +    debugMutexAlloc,
 1.18523 +    debugMutexFree,
 1.18524 +    debugMutexEnter,
 1.18525 +    debugMutexTry,
 1.18526 +    debugMutexLeave,
 1.18527 +
 1.18528 +    debugMutexHeld,
 1.18529 +    debugMutexNotheld
 1.18530 +  };
 1.18531 +
 1.18532 +  return &sMutex;
 1.18533 +}
 1.18534 +#endif /* SQLITE_DEBUG */
 1.18535 +
 1.18536 +/*
 1.18537 +** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
 1.18538 +** is used regardless of the run-time threadsafety setting.
 1.18539 +*/
 1.18540 +#ifdef SQLITE_MUTEX_NOOP
 1.18541 +SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
 1.18542 +  return sqlite3NoopMutex();
 1.18543 +}
 1.18544 +#endif /* defined(SQLITE_MUTEX_NOOP) */
 1.18545 +#endif /* !defined(SQLITE_MUTEX_OMIT) */
 1.18546 +
 1.18547 +/************** End of mutex_noop.c ******************************************/
 1.18548 +/************** Begin file mutex_unix.c **************************************/
 1.18549 +/*
 1.18550 +** 2007 August 28
 1.18551 +**
 1.18552 +** The author disclaims copyright to this source code.  In place of
 1.18553 +** a legal notice, here is a blessing:
 1.18554 +**
 1.18555 +**    May you do good and not evil.
 1.18556 +**    May you find forgiveness for yourself and forgive others.
 1.18557 +**    May you share freely, never taking more than you give.
 1.18558 +**
 1.18559 +*************************************************************************
 1.18560 +** This file contains the C functions that implement mutexes for pthreads
 1.18561 +*/
 1.18562 +
 1.18563 +/*
 1.18564 +** The code in this file is only used if we are compiling threadsafe
 1.18565 +** under unix with pthreads.
 1.18566 +**
 1.18567 +** Note that this implementation requires a version of pthreads that
 1.18568 +** supports recursive mutexes.
 1.18569 +*/
 1.18570 +#ifdef SQLITE_MUTEX_PTHREADS
 1.18571 +
 1.18572 +#include <pthread.h>
 1.18573 +
 1.18574 +/*
 1.18575 +** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
 1.18576 +** are necessary under two condidtions:  (1) Debug builds and (2) using
 1.18577 +** home-grown mutexes.  Encapsulate these conditions into a single #define.
 1.18578 +*/
 1.18579 +#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
 1.18580 +# define SQLITE_MUTEX_NREF 1
 1.18581 +#else
 1.18582 +# define SQLITE_MUTEX_NREF 0
 1.18583 +#endif
 1.18584 +
 1.18585 +/*
 1.18586 +** Each recursive mutex is an instance of the following structure.
 1.18587 +*/
 1.18588 +struct sqlite3_mutex {
 1.18589 +  pthread_mutex_t mutex;     /* Mutex controlling the lock */
 1.18590 +#if SQLITE_MUTEX_NREF
 1.18591 +  int id;                    /* Mutex type */
 1.18592 +  volatile int nRef;         /* Number of entrances */
 1.18593 +  volatile pthread_t owner;  /* Thread that is within this mutex */
 1.18594 +  int trace;                 /* True to trace changes */
 1.18595 +#endif
 1.18596 +};
 1.18597 +#if SQLITE_MUTEX_NREF
 1.18598 +#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
 1.18599 +#else
 1.18600 +#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
 1.18601 +#endif
 1.18602 +
 1.18603 +/*
 1.18604 +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
 1.18605 +** intended for use only inside assert() statements.  On some platforms,
 1.18606 +** there might be race conditions that can cause these routines to
 1.18607 +** deliver incorrect results.  In particular, if pthread_equal() is
 1.18608 +** not an atomic operation, then these routines might delivery
 1.18609 +** incorrect results.  On most platforms, pthread_equal() is a 
 1.18610 +** comparison of two integers and is therefore atomic.  But we are
 1.18611 +** told that HPUX is not such a platform.  If so, then these routines
 1.18612 +** will not always work correctly on HPUX.
 1.18613 +**
 1.18614 +** On those platforms where pthread_equal() is not atomic, SQLite
 1.18615 +** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
 1.18616 +** make sure no assert() statements are evaluated and hence these
 1.18617 +** routines are never called.
 1.18618 +*/
 1.18619 +#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
 1.18620 +static int pthreadMutexHeld(sqlite3_mutex *p){
 1.18621 +  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
 1.18622 +}
 1.18623 +static int pthreadMutexNotheld(sqlite3_mutex *p){
 1.18624 +  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
 1.18625 +}
 1.18626 +#endif
 1.18627 +
 1.18628 +/*
 1.18629 +** Initialize and deinitialize the mutex subsystem.
 1.18630 +*/
 1.18631 +static int pthreadMutexInit(void){ return SQLITE_OK; }
 1.18632 +static int pthreadMutexEnd(void){ return SQLITE_OK; }
 1.18633 +
 1.18634 +/*
 1.18635 +** The sqlite3_mutex_alloc() routine allocates a new
 1.18636 +** mutex and returns a pointer to it.  If it returns NULL
 1.18637 +** that means that a mutex could not be allocated.  SQLite
 1.18638 +** will unwind its stack and return an error.  The argument
 1.18639 +** to sqlite3_mutex_alloc() is one of these integer constants:
 1.18640 +**
 1.18641 +** <ul>
 1.18642 +** <li>  SQLITE_MUTEX_FAST
 1.18643 +** <li>  SQLITE_MUTEX_RECURSIVE
 1.18644 +** <li>  SQLITE_MUTEX_STATIC_MASTER
 1.18645 +** <li>  SQLITE_MUTEX_STATIC_MEM
 1.18646 +** <li>  SQLITE_MUTEX_STATIC_MEM2
 1.18647 +** <li>  SQLITE_MUTEX_STATIC_PRNG
 1.18648 +** <li>  SQLITE_MUTEX_STATIC_LRU
 1.18649 +** <li>  SQLITE_MUTEX_STATIC_PMEM
 1.18650 +** </ul>
 1.18651 +**
 1.18652 +** The first two constants cause sqlite3_mutex_alloc() to create
 1.18653 +** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
 1.18654 +** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
 1.18655 +** The mutex implementation does not need to make a distinction
 1.18656 +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
 1.18657 +** not want to.  But SQLite will only request a recursive mutex in
 1.18658 +** cases where it really needs one.  If a faster non-recursive mutex
 1.18659 +** implementation is available on the host platform, the mutex subsystem
 1.18660 +** might return such a mutex in response to SQLITE_MUTEX_FAST.
 1.18661 +**
 1.18662 +** The other allowed parameters to sqlite3_mutex_alloc() each return
 1.18663 +** a pointer to a static preexisting mutex.  Six static mutexes are
 1.18664 +** used by the current version of SQLite.  Future versions of SQLite
 1.18665 +** may add additional static mutexes.  Static mutexes are for internal
 1.18666 +** use by SQLite only.  Applications that use SQLite mutexes should
 1.18667 +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
 1.18668 +** SQLITE_MUTEX_RECURSIVE.
 1.18669 +**
 1.18670 +** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
 1.18671 +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
 1.18672 +** returns a different mutex on every call.  But for the static 
 1.18673 +** mutex types, the same mutex is returned on every call that has
 1.18674 +** the same type number.
 1.18675 +*/
 1.18676 +static sqlite3_mutex *pthreadMutexAlloc(int iType){
 1.18677 +  static sqlite3_mutex staticMutexes[] = {
 1.18678 +    SQLITE3_MUTEX_INITIALIZER,
 1.18679 +    SQLITE3_MUTEX_INITIALIZER,
 1.18680 +    SQLITE3_MUTEX_INITIALIZER,
 1.18681 +    SQLITE3_MUTEX_INITIALIZER,
 1.18682 +    SQLITE3_MUTEX_INITIALIZER,
 1.18683 +    SQLITE3_MUTEX_INITIALIZER
 1.18684 +  };
 1.18685 +  sqlite3_mutex *p;
 1.18686 +  switch( iType ){
 1.18687 +    case SQLITE_MUTEX_RECURSIVE: {
 1.18688 +      p = sqlite3MallocZero( sizeof(*p) );
 1.18689 +      if( p ){
 1.18690 +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
 1.18691 +        /* If recursive mutexes are not available, we will have to
 1.18692 +        ** build our own.  See below. */
 1.18693 +        pthread_mutex_init(&p->mutex, 0);
 1.18694 +#else
 1.18695 +        /* Use a recursive mutex if it is available */
 1.18696 +        pthread_mutexattr_t recursiveAttr;
 1.18697 +        pthread_mutexattr_init(&recursiveAttr);
 1.18698 +        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
 1.18699 +        pthread_mutex_init(&p->mutex, &recursiveAttr);
 1.18700 +        pthread_mutexattr_destroy(&recursiveAttr);
 1.18701 +#endif
 1.18702 +#if SQLITE_MUTEX_NREF
 1.18703 +        p->id = iType;
 1.18704 +#endif
 1.18705 +      }
 1.18706 +      break;
 1.18707 +    }
 1.18708 +    case SQLITE_MUTEX_FAST: {
 1.18709 +      p = sqlite3MallocZero( sizeof(*p) );
 1.18710 +      if( p ){
 1.18711 +#if SQLITE_MUTEX_NREF
 1.18712 +        p->id = iType;
 1.18713 +#endif
 1.18714 +        pthread_mutex_init(&p->mutex, 0);
 1.18715 +      }
 1.18716 +      break;
 1.18717 +    }
 1.18718 +    default: {
 1.18719 +      assert( iType-2 >= 0 );
 1.18720 +      assert( iType-2 < ArraySize(staticMutexes) );
 1.18721 +      p = &staticMutexes[iType-2];
 1.18722 +#if SQLITE_MUTEX_NREF
 1.18723 +      p->id = iType;
 1.18724 +#endif
 1.18725 +      break;
 1.18726 +    }
 1.18727 +  }
 1.18728 +  return p;
 1.18729 +}
 1.18730 +
 1.18731 +
 1.18732 +/*
 1.18733 +** This routine deallocates a previously
 1.18734 +** allocated mutex.  SQLite is careful to deallocate every
 1.18735 +** mutex that it allocates.
 1.18736 +*/
 1.18737 +static void pthreadMutexFree(sqlite3_mutex *p){
 1.18738 +  assert( p->nRef==0 );
 1.18739 +  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
 1.18740 +  pthread_mutex_destroy(&p->mutex);
 1.18741 +  sqlite3_free(p);
 1.18742 +}
 1.18743 +
 1.18744 +/*
 1.18745 +** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
 1.18746 +** to enter a mutex.  If another thread is already within the mutex,
 1.18747 +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
 1.18748 +** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
 1.18749 +** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
 1.18750 +** be entered multiple times by the same thread.  In such cases the,
 1.18751 +** mutex must be exited an equal number of times before another thread
 1.18752 +** can enter.  If the same thread tries to enter any other kind of mutex
 1.18753 +** more than once, the behavior is undefined.
 1.18754 +*/
 1.18755 +static void pthreadMutexEnter(sqlite3_mutex *p){
 1.18756 +  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
 1.18757 +
 1.18758 +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
 1.18759 +  /* If recursive mutexes are not available, then we have to grow
 1.18760 +  ** our own.  This implementation assumes that pthread_equal()
 1.18761 +  ** is atomic - that it cannot be deceived into thinking self
 1.18762 +  ** and p->owner are equal if p->owner changes between two values
 1.18763 +  ** that are not equal to self while the comparison is taking place.
 1.18764 +  ** This implementation also assumes a coherent cache - that 
 1.18765 +  ** separate processes cannot read different values from the same
 1.18766 +  ** address at the same time.  If either of these two conditions
 1.18767 +  ** are not met, then the mutexes will fail and problems will result.
 1.18768 +  */
 1.18769 +  {
 1.18770 +    pthread_t self = pthread_self();
 1.18771 +    if( p->nRef>0 && pthread_equal(p->owner, self) ){
 1.18772 +      p->nRef++;
 1.18773 +    }else{
 1.18774 +      pthread_mutex_lock(&p->mutex);
 1.18775 +      assert( p->nRef==0 );
 1.18776 +      p->owner = self;
 1.18777 +      p->nRef = 1;
 1.18778 +    }
 1.18779 +  }
 1.18780 +#else
 1.18781 +  /* Use the built-in recursive mutexes if they are available.
 1.18782 +  */
 1.18783 +  pthread_mutex_lock(&p->mutex);
 1.18784 +#if SQLITE_MUTEX_NREF
 1.18785 +  assert( p->nRef>0 || p->owner==0 );
 1.18786 +  p->owner = pthread_self();
 1.18787 +  p->nRef++;
 1.18788 +#endif
 1.18789 +#endif
 1.18790 +
 1.18791 +#ifdef SQLITE_DEBUG
 1.18792 +  if( p->trace ){
 1.18793 +    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
 1.18794 +  }
 1.18795 +#endif
 1.18796 +}
 1.18797 +static int pthreadMutexTry(sqlite3_mutex *p){
 1.18798 +  int rc;
 1.18799 +  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
 1.18800 +
 1.18801 +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
 1.18802 +  /* If recursive mutexes are not available, then we have to grow
 1.18803 +  ** our own.  This implementation assumes that pthread_equal()
 1.18804 +  ** is atomic - that it cannot be deceived into thinking self
 1.18805 +  ** and p->owner are equal if p->owner changes between two values
 1.18806 +  ** that are not equal to self while the comparison is taking place.
 1.18807 +  ** This implementation also assumes a coherent cache - that 
 1.18808 +  ** separate processes cannot read different values from the same
 1.18809 +  ** address at the same time.  If either of these two conditions
 1.18810 +  ** are not met, then the mutexes will fail and problems will result.
 1.18811 +  */
 1.18812 +  {
 1.18813 +    pthread_t self = pthread_self();
 1.18814 +    if( p->nRef>0 && pthread_equal(p->owner, self) ){
 1.18815 +      p->nRef++;
 1.18816 +      rc = SQLITE_OK;
 1.18817 +    }else if( pthread_mutex_trylock(&p->mutex)==0 ){
 1.18818 +      assert( p->nRef==0 );
 1.18819 +      p->owner = self;
 1.18820 +      p->nRef = 1;
 1.18821 +      rc = SQLITE_OK;
 1.18822 +    }else{
 1.18823 +      rc = SQLITE_BUSY;
 1.18824 +    }
 1.18825 +  }
 1.18826 +#else
 1.18827 +  /* Use the built-in recursive mutexes if they are available.
 1.18828 +  */
 1.18829 +  if( pthread_mutex_trylock(&p->mutex)==0 ){
 1.18830 +#if SQLITE_MUTEX_NREF
 1.18831 +    p->owner = pthread_self();
 1.18832 +    p->nRef++;
 1.18833 +#endif
 1.18834 +    rc = SQLITE_OK;
 1.18835 +  }else{
 1.18836 +    rc = SQLITE_BUSY;
 1.18837 +  }
 1.18838 +#endif
 1.18839 +
 1.18840 +#ifdef SQLITE_DEBUG
 1.18841 +  if( rc==SQLITE_OK && p->trace ){
 1.18842 +    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
 1.18843 +  }
 1.18844 +#endif
 1.18845 +  return rc;
 1.18846 +}
 1.18847 +
 1.18848 +/*
 1.18849 +** The sqlite3_mutex_leave() routine exits a mutex that was
 1.18850 +** previously entered by the same thread.  The behavior
 1.18851 +** is undefined if the mutex is not currently entered or
 1.18852 +** is not currently allocated.  SQLite will never do either.
 1.18853 +*/
 1.18854 +static void pthreadMutexLeave(sqlite3_mutex *p){
 1.18855 +  assert( pthreadMutexHeld(p) );
 1.18856 +#if SQLITE_MUTEX_NREF
 1.18857 +  p->nRef--;
 1.18858 +  if( p->nRef==0 ) p->owner = 0;
 1.18859 +#endif
 1.18860 +  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
 1.18861 +
 1.18862 +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
 1.18863 +  if( p->nRef==0 ){
 1.18864 +    pthread_mutex_unlock(&p->mutex);
 1.18865 +  }
 1.18866 +#else
 1.18867 +  pthread_mutex_unlock(&p->mutex);
 1.18868 +#endif
 1.18869 +
 1.18870 +#ifdef SQLITE_DEBUG
 1.18871 +  if( p->trace ){
 1.18872 +    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
 1.18873 +  }
 1.18874 +#endif
 1.18875 +}
 1.18876 +
 1.18877 +SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
 1.18878 +  static const sqlite3_mutex_methods sMutex = {
 1.18879 +    pthreadMutexInit,
 1.18880 +    pthreadMutexEnd,
 1.18881 +    pthreadMutexAlloc,
 1.18882 +    pthreadMutexFree,
 1.18883 +    pthreadMutexEnter,
 1.18884 +    pthreadMutexTry,
 1.18885 +    pthreadMutexLeave,
 1.18886 +#ifdef SQLITE_DEBUG
 1.18887 +    pthreadMutexHeld,
 1.18888 +    pthreadMutexNotheld
 1.18889 +#else
 1.18890 +    0,
 1.18891 +    0
 1.18892 +#endif
 1.18893 +  };
 1.18894 +
 1.18895 +  return &sMutex;
 1.18896 +}
 1.18897 +
 1.18898 +#endif /* SQLITE_MUTEX_PTHREADS */
 1.18899 +
 1.18900 +/************** End of mutex_unix.c ******************************************/
 1.18901 +/************** Begin file mutex_w32.c ***************************************/
 1.18902 +/*
 1.18903 +** 2007 August 14
 1.18904 +**
 1.18905 +** The author disclaims copyright to this source code.  In place of
 1.18906 +** a legal notice, here is a blessing:
 1.18907 +**
 1.18908 +**    May you do good and not evil.
 1.18909 +**    May you find forgiveness for yourself and forgive others.
 1.18910 +**    May you share freely, never taking more than you give.
 1.18911 +**
 1.18912 +*************************************************************************
 1.18913 +** This file contains the C functions that implement mutexes for win32
 1.18914 +*/
 1.18915 +
 1.18916 +/*
 1.18917 +** The code in this file is only used if we are compiling multithreaded
 1.18918 +** on a win32 system.
 1.18919 +*/
 1.18920 +#ifdef SQLITE_MUTEX_W32
 1.18921 +
 1.18922 +/*
 1.18923 +** Each recursive mutex is an instance of the following structure.
 1.18924 +*/
 1.18925 +struct sqlite3_mutex {
 1.18926 +  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
 1.18927 +  int id;                    /* Mutex type */
 1.18928 +#ifdef SQLITE_DEBUG
 1.18929 +  volatile int nRef;         /* Number of enterances */
 1.18930 +  volatile DWORD owner;      /* Thread holding this mutex */
 1.18931 +  int trace;                 /* True to trace changes */
 1.18932 +#endif
 1.18933 +};
 1.18934 +#define SQLITE_W32_MUTEX_INITIALIZER { 0 }
 1.18935 +#ifdef SQLITE_DEBUG
 1.18936 +#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
 1.18937 +#else
 1.18938 +#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
 1.18939 +#endif
 1.18940 +
 1.18941 +/*
 1.18942 +** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
 1.18943 +** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
 1.18944 +**
 1.18945 +** Here is an interesting observation:  Win95, Win98, and WinME lack
 1.18946 +** the LockFileEx() API.  But we can still statically link against that
 1.18947 +** API as long as we don't call it win running Win95/98/ME.  A call to
 1.18948 +** this routine is used to determine if the host is Win95/98/ME or
 1.18949 +** WinNT/2K/XP so that we will know whether or not we can safely call
 1.18950 +** the LockFileEx() API.
 1.18951 +**
 1.18952 +** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
 1.18953 +** which is only available if your application was compiled with 
 1.18954 +** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
 1.18955 +** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
 1.18956 +** this out as well.
 1.18957 +*/
 1.18958 +#if 0
 1.18959 +#if SQLITE_OS_WINCE || SQLITE_OS_WINRT
 1.18960 +# define mutexIsNT()  (1)
 1.18961 +#else
 1.18962 +  static int mutexIsNT(void){
 1.18963 +    static int osType = 0;
 1.18964 +    if( osType==0 ){
 1.18965 +      OSVERSIONINFO sInfo;
 1.18966 +      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
 1.18967 +      GetVersionEx(&sInfo);
 1.18968 +      osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
 1.18969 +    }
 1.18970 +    return osType==2;
 1.18971 +  }
 1.18972 +#endif /* SQLITE_OS_WINCE || SQLITE_OS_WINRT */
 1.18973 +#endif
 1.18974 +
 1.18975 +#ifdef SQLITE_DEBUG
 1.18976 +/*
 1.18977 +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
 1.18978 +** intended for use only inside assert() statements.
 1.18979 +*/
 1.18980 +static int winMutexHeld(sqlite3_mutex *p){
 1.18981 +  return p->nRef!=0 && p->owner==GetCurrentThreadId();
 1.18982 +}
 1.18983 +static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
 1.18984 +  return p->nRef==0 || p->owner!=tid;
 1.18985 +}
 1.18986 +static int winMutexNotheld(sqlite3_mutex *p){
 1.18987 +  DWORD tid = GetCurrentThreadId(); 
 1.18988 +  return winMutexNotheld2(p, tid);
 1.18989 +}
 1.18990 +#endif
 1.18991 +
 1.18992 +
 1.18993 +/*
 1.18994 +** Initialize and deinitialize the mutex subsystem.
 1.18995 +*/
 1.18996 +static sqlite3_mutex winMutex_staticMutexes[6] = {
 1.18997 +  SQLITE3_MUTEX_INITIALIZER,
 1.18998 +  SQLITE3_MUTEX_INITIALIZER,
 1.18999 +  SQLITE3_MUTEX_INITIALIZER,
 1.19000 +  SQLITE3_MUTEX_INITIALIZER,
 1.19001 +  SQLITE3_MUTEX_INITIALIZER,
 1.19002 +  SQLITE3_MUTEX_INITIALIZER
 1.19003 +};
 1.19004 +static int winMutex_isInit = 0;
 1.19005 +/* As winMutexInit() and winMutexEnd() are called as part
 1.19006 +** of the sqlite3_initialize and sqlite3_shutdown()
 1.19007 +** processing, the "interlocked" magic is probably not
 1.19008 +** strictly necessary.
 1.19009 +*/
 1.19010 +static LONG winMutex_lock = 0;
 1.19011 +
 1.19012 +SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
 1.19013 +
 1.19014 +static int winMutexInit(void){ 
 1.19015 +  /* The first to increment to 1 does actual initialization */
 1.19016 +  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
 1.19017 +    int i;
 1.19018 +    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
 1.19019 +#if SQLITE_OS_WINRT
 1.19020 +      InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
 1.19021 +#else
 1.19022 +      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
 1.19023 +#endif
 1.19024 +    }
 1.19025 +    winMutex_isInit = 1;
 1.19026 +  }else{
 1.19027 +    /* Someone else is in the process of initing the static mutexes */
 1.19028 +    while( !winMutex_isInit ){
 1.19029 +      sqlite3_win32_sleep(1);
 1.19030 +    }
 1.19031 +  }
 1.19032 +  return SQLITE_OK; 
 1.19033 +}
 1.19034 +
 1.19035 +static int winMutexEnd(void){ 
 1.19036 +  /* The first to decrement to 0 does actual shutdown 
 1.19037 +  ** (which should be the last to shutdown.) */
 1.19038 +  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
 1.19039 +    if( winMutex_isInit==1 ){
 1.19040 +      int i;
 1.19041 +      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
 1.19042 +        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
 1.19043 +      }
 1.19044 +      winMutex_isInit = 0;
 1.19045 +    }
 1.19046 +  }
 1.19047 +  return SQLITE_OK; 
 1.19048 +}
 1.19049 +
 1.19050 +/*
 1.19051 +** The sqlite3_mutex_alloc() routine allocates a new
 1.19052 +** mutex and returns a pointer to it.  If it returns NULL
 1.19053 +** that means that a mutex could not be allocated.  SQLite
 1.19054 +** will unwind its stack and return an error.  The argument
 1.19055 +** to sqlite3_mutex_alloc() is one of these integer constants:
 1.19056 +**
 1.19057 +** <ul>
 1.19058 +** <li>  SQLITE_MUTEX_FAST
 1.19059 +** <li>  SQLITE_MUTEX_RECURSIVE
 1.19060 +** <li>  SQLITE_MUTEX_STATIC_MASTER
 1.19061 +** <li>  SQLITE_MUTEX_STATIC_MEM
 1.19062 +** <li>  SQLITE_MUTEX_STATIC_MEM2
 1.19063 +** <li>  SQLITE_MUTEX_STATIC_PRNG
 1.19064 +** <li>  SQLITE_MUTEX_STATIC_LRU
 1.19065 +** <li>  SQLITE_MUTEX_STATIC_PMEM
 1.19066 +** </ul>
 1.19067 +**
 1.19068 +** The first two constants cause sqlite3_mutex_alloc() to create
 1.19069 +** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
 1.19070 +** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
 1.19071 +** The mutex implementation does not need to make a distinction
 1.19072 +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
 1.19073 +** not want to.  But SQLite will only request a recursive mutex in
 1.19074 +** cases where it really needs one.  If a faster non-recursive mutex
 1.19075 +** implementation is available on the host platform, the mutex subsystem
 1.19076 +** might return such a mutex in response to SQLITE_MUTEX_FAST.
 1.19077 +**
 1.19078 +** The other allowed parameters to sqlite3_mutex_alloc() each return
 1.19079 +** a pointer to a static preexisting mutex.  Six static mutexes are
 1.19080 +** used by the current version of SQLite.  Future versions of SQLite
 1.19081 +** may add additional static mutexes.  Static mutexes are for internal
 1.19082 +** use by SQLite only.  Applications that use SQLite mutexes should
 1.19083 +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
 1.19084 +** SQLITE_MUTEX_RECURSIVE.
 1.19085 +**
 1.19086 +** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
 1.19087 +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
 1.19088 +** returns a different mutex on every call.  But for the static 
 1.19089 +** mutex types, the same mutex is returned on every call that has
 1.19090 +** the same type number.
 1.19091 +*/
 1.19092 +static sqlite3_mutex *winMutexAlloc(int iType){
 1.19093 +  sqlite3_mutex *p;
 1.19094 +
 1.19095 +  switch( iType ){
 1.19096 +    case SQLITE_MUTEX_FAST:
 1.19097 +    case SQLITE_MUTEX_RECURSIVE: {
 1.19098 +      p = sqlite3MallocZero( sizeof(*p) );
 1.19099 +      if( p ){  
 1.19100 +#ifdef SQLITE_DEBUG
 1.19101 +        p->id = iType;
 1.19102 +#endif
 1.19103 +#if SQLITE_OS_WINRT
 1.19104 +        InitializeCriticalSectionEx(&p->mutex, 0, 0);
 1.19105 +#else
 1.19106 +        InitializeCriticalSection(&p->mutex);
 1.19107 +#endif
 1.19108 +      }
 1.19109 +      break;
 1.19110 +    }
 1.19111 +    default: {
 1.19112 +      assert( winMutex_isInit==1 );
 1.19113 +      assert( iType-2 >= 0 );
 1.19114 +      assert( iType-2 < ArraySize(winMutex_staticMutexes) );
 1.19115 +      p = &winMutex_staticMutexes[iType-2];
 1.19116 +#ifdef SQLITE_DEBUG
 1.19117 +      p->id = iType;
 1.19118 +#endif
 1.19119 +      break;
 1.19120 +    }
 1.19121 +  }
 1.19122 +  return p;
 1.19123 +}
 1.19124 +
 1.19125 +
 1.19126 +/*
 1.19127 +** This routine deallocates a previously
 1.19128 +** allocated mutex.  SQLite is careful to deallocate every
 1.19129 +** mutex that it allocates.
 1.19130 +*/
 1.19131 +static void winMutexFree(sqlite3_mutex *p){
 1.19132 +  assert( p );
 1.19133 +  assert( p->nRef==0 && p->owner==0 );
 1.19134 +  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
 1.19135 +  DeleteCriticalSection(&p->mutex);
 1.19136 +  sqlite3_free(p);
 1.19137 +}
 1.19138 +
 1.19139 +/*
 1.19140 +** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
 1.19141 +** to enter a mutex.  If another thread is already within the mutex,
 1.19142 +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
 1.19143 +** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
 1.19144 +** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
 1.19145 +** be entered multiple times by the same thread.  In such cases the,
 1.19146 +** mutex must be exited an equal number of times before another thread
 1.19147 +** can enter.  If the same thread tries to enter any other kind of mutex
 1.19148 +** more than once, the behavior is undefined.
 1.19149 +*/
 1.19150 +static void winMutexEnter(sqlite3_mutex *p){
 1.19151 +#ifdef SQLITE_DEBUG
 1.19152 +  DWORD tid = GetCurrentThreadId(); 
 1.19153 +  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
 1.19154 +#endif
 1.19155 +  EnterCriticalSection(&p->mutex);
 1.19156 +#ifdef SQLITE_DEBUG
 1.19157 +  assert( p->nRef>0 || p->owner==0 );
 1.19158 +  p->owner = tid; 
 1.19159 +  p->nRef++;
 1.19160 +  if( p->trace ){
 1.19161 +    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
 1.19162 +  }
 1.19163 +#endif
 1.19164 +}
 1.19165 +static int winMutexTry(sqlite3_mutex *p){
 1.19166 +#ifndef NDEBUG
 1.19167 +  DWORD tid = GetCurrentThreadId(); 
 1.19168 +#endif
 1.19169 +  int rc = SQLITE_BUSY;
 1.19170 +  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
 1.19171 +  /*
 1.19172 +  ** The sqlite3_mutex_try() routine is very rarely used, and when it
 1.19173 +  ** is used it is merely an optimization.  So it is OK for it to always
 1.19174 +  ** fail.  
 1.19175 +  **
 1.19176 +  ** The TryEnterCriticalSection() interface is only available on WinNT.
 1.19177 +  ** And some windows compilers complain if you try to use it without
 1.19178 +  ** first doing some #defines that prevent SQLite from building on Win98.
 1.19179 +  ** For that reason, we will omit this optimization for now.  See
 1.19180 +  ** ticket #2685.
 1.19181 +  */
 1.19182 +#if 0
 1.19183 +  if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
 1.19184 +    p->owner = tid;
 1.19185 +    p->nRef++;
 1.19186 +    rc = SQLITE_OK;
 1.19187 +  }
 1.19188 +#else
 1.19189 +  UNUSED_PARAMETER(p);
 1.19190 +#endif
 1.19191 +#ifdef SQLITE_DEBUG
 1.19192 +  if( rc==SQLITE_OK && p->trace ){
 1.19193 +    printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
 1.19194 +  }
 1.19195 +#endif
 1.19196 +  return rc;
 1.19197 +}
 1.19198 +
 1.19199 +/*
 1.19200 +** The sqlite3_mutex_leave() routine exits a mutex that was
 1.19201 +** previously entered by the same thread.  The behavior
 1.19202 +** is undefined if the mutex is not currently entered or
 1.19203 +** is not currently allocated.  SQLite will never do either.
 1.19204 +*/
 1.19205 +static void winMutexLeave(sqlite3_mutex *p){
 1.19206 +#ifndef NDEBUG
 1.19207 +  DWORD tid = GetCurrentThreadId();
 1.19208 +  assert( p->nRef>0 );
 1.19209 +  assert( p->owner==tid );
 1.19210 +  p->nRef--;
 1.19211 +  if( p->nRef==0 ) p->owner = 0;
 1.19212 +  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
 1.19213 +#endif
 1.19214 +  LeaveCriticalSection(&p->mutex);
 1.19215 +#ifdef SQLITE_DEBUG
 1.19216 +  if( p->trace ){
 1.19217 +    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
 1.19218 +  }
 1.19219 +#endif
 1.19220 +}
 1.19221 +
 1.19222 +SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
 1.19223 +  static const sqlite3_mutex_methods sMutex = {
 1.19224 +    winMutexInit,
 1.19225 +    winMutexEnd,
 1.19226 +    winMutexAlloc,
 1.19227 +    winMutexFree,
 1.19228 +    winMutexEnter,
 1.19229 +    winMutexTry,
 1.19230 +    winMutexLeave,
 1.19231 +#ifdef SQLITE_DEBUG
 1.19232 +    winMutexHeld,
 1.19233 +    winMutexNotheld
 1.19234 +#else
 1.19235 +    0,
 1.19236 +    0
 1.19237 +#endif
 1.19238 +  };
 1.19239 +
 1.19240 +  return &sMutex;
 1.19241 +}
 1.19242 +#endif /* SQLITE_MUTEX_W32 */
 1.19243 +
 1.19244 +/************** End of mutex_w32.c *******************************************/
 1.19245 +/************** Begin file malloc.c ******************************************/
 1.19246 +/*
 1.19247 +** 2001 September 15
 1.19248 +**
 1.19249 +** The author disclaims copyright to this source code.  In place of
 1.19250 +** a legal notice, here is a blessing:
 1.19251 +**
 1.19252 +**    May you do good and not evil.
 1.19253 +**    May you find forgiveness for yourself and forgive others.
 1.19254 +**    May you share freely, never taking more than you give.
 1.19255 +**
 1.19256 +*************************************************************************
 1.19257 +**
 1.19258 +** Memory allocation functions used throughout sqlite.
 1.19259 +*/
 1.19260 +/* #include <stdarg.h> */
 1.19261 +
 1.19262 +/*
 1.19263 +** Attempt to release up to n bytes of non-essential memory currently
 1.19264 +** held by SQLite. An example of non-essential memory is memory used to
 1.19265 +** cache database pages that are not currently in use.
 1.19266 +*/
 1.19267 +SQLITE_API int sqlite3_release_memory(int n){
 1.19268 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
 1.19269 +  return sqlite3PcacheReleaseMemory(n);
 1.19270 +#else
 1.19271 +  /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
 1.19272 +  ** is a no-op returning zero if SQLite is not compiled with
 1.19273 +  ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
 1.19274 +  UNUSED_PARAMETER(n);
 1.19275 +  return 0;
 1.19276 +#endif
 1.19277 +}
 1.19278 +
 1.19279 +/*
 1.19280 +** An instance of the following object records the location of
 1.19281 +** each unused scratch buffer.
 1.19282 +*/
 1.19283 +typedef struct ScratchFreeslot {
 1.19284 +  struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
 1.19285 +} ScratchFreeslot;
 1.19286 +
 1.19287 +/*
 1.19288 +** State information local to the memory allocation subsystem.
 1.19289 +*/
 1.19290 +static SQLITE_WSD struct Mem0Global {
 1.19291 +  sqlite3_mutex *mutex;         /* Mutex to serialize access */
 1.19292 +
 1.19293 +  /*
 1.19294 +  ** The alarm callback and its arguments.  The mem0.mutex lock will
 1.19295 +  ** be held while the callback is running.  Recursive calls into
 1.19296 +  ** the memory subsystem are allowed, but no new callbacks will be
 1.19297 +  ** issued.
 1.19298 +  */
 1.19299 +  sqlite3_int64 alarmThreshold;
 1.19300 +  void (*alarmCallback)(void*, sqlite3_int64,int);
 1.19301 +  void *alarmArg;
 1.19302 +
 1.19303 +  /*
 1.19304 +  ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
 1.19305 +  ** (so that a range test can be used to determine if an allocation
 1.19306 +  ** being freed came from pScratch) and a pointer to the list of
 1.19307 +  ** unused scratch allocations.
 1.19308 +  */
 1.19309 +  void *pScratchEnd;
 1.19310 +  ScratchFreeslot *pScratchFree;
 1.19311 +  u32 nScratchFree;
 1.19312 +
 1.19313 +  /*
 1.19314 +  ** True if heap is nearly "full" where "full" is defined by the
 1.19315 +  ** sqlite3_soft_heap_limit() setting.
 1.19316 +  */
 1.19317 +  int nearlyFull;
 1.19318 +} mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
 1.19319 +
 1.19320 +#define mem0 GLOBAL(struct Mem0Global, mem0)
 1.19321 +
 1.19322 +/*
 1.19323 +** This routine runs when the memory allocator sees that the
 1.19324 +** total memory allocation is about to exceed the soft heap
 1.19325 +** limit.
 1.19326 +*/
 1.19327 +static void softHeapLimitEnforcer(
 1.19328 +  void *NotUsed, 
 1.19329 +  sqlite3_int64 NotUsed2,
 1.19330 +  int allocSize
 1.19331 +){
 1.19332 +  UNUSED_PARAMETER2(NotUsed, NotUsed2);
 1.19333 +  sqlite3_release_memory(allocSize);
 1.19334 +}
 1.19335 +
 1.19336 +/*
 1.19337 +** Change the alarm callback
 1.19338 +*/
 1.19339 +static int sqlite3MemoryAlarm(
 1.19340 +  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
 1.19341 +  void *pArg,
 1.19342 +  sqlite3_int64 iThreshold
 1.19343 +){
 1.19344 +  int nUsed;
 1.19345 +  sqlite3_mutex_enter(mem0.mutex);
 1.19346 +  mem0.alarmCallback = xCallback;
 1.19347 +  mem0.alarmArg = pArg;
 1.19348 +  mem0.alarmThreshold = iThreshold;
 1.19349 +  nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
 1.19350 +  mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
 1.19351 +  sqlite3_mutex_leave(mem0.mutex);
 1.19352 +  return SQLITE_OK;
 1.19353 +}
 1.19354 +
 1.19355 +#ifndef SQLITE_OMIT_DEPRECATED
 1.19356 +/*
 1.19357 +** Deprecated external interface.  Internal/core SQLite code
 1.19358 +** should call sqlite3MemoryAlarm.
 1.19359 +*/
 1.19360 +SQLITE_API int sqlite3_memory_alarm(
 1.19361 +  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
 1.19362 +  void *pArg,
 1.19363 +  sqlite3_int64 iThreshold
 1.19364 +){
 1.19365 +  return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
 1.19366 +}
 1.19367 +#endif
 1.19368 +
 1.19369 +/*
 1.19370 +** Set the soft heap-size limit for the library. Passing a zero or 
 1.19371 +** negative value indicates no limit.
 1.19372 +*/
 1.19373 +SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
 1.19374 +  sqlite3_int64 priorLimit;
 1.19375 +  sqlite3_int64 excess;
 1.19376 +#ifndef SQLITE_OMIT_AUTOINIT
 1.19377 +  int rc = sqlite3_initialize();
 1.19378 +  if( rc ) return -1;
 1.19379 +#endif
 1.19380 +  sqlite3_mutex_enter(mem0.mutex);
 1.19381 +  priorLimit = mem0.alarmThreshold;
 1.19382 +  sqlite3_mutex_leave(mem0.mutex);
 1.19383 +  if( n<0 ) return priorLimit;
 1.19384 +  if( n>0 ){
 1.19385 +    sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
 1.19386 +  }else{
 1.19387 +    sqlite3MemoryAlarm(0, 0, 0);
 1.19388 +  }
 1.19389 +  excess = sqlite3_memory_used() - n;
 1.19390 +  if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
 1.19391 +  return priorLimit;
 1.19392 +}
 1.19393 +SQLITE_API void sqlite3_soft_heap_limit(int n){
 1.19394 +  if( n<0 ) n = 0;
 1.19395 +  sqlite3_soft_heap_limit64(n);
 1.19396 +}
 1.19397 +
 1.19398 +/*
 1.19399 +** Initialize the memory allocation subsystem.
 1.19400 +*/
 1.19401 +SQLITE_PRIVATE int sqlite3MallocInit(void){
 1.19402 +  if( sqlite3GlobalConfig.m.xMalloc==0 ){
 1.19403 +    sqlite3MemSetDefault();
 1.19404 +  }
 1.19405 +  memset(&mem0, 0, sizeof(mem0));
 1.19406 +  if( sqlite3GlobalConfig.bCoreMutex ){
 1.19407 +    mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
 1.19408 +  }
 1.19409 +  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
 1.19410 +      && sqlite3GlobalConfig.nScratch>0 ){
 1.19411 +    int i, n, sz;
 1.19412 +    ScratchFreeslot *pSlot;
 1.19413 +    sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
 1.19414 +    sqlite3GlobalConfig.szScratch = sz;
 1.19415 +    pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
 1.19416 +    n = sqlite3GlobalConfig.nScratch;
 1.19417 +    mem0.pScratchFree = pSlot;
 1.19418 +    mem0.nScratchFree = n;
 1.19419 +    for(i=0; i<n-1; i++){
 1.19420 +      pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
 1.19421 +      pSlot = pSlot->pNext;
 1.19422 +    }
 1.19423 +    pSlot->pNext = 0;
 1.19424 +    mem0.pScratchEnd = (void*)&pSlot[1];
 1.19425 +  }else{
 1.19426 +    mem0.pScratchEnd = 0;
 1.19427 +    sqlite3GlobalConfig.pScratch = 0;
 1.19428 +    sqlite3GlobalConfig.szScratch = 0;
 1.19429 +    sqlite3GlobalConfig.nScratch = 0;
 1.19430 +  }
 1.19431 +  if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
 1.19432 +      || sqlite3GlobalConfig.nPage<1 ){
 1.19433 +    sqlite3GlobalConfig.pPage = 0;
 1.19434 +    sqlite3GlobalConfig.szPage = 0;
 1.19435 +    sqlite3GlobalConfig.nPage = 0;
 1.19436 +  }
 1.19437 +  return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
 1.19438 +}
 1.19439 +
 1.19440 +/*
 1.19441 +** Return true if the heap is currently under memory pressure - in other
 1.19442 +** words if the amount of heap used is close to the limit set by
 1.19443 +** sqlite3_soft_heap_limit().
 1.19444 +*/
 1.19445 +SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
 1.19446 +  return mem0.nearlyFull;
 1.19447 +}
 1.19448 +
 1.19449 +/*
 1.19450 +** Deinitialize the memory allocation subsystem.
 1.19451 +*/
 1.19452 +SQLITE_PRIVATE void sqlite3MallocEnd(void){
 1.19453 +  if( sqlite3GlobalConfig.m.xShutdown ){
 1.19454 +    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
 1.19455 +  }
 1.19456 +  memset(&mem0, 0, sizeof(mem0));
 1.19457 +}
 1.19458 +
 1.19459 +/*
 1.19460 +** Return the amount of memory currently checked out.
 1.19461 +*/
 1.19462 +SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
 1.19463 +  int n, mx;
 1.19464 +  sqlite3_int64 res;
 1.19465 +  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
 1.19466 +  res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
 1.19467 +  return res;
 1.19468 +}
 1.19469 +
 1.19470 +/*
 1.19471 +** Return the maximum amount of memory that has ever been
 1.19472 +** checked out since either the beginning of this process
 1.19473 +** or since the most recent reset.
 1.19474 +*/
 1.19475 +SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
 1.19476 +  int n, mx;
 1.19477 +  sqlite3_int64 res;
 1.19478 +  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
 1.19479 +  res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
 1.19480 +  return res;
 1.19481 +}
 1.19482 +
 1.19483 +/*
 1.19484 +** Trigger the alarm 
 1.19485 +*/
 1.19486 +static void sqlite3MallocAlarm(int nByte){
 1.19487 +  void (*xCallback)(void*,sqlite3_int64,int);
 1.19488 +  sqlite3_int64 nowUsed;
 1.19489 +  void *pArg;
 1.19490 +  if( mem0.alarmCallback==0 ) return;
 1.19491 +  xCallback = mem0.alarmCallback;
 1.19492 +  nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
 1.19493 +  pArg = mem0.alarmArg;
 1.19494 +  mem0.alarmCallback = 0;
 1.19495 +  sqlite3_mutex_leave(mem0.mutex);
 1.19496 +  xCallback(pArg, nowUsed, nByte);
 1.19497 +  sqlite3_mutex_enter(mem0.mutex);
 1.19498 +  mem0.alarmCallback = xCallback;
 1.19499 +  mem0.alarmArg = pArg;
 1.19500 +}
 1.19501 +
 1.19502 +/*
 1.19503 +** Do a memory allocation with statistics and alarms.  Assume the
 1.19504 +** lock is already held.
 1.19505 +*/
 1.19506 +static int mallocWithAlarm(int n, void **pp){
 1.19507 +  int nFull;
 1.19508 +  void *p;
 1.19509 +  assert( sqlite3_mutex_held(mem0.mutex) );
 1.19510 +  nFull = sqlite3GlobalConfig.m.xRoundup(n);
 1.19511 +  sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
 1.19512 +  if( mem0.alarmCallback!=0 ){
 1.19513 +    int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
 1.19514 +    if( nUsed >= mem0.alarmThreshold - nFull ){
 1.19515 +      mem0.nearlyFull = 1;
 1.19516 +      sqlite3MallocAlarm(nFull);
 1.19517 +    }else{
 1.19518 +      mem0.nearlyFull = 0;
 1.19519 +    }
 1.19520 +  }
 1.19521 +  p = sqlite3GlobalConfig.m.xMalloc(nFull);
 1.19522 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
 1.19523 +  if( p==0 && mem0.alarmCallback ){
 1.19524 +    sqlite3MallocAlarm(nFull);
 1.19525 +    p = sqlite3GlobalConfig.m.xMalloc(nFull);
 1.19526 +  }
 1.19527 +#endif
 1.19528 +  if( p ){
 1.19529 +    nFull = sqlite3MallocSize(p);
 1.19530 +    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
 1.19531 +    sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
 1.19532 +  }
 1.19533 +  *pp = p;
 1.19534 +  return nFull;
 1.19535 +}
 1.19536 +
 1.19537 +/*
 1.19538 +** Allocate memory.  This routine is like sqlite3_malloc() except that it
 1.19539 +** assumes the memory subsystem has already been initialized.
 1.19540 +*/
 1.19541 +SQLITE_PRIVATE void *sqlite3Malloc(int n){
 1.19542 +  void *p;
 1.19543 +  if( n<=0               /* IMP: R-65312-04917 */ 
 1.19544 +   || n>=0x7fffff00
 1.19545 +  ){
 1.19546 +    /* A memory allocation of a number of bytes which is near the maximum
 1.19547 +    ** signed integer value might cause an integer overflow inside of the
 1.19548 +    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
 1.19549 +    ** 255 bytes of overhead.  SQLite itself will never use anything near
 1.19550 +    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
 1.19551 +    p = 0;
 1.19552 +  }else if( sqlite3GlobalConfig.bMemstat ){
 1.19553 +    sqlite3_mutex_enter(mem0.mutex);
 1.19554 +    mallocWithAlarm(n, &p);
 1.19555 +    sqlite3_mutex_leave(mem0.mutex);
 1.19556 +  }else{
 1.19557 +    p = sqlite3GlobalConfig.m.xMalloc(n);
 1.19558 +  }
 1.19559 +  assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
 1.19560 +  return p;
 1.19561 +}
 1.19562 +
 1.19563 +/*
 1.19564 +** This version of the memory allocation is for use by the application.
 1.19565 +** First make sure the memory subsystem is initialized, then do the
 1.19566 +** allocation.
 1.19567 +*/
 1.19568 +SQLITE_API void *sqlite3_malloc(int n){
 1.19569 +#ifndef SQLITE_OMIT_AUTOINIT
 1.19570 +  if( sqlite3_initialize() ) return 0;
 1.19571 +#endif
 1.19572 +  return sqlite3Malloc(n);
 1.19573 +}
 1.19574 +
 1.19575 +/*
 1.19576 +** Each thread may only have a single outstanding allocation from
 1.19577 +** xScratchMalloc().  We verify this constraint in the single-threaded
 1.19578 +** case by setting scratchAllocOut to 1 when an allocation
 1.19579 +** is outstanding clearing it when the allocation is freed.
 1.19580 +*/
 1.19581 +#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
 1.19582 +static int scratchAllocOut = 0;
 1.19583 +#endif
 1.19584 +
 1.19585 +
 1.19586 +/*
 1.19587 +** Allocate memory that is to be used and released right away.
 1.19588 +** This routine is similar to alloca() in that it is not intended
 1.19589 +** for situations where the memory might be held long-term.  This
 1.19590 +** routine is intended to get memory to old large transient data
 1.19591 +** structures that would not normally fit on the stack of an
 1.19592 +** embedded processor.
 1.19593 +*/
 1.19594 +SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
 1.19595 +  void *p;
 1.19596 +  assert( n>0 );
 1.19597 +
 1.19598 +  sqlite3_mutex_enter(mem0.mutex);
 1.19599 +  if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
 1.19600 +    p = mem0.pScratchFree;
 1.19601 +    mem0.pScratchFree = mem0.pScratchFree->pNext;
 1.19602 +    mem0.nScratchFree--;
 1.19603 +    sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
 1.19604 +    sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
 1.19605 +    sqlite3_mutex_leave(mem0.mutex);
 1.19606 +  }else{
 1.19607 +    if( sqlite3GlobalConfig.bMemstat ){
 1.19608 +      sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
 1.19609 +      n = mallocWithAlarm(n, &p);
 1.19610 +      if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
 1.19611 +      sqlite3_mutex_leave(mem0.mutex);
 1.19612 +    }else{
 1.19613 +      sqlite3_mutex_leave(mem0.mutex);
 1.19614 +      p = sqlite3GlobalConfig.m.xMalloc(n);
 1.19615 +    }
 1.19616 +    sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
 1.19617 +  }
 1.19618 +  assert( sqlite3_mutex_notheld(mem0.mutex) );
 1.19619 +
 1.19620 +
 1.19621 +#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
 1.19622 +  /* Verify that no more than two scratch allocations per thread
 1.19623 +  ** are outstanding at one time.  (This is only checked in the
 1.19624 +  ** single-threaded case since checking in the multi-threaded case
 1.19625 +  ** would be much more complicated.) */
 1.19626 +  assert( scratchAllocOut<=1 );
 1.19627 +  if( p ) scratchAllocOut++;
 1.19628 +#endif
 1.19629 +
 1.19630 +  return p;
 1.19631 +}
 1.19632 +SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
 1.19633 +  if( p ){
 1.19634 +
 1.19635 +#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
 1.19636 +    /* Verify that no more than two scratch allocation per thread
 1.19637 +    ** is outstanding at one time.  (This is only checked in the
 1.19638 +    ** single-threaded case since checking in the multi-threaded case
 1.19639 +    ** would be much more complicated.) */
 1.19640 +    assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
 1.19641 +    scratchAllocOut--;
 1.19642 +#endif
 1.19643 +
 1.19644 +    if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
 1.19645 +      /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
 1.19646 +      ScratchFreeslot *pSlot;
 1.19647 +      pSlot = (ScratchFreeslot*)p;
 1.19648 +      sqlite3_mutex_enter(mem0.mutex);
 1.19649 +      pSlot->pNext = mem0.pScratchFree;
 1.19650 +      mem0.pScratchFree = pSlot;
 1.19651 +      mem0.nScratchFree++;
 1.19652 +      assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
 1.19653 +      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
 1.19654 +      sqlite3_mutex_leave(mem0.mutex);
 1.19655 +    }else{
 1.19656 +      /* Release memory back to the heap */
 1.19657 +      assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
 1.19658 +      assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
 1.19659 +      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
 1.19660 +      if( sqlite3GlobalConfig.bMemstat ){
 1.19661 +        int iSize = sqlite3MallocSize(p);
 1.19662 +        sqlite3_mutex_enter(mem0.mutex);
 1.19663 +        sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
 1.19664 +        sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
 1.19665 +        sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
 1.19666 +        sqlite3GlobalConfig.m.xFree(p);
 1.19667 +        sqlite3_mutex_leave(mem0.mutex);
 1.19668 +      }else{
 1.19669 +        sqlite3GlobalConfig.m.xFree(p);
 1.19670 +      }
 1.19671 +    }
 1.19672 +  }
 1.19673 +}
 1.19674 +
 1.19675 +/*
 1.19676 +** TRUE if p is a lookaside memory allocation from db
 1.19677 +*/
 1.19678 +#ifndef SQLITE_OMIT_LOOKASIDE
 1.19679 +static int isLookaside(sqlite3 *db, void *p){
 1.19680 +  return p>=db->lookaside.pStart && p<db->lookaside.pEnd;
 1.19681 +}
 1.19682 +#else
 1.19683 +#define isLookaside(A,B) 0
 1.19684 +#endif
 1.19685 +
 1.19686 +/*
 1.19687 +** Return the size of a memory allocation previously obtained from
 1.19688 +** sqlite3Malloc() or sqlite3_malloc().
 1.19689 +*/
 1.19690 +SQLITE_PRIVATE int sqlite3MallocSize(void *p){
 1.19691 +  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
 1.19692 +  assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
 1.19693 +  return sqlite3GlobalConfig.m.xSize(p);
 1.19694 +}
 1.19695 +SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
 1.19696 +  assert( db!=0 );
 1.19697 +  assert( sqlite3_mutex_held(db->mutex) );
 1.19698 +  if( isLookaside(db, p) ){
 1.19699 +    return db->lookaside.sz;
 1.19700 +  }else{
 1.19701 +    assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
 1.19702 +    assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
 1.19703 +    assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
 1.19704 +    return sqlite3GlobalConfig.m.xSize(p);
 1.19705 +  }
 1.19706 +}
 1.19707 +
 1.19708 +/*
 1.19709 +** Free memory previously obtained from sqlite3Malloc().
 1.19710 +*/
 1.19711 +SQLITE_API void sqlite3_free(void *p){
 1.19712 +  if( p==0 ) return;  /* IMP: R-49053-54554 */
 1.19713 +  assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
 1.19714 +  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
 1.19715 +  if( sqlite3GlobalConfig.bMemstat ){
 1.19716 +    sqlite3_mutex_enter(mem0.mutex);
 1.19717 +    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
 1.19718 +    sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
 1.19719 +    sqlite3GlobalConfig.m.xFree(p);
 1.19720 +    sqlite3_mutex_leave(mem0.mutex);
 1.19721 +  }else{
 1.19722 +    sqlite3GlobalConfig.m.xFree(p);
 1.19723 +  }
 1.19724 +}
 1.19725 +
 1.19726 +/*
 1.19727 +** Free memory that might be associated with a particular database
 1.19728 +** connection.
 1.19729 +*/
 1.19730 +SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
 1.19731 +  assert( db==0 || sqlite3_mutex_held(db->mutex) );
 1.19732 +  if( p==0 ) return;
 1.19733 +  if( db ){
 1.19734 +    if( db->pnBytesFreed ){
 1.19735 +      *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
 1.19736 +      return;
 1.19737 +    }
 1.19738 +    if( isLookaside(db, p) ){
 1.19739 +      LookasideSlot *pBuf = (LookasideSlot*)p;
 1.19740 +#if SQLITE_DEBUG
 1.19741 +      /* Trash all content in the buffer being freed */
 1.19742 +      memset(p, 0xaa, db->lookaside.sz);
 1.19743 +#endif
 1.19744 +      pBuf->pNext = db->lookaside.pFree;
 1.19745 +      db->lookaside.pFree = pBuf;
 1.19746 +      db->lookaside.nOut--;
 1.19747 +      return;
 1.19748 +    }
 1.19749 +  }
 1.19750 +  assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
 1.19751 +  assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
 1.19752 +  assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
 1.19753 +  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
 1.19754 +  sqlite3_free(p);
 1.19755 +}
 1.19756 +
 1.19757 +/*
 1.19758 +** Change the size of an existing memory allocation
 1.19759 +*/
 1.19760 +SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
 1.19761 +  int nOld, nNew, nDiff;
 1.19762 +  void *pNew;
 1.19763 +  if( pOld==0 ){
 1.19764 +    return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
 1.19765 +  }
 1.19766 +  if( nBytes<=0 ){
 1.19767 +    sqlite3_free(pOld); /* IMP: R-31593-10574 */
 1.19768 +    return 0;
 1.19769 +  }
 1.19770 +  if( nBytes>=0x7fffff00 ){
 1.19771 +    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
 1.19772 +    return 0;
 1.19773 +  }
 1.19774 +  nOld = sqlite3MallocSize(pOld);
 1.19775 +  /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
 1.19776 +  ** argument to xRealloc is always a value returned by a prior call to
 1.19777 +  ** xRoundup. */
 1.19778 +  nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
 1.19779 +  if( nOld==nNew ){
 1.19780 +    pNew = pOld;
 1.19781 +  }else if( sqlite3GlobalConfig.bMemstat ){
 1.19782 +    sqlite3_mutex_enter(mem0.mutex);
 1.19783 +    sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
 1.19784 +    nDiff = nNew - nOld;
 1.19785 +    if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= 
 1.19786 +          mem0.alarmThreshold-nDiff ){
 1.19787 +      sqlite3MallocAlarm(nDiff);
 1.19788 +    }
 1.19789 +    assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
 1.19790 +    assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
 1.19791 +    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
 1.19792 +    if( pNew==0 && mem0.alarmCallback ){
 1.19793 +      sqlite3MallocAlarm(nBytes);
 1.19794 +      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
 1.19795 +    }
 1.19796 +    if( pNew ){
 1.19797 +      nNew = sqlite3MallocSize(pNew);
 1.19798 +      sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
 1.19799 +    }
 1.19800 +    sqlite3_mutex_leave(mem0.mutex);
 1.19801 +  }else{
 1.19802 +    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
 1.19803 +  }
 1.19804 +  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
 1.19805 +  return pNew;
 1.19806 +}
 1.19807 +
 1.19808 +/*
 1.19809 +** The public interface to sqlite3Realloc.  Make sure that the memory
 1.19810 +** subsystem is initialized prior to invoking sqliteRealloc.
 1.19811 +*/
 1.19812 +SQLITE_API void *sqlite3_realloc(void *pOld, int n){
 1.19813 +#ifndef SQLITE_OMIT_AUTOINIT
 1.19814 +  if( sqlite3_initialize() ) return 0;
 1.19815 +#endif
 1.19816 +  return sqlite3Realloc(pOld, n);
 1.19817 +}
 1.19818 +
 1.19819 +
 1.19820 +/*
 1.19821 +** Allocate and zero memory.
 1.19822 +*/ 
 1.19823 +SQLITE_PRIVATE void *sqlite3MallocZero(int n){
 1.19824 +  void *p = sqlite3Malloc(n);
 1.19825 +  if( p ){
 1.19826 +    memset(p, 0, n);
 1.19827 +  }
 1.19828 +  return p;
 1.19829 +}
 1.19830 +
 1.19831 +/*
 1.19832 +** Allocate and zero memory.  If the allocation fails, make
 1.19833 +** the mallocFailed flag in the connection pointer.
 1.19834 +*/
 1.19835 +SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
 1.19836 +  void *p = sqlite3DbMallocRaw(db, n);
 1.19837 +  if( p ){
 1.19838 +    memset(p, 0, n);
 1.19839 +  }
 1.19840 +  return p;
 1.19841 +}
 1.19842 +
 1.19843 +/*
 1.19844 +** Allocate and zero memory.  If the allocation fails, make
 1.19845 +** the mallocFailed flag in the connection pointer.
 1.19846 +**
 1.19847 +** If db!=0 and db->mallocFailed is true (indicating a prior malloc
 1.19848 +** failure on the same database connection) then always return 0.
 1.19849 +** Hence for a particular database connection, once malloc starts
 1.19850 +** failing, it fails consistently until mallocFailed is reset.
 1.19851 +** This is an important assumption.  There are many places in the
 1.19852 +** code that do things like this:
 1.19853 +**
 1.19854 +**         int *a = (int*)sqlite3DbMallocRaw(db, 100);
 1.19855 +**         int *b = (int*)sqlite3DbMallocRaw(db, 200);
 1.19856 +**         if( b ) a[10] = 9;
 1.19857 +**
 1.19858 +** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
 1.19859 +** that all prior mallocs (ex: "a") worked too.
 1.19860 +*/
 1.19861 +SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
 1.19862 +  void *p;
 1.19863 +  assert( db==0 || sqlite3_mutex_held(db->mutex) );
 1.19864 +  assert( db==0 || db->pnBytesFreed==0 );
 1.19865 +#ifndef SQLITE_OMIT_LOOKASIDE
 1.19866 +  if( db ){
 1.19867 +    LookasideSlot *pBuf;
 1.19868 +    if( db->mallocFailed ){
 1.19869 +      return 0;
 1.19870 +    }
 1.19871 +    if( db->lookaside.bEnabled ){
 1.19872 +      if( n>db->lookaside.sz ){
 1.19873 +        db->lookaside.anStat[1]++;
 1.19874 +      }else if( (pBuf = db->lookaside.pFree)==0 ){
 1.19875 +        db->lookaside.anStat[2]++;
 1.19876 +      }else{
 1.19877 +        db->lookaside.pFree = pBuf->pNext;
 1.19878 +        db->lookaside.nOut++;
 1.19879 +        db->lookaside.anStat[0]++;
 1.19880 +        if( db->lookaside.nOut>db->lookaside.mxOut ){
 1.19881 +          db->lookaside.mxOut = db->lookaside.nOut;
 1.19882 +        }
 1.19883 +        return (void*)pBuf;
 1.19884 +      }
 1.19885 +    }
 1.19886 +  }
 1.19887 +#else
 1.19888 +  if( db && db->mallocFailed ){
 1.19889 +    return 0;
 1.19890 +  }
 1.19891 +#endif
 1.19892 +  p = sqlite3Malloc(n);
 1.19893 +  if( !p && db ){
 1.19894 +    db->mallocFailed = 1;
 1.19895 +  }
 1.19896 +  sqlite3MemdebugSetType(p, MEMTYPE_DB |
 1.19897 +         ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
 1.19898 +  return p;
 1.19899 +}
 1.19900 +
 1.19901 +/*
 1.19902 +** Resize the block of memory pointed to by p to n bytes. If the
 1.19903 +** resize fails, set the mallocFailed flag in the connection object.
 1.19904 +*/
 1.19905 +SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
 1.19906 +  void *pNew = 0;
 1.19907 +  assert( db!=0 );
 1.19908 +  assert( sqlite3_mutex_held(db->mutex) );
 1.19909 +  if( db->mallocFailed==0 ){
 1.19910 +    if( p==0 ){
 1.19911 +      return sqlite3DbMallocRaw(db, n);
 1.19912 +    }
 1.19913 +    if( isLookaside(db, p) ){
 1.19914 +      if( n<=db->lookaside.sz ){
 1.19915 +        return p;
 1.19916 +      }
 1.19917 +      pNew = sqlite3DbMallocRaw(db, n);
 1.19918 +      if( pNew ){
 1.19919 +        memcpy(pNew, p, db->lookaside.sz);
 1.19920 +        sqlite3DbFree(db, p);
 1.19921 +      }
 1.19922 +    }else{
 1.19923 +      assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
 1.19924 +      assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
 1.19925 +      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
 1.19926 +      pNew = sqlite3_realloc(p, n);
 1.19927 +      if( !pNew ){
 1.19928 +        sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
 1.19929 +        db->mallocFailed = 1;
 1.19930 +      }
 1.19931 +      sqlite3MemdebugSetType(pNew, MEMTYPE_DB | 
 1.19932 +            (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
 1.19933 +    }
 1.19934 +  }
 1.19935 +  return pNew;
 1.19936 +}
 1.19937 +
 1.19938 +/*
 1.19939 +** Attempt to reallocate p.  If the reallocation fails, then free p
 1.19940 +** and set the mallocFailed flag in the database connection.
 1.19941 +*/
 1.19942 +SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
 1.19943 +  void *pNew;
 1.19944 +  pNew = sqlite3DbRealloc(db, p, n);
 1.19945 +  if( !pNew ){
 1.19946 +    sqlite3DbFree(db, p);
 1.19947 +  }
 1.19948 +  return pNew;
 1.19949 +}
 1.19950 +
 1.19951 +/*
 1.19952 +** Make a copy of a string in memory obtained from sqliteMalloc(). These 
 1.19953 +** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
 1.19954 +** is because when memory debugging is turned on, these two functions are 
 1.19955 +** called via macros that record the current file and line number in the
 1.19956 +** ThreadData structure.
 1.19957 +*/
 1.19958 +SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
 1.19959 +  char *zNew;
 1.19960 +  size_t n;
 1.19961 +  if( z==0 ){
 1.19962 +    return 0;
 1.19963 +  }
 1.19964 +  n = sqlite3Strlen30(z) + 1;
 1.19965 +  assert( (n&0x7fffffff)==n );
 1.19966 +  zNew = sqlite3DbMallocRaw(db, (int)n);
 1.19967 +  if( zNew ){
 1.19968 +    memcpy(zNew, z, n);
 1.19969 +  }
 1.19970 +  return zNew;
 1.19971 +}
 1.19972 +SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
 1.19973 +  char *zNew;
 1.19974 +  if( z==0 ){
 1.19975 +    return 0;
 1.19976 +  }
 1.19977 +  assert( (n&0x7fffffff)==n );
 1.19978 +  zNew = sqlite3DbMallocRaw(db, n+1);
 1.19979 +  if( zNew ){
 1.19980 +    memcpy(zNew, z, n);
 1.19981 +    zNew[n] = 0;
 1.19982 +  }
 1.19983 +  return zNew;
 1.19984 +}
 1.19985 +
 1.19986 +/*
 1.19987 +** Create a string from the zFromat argument and the va_list that follows.
 1.19988 +** Store the string in memory obtained from sqliteMalloc() and make *pz
 1.19989 +** point to that string.
 1.19990 +*/
 1.19991 +SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
 1.19992 +  va_list ap;
 1.19993 +  char *z;
 1.19994 +
 1.19995 +  va_start(ap, zFormat);
 1.19996 +  z = sqlite3VMPrintf(db, zFormat, ap);
 1.19997 +  va_end(ap);
 1.19998 +  sqlite3DbFree(db, *pz);
 1.19999 +  *pz = z;
 1.20000 +}
 1.20001 +
 1.20002 +
 1.20003 +/*
 1.20004 +** This function must be called before exiting any API function (i.e. 
 1.20005 +** returning control to the user) that has called sqlite3_malloc or
 1.20006 +** sqlite3_realloc.
 1.20007 +**
 1.20008 +** The returned value is normally a copy of the second argument to this
 1.20009 +** function. However, if a malloc() failure has occurred since the previous
 1.20010 +** invocation SQLITE_NOMEM is returned instead. 
 1.20011 +**
 1.20012 +** If the first argument, db, is not NULL and a malloc() error has occurred,
 1.20013 +** then the connection error-code (the value returned by sqlite3_errcode())
 1.20014 +** is set to SQLITE_NOMEM.
 1.20015 +*/
 1.20016 +SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
 1.20017 +  /* If the db handle is not NULL, then we must hold the connection handle
 1.20018 +  ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
 1.20019 +  ** is unsafe, as is the call to sqlite3Error().
 1.20020 +  */
 1.20021 +  assert( !db || sqlite3_mutex_held(db->mutex) );
 1.20022 +  if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
 1.20023 +    sqlite3Error(db, SQLITE_NOMEM, 0);
 1.20024 +    db->mallocFailed = 0;
 1.20025 +    rc = SQLITE_NOMEM;
 1.20026 +  }
 1.20027 +  return rc & (db ? db->errMask : 0xff);
 1.20028 +}
 1.20029 +
 1.20030 +/************** End of malloc.c **********************************************/
 1.20031 +/************** Begin file printf.c ******************************************/
 1.20032 +/*
 1.20033 +** The "printf" code that follows dates from the 1980's.  It is in
 1.20034 +** the public domain.  The original comments are included here for
 1.20035 +** completeness.  They are very out-of-date but might be useful as
 1.20036 +** an historical reference.  Most of the "enhancements" have been backed
 1.20037 +** out so that the functionality is now the same as standard printf().
 1.20038 +**
 1.20039 +**************************************************************************
 1.20040 +**
 1.20041 +** This file contains code for a set of "printf"-like routines.  These
 1.20042 +** routines format strings much like the printf() from the standard C
 1.20043 +** library, though the implementation here has enhancements to support
 1.20044 +** SQLlite.
 1.20045 +*/
 1.20046 +
 1.20047 +/*
 1.20048 +** Conversion types fall into various categories as defined by the
 1.20049 +** following enumeration.
 1.20050 +*/
 1.20051 +#define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
 1.20052 +#define etFLOAT       2 /* Floating point.  %f */
 1.20053 +#define etEXP         3 /* Exponentional notation. %e and %E */
 1.20054 +#define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
 1.20055 +#define etSIZE        5 /* Return number of characters processed so far. %n */
 1.20056 +#define etSTRING      6 /* Strings. %s */
 1.20057 +#define etDYNSTRING   7 /* Dynamically allocated strings. %z */
 1.20058 +#define etPERCENT     8 /* Percent symbol. %% */
 1.20059 +#define etCHARX       9 /* Characters. %c */
 1.20060 +/* The rest are extensions, not normally found in printf() */
 1.20061 +#define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
 1.20062 +#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
 1.20063 +                          NULL pointers replaced by SQL NULL.  %Q */
 1.20064 +#define etTOKEN      12 /* a pointer to a Token structure */
 1.20065 +#define etSRCLIST    13 /* a pointer to a SrcList */
 1.20066 +#define etPOINTER    14 /* The %p conversion */
 1.20067 +#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
 1.20068 +#define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
 1.20069 +
 1.20070 +#define etINVALID     0 /* Any unrecognized conversion type */
 1.20071 +
 1.20072 +
 1.20073 +/*
 1.20074 +** An "etByte" is an 8-bit unsigned value.
 1.20075 +*/
 1.20076 +typedef unsigned char etByte;
 1.20077 +
 1.20078 +/*
 1.20079 +** Each builtin conversion character (ex: the 'd' in "%d") is described
 1.20080 +** by an instance of the following structure
 1.20081 +*/
 1.20082 +typedef struct et_info {   /* Information about each format field */
 1.20083 +  char fmttype;            /* The format field code letter */
 1.20084 +  etByte base;             /* The base for radix conversion */
 1.20085 +  etByte flags;            /* One or more of FLAG_ constants below */
 1.20086 +  etByte type;             /* Conversion paradigm */
 1.20087 +  etByte charset;          /* Offset into aDigits[] of the digits string */
 1.20088 +  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
 1.20089 +} et_info;
 1.20090 +
 1.20091 +/*
 1.20092 +** Allowed values for et_info.flags
 1.20093 +*/
 1.20094 +#define FLAG_SIGNED  1     /* True if the value to convert is signed */
 1.20095 +#define FLAG_INTERN  2     /* True if for internal use only */
 1.20096 +#define FLAG_STRING  4     /* Allow infinity precision */
 1.20097 +
 1.20098 +
 1.20099 +/*
 1.20100 +** The following table is searched linearly, so it is good to put the
 1.20101 +** most frequently used conversion types first.
 1.20102 +*/
 1.20103 +static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
 1.20104 +static const char aPrefix[] = "-x0\000X0";
 1.20105 +static const et_info fmtinfo[] = {
 1.20106 +  {  'd', 10, 1, etRADIX,      0,  0 },
 1.20107 +  {  's',  0, 4, etSTRING,     0,  0 },
 1.20108 +  {  'g',  0, 1, etGENERIC,    30, 0 },
 1.20109 +  {  'z',  0, 4, etDYNSTRING,  0,  0 },
 1.20110 +  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
 1.20111 +  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
 1.20112 +  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
 1.20113 +  {  'c',  0, 0, etCHARX,      0,  0 },
 1.20114 +  {  'o',  8, 0, etRADIX,      0,  2 },
 1.20115 +  {  'u', 10, 0, etRADIX,      0,  0 },
 1.20116 +  {  'x', 16, 0, etRADIX,      16, 1 },
 1.20117 +  {  'X', 16, 0, etRADIX,      0,  4 },
 1.20118 +#ifndef SQLITE_OMIT_FLOATING_POINT
 1.20119 +  {  'f',  0, 1, etFLOAT,      0,  0 },
 1.20120 +  {  'e',  0, 1, etEXP,        30, 0 },
 1.20121 +  {  'E',  0, 1, etEXP,        14, 0 },
 1.20122 +  {  'G',  0, 1, etGENERIC,    14, 0 },
 1.20123 +#endif
 1.20124 +  {  'i', 10, 1, etRADIX,      0,  0 },
 1.20125 +  {  'n',  0, 0, etSIZE,       0,  0 },
 1.20126 +  {  '%',  0, 0, etPERCENT,    0,  0 },
 1.20127 +  {  'p', 16, 0, etPOINTER,    0,  1 },
 1.20128 +
 1.20129 +/* All the rest have the FLAG_INTERN bit set and are thus for internal
 1.20130 +** use only */
 1.20131 +  {  'T',  0, 2, etTOKEN,      0,  0 },
 1.20132 +  {  'S',  0, 2, etSRCLIST,    0,  0 },
 1.20133 +  {  'r', 10, 3, etORDINAL,    0,  0 },
 1.20134 +};
 1.20135 +
 1.20136 +/*
 1.20137 +** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
 1.20138 +** conversions will work.
 1.20139 +*/
 1.20140 +#ifndef SQLITE_OMIT_FLOATING_POINT
 1.20141 +/*
 1.20142 +** "*val" is a double such that 0.1 <= *val < 10.0
 1.20143 +** Return the ascii code for the leading digit of *val, then
 1.20144 +** multiply "*val" by 10.0 to renormalize.
 1.20145 +**
 1.20146 +** Example:
 1.20147 +**     input:     *val = 3.14159
 1.20148 +**     output:    *val = 1.4159    function return = '3'
 1.20149 +**
 1.20150 +** The counter *cnt is incremented each time.  After counter exceeds
 1.20151 +** 16 (the number of significant digits in a 64-bit float) '0' is
 1.20152 +** always returned.
 1.20153 +*/
 1.20154 +static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
 1.20155 +  int digit;
 1.20156 +  LONGDOUBLE_TYPE d;
 1.20157 +  if( (*cnt)<=0 ) return '0';
 1.20158 +  (*cnt)--;
 1.20159 +  digit = (int)*val;
 1.20160 +  d = digit;
 1.20161 +  digit += '0';
 1.20162 +  *val = (*val - d)*10.0;
 1.20163 +  return (char)digit;
 1.20164 +}
 1.20165 +#endif /* SQLITE_OMIT_FLOATING_POINT */
 1.20166 +
 1.20167 +/*
 1.20168 +** Append N space characters to the given string buffer.
 1.20169 +*/
 1.20170 +SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
 1.20171 +  static const char zSpaces[] = "                             ";
 1.20172 +  while( N>=(int)sizeof(zSpaces)-1 ){
 1.20173 +    sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
 1.20174 +    N -= sizeof(zSpaces)-1;
 1.20175 +  }
 1.20176 +  if( N>0 ){
 1.20177 +    sqlite3StrAccumAppend(pAccum, zSpaces, N);
 1.20178 +  }
 1.20179 +}
 1.20180 +
 1.20181 +/*
 1.20182 +** Set the StrAccum object to an error mode.
 1.20183 +*/
 1.20184 +static void setStrAccumError(StrAccum *p, u8 eError){
 1.20185 +  p->accError = eError;
 1.20186 +  p->nAlloc = 0;
 1.20187 +}
 1.20188 +
 1.20189 +/*
 1.20190 +** Extra argument values from a PrintfArguments object
 1.20191 +*/
 1.20192 +static sqlite3_int64 getIntArg(PrintfArguments *p){
 1.20193 +  if( p->nArg<=p->nUsed ) return 0;
 1.20194 +  return sqlite3_value_int64(p->apArg[p->nUsed++]);
 1.20195 +}
 1.20196 +static double getDoubleArg(PrintfArguments *p){
 1.20197 +  if( p->nArg<=p->nUsed ) return 0.0;
 1.20198 +  return sqlite3_value_double(p->apArg[p->nUsed++]);
 1.20199 +}
 1.20200 +static char *getTextArg(PrintfArguments *p){
 1.20201 +  if( p->nArg<=p->nUsed ) return 0;
 1.20202 +  return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
 1.20203 +}
 1.20204 +
 1.20205 +
 1.20206 +/*
 1.20207 +** On machines with a small stack size, you can redefine the
 1.20208 +** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
 1.20209 +*/
 1.20210 +#ifndef SQLITE_PRINT_BUF_SIZE
 1.20211 +# define SQLITE_PRINT_BUF_SIZE 70
 1.20212 +#endif
 1.20213 +#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
 1.20214 +
 1.20215 +/*
 1.20216 +** Render a string given by "fmt" into the StrAccum object.
 1.20217 +*/
 1.20218 +SQLITE_PRIVATE void sqlite3VXPrintf(
 1.20219 +  StrAccum *pAccum,          /* Accumulate results here */
 1.20220 +  u32 bFlags,                /* SQLITE_PRINTF_* flags */
 1.20221 +  const char *fmt,           /* Format string */
 1.20222 +  va_list ap                 /* arguments */
 1.20223 +){
 1.20224 +  int c;                     /* Next character in the format string */
 1.20225 +  char *bufpt;               /* Pointer to the conversion buffer */
 1.20226 +  int precision;             /* Precision of the current field */
 1.20227 +  int length;                /* Length of the field */
 1.20228 +  int idx;                   /* A general purpose loop counter */
 1.20229 +  int width;                 /* Width of the current field */
 1.20230 +  etByte flag_leftjustify;   /* True if "-" flag is present */
 1.20231 +  etByte flag_plussign;      /* True if "+" flag is present */
 1.20232 +  etByte flag_blanksign;     /* True if " " flag is present */
 1.20233 +  etByte flag_alternateform; /* True if "#" flag is present */
 1.20234 +  etByte flag_altform2;      /* True if "!" flag is present */
 1.20235 +  etByte flag_zeropad;       /* True if field width constant starts with zero */
 1.20236 +  etByte flag_long;          /* True if "l" flag is present */
 1.20237 +  etByte flag_longlong;      /* True if the "ll" flag is present */
 1.20238 +  etByte done;               /* Loop termination flag */
 1.20239 +  etByte xtype = 0;          /* Conversion paradigm */
 1.20240 +  u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
 1.20241 +  u8 useIntern;              /* Ok to use internal conversions (ex: %T) */
 1.20242 +  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
 1.20243 +  sqlite_uint64 longvalue;   /* Value for integer types */
 1.20244 +  LONGDOUBLE_TYPE realvalue; /* Value for real types */
 1.20245 +  const et_info *infop;      /* Pointer to the appropriate info structure */
 1.20246 +  char *zOut;                /* Rendering buffer */
 1.20247 +  int nOut;                  /* Size of the rendering buffer */
 1.20248 +  char *zExtra;              /* Malloced memory used by some conversion */
 1.20249 +#ifndef SQLITE_OMIT_FLOATING_POINT
 1.20250 +  int  exp, e2;              /* exponent of real numbers */
 1.20251 +  int nsd;                   /* Number of significant digits returned */
 1.20252 +  double rounder;            /* Used for rounding floating point values */
 1.20253 +  etByte flag_dp;            /* True if decimal point should be shown */
 1.20254 +  etByte flag_rtz;           /* True if trailing zeros should be removed */
 1.20255 +#endif
 1.20256 +  PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
 1.20257 +  char buf[etBUFSIZE];       /* Conversion buffer */
 1.20258 +
 1.20259 +  bufpt = 0;
 1.20260 +  if( bFlags ){
 1.20261 +    if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
 1.20262 +      pArgList = va_arg(ap, PrintfArguments*);
 1.20263 +    }
 1.20264 +    useIntern = bFlags & SQLITE_PRINTF_INTERNAL;
 1.20265 +  }else{
 1.20266 +    bArgList = useIntern = 0;
 1.20267 +  }
 1.20268 +  for(; (c=(*fmt))!=0; ++fmt){
 1.20269 +    if( c!='%' ){
 1.20270 +      int amt;
 1.20271 +      bufpt = (char *)fmt;
 1.20272 +      amt = 1;
 1.20273 +      while( (c=(*++fmt))!='%' && c!=0 ) amt++;
 1.20274 +      sqlite3StrAccumAppend(pAccum, bufpt, amt);
 1.20275 +      if( c==0 ) break;
 1.20276 +    }
 1.20277 +    if( (c=(*++fmt))==0 ){
 1.20278 +      sqlite3StrAccumAppend(pAccum, "%", 1);
 1.20279 +      break;
 1.20280 +    }
 1.20281 +    /* Find out what flags are present */
 1.20282 +    flag_leftjustify = flag_plussign = flag_blanksign = 
 1.20283 +     flag_alternateform = flag_altform2 = flag_zeropad = 0;
 1.20284 +    done = 0;
 1.20285 +    do{
 1.20286 +      switch( c ){
 1.20287 +        case '-':   flag_leftjustify = 1;     break;
 1.20288 +        case '+':   flag_plussign = 1;        break;
 1.20289 +        case ' ':   flag_blanksign = 1;       break;
 1.20290 +        case '#':   flag_alternateform = 1;   break;
 1.20291 +        case '!':   flag_altform2 = 1;        break;
 1.20292 +        case '0':   flag_zeropad = 1;         break;
 1.20293 +        default:    done = 1;                 break;
 1.20294 +      }
 1.20295 +    }while( !done && (c=(*++fmt))!=0 );
 1.20296 +    /* Get the field width */
 1.20297 +    width = 0;
 1.20298 +    if( c=='*' ){
 1.20299 +      if( bArgList ){
 1.20300 +        width = (int)getIntArg(pArgList);
 1.20301 +      }else{
 1.20302 +        width = va_arg(ap,int);
 1.20303 +      }
 1.20304 +      if( width<0 ){
 1.20305 +        flag_leftjustify = 1;
 1.20306 +        width = -width;
 1.20307 +      }
 1.20308 +      c = *++fmt;
 1.20309 +    }else{
 1.20310 +      while( c>='0' && c<='9' ){
 1.20311 +        width = width*10 + c - '0';
 1.20312 +        c = *++fmt;
 1.20313 +      }
 1.20314 +    }
 1.20315 +    /* Get the precision */
 1.20316 +    if( c=='.' ){
 1.20317 +      precision = 0;
 1.20318 +      c = *++fmt;
 1.20319 +      if( c=='*' ){
 1.20320 +        if( bArgList ){
 1.20321 +          precision = (int)getIntArg(pArgList);
 1.20322 +        }else{
 1.20323 +          precision = va_arg(ap,int);
 1.20324 +        }
 1.20325 +        if( precision<0 ) precision = -precision;
 1.20326 +        c = *++fmt;
 1.20327 +      }else{
 1.20328 +        while( c>='0' && c<='9' ){
 1.20329 +          precision = precision*10 + c - '0';
 1.20330 +          c = *++fmt;
 1.20331 +        }
 1.20332 +      }
 1.20333 +    }else{
 1.20334 +      precision = -1;
 1.20335 +    }
 1.20336 +    /* Get the conversion type modifier */
 1.20337 +    if( c=='l' ){
 1.20338 +      flag_long = 1;
 1.20339 +      c = *++fmt;
 1.20340 +      if( c=='l' ){
 1.20341 +        flag_longlong = 1;
 1.20342 +        c = *++fmt;
 1.20343 +      }else{
 1.20344 +        flag_longlong = 0;
 1.20345 +      }
 1.20346 +    }else{
 1.20347 +      flag_long = flag_longlong = 0;
 1.20348 +    }
 1.20349 +    /* Fetch the info entry for the field */
 1.20350 +    infop = &fmtinfo[0];
 1.20351 +    xtype = etINVALID;
 1.20352 +    for(idx=0; idx<ArraySize(fmtinfo); idx++){
 1.20353 +      if( c==fmtinfo[idx].fmttype ){
 1.20354 +        infop = &fmtinfo[idx];
 1.20355 +        if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
 1.20356 +          xtype = infop->type;
 1.20357 +        }else{
 1.20358 +          return;
 1.20359 +        }
 1.20360 +        break;
 1.20361 +      }
 1.20362 +    }
 1.20363 +    zExtra = 0;
 1.20364 +
 1.20365 +    /*
 1.20366 +    ** At this point, variables are initialized as follows:
 1.20367 +    **
 1.20368 +    **   flag_alternateform          TRUE if a '#' is present.
 1.20369 +    **   flag_altform2               TRUE if a '!' is present.
 1.20370 +    **   flag_plussign               TRUE if a '+' is present.
 1.20371 +    **   flag_leftjustify            TRUE if a '-' is present or if the
 1.20372 +    **                               field width was negative.
 1.20373 +    **   flag_zeropad                TRUE if the width began with 0.
 1.20374 +    **   flag_long                   TRUE if the letter 'l' (ell) prefixed
 1.20375 +    **                               the conversion character.
 1.20376 +    **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
 1.20377 +    **                               the conversion character.
 1.20378 +    **   flag_blanksign              TRUE if a ' ' is present.
 1.20379 +    **   width                       The specified field width.  This is
 1.20380 +    **                               always non-negative.  Zero is the default.
 1.20381 +    **   precision                   The specified precision.  The default
 1.20382 +    **                               is -1.
 1.20383 +    **   xtype                       The class of the conversion.
 1.20384 +    **   infop                       Pointer to the appropriate info struct.
 1.20385 +    */
 1.20386 +    switch( xtype ){
 1.20387 +      case etPOINTER:
 1.20388 +        flag_longlong = sizeof(char*)==sizeof(i64);
 1.20389 +        flag_long = sizeof(char*)==sizeof(long int);
 1.20390 +        /* Fall through into the next case */
 1.20391 +      case etORDINAL:
 1.20392 +      case etRADIX:
 1.20393 +        if( infop->flags & FLAG_SIGNED ){
 1.20394 +          i64 v;
 1.20395 +          if( bArgList ){
 1.20396 +            v = getIntArg(pArgList);
 1.20397 +          }else if( flag_longlong ){
 1.20398 +            v = va_arg(ap,i64);
 1.20399 +          }else if( flag_long ){
 1.20400 +            v = va_arg(ap,long int);
 1.20401 +          }else{
 1.20402 +            v = va_arg(ap,int);
 1.20403 +          }
 1.20404 +          if( v<0 ){
 1.20405 +            if( v==SMALLEST_INT64 ){
 1.20406 +              longvalue = ((u64)1)<<63;
 1.20407 +            }else{
 1.20408 +              longvalue = -v;
 1.20409 +            }
 1.20410 +            prefix = '-';
 1.20411 +          }else{
 1.20412 +            longvalue = v;
 1.20413 +            if( flag_plussign )        prefix = '+';
 1.20414 +            else if( flag_blanksign )  prefix = ' ';
 1.20415 +            else                       prefix = 0;
 1.20416 +          }
 1.20417 +        }else{
 1.20418 +          if( bArgList ){
 1.20419 +            longvalue = (u64)getIntArg(pArgList);
 1.20420 +          }else if( flag_longlong ){
 1.20421 +            longvalue = va_arg(ap,u64);
 1.20422 +          }else if( flag_long ){
 1.20423 +            longvalue = va_arg(ap,unsigned long int);
 1.20424 +          }else{
 1.20425 +            longvalue = va_arg(ap,unsigned int);
 1.20426 +          }
 1.20427 +          prefix = 0;
 1.20428 +        }
 1.20429 +        if( longvalue==0 ) flag_alternateform = 0;
 1.20430 +        if( flag_zeropad && precision<width-(prefix!=0) ){
 1.20431 +          precision = width-(prefix!=0);
 1.20432 +        }
 1.20433 +        if( precision<etBUFSIZE-10 ){
 1.20434 +          nOut = etBUFSIZE;
 1.20435 +          zOut = buf;
 1.20436 +        }else{
 1.20437 +          nOut = precision + 10;
 1.20438 +          zOut = zExtra = sqlite3Malloc( nOut );
 1.20439 +          if( zOut==0 ){
 1.20440 +            setStrAccumError(pAccum, STRACCUM_NOMEM);
 1.20441 +            return;
 1.20442 +          }
 1.20443 +        }
 1.20444 +        bufpt = &zOut[nOut-1];
 1.20445 +        if( xtype==etORDINAL ){
 1.20446 +          static const char zOrd[] = "thstndrd";
 1.20447 +          int x = (int)(longvalue % 10);
 1.20448 +          if( x>=4 || (longvalue/10)%10==1 ){
 1.20449 +            x = 0;
 1.20450 +          }
 1.20451 +          *(--bufpt) = zOrd[x*2+1];
 1.20452 +          *(--bufpt) = zOrd[x*2];
 1.20453 +        }
 1.20454 +        {
 1.20455 +          register const char *cset;      /* Use registers for speed */
 1.20456 +          register int base;
 1.20457 +          cset = &aDigits[infop->charset];
 1.20458 +          base = infop->base;
 1.20459 +          do{                                           /* Convert to ascii */
 1.20460 +            *(--bufpt) = cset[longvalue%base];
 1.20461 +            longvalue = longvalue/base;
 1.20462 +          }while( longvalue>0 );
 1.20463 +        }
 1.20464 +        length = (int)(&zOut[nOut-1]-bufpt);
 1.20465 +        for(idx=precision-length; idx>0; idx--){
 1.20466 +          *(--bufpt) = '0';                             /* Zero pad */
 1.20467 +        }
 1.20468 +        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
 1.20469 +        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
 1.20470 +          const char *pre;
 1.20471 +          char x;
 1.20472 +          pre = &aPrefix[infop->prefix];
 1.20473 +          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
 1.20474 +        }
 1.20475 +        length = (int)(&zOut[nOut-1]-bufpt);
 1.20476 +        break;
 1.20477 +      case etFLOAT:
 1.20478 +      case etEXP:
 1.20479 +      case etGENERIC:
 1.20480 +        if( bArgList ){
 1.20481 +          realvalue = getDoubleArg(pArgList);
 1.20482 +        }else{
 1.20483 +          realvalue = va_arg(ap,double);
 1.20484 +        }
 1.20485 +#ifdef SQLITE_OMIT_FLOATING_POINT
 1.20486 +        length = 0;
 1.20487 +#else
 1.20488 +        if( precision<0 ) precision = 6;         /* Set default precision */
 1.20489 +        if( realvalue<0.0 ){
 1.20490 +          realvalue = -realvalue;
 1.20491 +          prefix = '-';
 1.20492 +        }else{
 1.20493 +          if( flag_plussign )          prefix = '+';
 1.20494 +          else if( flag_blanksign )    prefix = ' ';
 1.20495 +          else                         prefix = 0;
 1.20496 +        }
 1.20497 +        if( xtype==etGENERIC && precision>0 ) precision--;
 1.20498 +        for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
 1.20499 +        if( xtype==etFLOAT ) realvalue += rounder;
 1.20500 +        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
 1.20501 +        exp = 0;
 1.20502 +        if( sqlite3IsNaN((double)realvalue) ){
 1.20503 +          bufpt = "NaN";
 1.20504 +          length = 3;
 1.20505 +          break;
 1.20506 +        }
 1.20507 +        if( realvalue>0.0 ){
 1.20508 +          LONGDOUBLE_TYPE scale = 1.0;
 1.20509 +          while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
 1.20510 +          while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
 1.20511 +          while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
 1.20512 +          while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
 1.20513 +          realvalue /= scale;
 1.20514 +          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
 1.20515 +          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
 1.20516 +          if( exp>350 ){
 1.20517 +            if( prefix=='-' ){
 1.20518 +              bufpt = "-Inf";
 1.20519 +            }else if( prefix=='+' ){
 1.20520 +              bufpt = "+Inf";
 1.20521 +            }else{
 1.20522 +              bufpt = "Inf";
 1.20523 +            }
 1.20524 +            length = sqlite3Strlen30(bufpt);
 1.20525 +            break;
 1.20526 +          }
 1.20527 +        }
 1.20528 +        bufpt = buf;
 1.20529 +        /*
 1.20530 +        ** If the field type is etGENERIC, then convert to either etEXP
 1.20531 +        ** or etFLOAT, as appropriate.
 1.20532 +        */
 1.20533 +        if( xtype!=etFLOAT ){
 1.20534 +          realvalue += rounder;
 1.20535 +          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
 1.20536 +        }
 1.20537 +        if( xtype==etGENERIC ){
 1.20538 +          flag_rtz = !flag_alternateform;
 1.20539 +          if( exp<-4 || exp>precision ){
 1.20540 +            xtype = etEXP;
 1.20541 +          }else{
 1.20542 +            precision = precision - exp;
 1.20543 +            xtype = etFLOAT;
 1.20544 +          }
 1.20545 +        }else{
 1.20546 +          flag_rtz = flag_altform2;
 1.20547 +        }
 1.20548 +        if( xtype==etEXP ){
 1.20549 +          e2 = 0;
 1.20550 +        }else{
 1.20551 +          e2 = exp;
 1.20552 +        }
 1.20553 +        if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){
 1.20554 +          bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+width+15 );
 1.20555 +          if( bufpt==0 ){
 1.20556 +            setStrAccumError(pAccum, STRACCUM_NOMEM);
 1.20557 +            return;
 1.20558 +          }
 1.20559 +        }
 1.20560 +        zOut = bufpt;
 1.20561 +        nsd = 16 + flag_altform2*10;
 1.20562 +        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
 1.20563 +        /* The sign in front of the number */
 1.20564 +        if( prefix ){
 1.20565 +          *(bufpt++) = prefix;
 1.20566 +        }
 1.20567 +        /* Digits prior to the decimal point */
 1.20568 +        if( e2<0 ){
 1.20569 +          *(bufpt++) = '0';
 1.20570 +        }else{
 1.20571 +          for(; e2>=0; e2--){
 1.20572 +            *(bufpt++) = et_getdigit(&realvalue,&nsd);
 1.20573 +          }
 1.20574 +        }
 1.20575 +        /* The decimal point */
 1.20576 +        if( flag_dp ){
 1.20577 +          *(bufpt++) = '.';
 1.20578 +        }
 1.20579 +        /* "0" digits after the decimal point but before the first
 1.20580 +        ** significant digit of the number */
 1.20581 +        for(e2++; e2<0; precision--, e2++){
 1.20582 +          assert( precision>0 );
 1.20583 +          *(bufpt++) = '0';
 1.20584 +        }
 1.20585 +        /* Significant digits after the decimal point */
 1.20586 +        while( (precision--)>0 ){
 1.20587 +          *(bufpt++) = et_getdigit(&realvalue,&nsd);
 1.20588 +        }
 1.20589 +        /* Remove trailing zeros and the "." if no digits follow the "." */
 1.20590 +        if( flag_rtz && flag_dp ){
 1.20591 +          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
 1.20592 +          assert( bufpt>zOut );
 1.20593 +          if( bufpt[-1]=='.' ){
 1.20594 +            if( flag_altform2 ){
 1.20595 +              *(bufpt++) = '0';
 1.20596 +            }else{
 1.20597 +              *(--bufpt) = 0;
 1.20598 +            }
 1.20599 +          }
 1.20600 +        }
 1.20601 +        /* Add the "eNNN" suffix */
 1.20602 +        if( xtype==etEXP ){
 1.20603 +          *(bufpt++) = aDigits[infop->charset];
 1.20604 +          if( exp<0 ){
 1.20605 +            *(bufpt++) = '-'; exp = -exp;
 1.20606 +          }else{
 1.20607 +            *(bufpt++) = '+';
 1.20608 +          }
 1.20609 +          if( exp>=100 ){
 1.20610 +            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
 1.20611 +            exp %= 100;
 1.20612 +          }
 1.20613 +          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
 1.20614 +          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
 1.20615 +        }
 1.20616 +        *bufpt = 0;
 1.20617 +
 1.20618 +        /* The converted number is in buf[] and zero terminated. Output it.
 1.20619 +        ** Note that the number is in the usual order, not reversed as with
 1.20620 +        ** integer conversions. */
 1.20621 +        length = (int)(bufpt-zOut);
 1.20622 +        bufpt = zOut;
 1.20623 +
 1.20624 +        /* Special case:  Add leading zeros if the flag_zeropad flag is
 1.20625 +        ** set and we are not left justified */
 1.20626 +        if( flag_zeropad && !flag_leftjustify && length < width){
 1.20627 +          int i;
 1.20628 +          int nPad = width - length;
 1.20629 +          for(i=width; i>=nPad; i--){
 1.20630 +            bufpt[i] = bufpt[i-nPad];
 1.20631 +          }
 1.20632 +          i = prefix!=0;
 1.20633 +          while( nPad-- ) bufpt[i++] = '0';
 1.20634 +          length = width;
 1.20635 +        }
 1.20636 +#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
 1.20637 +        break;
 1.20638 +      case etSIZE:
 1.20639 +        if( !bArgList ){
 1.20640 +          *(va_arg(ap,int*)) = pAccum->nChar;
 1.20641 +        }
 1.20642 +        length = width = 0;
 1.20643 +        break;
 1.20644 +      case etPERCENT:
 1.20645 +        buf[0] = '%';
 1.20646 +        bufpt = buf;
 1.20647 +        length = 1;
 1.20648 +        break;
 1.20649 +      case etCHARX:
 1.20650 +        if( bArgList ){
 1.20651 +          bufpt = getTextArg(pArgList);
 1.20652 +          c = bufpt ? bufpt[0] : 0;
 1.20653 +        }else{
 1.20654 +          c = va_arg(ap,int);
 1.20655 +        }
 1.20656 +        buf[0] = (char)c;
 1.20657 +        if( precision>=0 ){
 1.20658 +          for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
 1.20659 +          length = precision;
 1.20660 +        }else{
 1.20661 +          length =1;
 1.20662 +        }
 1.20663 +        bufpt = buf;
 1.20664 +        break;
 1.20665 +      case etSTRING:
 1.20666 +      case etDYNSTRING:
 1.20667 +        if( bArgList ){
 1.20668 +          bufpt = getTextArg(pArgList);
 1.20669 +        }else{
 1.20670 +          bufpt = va_arg(ap,char*);
 1.20671 +        }
 1.20672 +        if( bufpt==0 ){
 1.20673 +          bufpt = "";
 1.20674 +        }else if( xtype==etDYNSTRING && !bArgList ){
 1.20675 +          zExtra = bufpt;
 1.20676 +        }
 1.20677 +        if( precision>=0 ){
 1.20678 +          for(length=0; length<precision && bufpt[length]; length++){}
 1.20679 +        }else{
 1.20680 +          length = sqlite3Strlen30(bufpt);
 1.20681 +        }
 1.20682 +        break;
 1.20683 +      case etSQLESCAPE:
 1.20684 +      case etSQLESCAPE2:
 1.20685 +      case etSQLESCAPE3: {
 1.20686 +        int i, j, k, n, isnull;
 1.20687 +        int needQuote;
 1.20688 +        char ch;
 1.20689 +        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
 1.20690 +        char *escarg;
 1.20691 +
 1.20692 +        if( bArgList ){
 1.20693 +          escarg = getTextArg(pArgList);
 1.20694 +        }else{
 1.20695 +          escarg = va_arg(ap,char*);
 1.20696 +        }
 1.20697 +        isnull = escarg==0;
 1.20698 +        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
 1.20699 +        k = precision;
 1.20700 +        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
 1.20701 +          if( ch==q )  n++;
 1.20702 +        }
 1.20703 +        needQuote = !isnull && xtype==etSQLESCAPE2;
 1.20704 +        n += i + 1 + needQuote*2;
 1.20705 +        if( n>etBUFSIZE ){
 1.20706 +          bufpt = zExtra = sqlite3Malloc( n );
 1.20707 +          if( bufpt==0 ){
 1.20708 +            setStrAccumError(pAccum, STRACCUM_NOMEM);
 1.20709 +            return;
 1.20710 +          }
 1.20711 +        }else{
 1.20712 +          bufpt = buf;
 1.20713 +        }
 1.20714 +        j = 0;
 1.20715 +        if( needQuote ) bufpt[j++] = q;
 1.20716 +        k = i;
 1.20717 +        for(i=0; i<k; i++){
 1.20718 +          bufpt[j++] = ch = escarg[i];
 1.20719 +          if( ch==q ) bufpt[j++] = ch;
 1.20720 +        }
 1.20721 +        if( needQuote ) bufpt[j++] = q;
 1.20722 +        bufpt[j] = 0;
 1.20723 +        length = j;
 1.20724 +        /* The precision in %q and %Q means how many input characters to
 1.20725 +        ** consume, not the length of the output...
 1.20726 +        ** if( precision>=0 && precision<length ) length = precision; */
 1.20727 +        break;
 1.20728 +      }
 1.20729 +      case etTOKEN: {
 1.20730 +        Token *pToken = va_arg(ap, Token*);
 1.20731 +        assert( bArgList==0 );
 1.20732 +        if( pToken && pToken->n ){
 1.20733 +          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
 1.20734 +        }
 1.20735 +        length = width = 0;
 1.20736 +        break;
 1.20737 +      }
 1.20738 +      case etSRCLIST: {
 1.20739 +        SrcList *pSrc = va_arg(ap, SrcList*);
 1.20740 +        int k = va_arg(ap, int);
 1.20741 +        struct SrcList_item *pItem = &pSrc->a[k];
 1.20742 +        assert( bArgList==0 );
 1.20743 +        assert( k>=0 && k<pSrc->nSrc );
 1.20744 +        if( pItem->zDatabase ){
 1.20745 +          sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
 1.20746 +          sqlite3StrAccumAppend(pAccum, ".", 1);
 1.20747 +        }
 1.20748 +        sqlite3StrAccumAppendAll(pAccum, pItem->zName);
 1.20749 +        length = width = 0;
 1.20750 +        break;
 1.20751 +      }
 1.20752 +      default: {
 1.20753 +        assert( xtype==etINVALID );
 1.20754 +        return;
 1.20755 +      }
 1.20756 +    }/* End switch over the format type */
 1.20757 +    /*
 1.20758 +    ** The text of the conversion is pointed to by "bufpt" and is
 1.20759 +    ** "length" characters long.  The field width is "width".  Do
 1.20760 +    ** the output.
 1.20761 +    */
 1.20762 +    if( !flag_leftjustify ){
 1.20763 +      register int nspace;
 1.20764 +      nspace = width-length;
 1.20765 +      if( nspace>0 ){
 1.20766 +        sqlite3AppendSpace(pAccum, nspace);
 1.20767 +      }
 1.20768 +    }
 1.20769 +    if( length>0 ){
 1.20770 +      sqlite3StrAccumAppend(pAccum, bufpt, length);
 1.20771 +    }
 1.20772 +    if( flag_leftjustify ){
 1.20773 +      register int nspace;
 1.20774 +      nspace = width-length;
 1.20775 +      if( nspace>0 ){
 1.20776 +        sqlite3AppendSpace(pAccum, nspace);
 1.20777 +      }
 1.20778 +    }
 1.20779 +    if( zExtra ) sqlite3_free(zExtra);
 1.20780 +  }/* End for loop over the format string */
 1.20781 +} /* End of function */
 1.20782 +
 1.20783 +/*
 1.20784 +** Append N bytes of text from z to the StrAccum object.
 1.20785 +*/
 1.20786 +SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
 1.20787 +  assert( z!=0 );
 1.20788 +  assert( p->zText!=0 || p->nChar==0 || p->accError );
 1.20789 +  assert( N>=0 );
 1.20790 +  assert( p->accError==0 || p->nAlloc==0 );
 1.20791 +  if( p->nChar+N >= p->nAlloc ){
 1.20792 +    char *zNew;
 1.20793 +    if( p->accError ){
 1.20794 +      testcase(p->accError==STRACCUM_TOOBIG);
 1.20795 +      testcase(p->accError==STRACCUM_NOMEM);
 1.20796 +      return;
 1.20797 +    }
 1.20798 +    if( !p->useMalloc ){
 1.20799 +      N = p->nAlloc - p->nChar - 1;
 1.20800 +      setStrAccumError(p, STRACCUM_TOOBIG);
 1.20801 +      if( N<=0 ){
 1.20802 +        return;
 1.20803 +      }
 1.20804 +    }else{
 1.20805 +      char *zOld = (p->zText==p->zBase ? 0 : p->zText);
 1.20806 +      i64 szNew = p->nChar;
 1.20807 +      szNew += N + 1;
 1.20808 +      if( szNew > p->mxAlloc ){
 1.20809 +        sqlite3StrAccumReset(p);
 1.20810 +        setStrAccumError(p, STRACCUM_TOOBIG);
 1.20811 +        return;
 1.20812 +      }else{
 1.20813 +        p->nAlloc = (int)szNew;
 1.20814 +      }
 1.20815 +      if( p->useMalloc==1 ){
 1.20816 +        zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
 1.20817 +      }else{
 1.20818 +        zNew = sqlite3_realloc(zOld, p->nAlloc);
 1.20819 +      }
 1.20820 +      if( zNew ){
 1.20821 +        if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
 1.20822 +        p->zText = zNew;
 1.20823 +      }else{
 1.20824 +        sqlite3StrAccumReset(p);
 1.20825 +        setStrAccumError(p, STRACCUM_NOMEM);
 1.20826 +        return;
 1.20827 +      }
 1.20828 +    }
 1.20829 +  }
 1.20830 +  assert( p->zText );
 1.20831 +  memcpy(&p->zText[p->nChar], z, N);
 1.20832 +  p->nChar += N;
 1.20833 +}
 1.20834 +
 1.20835 +/*
 1.20836 +** Append the complete text of zero-terminated string z[] to the p string.
 1.20837 +*/
 1.20838 +SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
 1.20839 +  sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
 1.20840 +}
 1.20841 +
 1.20842 +
 1.20843 +/*
 1.20844 +** Finish off a string by making sure it is zero-terminated.
 1.20845 +** Return a pointer to the resulting string.  Return a NULL
 1.20846 +** pointer if any kind of error was encountered.
 1.20847 +*/
 1.20848 +SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
 1.20849 +  if( p->zText ){
 1.20850 +    p->zText[p->nChar] = 0;
 1.20851 +    if( p->useMalloc && p->zText==p->zBase ){
 1.20852 +      if( p->useMalloc==1 ){
 1.20853 +        p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
 1.20854 +      }else{
 1.20855 +        p->zText = sqlite3_malloc(p->nChar+1);
 1.20856 +      }
 1.20857 +      if( p->zText ){
 1.20858 +        memcpy(p->zText, p->zBase, p->nChar+1);
 1.20859 +      }else{
 1.20860 +        setStrAccumError(p, STRACCUM_NOMEM);
 1.20861 +      }
 1.20862 +    }
 1.20863 +  }
 1.20864 +  return p->zText;
 1.20865 +}
 1.20866 +
 1.20867 +/*
 1.20868 +** Reset an StrAccum string.  Reclaim all malloced memory.
 1.20869 +*/
 1.20870 +SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
 1.20871 +  if( p->zText!=p->zBase ){
 1.20872 +    if( p->useMalloc==1 ){
 1.20873 +      sqlite3DbFree(p->db, p->zText);
 1.20874 +    }else{
 1.20875 +      sqlite3_free(p->zText);
 1.20876 +    }
 1.20877 +  }
 1.20878 +  p->zText = 0;
 1.20879 +}
 1.20880 +
 1.20881 +/*
 1.20882 +** Initialize a string accumulator
 1.20883 +*/
 1.20884 +SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
 1.20885 +  p->zText = p->zBase = zBase;
 1.20886 +  p->db = 0;
 1.20887 +  p->nChar = 0;
 1.20888 +  p->nAlloc = n;
 1.20889 +  p->mxAlloc = mx;
 1.20890 +  p->useMalloc = 1;
 1.20891 +  p->accError = 0;
 1.20892 +}
 1.20893 +
 1.20894 +/*
 1.20895 +** Print into memory obtained from sqliteMalloc().  Use the internal
 1.20896 +** %-conversion extensions.
 1.20897 +*/
 1.20898 +SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
 1.20899 +  char *z;
 1.20900 +  char zBase[SQLITE_PRINT_BUF_SIZE];
 1.20901 +  StrAccum acc;
 1.20902 +  assert( db!=0 );
 1.20903 +  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
 1.20904 +                      db->aLimit[SQLITE_LIMIT_LENGTH]);
 1.20905 +  acc.db = db;
 1.20906 +  sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap);
 1.20907 +  z = sqlite3StrAccumFinish(&acc);
 1.20908 +  if( acc.accError==STRACCUM_NOMEM ){
 1.20909 +    db->mallocFailed = 1;
 1.20910 +  }
 1.20911 +  return z;
 1.20912 +}
 1.20913 +
 1.20914 +/*
 1.20915 +** Print into memory obtained from sqliteMalloc().  Use the internal
 1.20916 +** %-conversion extensions.
 1.20917 +*/
 1.20918 +SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
 1.20919 +  va_list ap;
 1.20920 +  char *z;
 1.20921 +  va_start(ap, zFormat);
 1.20922 +  z = sqlite3VMPrintf(db, zFormat, ap);
 1.20923 +  va_end(ap);
 1.20924 +  return z;
 1.20925 +}
 1.20926 +
 1.20927 +/*
 1.20928 +** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
 1.20929 +** the string and before returnning.  This routine is intended to be used
 1.20930 +** to modify an existing string.  For example:
 1.20931 +**
 1.20932 +**       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
 1.20933 +**
 1.20934 +*/
 1.20935 +SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
 1.20936 +  va_list ap;
 1.20937 +  char *z;
 1.20938 +  va_start(ap, zFormat);
 1.20939 +  z = sqlite3VMPrintf(db, zFormat, ap);
 1.20940 +  va_end(ap);
 1.20941 +  sqlite3DbFree(db, zStr);
 1.20942 +  return z;
 1.20943 +}
 1.20944 +
 1.20945 +/*
 1.20946 +** Print into memory obtained from sqlite3_malloc().  Omit the internal
 1.20947 +** %-conversion extensions.
 1.20948 +*/
 1.20949 +SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
 1.20950 +  char *z;
 1.20951 +  char zBase[SQLITE_PRINT_BUF_SIZE];
 1.20952 +  StrAccum acc;
 1.20953 +#ifndef SQLITE_OMIT_AUTOINIT
 1.20954 +  if( sqlite3_initialize() ) return 0;
 1.20955 +#endif
 1.20956 +  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
 1.20957 +  acc.useMalloc = 2;
 1.20958 +  sqlite3VXPrintf(&acc, 0, zFormat, ap);
 1.20959 +  z = sqlite3StrAccumFinish(&acc);
 1.20960 +  return z;
 1.20961 +}
 1.20962 +
 1.20963 +/*
 1.20964 +** Print into memory obtained from sqlite3_malloc()().  Omit the internal
 1.20965 +** %-conversion extensions.
 1.20966 +*/
 1.20967 +SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
 1.20968 +  va_list ap;
 1.20969 +  char *z;
 1.20970 +#ifndef SQLITE_OMIT_AUTOINIT
 1.20971 +  if( sqlite3_initialize() ) return 0;
 1.20972 +#endif
 1.20973 +  va_start(ap, zFormat);
 1.20974 +  z = sqlite3_vmprintf(zFormat, ap);
 1.20975 +  va_end(ap);
 1.20976 +  return z;
 1.20977 +}
 1.20978 +
 1.20979 +/*
 1.20980 +** sqlite3_snprintf() works like snprintf() except that it ignores the
 1.20981 +** current locale settings.  This is important for SQLite because we
 1.20982 +** are not able to use a "," as the decimal point in place of "." as
 1.20983 +** specified by some locales.
 1.20984 +**
 1.20985 +** Oops:  The first two arguments of sqlite3_snprintf() are backwards
 1.20986 +** from the snprintf() standard.  Unfortunately, it is too late to change
 1.20987 +** this without breaking compatibility, so we just have to live with the
 1.20988 +** mistake.
 1.20989 +**
 1.20990 +** sqlite3_vsnprintf() is the varargs version.
 1.20991 +*/
 1.20992 +SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
 1.20993 +  StrAccum acc;
 1.20994 +  if( n<=0 ) return zBuf;
 1.20995 +  sqlite3StrAccumInit(&acc, zBuf, n, 0);
 1.20996 +  acc.useMalloc = 0;
 1.20997 +  sqlite3VXPrintf(&acc, 0, zFormat, ap);
 1.20998 +  return sqlite3StrAccumFinish(&acc);
 1.20999 +}
 1.21000 +SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
 1.21001 +  char *z;
 1.21002 +  va_list ap;
 1.21003 +  va_start(ap,zFormat);
 1.21004 +  z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
 1.21005 +  va_end(ap);
 1.21006 +  return z;
 1.21007 +}
 1.21008 +
 1.21009 +/*
 1.21010 +** This is the routine that actually formats the sqlite3_log() message.
 1.21011 +** We house it in a separate routine from sqlite3_log() to avoid using
 1.21012 +** stack space on small-stack systems when logging is disabled.
 1.21013 +**
 1.21014 +** sqlite3_log() must render into a static buffer.  It cannot dynamically
 1.21015 +** allocate memory because it might be called while the memory allocator
 1.21016 +** mutex is held.
 1.21017 +*/
 1.21018 +static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
 1.21019 +  StrAccum acc;                          /* String accumulator */
 1.21020 +  char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
 1.21021 +
 1.21022 +  sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
 1.21023 +  acc.useMalloc = 0;
 1.21024 +  sqlite3VXPrintf(&acc, 0, zFormat, ap);
 1.21025 +  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
 1.21026 +                           sqlite3StrAccumFinish(&acc));
 1.21027 +}
 1.21028 +
 1.21029 +/*
 1.21030 +** Format and write a message to the log if logging is enabled.
 1.21031 +*/
 1.21032 +SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
 1.21033 +  va_list ap;                             /* Vararg list */
 1.21034 +  if( sqlite3GlobalConfig.xLog ){
 1.21035 +    va_start(ap, zFormat);
 1.21036 +    renderLogMsg(iErrCode, zFormat, ap);
 1.21037 +    va_end(ap);
 1.21038 +  }
 1.21039 +}
 1.21040 +
 1.21041 +#if defined(SQLITE_DEBUG)
 1.21042 +/*
 1.21043 +** A version of printf() that understands %lld.  Used for debugging.
 1.21044 +** The printf() built into some versions of windows does not understand %lld
 1.21045 +** and segfaults if you give it a long long int.
 1.21046 +*/
 1.21047 +SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
 1.21048 +  va_list ap;
 1.21049 +  StrAccum acc;
 1.21050 +  char zBuf[500];
 1.21051 +  sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
 1.21052 +  acc.useMalloc = 0;
 1.21053 +  va_start(ap,zFormat);
 1.21054 +  sqlite3VXPrintf(&acc, 0, zFormat, ap);
 1.21055 +  va_end(ap);
 1.21056 +  sqlite3StrAccumFinish(&acc);
 1.21057 +  fprintf(stdout,"%s", zBuf);
 1.21058 +  fflush(stdout);
 1.21059 +}
 1.21060 +#endif
 1.21061 +
 1.21062 +/*
 1.21063 +** variable-argument wrapper around sqlite3VXPrintf().
 1.21064 +*/
 1.21065 +SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){
 1.21066 +  va_list ap;
 1.21067 +  va_start(ap,zFormat);
 1.21068 +  sqlite3VXPrintf(p, bFlags, zFormat, ap);
 1.21069 +  va_end(ap);
 1.21070 +}
 1.21071 +
 1.21072 +/************** End of printf.c **********************************************/
 1.21073 +/************** Begin file random.c ******************************************/
 1.21074 +/*
 1.21075 +** 2001 September 15
 1.21076 +**
 1.21077 +** The author disclaims copyright to this source code.  In place of
 1.21078 +** a legal notice, here is a blessing:
 1.21079 +**
 1.21080 +**    May you do good and not evil.
 1.21081 +**    May you find forgiveness for yourself and forgive others.
 1.21082 +**    May you share freely, never taking more than you give.
 1.21083 +**
 1.21084 +*************************************************************************
 1.21085 +** This file contains code to implement a pseudo-random number
 1.21086 +** generator (PRNG) for SQLite.
 1.21087 +**
 1.21088 +** Random numbers are used by some of the database backends in order
 1.21089 +** to generate random integer keys for tables or random filenames.
 1.21090 +*/
 1.21091 +
 1.21092 +
 1.21093 +/* All threads share a single random number generator.
 1.21094 +** This structure is the current state of the generator.
 1.21095 +*/
 1.21096 +static SQLITE_WSD struct sqlite3PrngType {
 1.21097 +  unsigned char isInit;          /* True if initialized */
 1.21098 +  unsigned char i, j;            /* State variables */
 1.21099 +  unsigned char s[256];          /* State variables */
 1.21100 +} sqlite3Prng;
 1.21101 +
 1.21102 +/*
 1.21103 +** Return N random bytes.
 1.21104 +*/
 1.21105 +SQLITE_API void sqlite3_randomness(int N, void *pBuf){
 1.21106 +  unsigned char t;
 1.21107 +  unsigned char *zBuf = pBuf;
 1.21108 +
 1.21109 +  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
 1.21110 +  ** state vector.  If writable static data is unsupported on the target,
 1.21111 +  ** we have to locate the state vector at run-time.  In the more common
 1.21112 +  ** case where writable static data is supported, wsdPrng can refer directly
 1.21113 +  ** to the "sqlite3Prng" state vector declared above.
 1.21114 +  */
 1.21115 +#ifdef SQLITE_OMIT_WSD
 1.21116 +  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
 1.21117 +# define wsdPrng p[0]
 1.21118 +#else
 1.21119 +# define wsdPrng sqlite3Prng
 1.21120 +#endif
 1.21121 +
 1.21122 +#if SQLITE_THREADSAFE
 1.21123 +  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
 1.21124 +  sqlite3_mutex_enter(mutex);
 1.21125 +#endif
 1.21126 +
 1.21127 +  if( N<=0 ){
 1.21128 +    wsdPrng.isInit = 0;
 1.21129 +    sqlite3_mutex_leave(mutex);
 1.21130 +    return;
 1.21131 +  }
 1.21132 +
 1.21133 +  /* Initialize the state of the random number generator once,
 1.21134 +  ** the first time this routine is called.  The seed value does
 1.21135 +  ** not need to contain a lot of randomness since we are not
 1.21136 +  ** trying to do secure encryption or anything like that...
 1.21137 +  **
 1.21138 +  ** Nothing in this file or anywhere else in SQLite does any kind of
 1.21139 +  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
 1.21140 +  ** number generator) not as an encryption device.
 1.21141 +  */
 1.21142 +  if( !wsdPrng.isInit ){
 1.21143 +    int i;
 1.21144 +    char k[256];
 1.21145 +    wsdPrng.j = 0;
 1.21146 +    wsdPrng.i = 0;
 1.21147 +    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
 1.21148 +    for(i=0; i<256; i++){
 1.21149 +      wsdPrng.s[i] = (u8)i;
 1.21150 +    }
 1.21151 +    for(i=0; i<256; i++){
 1.21152 +      wsdPrng.j += wsdPrng.s[i] + k[i];
 1.21153 +      t = wsdPrng.s[wsdPrng.j];
 1.21154 +      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
 1.21155 +      wsdPrng.s[i] = t;
 1.21156 +    }
 1.21157 +    wsdPrng.isInit = 1;
 1.21158 +  }
 1.21159 +
 1.21160 +  assert( N>0 );
 1.21161 +  do{
 1.21162 +    wsdPrng.i++;
 1.21163 +    t = wsdPrng.s[wsdPrng.i];
 1.21164 +    wsdPrng.j += t;
 1.21165 +    wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
 1.21166 +    wsdPrng.s[wsdPrng.j] = t;
 1.21167 +    t += wsdPrng.s[wsdPrng.i];
 1.21168 +    *(zBuf++) = wsdPrng.s[t];
 1.21169 +  }while( --N );
 1.21170 +  sqlite3_mutex_leave(mutex);
 1.21171 +}
 1.21172 +
 1.21173 +#ifndef SQLITE_OMIT_BUILTIN_TEST
 1.21174 +/*
 1.21175 +** For testing purposes, we sometimes want to preserve the state of
 1.21176 +** PRNG and restore the PRNG to its saved state at a later time, or
 1.21177 +** to reset the PRNG to its initial state.  These routines accomplish
 1.21178 +** those tasks.
 1.21179 +**
 1.21180 +** The sqlite3_test_control() interface calls these routines to
 1.21181 +** control the PRNG.
 1.21182 +*/
 1.21183 +static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
 1.21184 +SQLITE_PRIVATE void sqlite3PrngSaveState(void){
 1.21185 +  memcpy(
 1.21186 +    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
 1.21187 +    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
 1.21188 +    sizeof(sqlite3Prng)
 1.21189 +  );
 1.21190 +}
 1.21191 +SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
 1.21192 +  memcpy(
 1.21193 +    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
 1.21194 +    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
 1.21195 +    sizeof(sqlite3Prng)
 1.21196 +  );
 1.21197 +}
 1.21198 +#endif /* SQLITE_OMIT_BUILTIN_TEST */
 1.21199 +
 1.21200 +/************** End of random.c **********************************************/
 1.21201 +/************** Begin file utf.c *********************************************/
 1.21202 +/*
 1.21203 +** 2004 April 13
 1.21204 +**
 1.21205 +** The author disclaims copyright to this source code.  In place of
 1.21206 +** a legal notice, here is a blessing:
 1.21207 +**
 1.21208 +**    May you do good and not evil.
 1.21209 +**    May you find forgiveness for yourself and forgive others.
 1.21210 +**    May you share freely, never taking more than you give.
 1.21211 +**
 1.21212 +*************************************************************************
 1.21213 +** This file contains routines used to translate between UTF-8, 
 1.21214 +** UTF-16, UTF-16BE, and UTF-16LE.
 1.21215 +**
 1.21216 +** Notes on UTF-8:
 1.21217 +**
 1.21218 +**   Byte-0    Byte-1    Byte-2    Byte-3    Value
 1.21219 +**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
 1.21220 +**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
 1.21221 +**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
 1.21222 +**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
 1.21223 +**
 1.21224 +**
 1.21225 +** Notes on UTF-16:  (with wwww+1==uuuuu)
 1.21226 +**
 1.21227 +**      Word-0               Word-1          Value
 1.21228 +**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
 1.21229 +**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
 1.21230 +**
 1.21231 +**
 1.21232 +** BOM or Byte Order Mark:
 1.21233 +**     0xff 0xfe   little-endian utf-16 follows
 1.21234 +**     0xfe 0xff   big-endian utf-16 follows
 1.21235 +**
 1.21236 +*/
 1.21237 +/* #include <assert.h> */
 1.21238 +
 1.21239 +#ifndef SQLITE_AMALGAMATION
 1.21240 +/*
 1.21241 +** The following constant value is used by the SQLITE_BIGENDIAN and
 1.21242 +** SQLITE_LITTLEENDIAN macros.
 1.21243 +*/
 1.21244 +SQLITE_PRIVATE const int sqlite3one = 1;
 1.21245 +#endif /* SQLITE_AMALGAMATION */
 1.21246 +
 1.21247 +/*
 1.21248 +** This lookup table is used to help decode the first byte of
 1.21249 +** a multi-byte UTF8 character.
 1.21250 +*/
 1.21251 +static const unsigned char sqlite3Utf8Trans1[] = {
 1.21252 +  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
 1.21253 +  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
 1.21254 +  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
 1.21255 +  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
 1.21256 +  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
 1.21257 +  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
 1.21258 +  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
 1.21259 +  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
 1.21260 +};
 1.21261 +
 1.21262 +
 1.21263 +#define WRITE_UTF8(zOut, c) {                          \
 1.21264 +  if( c<0x00080 ){                                     \
 1.21265 +    *zOut++ = (u8)(c&0xFF);                            \
 1.21266 +  }                                                    \
 1.21267 +  else if( c<0x00800 ){                                \
 1.21268 +    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
 1.21269 +    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
 1.21270 +  }                                                    \
 1.21271 +  else if( c<0x10000 ){                                \
 1.21272 +    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
 1.21273 +    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
 1.21274 +    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
 1.21275 +  }else{                                               \
 1.21276 +    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
 1.21277 +    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
 1.21278 +    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
 1.21279 +    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
 1.21280 +  }                                                    \
 1.21281 +}
 1.21282 +
 1.21283 +#define WRITE_UTF16LE(zOut, c) {                                    \
 1.21284 +  if( c<=0xFFFF ){                                                  \
 1.21285 +    *zOut++ = (u8)(c&0x00FF);                                       \
 1.21286 +    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
 1.21287 +  }else{                                                            \
 1.21288 +    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
 1.21289 +    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
 1.21290 +    *zOut++ = (u8)(c&0x00FF);                                       \
 1.21291 +    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
 1.21292 +  }                                                                 \
 1.21293 +}
 1.21294 +
 1.21295 +#define WRITE_UTF16BE(zOut, c) {                                    \
 1.21296 +  if( c<=0xFFFF ){                                                  \
 1.21297 +    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
 1.21298 +    *zOut++ = (u8)(c&0x00FF);                                       \
 1.21299 +  }else{                                                            \
 1.21300 +    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
 1.21301 +    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
 1.21302 +    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
 1.21303 +    *zOut++ = (u8)(c&0x00FF);                                       \
 1.21304 +  }                                                                 \
 1.21305 +}
 1.21306 +
 1.21307 +#define READ_UTF16LE(zIn, TERM, c){                                   \
 1.21308 +  c = (*zIn++);                                                       \
 1.21309 +  c += ((*zIn++)<<8);                                                 \
 1.21310 +  if( c>=0xD800 && c<0xE000 && TERM ){                                \
 1.21311 +    int c2 = (*zIn++);                                                \
 1.21312 +    c2 += ((*zIn++)<<8);                                              \
 1.21313 +    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
 1.21314 +  }                                                                   \
 1.21315 +}
 1.21316 +
 1.21317 +#define READ_UTF16BE(zIn, TERM, c){                                   \
 1.21318 +  c = ((*zIn++)<<8);                                                  \
 1.21319 +  c += (*zIn++);                                                      \
 1.21320 +  if( c>=0xD800 && c<0xE000 && TERM ){                                \
 1.21321 +    int c2 = ((*zIn++)<<8);                                           \
 1.21322 +    c2 += (*zIn++);                                                   \
 1.21323 +    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
 1.21324 +  }                                                                   \
 1.21325 +}
 1.21326 +
 1.21327 +/*
 1.21328 +** Translate a single UTF-8 character.  Return the unicode value.
 1.21329 +**
 1.21330 +** During translation, assume that the byte that zTerm points
 1.21331 +** is a 0x00.
 1.21332 +**
 1.21333 +** Write a pointer to the next unread byte back into *pzNext.
 1.21334 +**
 1.21335 +** Notes On Invalid UTF-8:
 1.21336 +**
 1.21337 +**  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
 1.21338 +**     be encoded as a multi-byte character.  Any multi-byte character that
 1.21339 +**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
 1.21340 +**
 1.21341 +**  *  This routine never allows a UTF16 surrogate value to be encoded.
 1.21342 +**     If a multi-byte character attempts to encode a value between
 1.21343 +**     0xd800 and 0xe000 then it is rendered as 0xfffd.
 1.21344 +**
 1.21345 +**  *  Bytes in the range of 0x80 through 0xbf which occur as the first
 1.21346 +**     byte of a character are interpreted as single-byte characters
 1.21347 +**     and rendered as themselves even though they are technically
 1.21348 +**     invalid characters.
 1.21349 +**
 1.21350 +**  *  This routine accepts an infinite number of different UTF8 encodings
 1.21351 +**     for unicode values 0x80 and greater.  It do not change over-length
 1.21352 +**     encodings to 0xfffd as some systems recommend.
 1.21353 +*/
 1.21354 +#define READ_UTF8(zIn, zTerm, c)                           \
 1.21355 +  c = *(zIn++);                                            \
 1.21356 +  if( c>=0xc0 ){                                           \
 1.21357 +    c = sqlite3Utf8Trans1[c-0xc0];                         \
 1.21358 +    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
 1.21359 +      c = (c<<6) + (0x3f & *(zIn++));                      \
 1.21360 +    }                                                      \
 1.21361 +    if( c<0x80                                             \
 1.21362 +        || (c&0xFFFFF800)==0xD800                          \
 1.21363 +        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
 1.21364 +  }
 1.21365 +SQLITE_PRIVATE u32 sqlite3Utf8Read(
 1.21366 +  const unsigned char **pz    /* Pointer to string from which to read char */
 1.21367 +){
 1.21368 +  unsigned int c;
 1.21369 +
 1.21370 +  /* Same as READ_UTF8() above but without the zTerm parameter.
 1.21371 +  ** For this routine, we assume the UTF8 string is always zero-terminated.
 1.21372 +  */
 1.21373 +  c = *((*pz)++);
 1.21374 +  if( c>=0xc0 ){
 1.21375 +    c = sqlite3Utf8Trans1[c-0xc0];
 1.21376 +    while( (*(*pz) & 0xc0)==0x80 ){
 1.21377 +      c = (c<<6) + (0x3f & *((*pz)++));
 1.21378 +    }
 1.21379 +    if( c<0x80
 1.21380 +        || (c&0xFFFFF800)==0xD800
 1.21381 +        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
 1.21382 +  }
 1.21383 +  return c;
 1.21384 +}
 1.21385 +
 1.21386 +
 1.21387 +
 1.21388 +
 1.21389 +/*
 1.21390 +** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
 1.21391 +** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
 1.21392 +*/ 
 1.21393 +/* #define TRANSLATE_TRACE 1 */
 1.21394 +
 1.21395 +#ifndef SQLITE_OMIT_UTF16
 1.21396 +/*
 1.21397 +** This routine transforms the internal text encoding used by pMem to
 1.21398 +** desiredEnc. It is an error if the string is already of the desired
 1.21399 +** encoding, or if *pMem does not contain a string value.
 1.21400 +*/
 1.21401 +SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
 1.21402 +  int len;                    /* Maximum length of output string in bytes */
 1.21403 +  unsigned char *zOut;                  /* Output buffer */
 1.21404 +  unsigned char *zIn;                   /* Input iterator */
 1.21405 +  unsigned char *zTerm;                 /* End of input */
 1.21406 +  unsigned char *z;                     /* Output iterator */
 1.21407 +  unsigned int c;
 1.21408 +
 1.21409 +  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 1.21410 +  assert( pMem->flags&MEM_Str );
 1.21411 +  assert( pMem->enc!=desiredEnc );
 1.21412 +  assert( pMem->enc!=0 );
 1.21413 +  assert( pMem->n>=0 );
 1.21414 +
 1.21415 +#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
 1.21416 +  {
 1.21417 +    char zBuf[100];
 1.21418 +    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
 1.21419 +    fprintf(stderr, "INPUT:  %s\n", zBuf);
 1.21420 +  }
 1.21421 +#endif
 1.21422 +
 1.21423 +  /* If the translation is between UTF-16 little and big endian, then 
 1.21424 +  ** all that is required is to swap the byte order. This case is handled
 1.21425 +  ** differently from the others.
 1.21426 +  */
 1.21427 +  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
 1.21428 +    u8 temp;
 1.21429 +    int rc;
 1.21430 +    rc = sqlite3VdbeMemMakeWriteable(pMem);
 1.21431 +    if( rc!=SQLITE_OK ){
 1.21432 +      assert( rc==SQLITE_NOMEM );
 1.21433 +      return SQLITE_NOMEM;
 1.21434 +    }
 1.21435 +    zIn = (u8*)pMem->z;
 1.21436 +    zTerm = &zIn[pMem->n&~1];
 1.21437 +    while( zIn<zTerm ){
 1.21438 +      temp = *zIn;
 1.21439 +      *zIn = *(zIn+1);
 1.21440 +      zIn++;
 1.21441 +      *zIn++ = temp;
 1.21442 +    }
 1.21443 +    pMem->enc = desiredEnc;
 1.21444 +    goto translate_out;
 1.21445 +  }
 1.21446 +
 1.21447 +  /* Set len to the maximum number of bytes required in the output buffer. */
 1.21448 +  if( desiredEnc==SQLITE_UTF8 ){
 1.21449 +    /* When converting from UTF-16, the maximum growth results from
 1.21450 +    ** translating a 2-byte character to a 4-byte UTF-8 character.
 1.21451 +    ** A single byte is required for the output string
 1.21452 +    ** nul-terminator.
 1.21453 +    */
 1.21454 +    pMem->n &= ~1;
 1.21455 +    len = pMem->n * 2 + 1;
 1.21456 +  }else{
 1.21457 +    /* When converting from UTF-8 to UTF-16 the maximum growth is caused
 1.21458 +    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
 1.21459 +    ** character. Two bytes are required in the output buffer for the
 1.21460 +    ** nul-terminator.
 1.21461 +    */
 1.21462 +    len = pMem->n * 2 + 2;
 1.21463 +  }
 1.21464 +
 1.21465 +  /* Set zIn to point at the start of the input buffer and zTerm to point 1
 1.21466 +  ** byte past the end.
 1.21467 +  **
 1.21468 +  ** Variable zOut is set to point at the output buffer, space obtained
 1.21469 +  ** from sqlite3_malloc().
 1.21470 +  */
 1.21471 +  zIn = (u8*)pMem->z;
 1.21472 +  zTerm = &zIn[pMem->n];
 1.21473 +  zOut = sqlite3DbMallocRaw(pMem->db, len);
 1.21474 +  if( !zOut ){
 1.21475 +    return SQLITE_NOMEM;
 1.21476 +  }
 1.21477 +  z = zOut;
 1.21478 +
 1.21479 +  if( pMem->enc==SQLITE_UTF8 ){
 1.21480 +    if( desiredEnc==SQLITE_UTF16LE ){
 1.21481 +      /* UTF-8 -> UTF-16 Little-endian */
 1.21482 +      while( zIn<zTerm ){
 1.21483 +        READ_UTF8(zIn, zTerm, c);
 1.21484 +        WRITE_UTF16LE(z, c);
 1.21485 +      }
 1.21486 +    }else{
 1.21487 +      assert( desiredEnc==SQLITE_UTF16BE );
 1.21488 +      /* UTF-8 -> UTF-16 Big-endian */
 1.21489 +      while( zIn<zTerm ){
 1.21490 +        READ_UTF8(zIn, zTerm, c);
 1.21491 +        WRITE_UTF16BE(z, c);
 1.21492 +      }
 1.21493 +    }
 1.21494 +    pMem->n = (int)(z - zOut);
 1.21495 +    *z++ = 0;
 1.21496 +  }else{
 1.21497 +    assert( desiredEnc==SQLITE_UTF8 );
 1.21498 +    if( pMem->enc==SQLITE_UTF16LE ){
 1.21499 +      /* UTF-16 Little-endian -> UTF-8 */
 1.21500 +      while( zIn<zTerm ){
 1.21501 +        READ_UTF16LE(zIn, zIn<zTerm, c); 
 1.21502 +        WRITE_UTF8(z, c);
 1.21503 +      }
 1.21504 +    }else{
 1.21505 +      /* UTF-16 Big-endian -> UTF-8 */
 1.21506 +      while( zIn<zTerm ){
 1.21507 +        READ_UTF16BE(zIn, zIn<zTerm, c); 
 1.21508 +        WRITE_UTF8(z, c);
 1.21509 +      }
 1.21510 +    }
 1.21511 +    pMem->n = (int)(z - zOut);
 1.21512 +  }
 1.21513 +  *z = 0;
 1.21514 +  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
 1.21515 +
 1.21516 +  sqlite3VdbeMemRelease(pMem);
 1.21517 +  pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
 1.21518 +  pMem->enc = desiredEnc;
 1.21519 +  pMem->flags |= (MEM_Term);
 1.21520 +  pMem->z = (char*)zOut;
 1.21521 +  pMem->zMalloc = pMem->z;
 1.21522 +
 1.21523 +translate_out:
 1.21524 +#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
 1.21525 +  {
 1.21526 +    char zBuf[100];
 1.21527 +    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
 1.21528 +    fprintf(stderr, "OUTPUT: %s\n", zBuf);
 1.21529 +  }
 1.21530 +#endif
 1.21531 +  return SQLITE_OK;
 1.21532 +}
 1.21533 +
 1.21534 +/*
 1.21535 +** This routine checks for a byte-order mark at the beginning of the 
 1.21536 +** UTF-16 string stored in *pMem. If one is present, it is removed and
 1.21537 +** the encoding of the Mem adjusted. This routine does not do any
 1.21538 +** byte-swapping, it just sets Mem.enc appropriately.
 1.21539 +**
 1.21540 +** The allocation (static, dynamic etc.) and encoding of the Mem may be
 1.21541 +** changed by this function.
 1.21542 +*/
 1.21543 +SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
 1.21544 +  int rc = SQLITE_OK;
 1.21545 +  u8 bom = 0;
 1.21546 +
 1.21547 +  assert( pMem->n>=0 );
 1.21548 +  if( pMem->n>1 ){
 1.21549 +    u8 b1 = *(u8 *)pMem->z;
 1.21550 +    u8 b2 = *(((u8 *)pMem->z) + 1);
 1.21551 +    if( b1==0xFE && b2==0xFF ){
 1.21552 +      bom = SQLITE_UTF16BE;
 1.21553 +    }
 1.21554 +    if( b1==0xFF && b2==0xFE ){
 1.21555 +      bom = SQLITE_UTF16LE;
 1.21556 +    }
 1.21557 +  }
 1.21558 +  
 1.21559 +  if( bom ){
 1.21560 +    rc = sqlite3VdbeMemMakeWriteable(pMem);
 1.21561 +    if( rc==SQLITE_OK ){
 1.21562 +      pMem->n -= 2;
 1.21563 +      memmove(pMem->z, &pMem->z[2], pMem->n);
 1.21564 +      pMem->z[pMem->n] = '\0';
 1.21565 +      pMem->z[pMem->n+1] = '\0';
 1.21566 +      pMem->flags |= MEM_Term;
 1.21567 +      pMem->enc = bom;
 1.21568 +    }
 1.21569 +  }
 1.21570 +  return rc;
 1.21571 +}
 1.21572 +#endif /* SQLITE_OMIT_UTF16 */
 1.21573 +
 1.21574 +/*
 1.21575 +** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
 1.21576 +** return the number of unicode characters in pZ up to (but not including)
 1.21577 +** the first 0x00 byte. If nByte is not less than zero, return the
 1.21578 +** number of unicode characters in the first nByte of pZ (or up to 
 1.21579 +** the first 0x00, whichever comes first).
 1.21580 +*/
 1.21581 +SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
 1.21582 +  int r = 0;
 1.21583 +  const u8 *z = (const u8*)zIn;
 1.21584 +  const u8 *zTerm;
 1.21585 +  if( nByte>=0 ){
 1.21586 +    zTerm = &z[nByte];
 1.21587 +  }else{
 1.21588 +    zTerm = (const u8*)(-1);
 1.21589 +  }
 1.21590 +  assert( z<=zTerm );
 1.21591 +  while( *z!=0 && z<zTerm ){
 1.21592 +    SQLITE_SKIP_UTF8(z);
 1.21593 +    r++;
 1.21594 +  }
 1.21595 +  return r;
 1.21596 +}
 1.21597 +
 1.21598 +/* This test function is not currently used by the automated test-suite. 
 1.21599 +** Hence it is only available in debug builds.
 1.21600 +*/
 1.21601 +#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
 1.21602 +/*
 1.21603 +** Translate UTF-8 to UTF-8.
 1.21604 +**
 1.21605 +** This has the effect of making sure that the string is well-formed
 1.21606 +** UTF-8.  Miscoded characters are removed.
 1.21607 +**
 1.21608 +** The translation is done in-place and aborted if the output
 1.21609 +** overruns the input.
 1.21610 +*/
 1.21611 +SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
 1.21612 +  unsigned char *zOut = zIn;
 1.21613 +  unsigned char *zStart = zIn;
 1.21614 +  u32 c;
 1.21615 +
 1.21616 +  while( zIn[0] && zOut<=zIn ){
 1.21617 +    c = sqlite3Utf8Read((const u8**)&zIn);
 1.21618 +    if( c!=0xfffd ){
 1.21619 +      WRITE_UTF8(zOut, c);
 1.21620 +    }
 1.21621 +  }
 1.21622 +  *zOut = 0;
 1.21623 +  return (int)(zOut - zStart);
 1.21624 +}
 1.21625 +#endif
 1.21626 +
 1.21627 +#ifndef SQLITE_OMIT_UTF16
 1.21628 +/*
 1.21629 +** Convert a UTF-16 string in the native encoding into a UTF-8 string.
 1.21630 +** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
 1.21631 +** be freed by the calling function.
 1.21632 +**
 1.21633 +** NULL is returned if there is an allocation error.
 1.21634 +*/
 1.21635 +SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
 1.21636 +  Mem m;
 1.21637 +  memset(&m, 0, sizeof(m));
 1.21638 +  m.db = db;
 1.21639 +  sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
 1.21640 +  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
 1.21641 +  if( db->mallocFailed ){
 1.21642 +    sqlite3VdbeMemRelease(&m);
 1.21643 +    m.z = 0;
 1.21644 +  }
 1.21645 +  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
 1.21646 +  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
 1.21647 +  assert( m.z || db->mallocFailed );
 1.21648 +  return m.z;
 1.21649 +}
 1.21650 +
 1.21651 +/*
 1.21652 +** zIn is a UTF-16 encoded unicode string at least nChar characters long.
 1.21653 +** Return the number of bytes in the first nChar unicode characters
 1.21654 +** in pZ.  nChar must be non-negative.
 1.21655 +*/
 1.21656 +SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
 1.21657 +  int c;
 1.21658 +  unsigned char const *z = zIn;
 1.21659 +  int n = 0;
 1.21660 +  
 1.21661 +  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
 1.21662 +    while( n<nChar ){
 1.21663 +      READ_UTF16BE(z, 1, c);
 1.21664 +      n++;
 1.21665 +    }
 1.21666 +  }else{
 1.21667 +    while( n<nChar ){
 1.21668 +      READ_UTF16LE(z, 1, c);
 1.21669 +      n++;
 1.21670 +    }
 1.21671 +  }
 1.21672 +  return (int)(z-(unsigned char const *)zIn);
 1.21673 +}
 1.21674 +
 1.21675 +#if defined(SQLITE_TEST)
 1.21676 +/*
 1.21677 +** This routine is called from the TCL test function "translate_selftest".
 1.21678 +** It checks that the primitives for serializing and deserializing
 1.21679 +** characters in each encoding are inverses of each other.
 1.21680 +*/
 1.21681 +SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
 1.21682 +  unsigned int i, t;
 1.21683 +  unsigned char zBuf[20];
 1.21684 +  unsigned char *z;
 1.21685 +  int n;
 1.21686 +  unsigned int c;
 1.21687 +
 1.21688 +  for(i=0; i<0x00110000; i++){
 1.21689 +    z = zBuf;
 1.21690 +    WRITE_UTF8(z, i);
 1.21691 +    n = (int)(z-zBuf);
 1.21692 +    assert( n>0 && n<=4 );
 1.21693 +    z[0] = 0;
 1.21694 +    z = zBuf;
 1.21695 +    c = sqlite3Utf8Read((const u8**)&z);
 1.21696 +    t = i;
 1.21697 +    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
 1.21698 +    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
 1.21699 +    assert( c==t );
 1.21700 +    assert( (z-zBuf)==n );
 1.21701 +  }
 1.21702 +  for(i=0; i<0x00110000; i++){
 1.21703 +    if( i>=0xD800 && i<0xE000 ) continue;
 1.21704 +    z = zBuf;
 1.21705 +    WRITE_UTF16LE(z, i);
 1.21706 +    n = (int)(z-zBuf);
 1.21707 +    assert( n>0 && n<=4 );
 1.21708 +    z[0] = 0;
 1.21709 +    z = zBuf;
 1.21710 +    READ_UTF16LE(z, 1, c);
 1.21711 +    assert( c==i );
 1.21712 +    assert( (z-zBuf)==n );
 1.21713 +  }
 1.21714 +  for(i=0; i<0x00110000; i++){
 1.21715 +    if( i>=0xD800 && i<0xE000 ) continue;
 1.21716 +    z = zBuf;
 1.21717 +    WRITE_UTF16BE(z, i);
 1.21718 +    n = (int)(z-zBuf);
 1.21719 +    assert( n>0 && n<=4 );
 1.21720 +    z[0] = 0;
 1.21721 +    z = zBuf;
 1.21722 +    READ_UTF16BE(z, 1, c);
 1.21723 +    assert( c==i );
 1.21724 +    assert( (z-zBuf)==n );
 1.21725 +  }
 1.21726 +}
 1.21727 +#endif /* SQLITE_TEST */
 1.21728 +#endif /* SQLITE_OMIT_UTF16 */
 1.21729 +
 1.21730 +/************** End of utf.c *************************************************/
 1.21731 +/************** Begin file util.c ********************************************/
 1.21732 +/*
 1.21733 +** 2001 September 15
 1.21734 +**
 1.21735 +** The author disclaims copyright to this source code.  In place of
 1.21736 +** a legal notice, here is a blessing:
 1.21737 +**
 1.21738 +**    May you do good and not evil.
 1.21739 +**    May you find forgiveness for yourself and forgive others.
 1.21740 +**    May you share freely, never taking more than you give.
 1.21741 +**
 1.21742 +*************************************************************************
 1.21743 +** Utility functions used throughout sqlite.
 1.21744 +**
 1.21745 +** This file contains functions for allocating memory, comparing
 1.21746 +** strings, and stuff like that.
 1.21747 +**
 1.21748 +*/
 1.21749 +/* #include <stdarg.h> */
 1.21750 +#ifdef SQLITE_HAVE_ISNAN
 1.21751 +# include <math.h>
 1.21752 +#endif
 1.21753 +
 1.21754 +/*
 1.21755 +** Routine needed to support the testcase() macro.
 1.21756 +*/
 1.21757 +#ifdef SQLITE_COVERAGE_TEST
 1.21758 +SQLITE_PRIVATE void sqlite3Coverage(int x){
 1.21759 +  static unsigned dummy = 0;
 1.21760 +  dummy += (unsigned)x;
 1.21761 +}
 1.21762 +#endif
 1.21763 +
 1.21764 +#ifndef SQLITE_OMIT_FLOATING_POINT
 1.21765 +/*
 1.21766 +** Return true if the floating point value is Not a Number (NaN).
 1.21767 +**
 1.21768 +** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
 1.21769 +** Otherwise, we have our own implementation that works on most systems.
 1.21770 +*/
 1.21771 +SQLITE_PRIVATE int sqlite3IsNaN(double x){
 1.21772 +  int rc;   /* The value return */
 1.21773 +#if !defined(SQLITE_HAVE_ISNAN)
 1.21774 +  /*
 1.21775 +  ** Systems that support the isnan() library function should probably
 1.21776 +  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
 1.21777 +  ** found that many systems do not have a working isnan() function so
 1.21778 +  ** this implementation is provided as an alternative.
 1.21779 +  **
 1.21780 +  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
 1.21781 +  ** On the other hand, the use of -ffast-math comes with the following
 1.21782 +  ** warning:
 1.21783 +  **
 1.21784 +  **      This option [-ffast-math] should never be turned on by any
 1.21785 +  **      -O option since it can result in incorrect output for programs
 1.21786 +  **      which depend on an exact implementation of IEEE or ISO 
 1.21787 +  **      rules/specifications for math functions.
 1.21788 +  **
 1.21789 +  ** Under MSVC, this NaN test may fail if compiled with a floating-
 1.21790 +  ** point precision mode other than /fp:precise.  From the MSDN 
 1.21791 +  ** documentation:
 1.21792 +  **
 1.21793 +  **      The compiler [with /fp:precise] will properly handle comparisons 
 1.21794 +  **      involving NaN. For example, x != x evaluates to true if x is NaN 
 1.21795 +  **      ...
 1.21796 +  */
 1.21797 +#ifdef __FAST_MATH__
 1.21798 +# error SQLite will not work correctly with the -ffast-math option of GCC.
 1.21799 +#endif
 1.21800 +  volatile double y = x;
 1.21801 +  volatile double z = y;
 1.21802 +  rc = (y!=z);
 1.21803 +#else  /* if defined(SQLITE_HAVE_ISNAN) */
 1.21804 +  rc = isnan(x);
 1.21805 +#endif /* SQLITE_HAVE_ISNAN */
 1.21806 +  testcase( rc );
 1.21807 +  return rc;
 1.21808 +}
 1.21809 +#endif /* SQLITE_OMIT_FLOATING_POINT */
 1.21810 +
 1.21811 +/*
 1.21812 +** Compute a string length that is limited to what can be stored in
 1.21813 +** lower 30 bits of a 32-bit signed integer.
 1.21814 +**
 1.21815 +** The value returned will never be negative.  Nor will it ever be greater
 1.21816 +** than the actual length of the string.  For very long strings (greater
 1.21817 +** than 1GiB) the value returned might be less than the true string length.
 1.21818 +*/
 1.21819 +SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
 1.21820 +  const char *z2 = z;
 1.21821 +  if( z==0 ) return 0;
 1.21822 +  while( *z2 ){ z2++; }
 1.21823 +  return 0x3fffffff & (int)(z2 - z);
 1.21824 +}
 1.21825 +
 1.21826 +/*
 1.21827 +** Set the most recent error code and error string for the sqlite
 1.21828 +** handle "db". The error code is set to "err_code".
 1.21829 +**
 1.21830 +** If it is not NULL, string zFormat specifies the format of the
 1.21831 +** error string in the style of the printf functions: The following
 1.21832 +** format characters are allowed:
 1.21833 +**
 1.21834 +**      %s      Insert a string
 1.21835 +**      %z      A string that should be freed after use
 1.21836 +**      %d      Insert an integer
 1.21837 +**      %T      Insert a token
 1.21838 +**      %S      Insert the first element of a SrcList
 1.21839 +**
 1.21840 +** zFormat and any string tokens that follow it are assumed to be
 1.21841 +** encoded in UTF-8.
 1.21842 +**
 1.21843 +** To clear the most recent error for sqlite handle "db", sqlite3Error
 1.21844 +** should be called with err_code set to SQLITE_OK and zFormat set
 1.21845 +** to NULL.
 1.21846 +*/
 1.21847 +SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
 1.21848 +  assert( db!=0 );
 1.21849 +  db->errCode = err_code;
 1.21850 +  if( zFormat && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
 1.21851 +    char *z;
 1.21852 +    va_list ap;
 1.21853 +    va_start(ap, zFormat);
 1.21854 +    z = sqlite3VMPrintf(db, zFormat, ap);
 1.21855 +    va_end(ap);
 1.21856 +    sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
 1.21857 +  }else if( db->pErr ){
 1.21858 +    sqlite3ValueSetNull(db->pErr);
 1.21859 +  }
 1.21860 +}
 1.21861 +
 1.21862 +/*
 1.21863 +** Add an error message to pParse->zErrMsg and increment pParse->nErr.
 1.21864 +** The following formatting characters are allowed:
 1.21865 +**
 1.21866 +**      %s      Insert a string
 1.21867 +**      %z      A string that should be freed after use
 1.21868 +**      %d      Insert an integer
 1.21869 +**      %T      Insert a token
 1.21870 +**      %S      Insert the first element of a SrcList
 1.21871 +**
 1.21872 +** This function should be used to report any error that occurs whilst
 1.21873 +** compiling an SQL statement (i.e. within sqlite3_prepare()). The
 1.21874 +** last thing the sqlite3_prepare() function does is copy the error
 1.21875 +** stored by this function into the database handle using sqlite3Error().
 1.21876 +** Function sqlite3Error() should be used during statement execution
 1.21877 +** (sqlite3_step() etc.).
 1.21878 +*/
 1.21879 +SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
 1.21880 +  char *zMsg;
 1.21881 +  va_list ap;
 1.21882 +  sqlite3 *db = pParse->db;
 1.21883 +  va_start(ap, zFormat);
 1.21884 +  zMsg = sqlite3VMPrintf(db, zFormat, ap);
 1.21885 +  va_end(ap);
 1.21886 +  if( db->suppressErr ){
 1.21887 +    sqlite3DbFree(db, zMsg);
 1.21888 +  }else{
 1.21889 +    pParse->nErr++;
 1.21890 +    sqlite3DbFree(db, pParse->zErrMsg);
 1.21891 +    pParse->zErrMsg = zMsg;
 1.21892 +    pParse->rc = SQLITE_ERROR;
 1.21893 +  }
 1.21894 +}
 1.21895 +
 1.21896 +/*
 1.21897 +** Convert an SQL-style quoted string into a normal string by removing
 1.21898 +** the quote characters.  The conversion is done in-place.  If the
 1.21899 +** input does not begin with a quote character, then this routine
 1.21900 +** is a no-op.
 1.21901 +**
 1.21902 +** The input string must be zero-terminated.  A new zero-terminator
 1.21903 +** is added to the dequoted string.
 1.21904 +**
 1.21905 +** The return value is -1 if no dequoting occurs or the length of the
 1.21906 +** dequoted string, exclusive of the zero terminator, if dequoting does
 1.21907 +** occur.
 1.21908 +**
 1.21909 +** 2002-Feb-14: This routine is extended to remove MS-Access style
 1.21910 +** brackets from around identifers.  For example:  "[a-b-c]" becomes
 1.21911 +** "a-b-c".
 1.21912 +*/
 1.21913 +SQLITE_PRIVATE int sqlite3Dequote(char *z){
 1.21914 +  char quote;
 1.21915 +  int i, j;
 1.21916 +  if( z==0 ) return -1;
 1.21917 +  quote = z[0];
 1.21918 +  switch( quote ){
 1.21919 +    case '\'':  break;
 1.21920 +    case '"':   break;
 1.21921 +    case '`':   break;                /* For MySQL compatibility */
 1.21922 +    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
 1.21923 +    default:    return -1;
 1.21924 +  }
 1.21925 +  for(i=1, j=0;; i++){
 1.21926 +    assert( z[i] );
 1.21927 +    if( z[i]==quote ){
 1.21928 +      if( z[i+1]==quote ){
 1.21929 +        z[j++] = quote;
 1.21930 +        i++;
 1.21931 +      }else{
 1.21932 +        break;
 1.21933 +      }
 1.21934 +    }else{
 1.21935 +      z[j++] = z[i];
 1.21936 +    }
 1.21937 +  }
 1.21938 +  z[j] = 0;
 1.21939 +  return j;
 1.21940 +}
 1.21941 +
 1.21942 +/* Convenient short-hand */
 1.21943 +#define UpperToLower sqlite3UpperToLower
 1.21944 +
 1.21945 +/*
 1.21946 +** Some systems have stricmp().  Others have strcasecmp().  Because
 1.21947 +** there is no consistency, we will define our own.
 1.21948 +**
 1.21949 +** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
 1.21950 +** sqlite3_strnicmp() APIs allow applications and extensions to compare
 1.21951 +** the contents of two buffers containing UTF-8 strings in a
 1.21952 +** case-independent fashion, using the same definition of "case
 1.21953 +** independence" that SQLite uses internally when comparing identifiers.
 1.21954 +*/
 1.21955 +SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
 1.21956 +  register unsigned char *a, *b;
 1.21957 +  a = (unsigned char *)zLeft;
 1.21958 +  b = (unsigned char *)zRight;
 1.21959 +  while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
 1.21960 +  return UpperToLower[*a] - UpperToLower[*b];
 1.21961 +}
 1.21962 +SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
 1.21963 +  register unsigned char *a, *b;
 1.21964 +  a = (unsigned char *)zLeft;
 1.21965 +  b = (unsigned char *)zRight;
 1.21966 +  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
 1.21967 +  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
 1.21968 +}
 1.21969 +
 1.21970 +/*
 1.21971 +** The string z[] is an text representation of a real number.
 1.21972 +** Convert this string to a double and write it into *pResult.
 1.21973 +**
 1.21974 +** The string z[] is length bytes in length (bytes, not characters) and
 1.21975 +** uses the encoding enc.  The string is not necessarily zero-terminated.
 1.21976 +**
 1.21977 +** Return TRUE if the result is a valid real number (or integer) and FALSE
 1.21978 +** if the string is empty or contains extraneous text.  Valid numbers
 1.21979 +** are in one of these formats:
 1.21980 +**
 1.21981 +**    [+-]digits[E[+-]digits]
 1.21982 +**    [+-]digits.[digits][E[+-]digits]
 1.21983 +**    [+-].digits[E[+-]digits]
 1.21984 +**
 1.21985 +** Leading and trailing whitespace is ignored for the purpose of determining
 1.21986 +** validity.
 1.21987 +**
 1.21988 +** If some prefix of the input string is a valid number, this routine
 1.21989 +** returns FALSE but it still converts the prefix and writes the result
 1.21990 +** into *pResult.
 1.21991 +*/
 1.21992 +SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
 1.21993 +#ifndef SQLITE_OMIT_FLOATING_POINT
 1.21994 +  int incr;
 1.21995 +  const char *zEnd = z + length;
 1.21996 +  /* sign * significand * (10 ^ (esign * exponent)) */
 1.21997 +  int sign = 1;    /* sign of significand */
 1.21998 +  i64 s = 0;       /* significand */
 1.21999 +  int d = 0;       /* adjust exponent for shifting decimal point */
 1.22000 +  int esign = 1;   /* sign of exponent */
 1.22001 +  int e = 0;       /* exponent */
 1.22002 +  int eValid = 1;  /* True exponent is either not used or is well-formed */
 1.22003 +  double result;
 1.22004 +  int nDigits = 0;
 1.22005 +  int nonNum = 0;
 1.22006 +
 1.22007 +  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
 1.22008 +  *pResult = 0.0;   /* Default return value, in case of an error */
 1.22009 +
 1.22010 +  if( enc==SQLITE_UTF8 ){
 1.22011 +    incr = 1;
 1.22012 +  }else{
 1.22013 +    int i;
 1.22014 +    incr = 2;
 1.22015 +    assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
 1.22016 +    for(i=3-enc; i<length && z[i]==0; i+=2){}
 1.22017 +    nonNum = i<length;
 1.22018 +    zEnd = z+i+enc-3;
 1.22019 +    z += (enc&1);
 1.22020 +  }
 1.22021 +
 1.22022 +  /* skip leading spaces */
 1.22023 +  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
 1.22024 +  if( z>=zEnd ) return 0;
 1.22025 +
 1.22026 +  /* get sign of significand */
 1.22027 +  if( *z=='-' ){
 1.22028 +    sign = -1;
 1.22029 +    z+=incr;
 1.22030 +  }else if( *z=='+' ){
 1.22031 +    z+=incr;
 1.22032 +  }
 1.22033 +
 1.22034 +  /* skip leading zeroes */
 1.22035 +  while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
 1.22036 +
 1.22037 +  /* copy max significant digits to significand */
 1.22038 +  while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
 1.22039 +    s = s*10 + (*z - '0');
 1.22040 +    z+=incr, nDigits++;
 1.22041 +  }
 1.22042 +
 1.22043 +  /* skip non-significant significand digits
 1.22044 +  ** (increase exponent by d to shift decimal left) */
 1.22045 +  while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
 1.22046 +  if( z>=zEnd ) goto do_atof_calc;
 1.22047 +
 1.22048 +  /* if decimal point is present */
 1.22049 +  if( *z=='.' ){
 1.22050 +    z+=incr;
 1.22051 +    /* copy digits from after decimal to significand
 1.22052 +    ** (decrease exponent by d to shift decimal right) */
 1.22053 +    while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
 1.22054 +      s = s*10 + (*z - '0');
 1.22055 +      z+=incr, nDigits++, d--;
 1.22056 +    }
 1.22057 +    /* skip non-significant digits */
 1.22058 +    while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
 1.22059 +  }
 1.22060 +  if( z>=zEnd ) goto do_atof_calc;
 1.22061 +
 1.22062 +  /* if exponent is present */
 1.22063 +  if( *z=='e' || *z=='E' ){
 1.22064 +    z+=incr;
 1.22065 +    eValid = 0;
 1.22066 +    if( z>=zEnd ) goto do_atof_calc;
 1.22067 +    /* get sign of exponent */
 1.22068 +    if( *z=='-' ){
 1.22069 +      esign = -1;
 1.22070 +      z+=incr;
 1.22071 +    }else if( *z=='+' ){
 1.22072 +      z+=incr;
 1.22073 +    }
 1.22074 +    /* copy digits to exponent */
 1.22075 +    while( z<zEnd && sqlite3Isdigit(*z) ){
 1.22076 +      e = e<10000 ? (e*10 + (*z - '0')) : 10000;
 1.22077 +      z+=incr;
 1.22078 +      eValid = 1;
 1.22079 +    }
 1.22080 +  }
 1.22081 +
 1.22082 +  /* skip trailing spaces */
 1.22083 +  if( nDigits && eValid ){
 1.22084 +    while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
 1.22085 +  }
 1.22086 +
 1.22087 +do_atof_calc:
 1.22088 +  /* adjust exponent by d, and update sign */
 1.22089 +  e = (e*esign) + d;
 1.22090 +  if( e<0 ) {
 1.22091 +    esign = -1;
 1.22092 +    e *= -1;
 1.22093 +  } else {
 1.22094 +    esign = 1;
 1.22095 +  }
 1.22096 +
 1.22097 +  /* if 0 significand */
 1.22098 +  if( !s ) {
 1.22099 +    /* In the IEEE 754 standard, zero is signed.
 1.22100 +    ** Add the sign if we've seen at least one digit */
 1.22101 +    result = (sign<0 && nDigits) ? -(double)0 : (double)0;
 1.22102 +  } else {
 1.22103 +    /* attempt to reduce exponent */
 1.22104 +    if( esign>0 ){
 1.22105 +      while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
 1.22106 +    }else{
 1.22107 +      while( !(s%10) && e>0 ) e--,s/=10;
 1.22108 +    }
 1.22109 +
 1.22110 +    /* adjust the sign of significand */
 1.22111 +    s = sign<0 ? -s : s;
 1.22112 +
 1.22113 +    /* if exponent, scale significand as appropriate
 1.22114 +    ** and store in result. */
 1.22115 +    if( e ){
 1.22116 +      LONGDOUBLE_TYPE scale = 1.0;
 1.22117 +      /* attempt to handle extremely small/large numbers better */
 1.22118 +      if( e>307 && e<342 ){
 1.22119 +        while( e%308 ) { scale *= 1.0e+1; e -= 1; }
 1.22120 +        if( esign<0 ){
 1.22121 +          result = s / scale;
 1.22122 +          result /= 1.0e+308;
 1.22123 +        }else{
 1.22124 +          result = s * scale;
 1.22125 +          result *= 1.0e+308;
 1.22126 +        }
 1.22127 +      }else if( e>=342 ){
 1.22128 +        if( esign<0 ){
 1.22129 +          result = 0.0*s;
 1.22130 +        }else{
 1.22131 +          result = 1e308*1e308*s;  /* Infinity */
 1.22132 +        }
 1.22133 +      }else{
 1.22134 +        /* 1.0e+22 is the largest power of 10 than can be 
 1.22135 +        ** represented exactly. */
 1.22136 +        while( e%22 ) { scale *= 1.0e+1; e -= 1; }
 1.22137 +        while( e>0 ) { scale *= 1.0e+22; e -= 22; }
 1.22138 +        if( esign<0 ){
 1.22139 +          result = s / scale;
 1.22140 +        }else{
 1.22141 +          result = s * scale;
 1.22142 +        }
 1.22143 +      }
 1.22144 +    } else {
 1.22145 +      result = (double)s;
 1.22146 +    }
 1.22147 +  }
 1.22148 +
 1.22149 +  /* store the result */
 1.22150 +  *pResult = result;
 1.22151 +
 1.22152 +  /* return true if number and no extra non-whitespace chracters after */
 1.22153 +  return z>=zEnd && nDigits>0 && eValid && nonNum==0;
 1.22154 +#else
 1.22155 +  return !sqlite3Atoi64(z, pResult, length, enc);
 1.22156 +#endif /* SQLITE_OMIT_FLOATING_POINT */
 1.22157 +}
 1.22158 +
 1.22159 +/*
 1.22160 +** Compare the 19-character string zNum against the text representation
 1.22161 +** value 2^63:  9223372036854775808.  Return negative, zero, or positive
 1.22162 +** if zNum is less than, equal to, or greater than the string.
 1.22163 +** Note that zNum must contain exactly 19 characters.
 1.22164 +**
 1.22165 +** Unlike memcmp() this routine is guaranteed to return the difference
 1.22166 +** in the values of the last digit if the only difference is in the
 1.22167 +** last digit.  So, for example,
 1.22168 +**
 1.22169 +**      compare2pow63("9223372036854775800", 1)
 1.22170 +**
 1.22171 +** will return -8.
 1.22172 +*/
 1.22173 +static int compare2pow63(const char *zNum, int incr){
 1.22174 +  int c = 0;
 1.22175 +  int i;
 1.22176 +                    /* 012345678901234567 */
 1.22177 +  const char *pow63 = "922337203685477580";
 1.22178 +  for(i=0; c==0 && i<18; i++){
 1.22179 +    c = (zNum[i*incr]-pow63[i])*10;
 1.22180 +  }
 1.22181 +  if( c==0 ){
 1.22182 +    c = zNum[18*incr] - '8';
 1.22183 +    testcase( c==(-1) );
 1.22184 +    testcase( c==0 );
 1.22185 +    testcase( c==(+1) );
 1.22186 +  }
 1.22187 +  return c;
 1.22188 +}
 1.22189 +
 1.22190 +
 1.22191 +/*
 1.22192 +** Convert zNum to a 64-bit signed integer.
 1.22193 +**
 1.22194 +** If the zNum value is representable as a 64-bit twos-complement 
 1.22195 +** integer, then write that value into *pNum and return 0.
 1.22196 +**
 1.22197 +** If zNum is exactly 9223372036854775808, return 2.  This special
 1.22198 +** case is broken out because while 9223372036854775808 cannot be a 
 1.22199 +** signed 64-bit integer, its negative -9223372036854775808 can be.
 1.22200 +**
 1.22201 +** If zNum is too big for a 64-bit integer and is not
 1.22202 +** 9223372036854775808  or if zNum contains any non-numeric text,
 1.22203 +** then return 1.
 1.22204 +**
 1.22205 +** length is the number of bytes in the string (bytes, not characters).
 1.22206 +** The string is not necessarily zero-terminated.  The encoding is
 1.22207 +** given by enc.
 1.22208 +*/
 1.22209 +SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
 1.22210 +  int incr;
 1.22211 +  u64 u = 0;
 1.22212 +  int neg = 0; /* assume positive */
 1.22213 +  int i;
 1.22214 +  int c = 0;
 1.22215 +  int nonNum = 0;
 1.22216 +  const char *zStart;
 1.22217 +  const char *zEnd = zNum + length;
 1.22218 +  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
 1.22219 +  if( enc==SQLITE_UTF8 ){
 1.22220 +    incr = 1;
 1.22221 +  }else{
 1.22222 +    incr = 2;
 1.22223 +    assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
 1.22224 +    for(i=3-enc; i<length && zNum[i]==0; i+=2){}
 1.22225 +    nonNum = i<length;
 1.22226 +    zEnd = zNum+i+enc-3;
 1.22227 +    zNum += (enc&1);
 1.22228 +  }
 1.22229 +  while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
 1.22230 +  if( zNum<zEnd ){
 1.22231 +    if( *zNum=='-' ){
 1.22232 +      neg = 1;
 1.22233 +      zNum+=incr;
 1.22234 +    }else if( *zNum=='+' ){
 1.22235 +      zNum+=incr;
 1.22236 +    }
 1.22237 +  }
 1.22238 +  zStart = zNum;
 1.22239 +  while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
 1.22240 +  for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
 1.22241 +    u = u*10 + c - '0';
 1.22242 +  }
 1.22243 +  if( u>LARGEST_INT64 ){
 1.22244 +    *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
 1.22245 +  }else if( neg ){
 1.22246 +    *pNum = -(i64)u;
 1.22247 +  }else{
 1.22248 +    *pNum = (i64)u;
 1.22249 +  }
 1.22250 +  testcase( i==18 );
 1.22251 +  testcase( i==19 );
 1.22252 +  testcase( i==20 );
 1.22253 +  if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
 1.22254 +    /* zNum is empty or contains non-numeric text or is longer
 1.22255 +    ** than 19 digits (thus guaranteeing that it is too large) */
 1.22256 +    return 1;
 1.22257 +  }else if( i<19*incr ){
 1.22258 +    /* Less than 19 digits, so we know that it fits in 64 bits */
 1.22259 +    assert( u<=LARGEST_INT64 );
 1.22260 +    return 0;
 1.22261 +  }else{
 1.22262 +    /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
 1.22263 +    c = compare2pow63(zNum, incr);
 1.22264 +    if( c<0 ){
 1.22265 +      /* zNum is less than 9223372036854775808 so it fits */
 1.22266 +      assert( u<=LARGEST_INT64 );
 1.22267 +      return 0;
 1.22268 +    }else if( c>0 ){
 1.22269 +      /* zNum is greater than 9223372036854775808 so it overflows */
 1.22270 +      return 1;
 1.22271 +    }else{
 1.22272 +      /* zNum is exactly 9223372036854775808.  Fits if negative.  The
 1.22273 +      ** special case 2 overflow if positive */
 1.22274 +      assert( u-1==LARGEST_INT64 );
 1.22275 +      return neg ? 0 : 2;
 1.22276 +    }
 1.22277 +  }
 1.22278 +}
 1.22279 +
 1.22280 +/*
 1.22281 +** If zNum represents an integer that will fit in 32-bits, then set
 1.22282 +** *pValue to that integer and return true.  Otherwise return false.
 1.22283 +**
 1.22284 +** Any non-numeric characters that following zNum are ignored.
 1.22285 +** This is different from sqlite3Atoi64() which requires the
 1.22286 +** input number to be zero-terminated.
 1.22287 +*/
 1.22288 +SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
 1.22289 +  sqlite_int64 v = 0;
 1.22290 +  int i, c;
 1.22291 +  int neg = 0;
 1.22292 +  if( zNum[0]=='-' ){
 1.22293 +    neg = 1;
 1.22294 +    zNum++;
 1.22295 +  }else if( zNum[0]=='+' ){
 1.22296 +    zNum++;
 1.22297 +  }
 1.22298 +  while( zNum[0]=='0' ) zNum++;
 1.22299 +  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
 1.22300 +    v = v*10 + c;
 1.22301 +  }
 1.22302 +
 1.22303 +  /* The longest decimal representation of a 32 bit integer is 10 digits:
 1.22304 +  **
 1.22305 +  **             1234567890
 1.22306 +  **     2^31 -> 2147483648
 1.22307 +  */
 1.22308 +  testcase( i==10 );
 1.22309 +  if( i>10 ){
 1.22310 +    return 0;
 1.22311 +  }
 1.22312 +  testcase( v-neg==2147483647 );
 1.22313 +  if( v-neg>2147483647 ){
 1.22314 +    return 0;
 1.22315 +  }
 1.22316 +  if( neg ){
 1.22317 +    v = -v;
 1.22318 +  }
 1.22319 +  *pValue = (int)v;
 1.22320 +  return 1;
 1.22321 +}
 1.22322 +
 1.22323 +/*
 1.22324 +** Return a 32-bit integer value extracted from a string.  If the
 1.22325 +** string is not an integer, just return 0.
 1.22326 +*/
 1.22327 +SQLITE_PRIVATE int sqlite3Atoi(const char *z){
 1.22328 +  int x = 0;
 1.22329 +  if( z ) sqlite3GetInt32(z, &x);
 1.22330 +  return x;
 1.22331 +}
 1.22332 +
 1.22333 +/*
 1.22334 +** The variable-length integer encoding is as follows:
 1.22335 +**
 1.22336 +** KEY:
 1.22337 +**         A = 0xxxxxxx    7 bits of data and one flag bit
 1.22338 +**         B = 1xxxxxxx    7 bits of data and one flag bit
 1.22339 +**         C = xxxxxxxx    8 bits of data
 1.22340 +**
 1.22341 +**  7 bits - A
 1.22342 +** 14 bits - BA
 1.22343 +** 21 bits - BBA
 1.22344 +** 28 bits - BBBA
 1.22345 +** 35 bits - BBBBA
 1.22346 +** 42 bits - BBBBBA
 1.22347 +** 49 bits - BBBBBBA
 1.22348 +** 56 bits - BBBBBBBA
 1.22349 +** 64 bits - BBBBBBBBC
 1.22350 +*/
 1.22351 +
 1.22352 +/*
 1.22353 +** Write a 64-bit variable-length integer to memory starting at p[0].
 1.22354 +** The length of data write will be between 1 and 9 bytes.  The number
 1.22355 +** of bytes written is returned.
 1.22356 +**
 1.22357 +** A variable-length integer consists of the lower 7 bits of each byte
 1.22358 +** for all bytes that have the 8th bit set and one byte with the 8th
 1.22359 +** bit clear.  Except, if we get to the 9th byte, it stores the full
 1.22360 +** 8 bits and is the last byte.
 1.22361 +*/
 1.22362 +SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
 1.22363 +  int i, j, n;
 1.22364 +  u8 buf[10];
 1.22365 +  if( v & (((u64)0xff000000)<<32) ){
 1.22366 +    p[8] = (u8)v;
 1.22367 +    v >>= 8;
 1.22368 +    for(i=7; i>=0; i--){
 1.22369 +      p[i] = (u8)((v & 0x7f) | 0x80);
 1.22370 +      v >>= 7;
 1.22371 +    }
 1.22372 +    return 9;
 1.22373 +  }    
 1.22374 +  n = 0;
 1.22375 +  do{
 1.22376 +    buf[n++] = (u8)((v & 0x7f) | 0x80);
 1.22377 +    v >>= 7;
 1.22378 +  }while( v!=0 );
 1.22379 +  buf[0] &= 0x7f;
 1.22380 +  assert( n<=9 );
 1.22381 +  for(i=0, j=n-1; j>=0; j--, i++){
 1.22382 +    p[i] = buf[j];
 1.22383 +  }
 1.22384 +  return n;
 1.22385 +}
 1.22386 +
 1.22387 +/*
 1.22388 +** This routine is a faster version of sqlite3PutVarint() that only
 1.22389 +** works for 32-bit positive integers and which is optimized for
 1.22390 +** the common case of small integers.  A MACRO version, putVarint32,
 1.22391 +** is provided which inlines the single-byte case.  All code should use
 1.22392 +** the MACRO version as this function assumes the single-byte case has
 1.22393 +** already been handled.
 1.22394 +*/
 1.22395 +SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
 1.22396 +#ifndef putVarint32
 1.22397 +  if( (v & ~0x7f)==0 ){
 1.22398 +    p[0] = v;
 1.22399 +    return 1;
 1.22400 +  }
 1.22401 +#endif
 1.22402 +  if( (v & ~0x3fff)==0 ){
 1.22403 +    p[0] = (u8)((v>>7) | 0x80);
 1.22404 +    p[1] = (u8)(v & 0x7f);
 1.22405 +    return 2;
 1.22406 +  }
 1.22407 +  return sqlite3PutVarint(p, v);
 1.22408 +}
 1.22409 +
 1.22410 +/*
 1.22411 +** Bitmasks used by sqlite3GetVarint().  These precomputed constants
 1.22412 +** are defined here rather than simply putting the constant expressions
 1.22413 +** inline in order to work around bugs in the RVT compiler.
 1.22414 +**
 1.22415 +** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
 1.22416 +**
 1.22417 +** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
 1.22418 +*/
 1.22419 +#define SLOT_2_0     0x001fc07f
 1.22420 +#define SLOT_4_2_0   0xf01fc07f
 1.22421 +
 1.22422 +
 1.22423 +/*
 1.22424 +** Read a 64-bit variable-length integer from memory starting at p[0].
 1.22425 +** Return the number of bytes read.  The value is stored in *v.
 1.22426 +*/
 1.22427 +SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
 1.22428 +  u32 a,b,s;
 1.22429 +
 1.22430 +  a = *p;
 1.22431 +  /* a: p0 (unmasked) */
 1.22432 +  if (!(a&0x80))
 1.22433 +  {
 1.22434 +    *v = a;
 1.22435 +    return 1;
 1.22436 +  }
 1.22437 +
 1.22438 +  p++;
 1.22439 +  b = *p;
 1.22440 +  /* b: p1 (unmasked) */
 1.22441 +  if (!(b&0x80))
 1.22442 +  {
 1.22443 +    a &= 0x7f;
 1.22444 +    a = a<<7;
 1.22445 +    a |= b;
 1.22446 +    *v = a;
 1.22447 +    return 2;
 1.22448 +  }
 1.22449 +
 1.22450 +  /* Verify that constants are precomputed correctly */
 1.22451 +  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
 1.22452 +  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
 1.22453 +
 1.22454 +  p++;
 1.22455 +  a = a<<14;
 1.22456 +  a |= *p;
 1.22457 +  /* a: p0<<14 | p2 (unmasked) */
 1.22458 +  if (!(a&0x80))
 1.22459 +  {
 1.22460 +    a &= SLOT_2_0;
 1.22461 +    b &= 0x7f;
 1.22462 +    b = b<<7;
 1.22463 +    a |= b;
 1.22464 +    *v = a;
 1.22465 +    return 3;
 1.22466 +  }
 1.22467 +
 1.22468 +  /* CSE1 from below */
 1.22469 +  a &= SLOT_2_0;
 1.22470 +  p++;
 1.22471 +  b = b<<14;
 1.22472 +  b |= *p;
 1.22473 +  /* b: p1<<14 | p3 (unmasked) */
 1.22474 +  if (!(b&0x80))
 1.22475 +  {
 1.22476 +    b &= SLOT_2_0;
 1.22477 +    /* moved CSE1 up */
 1.22478 +    /* a &= (0x7f<<14)|(0x7f); */
 1.22479 +    a = a<<7;
 1.22480 +    a |= b;
 1.22481 +    *v = a;
 1.22482 +    return 4;
 1.22483 +  }
 1.22484 +
 1.22485 +  /* a: p0<<14 | p2 (masked) */
 1.22486 +  /* b: p1<<14 | p3 (unmasked) */
 1.22487 +  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
 1.22488 +  /* moved CSE1 up */
 1.22489 +  /* a &= (0x7f<<14)|(0x7f); */
 1.22490 +  b &= SLOT_2_0;
 1.22491 +  s = a;
 1.22492 +  /* s: p0<<14 | p2 (masked) */
 1.22493 +
 1.22494 +  p++;
 1.22495 +  a = a<<14;
 1.22496 +  a |= *p;
 1.22497 +  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
 1.22498 +  if (!(a&0x80))
 1.22499 +  {
 1.22500 +    /* we can skip these cause they were (effectively) done above in calc'ing s */
 1.22501 +    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
 1.22502 +    /* b &= (0x7f<<14)|(0x7f); */
 1.22503 +    b = b<<7;
 1.22504 +    a |= b;
 1.22505 +    s = s>>18;
 1.22506 +    *v = ((u64)s)<<32 | a;
 1.22507 +    return 5;
 1.22508 +  }
 1.22509 +
 1.22510 +  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
 1.22511 +  s = s<<7;
 1.22512 +  s |= b;
 1.22513 +  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
 1.22514 +
 1.22515 +  p++;
 1.22516 +  b = b<<14;
 1.22517 +  b |= *p;
 1.22518 +  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
 1.22519 +  if (!(b&0x80))
 1.22520 +  {
 1.22521 +    /* we can skip this cause it was (effectively) done above in calc'ing s */
 1.22522 +    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
 1.22523 +    a &= SLOT_2_0;
 1.22524 +    a = a<<7;
 1.22525 +    a |= b;
 1.22526 +    s = s>>18;
 1.22527 +    *v = ((u64)s)<<32 | a;
 1.22528 +    return 6;
 1.22529 +  }
 1.22530 +
 1.22531 +  p++;
 1.22532 +  a = a<<14;
 1.22533 +  a |= *p;
 1.22534 +  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
 1.22535 +  if (!(a&0x80))
 1.22536 +  {
 1.22537 +    a &= SLOT_4_2_0;
 1.22538 +    b &= SLOT_2_0;
 1.22539 +    b = b<<7;
 1.22540 +    a |= b;
 1.22541 +    s = s>>11;
 1.22542 +    *v = ((u64)s)<<32 | a;
 1.22543 +    return 7;
 1.22544 +  }
 1.22545 +
 1.22546 +  /* CSE2 from below */
 1.22547 +  a &= SLOT_2_0;
 1.22548 +  p++;
 1.22549 +  b = b<<14;
 1.22550 +  b |= *p;
 1.22551 +  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
 1.22552 +  if (!(b&0x80))
 1.22553 +  {
 1.22554 +    b &= SLOT_4_2_0;
 1.22555 +    /* moved CSE2 up */
 1.22556 +    /* a &= (0x7f<<14)|(0x7f); */
 1.22557 +    a = a<<7;
 1.22558 +    a |= b;
 1.22559 +    s = s>>4;
 1.22560 +    *v = ((u64)s)<<32 | a;
 1.22561 +    return 8;
 1.22562 +  }
 1.22563 +
 1.22564 +  p++;
 1.22565 +  a = a<<15;
 1.22566 +  a |= *p;
 1.22567 +  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
 1.22568 +
 1.22569 +  /* moved CSE2 up */
 1.22570 +  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
 1.22571 +  b &= SLOT_2_0;
 1.22572 +  b = b<<8;
 1.22573 +  a |= b;
 1.22574 +
 1.22575 +  s = s<<4;
 1.22576 +  b = p[-4];
 1.22577 +  b &= 0x7f;
 1.22578 +  b = b>>3;
 1.22579 +  s |= b;
 1.22580 +
 1.22581 +  *v = ((u64)s)<<32 | a;
 1.22582 +
 1.22583 +  return 9;
 1.22584 +}
 1.22585 +
 1.22586 +/*
 1.22587 +** Read a 32-bit variable-length integer from memory starting at p[0].
 1.22588 +** Return the number of bytes read.  The value is stored in *v.
 1.22589 +**
 1.22590 +** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
 1.22591 +** integer, then set *v to 0xffffffff.
 1.22592 +**
 1.22593 +** A MACRO version, getVarint32, is provided which inlines the 
 1.22594 +** single-byte case.  All code should use the MACRO version as 
 1.22595 +** this function assumes the single-byte case has already been handled.
 1.22596 +*/
 1.22597 +SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
 1.22598 +  u32 a,b;
 1.22599 +
 1.22600 +  /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
 1.22601 +  ** by the getVarin32() macro */
 1.22602 +  a = *p;
 1.22603 +  /* a: p0 (unmasked) */
 1.22604 +#ifndef getVarint32
 1.22605 +  if (!(a&0x80))
 1.22606 +  {
 1.22607 +    /* Values between 0 and 127 */
 1.22608 +    *v = a;
 1.22609 +    return 1;
 1.22610 +  }
 1.22611 +#endif
 1.22612 +
 1.22613 +  /* The 2-byte case */
 1.22614 +  p++;
 1.22615 +  b = *p;
 1.22616 +  /* b: p1 (unmasked) */
 1.22617 +  if (!(b&0x80))
 1.22618 +  {
 1.22619 +    /* Values between 128 and 16383 */
 1.22620 +    a &= 0x7f;
 1.22621 +    a = a<<7;
 1.22622 +    *v = a | b;
 1.22623 +    return 2;
 1.22624 +  }
 1.22625 +
 1.22626 +  /* The 3-byte case */
 1.22627 +  p++;
 1.22628 +  a = a<<14;
 1.22629 +  a |= *p;
 1.22630 +  /* a: p0<<14 | p2 (unmasked) */
 1.22631 +  if (!(a&0x80))
 1.22632 +  {
 1.22633 +    /* Values between 16384 and 2097151 */
 1.22634 +    a &= (0x7f<<14)|(0x7f);
 1.22635 +    b &= 0x7f;
 1.22636 +    b = b<<7;
 1.22637 +    *v = a | b;
 1.22638 +    return 3;
 1.22639 +  }
 1.22640 +
 1.22641 +  /* A 32-bit varint is used to store size information in btrees.
 1.22642 +  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
 1.22643 +  ** A 3-byte varint is sufficient, for example, to record the size
 1.22644 +  ** of a 1048569-byte BLOB or string.
 1.22645 +  **
 1.22646 +  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
 1.22647 +  ** rare larger cases can be handled by the slower 64-bit varint
 1.22648 +  ** routine.
 1.22649 +  */
 1.22650 +#if 1
 1.22651 +  {
 1.22652 +    u64 v64;
 1.22653 +    u8 n;
 1.22654 +
 1.22655 +    p -= 2;
 1.22656 +    n = sqlite3GetVarint(p, &v64);
 1.22657 +    assert( n>3 && n<=9 );
 1.22658 +    if( (v64 & SQLITE_MAX_U32)!=v64 ){
 1.22659 +      *v = 0xffffffff;
 1.22660 +    }else{
 1.22661 +      *v = (u32)v64;
 1.22662 +    }
 1.22663 +    return n;
 1.22664 +  }
 1.22665 +
 1.22666 +#else
 1.22667 +  /* For following code (kept for historical record only) shows an
 1.22668 +  ** unrolling for the 3- and 4-byte varint cases.  This code is
 1.22669 +  ** slightly faster, but it is also larger and much harder to test.
 1.22670 +  */
 1.22671 +  p++;
 1.22672 +  b = b<<14;
 1.22673 +  b |= *p;
 1.22674 +  /* b: p1<<14 | p3 (unmasked) */
 1.22675 +  if (!(b&0x80))
 1.22676 +  {
 1.22677 +    /* Values between 2097152 and 268435455 */
 1.22678 +    b &= (0x7f<<14)|(0x7f);
 1.22679 +    a &= (0x7f<<14)|(0x7f);
 1.22680 +    a = a<<7;
 1.22681 +    *v = a | b;
 1.22682 +    return 4;
 1.22683 +  }
 1.22684 +
 1.22685 +  p++;
 1.22686 +  a = a<<14;
 1.22687 +  a |= *p;
 1.22688 +  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
 1.22689 +  if (!(a&0x80))
 1.22690 +  {
 1.22691 +    /* Values  between 268435456 and 34359738367 */
 1.22692 +    a &= SLOT_4_2_0;
 1.22693 +    b &= SLOT_4_2_0;
 1.22694 +    b = b<<7;
 1.22695 +    *v = a | b;
 1.22696 +    return 5;
 1.22697 +  }
 1.22698 +
 1.22699 +  /* We can only reach this point when reading a corrupt database
 1.22700 +  ** file.  In that case we are not in any hurry.  Use the (relatively
 1.22701 +  ** slow) general-purpose sqlite3GetVarint() routine to extract the
 1.22702 +  ** value. */
 1.22703 +  {
 1.22704 +    u64 v64;
 1.22705 +    u8 n;
 1.22706 +
 1.22707 +    p -= 4;
 1.22708 +    n = sqlite3GetVarint(p, &v64);
 1.22709 +    assert( n>5 && n<=9 );
 1.22710 +    *v = (u32)v64;
 1.22711 +    return n;
 1.22712 +  }
 1.22713 +#endif
 1.22714 +}
 1.22715 +
 1.22716 +/*
 1.22717 +** Return the number of bytes that will be needed to store the given
 1.22718 +** 64-bit integer.
 1.22719 +*/
 1.22720 +SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
 1.22721 +  int i = 0;
 1.22722 +  do{
 1.22723 +    i++;
 1.22724 +    v >>= 7;
 1.22725 +  }while( v!=0 && ALWAYS(i<9) );
 1.22726 +  return i;
 1.22727 +}
 1.22728 +
 1.22729 +
 1.22730 +/*
 1.22731 +** Read or write a four-byte big-endian integer value.
 1.22732 +*/
 1.22733 +SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
 1.22734 +  testcase( p[0]&0x80 );
 1.22735 +  return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
 1.22736 +}
 1.22737 +SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
 1.22738 +  p[0] = (u8)(v>>24);
 1.22739 +  p[1] = (u8)(v>>16);
 1.22740 +  p[2] = (u8)(v>>8);
 1.22741 +  p[3] = (u8)v;
 1.22742 +}
 1.22743 +
 1.22744 +
 1.22745 +
 1.22746 +/*
 1.22747 +** Translate a single byte of Hex into an integer.
 1.22748 +** This routine only works if h really is a valid hexadecimal
 1.22749 +** character:  0..9a..fA..F
 1.22750 +*/
 1.22751 +SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
 1.22752 +  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
 1.22753 +#ifdef SQLITE_ASCII
 1.22754 +  h += 9*(1&(h>>6));
 1.22755 +#endif
 1.22756 +#ifdef SQLITE_EBCDIC
 1.22757 +  h += 9*(1&~(h>>4));
 1.22758 +#endif
 1.22759 +  return (u8)(h & 0xf);
 1.22760 +}
 1.22761 +
 1.22762 +#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
 1.22763 +/*
 1.22764 +** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
 1.22765 +** value.  Return a pointer to its binary value.  Space to hold the
 1.22766 +** binary value has been obtained from malloc and must be freed by
 1.22767 +** the calling routine.
 1.22768 +*/
 1.22769 +SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
 1.22770 +  char *zBlob;
 1.22771 +  int i;
 1.22772 +
 1.22773 +  zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
 1.22774 +  n--;
 1.22775 +  if( zBlob ){
 1.22776 +    for(i=0; i<n; i+=2){
 1.22777 +      zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
 1.22778 +    }
 1.22779 +    zBlob[i/2] = 0;
 1.22780 +  }
 1.22781 +  return zBlob;
 1.22782 +}
 1.22783 +#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
 1.22784 +
 1.22785 +/*
 1.22786 +** Log an error that is an API call on a connection pointer that should
 1.22787 +** not have been used.  The "type" of connection pointer is given as the
 1.22788 +** argument.  The zType is a word like "NULL" or "closed" or "invalid".
 1.22789 +*/
 1.22790 +static void logBadConnection(const char *zType){
 1.22791 +  sqlite3_log(SQLITE_MISUSE, 
 1.22792 +     "API call with %s database connection pointer",
 1.22793 +     zType
 1.22794 +  );
 1.22795 +}
 1.22796 +
 1.22797 +/*
 1.22798 +** Check to make sure we have a valid db pointer.  This test is not
 1.22799 +** foolproof but it does provide some measure of protection against
 1.22800 +** misuse of the interface such as passing in db pointers that are
 1.22801 +** NULL or which have been previously closed.  If this routine returns
 1.22802 +** 1 it means that the db pointer is valid and 0 if it should not be
 1.22803 +** dereferenced for any reason.  The calling function should invoke
 1.22804 +** SQLITE_MISUSE immediately.
 1.22805 +**
 1.22806 +** sqlite3SafetyCheckOk() requires that the db pointer be valid for
 1.22807 +** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
 1.22808 +** open properly and is not fit for general use but which can be
 1.22809 +** used as an argument to sqlite3_errmsg() or sqlite3_close().
 1.22810 +*/
 1.22811 +SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
 1.22812 +  u32 magic;
 1.22813 +  if( db==0 ){
 1.22814 +    logBadConnection("NULL");
 1.22815 +    return 0;
 1.22816 +  }
 1.22817 +  magic = db->magic;
 1.22818 +  if( magic!=SQLITE_MAGIC_OPEN ){
 1.22819 +    if( sqlite3SafetyCheckSickOrOk(db) ){
 1.22820 +      testcase( sqlite3GlobalConfig.xLog!=0 );
 1.22821 +      logBadConnection("unopened");
 1.22822 +    }
 1.22823 +    return 0;
 1.22824 +  }else{
 1.22825 +    return 1;
 1.22826 +  }
 1.22827 +}
 1.22828 +SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
 1.22829 +  u32 magic;
 1.22830 +  magic = db->magic;
 1.22831 +  if( magic!=SQLITE_MAGIC_SICK &&
 1.22832 +      magic!=SQLITE_MAGIC_OPEN &&
 1.22833 +      magic!=SQLITE_MAGIC_BUSY ){
 1.22834 +    testcase( sqlite3GlobalConfig.xLog!=0 );
 1.22835 +    logBadConnection("invalid");
 1.22836 +    return 0;
 1.22837 +  }else{
 1.22838 +    return 1;
 1.22839 +  }
 1.22840 +}
 1.22841 +
 1.22842 +/*
 1.22843 +** Attempt to add, substract, or multiply the 64-bit signed value iB against
 1.22844 +** the other 64-bit signed integer at *pA and store the result in *pA.
 1.22845 +** Return 0 on success.  Or if the operation would have resulted in an
 1.22846 +** overflow, leave *pA unchanged and return 1.
 1.22847 +*/
 1.22848 +SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
 1.22849 +  i64 iA = *pA;
 1.22850 +  testcase( iA==0 ); testcase( iA==1 );
 1.22851 +  testcase( iB==-1 ); testcase( iB==0 );
 1.22852 +  if( iB>=0 ){
 1.22853 +    testcase( iA>0 && LARGEST_INT64 - iA == iB );
 1.22854 +    testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
 1.22855 +    if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
 1.22856 +  }else{
 1.22857 +    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
 1.22858 +    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
 1.22859 +    if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
 1.22860 +  }
 1.22861 +  *pA += iB;
 1.22862 +  return 0; 
 1.22863 +}
 1.22864 +SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
 1.22865 +  testcase( iB==SMALLEST_INT64+1 );
 1.22866 +  if( iB==SMALLEST_INT64 ){
 1.22867 +    testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
 1.22868 +    if( (*pA)>=0 ) return 1;
 1.22869 +    *pA -= iB;
 1.22870 +    return 0;
 1.22871 +  }else{
 1.22872 +    return sqlite3AddInt64(pA, -iB);
 1.22873 +  }
 1.22874 +}
 1.22875 +#define TWOPOWER32 (((i64)1)<<32)
 1.22876 +#define TWOPOWER31 (((i64)1)<<31)
 1.22877 +SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
 1.22878 +  i64 iA = *pA;
 1.22879 +  i64 iA1, iA0, iB1, iB0, r;
 1.22880 +
 1.22881 +  iA1 = iA/TWOPOWER32;
 1.22882 +  iA0 = iA % TWOPOWER32;
 1.22883 +  iB1 = iB/TWOPOWER32;
 1.22884 +  iB0 = iB % TWOPOWER32;
 1.22885 +  if( iA1==0 ){
 1.22886 +    if( iB1==0 ){
 1.22887 +      *pA *= iB;
 1.22888 +      return 0;
 1.22889 +    }
 1.22890 +    r = iA0*iB1;
 1.22891 +  }else if( iB1==0 ){
 1.22892 +    r = iA1*iB0;
 1.22893 +  }else{
 1.22894 +    /* If both iA1 and iB1 are non-zero, overflow will result */
 1.22895 +    return 1;
 1.22896 +  }
 1.22897 +  testcase( r==(-TWOPOWER31)-1 );
 1.22898 +  testcase( r==(-TWOPOWER31) );
 1.22899 +  testcase( r==TWOPOWER31 );
 1.22900 +  testcase( r==TWOPOWER31-1 );
 1.22901 +  if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
 1.22902 +  r *= TWOPOWER32;
 1.22903 +  if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
 1.22904 +  *pA = r;
 1.22905 +  return 0;
 1.22906 +}
 1.22907 +
 1.22908 +/*
 1.22909 +** Compute the absolute value of a 32-bit signed integer, of possible.  Or 
 1.22910 +** if the integer has a value of -2147483648, return +2147483647
 1.22911 +*/
 1.22912 +SQLITE_PRIVATE int sqlite3AbsInt32(int x){
 1.22913 +  if( x>=0 ) return x;
 1.22914 +  if( x==(int)0x80000000 ) return 0x7fffffff;
 1.22915 +  return -x;
 1.22916 +}
 1.22917 +
 1.22918 +#ifdef SQLITE_ENABLE_8_3_NAMES
 1.22919 +/*
 1.22920 +** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
 1.22921 +** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
 1.22922 +** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
 1.22923 +** three characters, then shorten the suffix on z[] to be the last three
 1.22924 +** characters of the original suffix.
 1.22925 +**
 1.22926 +** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
 1.22927 +** do the suffix shortening regardless of URI parameter.
 1.22928 +**
 1.22929 +** Examples:
 1.22930 +**
 1.22931 +**     test.db-journal    =>   test.nal
 1.22932 +**     test.db-wal        =>   test.wal
 1.22933 +**     test.db-shm        =>   test.shm
 1.22934 +**     test.db-mj7f3319fa =>   test.9fa
 1.22935 +*/
 1.22936 +SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
 1.22937 +#if SQLITE_ENABLE_8_3_NAMES<2
 1.22938 +  if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
 1.22939 +#endif
 1.22940 +  {
 1.22941 +    int i, sz;
 1.22942 +    sz = sqlite3Strlen30(z);
 1.22943 +    for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
 1.22944 +    if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
 1.22945 +  }
 1.22946 +}
 1.22947 +#endif
 1.22948 +
 1.22949 +/* 
 1.22950 +** Find (an approximate) sum of two LogEst values.  This computation is
 1.22951 +** not a simple "+" operator because LogEst is stored as a logarithmic
 1.22952 +** value.
 1.22953 +** 
 1.22954 +*/
 1.22955 +SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
 1.22956 +  static const unsigned char x[] = {
 1.22957 +     10, 10,                         /* 0,1 */
 1.22958 +      9, 9,                          /* 2,3 */
 1.22959 +      8, 8,                          /* 4,5 */
 1.22960 +      7, 7, 7,                       /* 6,7,8 */
 1.22961 +      6, 6, 6,                       /* 9,10,11 */
 1.22962 +      5, 5, 5,                       /* 12-14 */
 1.22963 +      4, 4, 4, 4,                    /* 15-18 */
 1.22964 +      3, 3, 3, 3, 3, 3,              /* 19-24 */
 1.22965 +      2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
 1.22966 +  };
 1.22967 +  if( a>=b ){
 1.22968 +    if( a>b+49 ) return a;
 1.22969 +    if( a>b+31 ) return a+1;
 1.22970 +    return a+x[a-b];
 1.22971 +  }else{
 1.22972 +    if( b>a+49 ) return b;
 1.22973 +    if( b>a+31 ) return b+1;
 1.22974 +    return b+x[b-a];
 1.22975 +  }
 1.22976 +}
 1.22977 +
 1.22978 +/*
 1.22979 +** Convert an integer into a LogEst.  In other words, compute a
 1.22980 +** good approximatation for 10*log2(x).
 1.22981 +*/
 1.22982 +SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
 1.22983 +  static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
 1.22984 +  LogEst y = 40;
 1.22985 +  if( x<8 ){
 1.22986 +    if( x<2 ) return 0;
 1.22987 +    while( x<8 ){  y -= 10; x <<= 1; }
 1.22988 +  }else{
 1.22989 +    while( x>255 ){ y += 40; x >>= 4; }
 1.22990 +    while( x>15 ){  y += 10; x >>= 1; }
 1.22991 +  }
 1.22992 +  return a[x&7] + y - 10;
 1.22993 +}
 1.22994 +
 1.22995 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.22996 +/*
 1.22997 +** Convert a double into a LogEst
 1.22998 +** In other words, compute an approximation for 10*log2(x).
 1.22999 +*/
 1.23000 +SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
 1.23001 +  u64 a;
 1.23002 +  LogEst e;
 1.23003 +  assert( sizeof(x)==8 && sizeof(a)==8 );
 1.23004 +  if( x<=1 ) return 0;
 1.23005 +  if( x<=2000000000 ) return sqlite3LogEst((u64)x);
 1.23006 +  memcpy(&a, &x, 8);
 1.23007 +  e = (a>>52) - 1022;
 1.23008 +  return e*10;
 1.23009 +}
 1.23010 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
 1.23011 +
 1.23012 +/*
 1.23013 +** Convert a LogEst into an integer.
 1.23014 +*/
 1.23015 +SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
 1.23016 +  u64 n;
 1.23017 +  if( x<10 ) return 1;
 1.23018 +  n = x%10;
 1.23019 +  x /= 10;
 1.23020 +  if( n>=5 ) n -= 2;
 1.23021 +  else if( n>=1 ) n -= 1;
 1.23022 +  if( x>=3 ){
 1.23023 +    return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
 1.23024 +  }
 1.23025 +  return (n+8)>>(3-x);
 1.23026 +}
 1.23027 +
 1.23028 +/************** End of util.c ************************************************/
 1.23029 +/************** Begin file hash.c ********************************************/
 1.23030 +/*
 1.23031 +** 2001 September 22
 1.23032 +**
 1.23033 +** The author disclaims copyright to this source code.  In place of
 1.23034 +** a legal notice, here is a blessing:
 1.23035 +**
 1.23036 +**    May you do good and not evil.
 1.23037 +**    May you find forgiveness for yourself and forgive others.
 1.23038 +**    May you share freely, never taking more than you give.
 1.23039 +**
 1.23040 +*************************************************************************
 1.23041 +** This is the implementation of generic hash-tables
 1.23042 +** used in SQLite.
 1.23043 +*/
 1.23044 +/* #include <assert.h> */
 1.23045 +
 1.23046 +/* Turn bulk memory into a hash table object by initializing the
 1.23047 +** fields of the Hash structure.
 1.23048 +**
 1.23049 +** "pNew" is a pointer to the hash table that is to be initialized.
 1.23050 +*/
 1.23051 +SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
 1.23052 +  assert( pNew!=0 );
 1.23053 +  pNew->first = 0;
 1.23054 +  pNew->count = 0;
 1.23055 +  pNew->htsize = 0;
 1.23056 +  pNew->ht = 0;
 1.23057 +}
 1.23058 +
 1.23059 +/* Remove all entries from a hash table.  Reclaim all memory.
 1.23060 +** Call this routine to delete a hash table or to reset a hash table
 1.23061 +** to the empty state.
 1.23062 +*/
 1.23063 +SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
 1.23064 +  HashElem *elem;         /* For looping over all elements of the table */
 1.23065 +
 1.23066 +  assert( pH!=0 );
 1.23067 +  elem = pH->first;
 1.23068 +  pH->first = 0;
 1.23069 +  sqlite3_free(pH->ht);
 1.23070 +  pH->ht = 0;
 1.23071 +  pH->htsize = 0;
 1.23072 +  while( elem ){
 1.23073 +    HashElem *next_elem = elem->next;
 1.23074 +    sqlite3_free(elem);
 1.23075 +    elem = next_elem;
 1.23076 +  }
 1.23077 +  pH->count = 0;
 1.23078 +}
 1.23079 +
 1.23080 +/*
 1.23081 +** The hashing function.
 1.23082 +*/
 1.23083 +static unsigned int strHash(const char *z, int nKey){
 1.23084 +  unsigned int h = 0;
 1.23085 +  assert( nKey>=0 );
 1.23086 +  while( nKey > 0  ){
 1.23087 +    h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
 1.23088 +    nKey--;
 1.23089 +  }
 1.23090 +  return h;
 1.23091 +}
 1.23092 +
 1.23093 +
 1.23094 +/* Link pNew element into the hash table pH.  If pEntry!=0 then also
 1.23095 +** insert pNew into the pEntry hash bucket.
 1.23096 +*/
 1.23097 +static void insertElement(
 1.23098 +  Hash *pH,              /* The complete hash table */
 1.23099 +  struct _ht *pEntry,    /* The entry into which pNew is inserted */
 1.23100 +  HashElem *pNew         /* The element to be inserted */
 1.23101 +){
 1.23102 +  HashElem *pHead;       /* First element already in pEntry */
 1.23103 +  if( pEntry ){
 1.23104 +    pHead = pEntry->count ? pEntry->chain : 0;
 1.23105 +    pEntry->count++;
 1.23106 +    pEntry->chain = pNew;
 1.23107 +  }else{
 1.23108 +    pHead = 0;
 1.23109 +  }
 1.23110 +  if( pHead ){
 1.23111 +    pNew->next = pHead;
 1.23112 +    pNew->prev = pHead->prev;
 1.23113 +    if( pHead->prev ){ pHead->prev->next = pNew; }
 1.23114 +    else             { pH->first = pNew; }
 1.23115 +    pHead->prev = pNew;
 1.23116 +  }else{
 1.23117 +    pNew->next = pH->first;
 1.23118 +    if( pH->first ){ pH->first->prev = pNew; }
 1.23119 +    pNew->prev = 0;
 1.23120 +    pH->first = pNew;
 1.23121 +  }
 1.23122 +}
 1.23123 +
 1.23124 +
 1.23125 +/* Resize the hash table so that it cantains "new_size" buckets.
 1.23126 +**
 1.23127 +** The hash table might fail to resize if sqlite3_malloc() fails or
 1.23128 +** if the new size is the same as the prior size.
 1.23129 +** Return TRUE if the resize occurs and false if not.
 1.23130 +*/
 1.23131 +static int rehash(Hash *pH, unsigned int new_size){
 1.23132 +  struct _ht *new_ht;            /* The new hash table */
 1.23133 +  HashElem *elem, *next_elem;    /* For looping over existing elements */
 1.23134 +
 1.23135 +#if SQLITE_MALLOC_SOFT_LIMIT>0
 1.23136 +  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
 1.23137 +    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
 1.23138 +  }
 1.23139 +  if( new_size==pH->htsize ) return 0;
 1.23140 +#endif
 1.23141 +
 1.23142 +  /* The inability to allocates space for a larger hash table is
 1.23143 +  ** a performance hit but it is not a fatal error.  So mark the
 1.23144 +  ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of 
 1.23145 +  ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
 1.23146 +  ** only zeroes the requested number of bytes whereas this module will
 1.23147 +  ** use the actual amount of space allocated for the hash table (which
 1.23148 +  ** may be larger than the requested amount).
 1.23149 +  */
 1.23150 +  sqlite3BeginBenignMalloc();
 1.23151 +  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
 1.23152 +  sqlite3EndBenignMalloc();
 1.23153 +
 1.23154 +  if( new_ht==0 ) return 0;
 1.23155 +  sqlite3_free(pH->ht);
 1.23156 +  pH->ht = new_ht;
 1.23157 +  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
 1.23158 +  memset(new_ht, 0, new_size*sizeof(struct _ht));
 1.23159 +  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
 1.23160 +    unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
 1.23161 +    next_elem = elem->next;
 1.23162 +    insertElement(pH, &new_ht[h], elem);
 1.23163 +  }
 1.23164 +  return 1;
 1.23165 +}
 1.23166 +
 1.23167 +/* This function (for internal use only) locates an element in an
 1.23168 +** hash table that matches the given key.  The hash for this key has
 1.23169 +** already been computed and is passed as the 4th parameter.
 1.23170 +*/
 1.23171 +static HashElem *findElementGivenHash(
 1.23172 +  const Hash *pH,     /* The pH to be searched */
 1.23173 +  const char *pKey,   /* The key we are searching for */
 1.23174 +  int nKey,           /* Bytes in key (not counting zero terminator) */
 1.23175 +  unsigned int h      /* The hash for this key. */
 1.23176 +){
 1.23177 +  HashElem *elem;                /* Used to loop thru the element list */
 1.23178 +  int count;                     /* Number of elements left to test */
 1.23179 +
 1.23180 +  if( pH->ht ){
 1.23181 +    struct _ht *pEntry = &pH->ht[h];
 1.23182 +    elem = pEntry->chain;
 1.23183 +    count = pEntry->count;
 1.23184 +  }else{
 1.23185 +    elem = pH->first;
 1.23186 +    count = pH->count;
 1.23187 +  }
 1.23188 +  while( count-- && ALWAYS(elem) ){
 1.23189 +    if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
 1.23190 +      return elem;
 1.23191 +    }
 1.23192 +    elem = elem->next;
 1.23193 +  }
 1.23194 +  return 0;
 1.23195 +}
 1.23196 +
 1.23197 +/* Remove a single entry from the hash table given a pointer to that
 1.23198 +** element and a hash on the element's key.
 1.23199 +*/
 1.23200 +static void removeElementGivenHash(
 1.23201 +  Hash *pH,         /* The pH containing "elem" */
 1.23202 +  HashElem* elem,   /* The element to be removed from the pH */
 1.23203 +  unsigned int h    /* Hash value for the element */
 1.23204 +){
 1.23205 +  struct _ht *pEntry;
 1.23206 +  if( elem->prev ){
 1.23207 +    elem->prev->next = elem->next; 
 1.23208 +  }else{
 1.23209 +    pH->first = elem->next;
 1.23210 +  }
 1.23211 +  if( elem->next ){
 1.23212 +    elem->next->prev = elem->prev;
 1.23213 +  }
 1.23214 +  if( pH->ht ){
 1.23215 +    pEntry = &pH->ht[h];
 1.23216 +    if( pEntry->chain==elem ){
 1.23217 +      pEntry->chain = elem->next;
 1.23218 +    }
 1.23219 +    pEntry->count--;
 1.23220 +    assert( pEntry->count>=0 );
 1.23221 +  }
 1.23222 +  sqlite3_free( elem );
 1.23223 +  pH->count--;
 1.23224 +  if( pH->count==0 ){
 1.23225 +    assert( pH->first==0 );
 1.23226 +    assert( pH->count==0 );
 1.23227 +    sqlite3HashClear(pH);
 1.23228 +  }
 1.23229 +}
 1.23230 +
 1.23231 +/* Attempt to locate an element of the hash table pH with a key
 1.23232 +** that matches pKey,nKey.  Return the data for this element if it is
 1.23233 +** found, or NULL if there is no match.
 1.23234 +*/
 1.23235 +SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
 1.23236 +  HashElem *elem;    /* The element that matches key */
 1.23237 +  unsigned int h;    /* A hash on key */
 1.23238 +
 1.23239 +  assert( pH!=0 );
 1.23240 +  assert( pKey!=0 );
 1.23241 +  assert( nKey>=0 );
 1.23242 +  if( pH->ht ){
 1.23243 +    h = strHash(pKey, nKey) % pH->htsize;
 1.23244 +  }else{
 1.23245 +    h = 0;
 1.23246 +  }
 1.23247 +  elem = findElementGivenHash(pH, pKey, nKey, h);
 1.23248 +  return elem ? elem->data : 0;
 1.23249 +}
 1.23250 +
 1.23251 +/* Insert an element into the hash table pH.  The key is pKey,nKey
 1.23252 +** and the data is "data".
 1.23253 +**
 1.23254 +** If no element exists with a matching key, then a new
 1.23255 +** element is created and NULL is returned.
 1.23256 +**
 1.23257 +** If another element already exists with the same key, then the
 1.23258 +** new data replaces the old data and the old data is returned.
 1.23259 +** The key is not copied in this instance.  If a malloc fails, then
 1.23260 +** the new data is returned and the hash table is unchanged.
 1.23261 +**
 1.23262 +** If the "data" parameter to this function is NULL, then the
 1.23263 +** element corresponding to "key" is removed from the hash table.
 1.23264 +*/
 1.23265 +SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
 1.23266 +  unsigned int h;       /* the hash of the key modulo hash table size */
 1.23267 +  HashElem *elem;       /* Used to loop thru the element list */
 1.23268 +  HashElem *new_elem;   /* New element added to the pH */
 1.23269 +
 1.23270 +  assert( pH!=0 );
 1.23271 +  assert( pKey!=0 );
 1.23272 +  assert( nKey>=0 );
 1.23273 +  if( pH->htsize ){
 1.23274 +    h = strHash(pKey, nKey) % pH->htsize;
 1.23275 +  }else{
 1.23276 +    h = 0;
 1.23277 +  }
 1.23278 +  elem = findElementGivenHash(pH,pKey,nKey,h);
 1.23279 +  if( elem ){
 1.23280 +    void *old_data = elem->data;
 1.23281 +    if( data==0 ){
 1.23282 +      removeElementGivenHash(pH,elem,h);
 1.23283 +    }else{
 1.23284 +      elem->data = data;
 1.23285 +      elem->pKey = pKey;
 1.23286 +      assert(nKey==elem->nKey);
 1.23287 +    }
 1.23288 +    return old_data;
 1.23289 +  }
 1.23290 +  if( data==0 ) return 0;
 1.23291 +  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
 1.23292 +  if( new_elem==0 ) return data;
 1.23293 +  new_elem->pKey = pKey;
 1.23294 +  new_elem->nKey = nKey;
 1.23295 +  new_elem->data = data;
 1.23296 +  pH->count++;
 1.23297 +  if( pH->count>=10 && pH->count > 2*pH->htsize ){
 1.23298 +    if( rehash(pH, pH->count*2) ){
 1.23299 +      assert( pH->htsize>0 );
 1.23300 +      h = strHash(pKey, nKey) % pH->htsize;
 1.23301 +    }
 1.23302 +  }
 1.23303 +  if( pH->ht ){
 1.23304 +    insertElement(pH, &pH->ht[h], new_elem);
 1.23305 +  }else{
 1.23306 +    insertElement(pH, 0, new_elem);
 1.23307 +  }
 1.23308 +  return 0;
 1.23309 +}
 1.23310 +
 1.23311 +/************** End of hash.c ************************************************/
 1.23312 +/************** Begin file opcodes.c *****************************************/
 1.23313 +/* Automatically generated.  Do not edit */
 1.23314 +/* See the mkopcodec.awk script for details. */
 1.23315 +#if !defined(SQLITE_OMIT_EXPLAIN) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
 1.23316 +#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
 1.23317 +# define OpHelp(X) "\0" X
 1.23318 +#else
 1.23319 +# define OpHelp(X)
 1.23320 +#endif
 1.23321 +SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
 1.23322 + static const char *const azName[] = { "?",
 1.23323 +     /*   1 */ "Function"         OpHelp("r[P3]=func(r[P2@P5])"),
 1.23324 +     /*   2 */ "Savepoint"        OpHelp(""),
 1.23325 +     /*   3 */ "AutoCommit"       OpHelp(""),
 1.23326 +     /*   4 */ "Transaction"      OpHelp(""),
 1.23327 +     /*   5 */ "SorterNext"       OpHelp(""),
 1.23328 +     /*   6 */ "PrevIfOpen"       OpHelp(""),
 1.23329 +     /*   7 */ "NextIfOpen"       OpHelp(""),
 1.23330 +     /*   8 */ "Prev"             OpHelp(""),
 1.23331 +     /*   9 */ "Next"             OpHelp(""),
 1.23332 +     /*  10 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
 1.23333 +     /*  11 */ "Checkpoint"       OpHelp(""),
 1.23334 +     /*  12 */ "JournalMode"      OpHelp(""),
 1.23335 +     /*  13 */ "Vacuum"           OpHelp(""),
 1.23336 +     /*  14 */ "VFilter"          OpHelp("iPlan=r[P3] zPlan='P4'"),
 1.23337 +     /*  15 */ "VUpdate"          OpHelp("data=r[P3@P2]"),
 1.23338 +     /*  16 */ "Goto"             OpHelp(""),
 1.23339 +     /*  17 */ "Gosub"            OpHelp(""),
 1.23340 +     /*  18 */ "Return"           OpHelp(""),
 1.23341 +     /*  19 */ "Not"              OpHelp("r[P2]= !r[P1]"),
 1.23342 +     /*  20 */ "InitCoroutine"    OpHelp(""),
 1.23343 +     /*  21 */ "EndCoroutine"     OpHelp(""),
 1.23344 +     /*  22 */ "Yield"            OpHelp(""),
 1.23345 +     /*  23 */ "HaltIfNull"       OpHelp("if r[P3]=null halt"),
 1.23346 +     /*  24 */ "Halt"             OpHelp(""),
 1.23347 +     /*  25 */ "Integer"          OpHelp("r[P2]=P1"),
 1.23348 +     /*  26 */ "Int64"            OpHelp("r[P2]=P4"),
 1.23349 +     /*  27 */ "String"           OpHelp("r[P2]='P4' (len=P1)"),
 1.23350 +     /*  28 */ "Null"             OpHelp("r[P2..P3]=NULL"),
 1.23351 +     /*  29 */ "SoftNull"         OpHelp("r[P1]=NULL"),
 1.23352 +     /*  30 */ "Blob"             OpHelp("r[P2]=P4 (len=P1)"),
 1.23353 +     /*  31 */ "Variable"         OpHelp("r[P2]=parameter(P1,P4)"),
 1.23354 +     /*  32 */ "Move"             OpHelp("r[P2@P3]=r[P1@P3]"),
 1.23355 +     /*  33 */ "Copy"             OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
 1.23356 +     /*  34 */ "SCopy"            OpHelp("r[P2]=r[P1]"),
 1.23357 +     /*  35 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
 1.23358 +     /*  36 */ "CollSeq"          OpHelp(""),
 1.23359 +     /*  37 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
 1.23360 +     /*  38 */ "MustBeInt"        OpHelp(""),
 1.23361 +     /*  39 */ "RealAffinity"     OpHelp(""),
 1.23362 +     /*  40 */ "Permutation"      OpHelp(""),
 1.23363 +     /*  41 */ "Compare"          OpHelp(""),
 1.23364 +     /*  42 */ "Jump"             OpHelp(""),
 1.23365 +     /*  43 */ "Once"             OpHelp(""),
 1.23366 +     /*  44 */ "If"               OpHelp(""),
 1.23367 +     /*  45 */ "IfNot"            OpHelp(""),
 1.23368 +     /*  46 */ "Column"           OpHelp("r[P3]=PX"),
 1.23369 +     /*  47 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
 1.23370 +     /*  48 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
 1.23371 +     /*  49 */ "Count"            OpHelp("r[P2]=count()"),
 1.23372 +     /*  50 */ "ReadCookie"       OpHelp(""),
 1.23373 +     /*  51 */ "SetCookie"        OpHelp(""),
 1.23374 +     /*  52 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
 1.23375 +     /*  53 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
 1.23376 +     /*  54 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
 1.23377 +     /*  55 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
 1.23378 +     /*  56 */ "SorterOpen"       OpHelp(""),
 1.23379 +     /*  57 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
 1.23380 +     /*  58 */ "Close"            OpHelp(""),
 1.23381 +     /*  59 */ "SeekLT"           OpHelp(""),
 1.23382 +     /*  60 */ "SeekLE"           OpHelp(""),
 1.23383 +     /*  61 */ "SeekGE"           OpHelp(""),
 1.23384 +     /*  62 */ "SeekGT"           OpHelp(""),
 1.23385 +     /*  63 */ "Seek"             OpHelp("intkey=r[P2]"),
 1.23386 +     /*  64 */ "NoConflict"       OpHelp("key=r[P3@P4]"),
 1.23387 +     /*  65 */ "NotFound"         OpHelp("key=r[P3@P4]"),
 1.23388 +     /*  66 */ "Found"            OpHelp("key=r[P3@P4]"),
 1.23389 +     /*  67 */ "NotExists"        OpHelp("intkey=r[P3]"),
 1.23390 +     /*  68 */ "Sequence"         OpHelp("r[P2]=rowid"),
 1.23391 +     /*  69 */ "NewRowid"         OpHelp("r[P2]=rowid"),
 1.23392 +     /*  70 */ "Insert"           OpHelp("intkey=r[P3] data=r[P2]"),
 1.23393 +     /*  71 */ "Or"               OpHelp("r[P3]=(r[P1] || r[P2])"),
 1.23394 +     /*  72 */ "And"              OpHelp("r[P3]=(r[P1] && r[P2])"),
 1.23395 +     /*  73 */ "InsertInt"        OpHelp("intkey=P3 data=r[P2]"),
 1.23396 +     /*  74 */ "Delete"           OpHelp(""),
 1.23397 +     /*  75 */ "ResetCount"       OpHelp(""),
 1.23398 +     /*  76 */ "IsNull"           OpHelp("if r[P1]==NULL goto P2"),
 1.23399 +     /*  77 */ "NotNull"          OpHelp("if r[P1]!=NULL goto P2"),
 1.23400 +     /*  78 */ "Ne"               OpHelp("if r[P1]!=r[P3] goto P2"),
 1.23401 +     /*  79 */ "Eq"               OpHelp("if r[P1]==r[P3] goto P2"),
 1.23402 +     /*  80 */ "Gt"               OpHelp("if r[P1]>r[P3] goto P2"),
 1.23403 +     /*  81 */ "Le"               OpHelp("if r[P1]<=r[P3] goto P2"),
 1.23404 +     /*  82 */ "Lt"               OpHelp("if r[P1]<r[P3] goto P2"),
 1.23405 +     /*  83 */ "Ge"               OpHelp("if r[P1]>=r[P3] goto P2"),
 1.23406 +     /*  84 */ "SorterCompare"    OpHelp("if key(P1)!=rtrim(r[P3],P4) goto P2"),
 1.23407 +     /*  85 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
 1.23408 +     /*  86 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
 1.23409 +     /*  87 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
 1.23410 +     /*  88 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
 1.23411 +     /*  89 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
 1.23412 +     /*  90 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
 1.23413 +     /*  91 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
 1.23414 +     /*  92 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
 1.23415 +     /*  93 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
 1.23416 +     /*  94 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
 1.23417 +     /*  95 */ "SorterData"       OpHelp("r[P2]=data"),
 1.23418 +     /*  96 */ "BitNot"           OpHelp("r[P1]= ~r[P1]"),
 1.23419 +     /*  97 */ "String8"          OpHelp("r[P2]='P4'"),
 1.23420 +     /*  98 */ "RowKey"           OpHelp("r[P2]=key"),
 1.23421 +     /*  99 */ "RowData"          OpHelp("r[P2]=data"),
 1.23422 +     /* 100 */ "Rowid"            OpHelp("r[P2]=rowid"),
 1.23423 +     /* 101 */ "NullRow"          OpHelp(""),
 1.23424 +     /* 102 */ "Last"             OpHelp(""),
 1.23425 +     /* 103 */ "SorterSort"       OpHelp(""),
 1.23426 +     /* 104 */ "Sort"             OpHelp(""),
 1.23427 +     /* 105 */ "Rewind"           OpHelp(""),
 1.23428 +     /* 106 */ "SorterInsert"     OpHelp(""),
 1.23429 +     /* 107 */ "IdxInsert"        OpHelp("key=r[P2]"),
 1.23430 +     /* 108 */ "IdxDelete"        OpHelp("key=r[P2@P3]"),
 1.23431 +     /* 109 */ "IdxRowid"         OpHelp("r[P2]=rowid"),
 1.23432 +     /* 110 */ "IdxLE"            OpHelp("key=r[P3@P4]"),
 1.23433 +     /* 111 */ "IdxGT"            OpHelp("key=r[P3@P4]"),
 1.23434 +     /* 112 */ "IdxLT"            OpHelp("key=r[P3@P4]"),
 1.23435 +     /* 113 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
 1.23436 +     /* 114 */ "Destroy"          OpHelp(""),
 1.23437 +     /* 115 */ "Clear"            OpHelp(""),
 1.23438 +     /* 116 */ "CreateIndex"      OpHelp("r[P2]=root iDb=P1"),
 1.23439 +     /* 117 */ "CreateTable"      OpHelp("r[P2]=root iDb=P1"),
 1.23440 +     /* 118 */ "ParseSchema"      OpHelp(""),
 1.23441 +     /* 119 */ "LoadAnalysis"     OpHelp(""),
 1.23442 +     /* 120 */ "DropTable"        OpHelp(""),
 1.23443 +     /* 121 */ "DropIndex"        OpHelp(""),
 1.23444 +     /* 122 */ "DropTrigger"      OpHelp(""),
 1.23445 +     /* 123 */ "IntegrityCk"      OpHelp(""),
 1.23446 +     /* 124 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
 1.23447 +     /* 125 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
 1.23448 +     /* 126 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
 1.23449 +     /* 127 */ "Program"          OpHelp(""),
 1.23450 +     /* 128 */ "Param"            OpHelp(""),
 1.23451 +     /* 129 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
 1.23452 +     /* 130 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
 1.23453 +     /* 131 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
 1.23454 +     /* 132 */ "IfPos"            OpHelp("if r[P1]>0 goto P2"),
 1.23455 +     /* 133 */ "Real"             OpHelp("r[P2]=P4"),
 1.23456 +     /* 134 */ "IfNeg"            OpHelp("if r[P1]<0 goto P2"),
 1.23457 +     /* 135 */ "IfZero"           OpHelp("r[P1]+=P3, if r[P1]==0 goto P2"),
 1.23458 +     /* 136 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
 1.23459 +     /* 137 */ "IncrVacuum"       OpHelp(""),
 1.23460 +     /* 138 */ "Expire"           OpHelp(""),
 1.23461 +     /* 139 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
 1.23462 +     /* 140 */ "VBegin"           OpHelp(""),
 1.23463 +     /* 141 */ "VCreate"          OpHelp(""),
 1.23464 +     /* 142 */ "VDestroy"         OpHelp(""),
 1.23465 +     /* 143 */ "ToText"           OpHelp(""),
 1.23466 +     /* 144 */ "ToBlob"           OpHelp(""),
 1.23467 +     /* 145 */ "ToNumeric"        OpHelp(""),
 1.23468 +     /* 146 */ "ToInt"            OpHelp(""),
 1.23469 +     /* 147 */ "ToReal"           OpHelp(""),
 1.23470 +     /* 148 */ "VOpen"            OpHelp(""),
 1.23471 +     /* 149 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
 1.23472 +     /* 150 */ "VNext"            OpHelp(""),
 1.23473 +     /* 151 */ "VRename"          OpHelp(""),
 1.23474 +     /* 152 */ "Pagecount"        OpHelp(""),
 1.23475 +     /* 153 */ "MaxPgcnt"         OpHelp(""),
 1.23476 +     /* 154 */ "Init"             OpHelp("Start at P2"),
 1.23477 +     /* 155 */ "Noop"             OpHelp(""),
 1.23478 +     /* 156 */ "Explain"          OpHelp(""),
 1.23479 +  };
 1.23480 +  return azName[i];
 1.23481 +}
 1.23482 +#endif
 1.23483 +
 1.23484 +/************** End of opcodes.c *********************************************/
 1.23485 +/************** Begin file os_unix.c *****************************************/
 1.23486 +/*
 1.23487 +** 2004 May 22
 1.23488 +**
 1.23489 +** The author disclaims copyright to this source code.  In place of
 1.23490 +** a legal notice, here is a blessing:
 1.23491 +**
 1.23492 +**    May you do good and not evil.
 1.23493 +**    May you find forgiveness for yourself and forgive others.
 1.23494 +**    May you share freely, never taking more than you give.
 1.23495 +**
 1.23496 +******************************************************************************
 1.23497 +**
 1.23498 +** This file contains the VFS implementation for unix-like operating systems
 1.23499 +** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
 1.23500 +**
 1.23501 +** There are actually several different VFS implementations in this file.
 1.23502 +** The differences are in the way that file locking is done.  The default
 1.23503 +** implementation uses Posix Advisory Locks.  Alternative implementations
 1.23504 +** use flock(), dot-files, various proprietary locking schemas, or simply
 1.23505 +** skip locking all together.
 1.23506 +**
 1.23507 +** This source file is organized into divisions where the logic for various
 1.23508 +** subfunctions is contained within the appropriate division.  PLEASE
 1.23509 +** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
 1.23510 +** in the correct division and should be clearly labeled.
 1.23511 +**
 1.23512 +** The layout of divisions is as follows:
 1.23513 +**
 1.23514 +**   *  General-purpose declarations and utility functions.
 1.23515 +**   *  Unique file ID logic used by VxWorks.
 1.23516 +**   *  Various locking primitive implementations (all except proxy locking):
 1.23517 +**      + for Posix Advisory Locks
 1.23518 +**      + for no-op locks
 1.23519 +**      + for dot-file locks
 1.23520 +**      + for flock() locking
 1.23521 +**      + for named semaphore locks (VxWorks only)
 1.23522 +**      + for AFP filesystem locks (MacOSX only)
 1.23523 +**   *  sqlite3_file methods not associated with locking.
 1.23524 +**   *  Definitions of sqlite3_io_methods objects for all locking
 1.23525 +**      methods plus "finder" functions for each locking method.
 1.23526 +**   *  sqlite3_vfs method implementations.
 1.23527 +**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
 1.23528 +**   *  Definitions of sqlite3_vfs objects for all locking methods
 1.23529 +**      plus implementations of sqlite3_os_init() and sqlite3_os_end().
 1.23530 +*/
 1.23531 +#if SQLITE_OS_UNIX              /* This file is used on unix only */
 1.23532 +
 1.23533 +/*
 1.23534 +** There are various methods for file locking used for concurrency
 1.23535 +** control:
 1.23536 +**
 1.23537 +**   1. POSIX locking (the default),
 1.23538 +**   2. No locking,
 1.23539 +**   3. Dot-file locking,
 1.23540 +**   4. flock() locking,
 1.23541 +**   5. AFP locking (OSX only),
 1.23542 +**   6. Named POSIX semaphores (VXWorks only),
 1.23543 +**   7. proxy locking. (OSX only)
 1.23544 +**
 1.23545 +** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
 1.23546 +** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
 1.23547 +** selection of the appropriate locking style based on the filesystem
 1.23548 +** where the database is located.  
 1.23549 +*/
 1.23550 +#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
 1.23551 +#  if defined(__APPLE__)
 1.23552 +#    define SQLITE_ENABLE_LOCKING_STYLE 1
 1.23553 +#  else
 1.23554 +#    define SQLITE_ENABLE_LOCKING_STYLE 0
 1.23555 +#  endif
 1.23556 +#endif
 1.23557 +
 1.23558 +/*
 1.23559 +** Define the OS_VXWORKS pre-processor macro to 1 if building on 
 1.23560 +** vxworks, or 0 otherwise.
 1.23561 +*/
 1.23562 +#ifndef OS_VXWORKS
 1.23563 +#  if defined(__RTP__) || defined(_WRS_KERNEL)
 1.23564 +#    define OS_VXWORKS 1
 1.23565 +#  else
 1.23566 +#    define OS_VXWORKS 0
 1.23567 +#  endif
 1.23568 +#endif
 1.23569 +
 1.23570 +/*
 1.23571 +** standard include files.
 1.23572 +*/
 1.23573 +#include <sys/types.h>
 1.23574 +#include <sys/stat.h>
 1.23575 +#include <fcntl.h>
 1.23576 +#include <unistd.h>
 1.23577 +/* #include <time.h> */
 1.23578 +#include <sys/time.h>
 1.23579 +#include <errno.h>
 1.23580 +#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
 1.23581 +#include <sys/mman.h>
 1.23582 +#endif
 1.23583 +
 1.23584 +
 1.23585 +#if SQLITE_ENABLE_LOCKING_STYLE
 1.23586 +# include <sys/ioctl.h>
 1.23587 +# if OS_VXWORKS
 1.23588 +#  include <semaphore.h>
 1.23589 +#  include <limits.h>
 1.23590 +# else
 1.23591 +#  include <sys/file.h>
 1.23592 +#  include <sys/param.h>
 1.23593 +# endif
 1.23594 +#endif /* SQLITE_ENABLE_LOCKING_STYLE */
 1.23595 +
 1.23596 +#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
 1.23597 +# include <sys/mount.h>
 1.23598 +#endif
 1.23599 +
 1.23600 +#ifdef HAVE_UTIME
 1.23601 +# include <utime.h>
 1.23602 +#endif
 1.23603 +
 1.23604 +/*
 1.23605 +** Allowed values of unixFile.fsFlags
 1.23606 +*/
 1.23607 +#define SQLITE_FSFLAGS_IS_MSDOS     0x1
 1.23608 +
 1.23609 +/*
 1.23610 +** If we are to be thread-safe, include the pthreads header and define
 1.23611 +** the SQLITE_UNIX_THREADS macro.
 1.23612 +*/
 1.23613 +#if SQLITE_THREADSAFE
 1.23614 +/* # include <pthread.h> */
 1.23615 +# define SQLITE_UNIX_THREADS 1
 1.23616 +#endif
 1.23617 +
 1.23618 +/*
 1.23619 +** Default permissions when creating a new file
 1.23620 +*/
 1.23621 +#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
 1.23622 +# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
 1.23623 +#endif
 1.23624 +
 1.23625 +/*
 1.23626 +** Default permissions when creating auto proxy dir
 1.23627 +*/
 1.23628 +#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
 1.23629 +# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
 1.23630 +#endif
 1.23631 +
 1.23632 +/*
 1.23633 +** Maximum supported path-length.
 1.23634 +*/
 1.23635 +#define MAX_PATHNAME 512
 1.23636 +
 1.23637 +/*
 1.23638 +** Only set the lastErrno if the error code is a real error and not 
 1.23639 +** a normal expected return code of SQLITE_BUSY or SQLITE_OK
 1.23640 +*/
 1.23641 +#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
 1.23642 +
 1.23643 +/* Forward references */
 1.23644 +typedef struct unixShm unixShm;               /* Connection shared memory */
 1.23645 +typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
 1.23646 +typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
 1.23647 +typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
 1.23648 +
 1.23649 +/*
 1.23650 +** Sometimes, after a file handle is closed by SQLite, the file descriptor
 1.23651 +** cannot be closed immediately. In these cases, instances of the following
 1.23652 +** structure are used to store the file descriptor while waiting for an
 1.23653 +** opportunity to either close or reuse it.
 1.23654 +*/
 1.23655 +struct UnixUnusedFd {
 1.23656 +  int fd;                   /* File descriptor to close */
 1.23657 +  int flags;                /* Flags this file descriptor was opened with */
 1.23658 +  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
 1.23659 +};
 1.23660 +
 1.23661 +/*
 1.23662 +** The unixFile structure is subclass of sqlite3_file specific to the unix
 1.23663 +** VFS implementations.
 1.23664 +*/
 1.23665 +typedef struct unixFile unixFile;
 1.23666 +struct unixFile {
 1.23667 +  sqlite3_io_methods const *pMethod;  /* Always the first entry */
 1.23668 +  sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
 1.23669 +  unixInodeInfo *pInode;              /* Info about locks on this inode */
 1.23670 +  int h;                              /* The file descriptor */
 1.23671 +  unsigned char eFileLock;            /* The type of lock held on this fd */
 1.23672 +  unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
 1.23673 +  int lastErrno;                      /* The unix errno from last I/O error */
 1.23674 +  void *lockingContext;               /* Locking style specific state */
 1.23675 +  UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
 1.23676 +  const char *zPath;                  /* Name of the file */
 1.23677 +  unixShm *pShm;                      /* Shared memory segment information */
 1.23678 +  int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
 1.23679 +#if SQLITE_MAX_MMAP_SIZE>0
 1.23680 +  int nFetchOut;                      /* Number of outstanding xFetch refs */
 1.23681 +  sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */
 1.23682 +  sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */
 1.23683 +  sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */
 1.23684 +  void *pMapRegion;                   /* Memory mapped region */
 1.23685 +#endif
 1.23686 +#ifdef __QNXNTO__
 1.23687 +  int sectorSize;                     /* Device sector size */
 1.23688 +  int deviceCharacteristics;          /* Precomputed device characteristics */
 1.23689 +#endif
 1.23690 +#if SQLITE_ENABLE_LOCKING_STYLE
 1.23691 +  int openFlags;                      /* The flags specified at open() */
 1.23692 +#endif
 1.23693 +#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
 1.23694 +  unsigned fsFlags;                   /* cached details from statfs() */
 1.23695 +#endif
 1.23696 +#if OS_VXWORKS
 1.23697 +  struct vxworksFileId *pId;          /* Unique file ID */
 1.23698 +#endif
 1.23699 +#ifdef SQLITE_DEBUG
 1.23700 +  /* The next group of variables are used to track whether or not the
 1.23701 +  ** transaction counter in bytes 24-27 of database files are updated
 1.23702 +  ** whenever any part of the database changes.  An assertion fault will
 1.23703 +  ** occur if a file is updated without also updating the transaction
 1.23704 +  ** counter.  This test is made to avoid new problems similar to the
 1.23705 +  ** one described by ticket #3584. 
 1.23706 +  */
 1.23707 +  unsigned char transCntrChng;   /* True if the transaction counter changed */
 1.23708 +  unsigned char dbUpdate;        /* True if any part of database file changed */
 1.23709 +  unsigned char inNormalWrite;   /* True if in a normal write operation */
 1.23710 +
 1.23711 +#endif
 1.23712 +
 1.23713 +#ifdef SQLITE_TEST
 1.23714 +  /* In test mode, increase the size of this structure a bit so that 
 1.23715 +  ** it is larger than the struct CrashFile defined in test6.c.
 1.23716 +  */
 1.23717 +  char aPadding[32];
 1.23718 +#endif
 1.23719 +};
 1.23720 +
 1.23721 +/* This variable holds the process id (pid) from when the xRandomness()
 1.23722 +** method was called.  If xOpen() is called from a different process id,
 1.23723 +** indicating that a fork() has occurred, the PRNG will be reset.
 1.23724 +*/
 1.23725 +static int randomnessPid = 0;
 1.23726 +
 1.23727 +/*
 1.23728 +** Allowed values for the unixFile.ctrlFlags bitmask:
 1.23729 +*/
 1.23730 +#define UNIXFILE_EXCL        0x01     /* Connections from one process only */
 1.23731 +#define UNIXFILE_RDONLY      0x02     /* Connection is read only */
 1.23732 +#define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
 1.23733 +#ifndef SQLITE_DISABLE_DIRSYNC
 1.23734 +# define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
 1.23735 +#else
 1.23736 +# define UNIXFILE_DIRSYNC    0x00
 1.23737 +#endif
 1.23738 +#define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
 1.23739 +#define UNIXFILE_DELETE      0x20     /* Delete on close */
 1.23740 +#define UNIXFILE_URI         0x40     /* Filename might have query parameters */
 1.23741 +#define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
 1.23742 +#define UNIXFILE_WARNED    0x0100     /* verifyDbFile() warnings have been issued */
 1.23743 +
 1.23744 +/*
 1.23745 +** Include code that is common to all os_*.c files
 1.23746 +*/
 1.23747 +/************** Include os_common.h in the middle of os_unix.c ***************/
 1.23748 +/************** Begin file os_common.h ***************************************/
 1.23749 +/*
 1.23750 +** 2004 May 22
 1.23751 +**
 1.23752 +** The author disclaims copyright to this source code.  In place of
 1.23753 +** a legal notice, here is a blessing:
 1.23754 +**
 1.23755 +**    May you do good and not evil.
 1.23756 +**    May you find forgiveness for yourself and forgive others.
 1.23757 +**    May you share freely, never taking more than you give.
 1.23758 +**
 1.23759 +******************************************************************************
 1.23760 +**
 1.23761 +** This file contains macros and a little bit of code that is common to
 1.23762 +** all of the platform-specific files (os_*.c) and is #included into those
 1.23763 +** files.
 1.23764 +**
 1.23765 +** This file should be #included by the os_*.c files only.  It is not a
 1.23766 +** general purpose header file.
 1.23767 +*/
 1.23768 +#ifndef _OS_COMMON_H_
 1.23769 +#define _OS_COMMON_H_
 1.23770 +
 1.23771 +/*
 1.23772 +** At least two bugs have slipped in because we changed the MEMORY_DEBUG
 1.23773 +** macro to SQLITE_DEBUG and some older makefiles have not yet made the
 1.23774 +** switch.  The following code should catch this problem at compile-time.
 1.23775 +*/
 1.23776 +#ifdef MEMORY_DEBUG
 1.23777 +# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
 1.23778 +#endif
 1.23779 +
 1.23780 +#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
 1.23781 +# ifndef SQLITE_DEBUG_OS_TRACE
 1.23782 +#   define SQLITE_DEBUG_OS_TRACE 0
 1.23783 +# endif
 1.23784 +  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
 1.23785 +# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
 1.23786 +#else
 1.23787 +# define OSTRACE(X)
 1.23788 +#endif
 1.23789 +
 1.23790 +/*
 1.23791 +** Macros for performance tracing.  Normally turned off.  Only works
 1.23792 +** on i486 hardware.
 1.23793 +*/
 1.23794 +#ifdef SQLITE_PERFORMANCE_TRACE
 1.23795 +
 1.23796 +/* 
 1.23797 +** hwtime.h contains inline assembler code for implementing 
 1.23798 +** high-performance timing routines.
 1.23799 +*/
 1.23800 +/************** Include hwtime.h in the middle of os_common.h ****************/
 1.23801 +/************** Begin file hwtime.h ******************************************/
 1.23802 +/*
 1.23803 +** 2008 May 27
 1.23804 +**
 1.23805 +** The author disclaims copyright to this source code.  In place of
 1.23806 +** a legal notice, here is a blessing:
 1.23807 +**
 1.23808 +**    May you do good and not evil.
 1.23809 +**    May you find forgiveness for yourself and forgive others.
 1.23810 +**    May you share freely, never taking more than you give.
 1.23811 +**
 1.23812 +******************************************************************************
 1.23813 +**
 1.23814 +** This file contains inline asm code for retrieving "high-performance"
 1.23815 +** counters for x86 class CPUs.
 1.23816 +*/
 1.23817 +#ifndef _HWTIME_H_
 1.23818 +#define _HWTIME_H_
 1.23819 +
 1.23820 +/*
 1.23821 +** The following routine only works on pentium-class (or newer) processors.
 1.23822 +** It uses the RDTSC opcode to read the cycle count value out of the
 1.23823 +** processor and returns that value.  This can be used for high-res
 1.23824 +** profiling.
 1.23825 +*/
 1.23826 +#if (defined(__GNUC__) || defined(_MSC_VER)) && \
 1.23827 +      (defined(i386) || defined(__i386__) || defined(_M_IX86))
 1.23828 +
 1.23829 +  #if defined(__GNUC__)
 1.23830 +
 1.23831 +  __inline__ sqlite_uint64 sqlite3Hwtime(void){
 1.23832 +     unsigned int lo, hi;
 1.23833 +     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
 1.23834 +     return (sqlite_uint64)hi << 32 | lo;
 1.23835 +  }
 1.23836 +
 1.23837 +  #elif defined(_MSC_VER)
 1.23838 +
 1.23839 +  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
 1.23840 +     __asm {
 1.23841 +        rdtsc
 1.23842 +        ret       ; return value at EDX:EAX
 1.23843 +     }
 1.23844 +  }
 1.23845 +
 1.23846 +  #endif
 1.23847 +
 1.23848 +#elif (defined(__GNUC__) && defined(__x86_64__))
 1.23849 +
 1.23850 +  __inline__ sqlite_uint64 sqlite3Hwtime(void){
 1.23851 +      unsigned long val;
 1.23852 +      __asm__ __volatile__ ("rdtsc" : "=A" (val));
 1.23853 +      return val;
 1.23854 +  }
 1.23855 + 
 1.23856 +#elif (defined(__GNUC__) && defined(__ppc__))
 1.23857 +
 1.23858 +  __inline__ sqlite_uint64 sqlite3Hwtime(void){
 1.23859 +      unsigned long long retval;
 1.23860 +      unsigned long junk;
 1.23861 +      __asm__ __volatile__ ("\n\
 1.23862 +          1:      mftbu   %1\n\
 1.23863 +                  mftb    %L0\n\
 1.23864 +                  mftbu   %0\n\
 1.23865 +                  cmpw    %0,%1\n\
 1.23866 +                  bne     1b"
 1.23867 +                  : "=r" (retval), "=r" (junk));
 1.23868 +      return retval;
 1.23869 +  }
 1.23870 +
 1.23871 +#else
 1.23872 +
 1.23873 +  #error Need implementation of sqlite3Hwtime() for your platform.
 1.23874 +
 1.23875 +  /*
 1.23876 +  ** To compile without implementing sqlite3Hwtime() for your platform,
 1.23877 +  ** you can remove the above #error and use the following
 1.23878 +  ** stub function.  You will lose timing support for many
 1.23879 +  ** of the debugging and testing utilities, but it should at
 1.23880 +  ** least compile and run.
 1.23881 +  */
 1.23882 +SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
 1.23883 +
 1.23884 +#endif
 1.23885 +
 1.23886 +#endif /* !defined(_HWTIME_H_) */
 1.23887 +
 1.23888 +/************** End of hwtime.h **********************************************/
 1.23889 +/************** Continuing where we left off in os_common.h ******************/
 1.23890 +
 1.23891 +static sqlite_uint64 g_start;
 1.23892 +static sqlite_uint64 g_elapsed;
 1.23893 +#define TIMER_START       g_start=sqlite3Hwtime()
 1.23894 +#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
 1.23895 +#define TIMER_ELAPSED     g_elapsed
 1.23896 +#else
 1.23897 +#define TIMER_START
 1.23898 +#define TIMER_END
 1.23899 +#define TIMER_ELAPSED     ((sqlite_uint64)0)
 1.23900 +#endif
 1.23901 +
 1.23902 +/*
 1.23903 +** If we compile with the SQLITE_TEST macro set, then the following block
 1.23904 +** of code will give us the ability to simulate a disk I/O error.  This
 1.23905 +** is used for testing the I/O recovery logic.
 1.23906 +*/
 1.23907 +#ifdef SQLITE_TEST
 1.23908 +SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
 1.23909 +SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
 1.23910 +SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
 1.23911 +SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
 1.23912 +SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
 1.23913 +SQLITE_API int sqlite3_diskfull_pending = 0;
 1.23914 +SQLITE_API int sqlite3_diskfull = 0;
 1.23915 +#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
 1.23916 +#define SimulateIOError(CODE)  \
 1.23917 +  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
 1.23918 +       || sqlite3_io_error_pending-- == 1 )  \
 1.23919 +              { local_ioerr(); CODE; }
 1.23920 +static void local_ioerr(){
 1.23921 +  IOTRACE(("IOERR\n"));
 1.23922 +  sqlite3_io_error_hit++;
 1.23923 +  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
 1.23924 +}
 1.23925 +#define SimulateDiskfullError(CODE) \
 1.23926 +   if( sqlite3_diskfull_pending ){ \
 1.23927 +     if( sqlite3_diskfull_pending == 1 ){ \
 1.23928 +       local_ioerr(); \
 1.23929 +       sqlite3_diskfull = 1; \
 1.23930 +       sqlite3_io_error_hit = 1; \
 1.23931 +       CODE; \
 1.23932 +     }else{ \
 1.23933 +       sqlite3_diskfull_pending--; \
 1.23934 +     } \
 1.23935 +   }
 1.23936 +#else
 1.23937 +#define SimulateIOErrorBenign(X)
 1.23938 +#define SimulateIOError(A)
 1.23939 +#define SimulateDiskfullError(A)
 1.23940 +#endif
 1.23941 +
 1.23942 +/*
 1.23943 +** When testing, keep a count of the number of open files.
 1.23944 +*/
 1.23945 +#ifdef SQLITE_TEST
 1.23946 +SQLITE_API int sqlite3_open_file_count = 0;
 1.23947 +#define OpenCounter(X)  sqlite3_open_file_count+=(X)
 1.23948 +#else
 1.23949 +#define OpenCounter(X)
 1.23950 +#endif
 1.23951 +
 1.23952 +#endif /* !defined(_OS_COMMON_H_) */
 1.23953 +
 1.23954 +/************** End of os_common.h *******************************************/
 1.23955 +/************** Continuing where we left off in os_unix.c ********************/
 1.23956 +
 1.23957 +/*
 1.23958 +** Define various macros that are missing from some systems.
 1.23959 +*/
 1.23960 +#ifndef O_LARGEFILE
 1.23961 +# define O_LARGEFILE 0
 1.23962 +#endif
 1.23963 +#ifdef SQLITE_DISABLE_LFS
 1.23964 +# undef O_LARGEFILE
 1.23965 +# define O_LARGEFILE 0
 1.23966 +#endif
 1.23967 +#ifndef O_NOFOLLOW
 1.23968 +# define O_NOFOLLOW 0
 1.23969 +#endif
 1.23970 +#ifndef O_BINARY
 1.23971 +# define O_BINARY 0
 1.23972 +#endif
 1.23973 +
 1.23974 +/*
 1.23975 +** The threadid macro resolves to the thread-id or to 0.  Used for
 1.23976 +** testing and debugging only.
 1.23977 +*/
 1.23978 +#if SQLITE_THREADSAFE
 1.23979 +#define threadid pthread_self()
 1.23980 +#else
 1.23981 +#define threadid 0
 1.23982 +#endif
 1.23983 +
 1.23984 +/*
 1.23985 +** HAVE_MREMAP defaults to true on Linux and false everywhere else.
 1.23986 +*/
 1.23987 +#if !defined(HAVE_MREMAP)
 1.23988 +# if defined(__linux__) && defined(_GNU_SOURCE)
 1.23989 +#  define HAVE_MREMAP 1
 1.23990 +# else
 1.23991 +#  define HAVE_MREMAP 0
 1.23992 +# endif
 1.23993 +#endif
 1.23994 +
 1.23995 +/*
 1.23996 +** Different Unix systems declare open() in different ways.  Same use
 1.23997 +** open(const char*,int,mode_t).  Others use open(const char*,int,...).
 1.23998 +** The difference is important when using a pointer to the function.
 1.23999 +**
 1.24000 +** The safest way to deal with the problem is to always use this wrapper
 1.24001 +** which always has the same well-defined interface.
 1.24002 +*/
 1.24003 +static int posixOpen(const char *zFile, int flags, int mode){
 1.24004 +  return open(zFile, flags, mode);
 1.24005 +}
 1.24006 +
 1.24007 +/*
 1.24008 +** On some systems, calls to fchown() will trigger a message in a security
 1.24009 +** log if they come from non-root processes.  So avoid calling fchown() if
 1.24010 +** we are not running as root.
 1.24011 +*/
 1.24012 +static int posixFchown(int fd, uid_t uid, gid_t gid){
 1.24013 +  return geteuid() ? 0 : fchown(fd,uid,gid);
 1.24014 +}
 1.24015 +
 1.24016 +/* Forward reference */
 1.24017 +static int openDirectory(const char*, int*);
 1.24018 +
 1.24019 +/*
 1.24020 +** Many system calls are accessed through pointer-to-functions so that
 1.24021 +** they may be overridden at runtime to facilitate fault injection during
 1.24022 +** testing and sandboxing.  The following array holds the names and pointers
 1.24023 +** to all overrideable system calls.
 1.24024 +*/
 1.24025 +static struct unix_syscall {
 1.24026 +  const char *zName;            /* Name of the system call */
 1.24027 +  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
 1.24028 +  sqlite3_syscall_ptr pDefault; /* Default value */
 1.24029 +} aSyscall[] = {
 1.24030 +  { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
 1.24031 +#define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
 1.24032 +
 1.24033 +  { "close",        (sqlite3_syscall_ptr)close,      0  },
 1.24034 +#define osClose     ((int(*)(int))aSyscall[1].pCurrent)
 1.24035 +
 1.24036 +  { "access",       (sqlite3_syscall_ptr)access,     0  },
 1.24037 +#define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
 1.24038 +
 1.24039 +  { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
 1.24040 +#define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
 1.24041 +
 1.24042 +  { "stat",         (sqlite3_syscall_ptr)stat,       0  },
 1.24043 +#define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
 1.24044 +
 1.24045 +/*
 1.24046 +** The DJGPP compiler environment looks mostly like Unix, but it
 1.24047 +** lacks the fcntl() system call.  So redefine fcntl() to be something
 1.24048 +** that always succeeds.  This means that locking does not occur under
 1.24049 +** DJGPP.  But it is DOS - what did you expect?
 1.24050 +*/
 1.24051 +#ifdef __DJGPP__
 1.24052 +  { "fstat",        0,                 0  },
 1.24053 +#define osFstat(a,b,c)    0
 1.24054 +#else     
 1.24055 +  { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
 1.24056 +#define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
 1.24057 +#endif
 1.24058 +
 1.24059 +  { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
 1.24060 +#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
 1.24061 +
 1.24062 +  { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
 1.24063 +#define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
 1.24064 +
 1.24065 +  { "read",         (sqlite3_syscall_ptr)read,       0  },
 1.24066 +#define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
 1.24067 +
 1.24068 +#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
 1.24069 +  { "pread",        (sqlite3_syscall_ptr)pread,      0  },
 1.24070 +#else
 1.24071 +  { "pread",        (sqlite3_syscall_ptr)0,          0  },
 1.24072 +#endif
 1.24073 +#define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
 1.24074 +
 1.24075 +#if defined(USE_PREAD64)
 1.24076 +  { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
 1.24077 +#else
 1.24078 +  { "pread64",      (sqlite3_syscall_ptr)0,          0  },
 1.24079 +#endif
 1.24080 +#define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
 1.24081 +
 1.24082 +  { "write",        (sqlite3_syscall_ptr)write,      0  },
 1.24083 +#define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
 1.24084 +
 1.24085 +#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
 1.24086 +  { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
 1.24087 +#else
 1.24088 +  { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
 1.24089 +#endif
 1.24090 +#define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
 1.24091 +                    aSyscall[12].pCurrent)
 1.24092 +
 1.24093 +#if defined(USE_PREAD64)
 1.24094 +  { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
 1.24095 +#else
 1.24096 +  { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
 1.24097 +#endif
 1.24098 +#define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
 1.24099 +                    aSyscall[13].pCurrent)
 1.24100 +
 1.24101 +  { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
 1.24102 +#define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
 1.24103 +
 1.24104 +#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
 1.24105 +  { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
 1.24106 +#else
 1.24107 +  { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
 1.24108 +#endif
 1.24109 +#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
 1.24110 +
 1.24111 +  { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
 1.24112 +#define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
 1.24113 +
 1.24114 +  { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
 1.24115 +#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
 1.24116 +
 1.24117 +  { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
 1.24118 +#define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
 1.24119 +
 1.24120 +  { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
 1.24121 +#define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
 1.24122 +
 1.24123 +  { "fchown",       (sqlite3_syscall_ptr)posixFchown,     0 },
 1.24124 +#define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
 1.24125 +
 1.24126 +#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
 1.24127 +  { "mmap",       (sqlite3_syscall_ptr)mmap,     0 },
 1.24128 +#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
 1.24129 +
 1.24130 +  { "munmap",       (sqlite3_syscall_ptr)munmap,          0 },
 1.24131 +#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
 1.24132 +
 1.24133 +#if HAVE_MREMAP
 1.24134 +  { "mremap",       (sqlite3_syscall_ptr)mremap,          0 },
 1.24135 +#else
 1.24136 +  { "mremap",       (sqlite3_syscall_ptr)0,               0 },
 1.24137 +#endif
 1.24138 +#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
 1.24139 +#endif
 1.24140 +
 1.24141 +}; /* End of the overrideable system calls */
 1.24142 +
 1.24143 +/*
 1.24144 +** This is the xSetSystemCall() method of sqlite3_vfs for all of the
 1.24145 +** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
 1.24146 +** system call pointer, or SQLITE_NOTFOUND if there is no configurable
 1.24147 +** system call named zName.
 1.24148 +*/
 1.24149 +static int unixSetSystemCall(
 1.24150 +  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
 1.24151 +  const char *zName,            /* Name of system call to override */
 1.24152 +  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
 1.24153 +){
 1.24154 +  unsigned int i;
 1.24155 +  int rc = SQLITE_NOTFOUND;
 1.24156 +
 1.24157 +  UNUSED_PARAMETER(pNotUsed);
 1.24158 +  if( zName==0 ){
 1.24159 +    /* If no zName is given, restore all system calls to their default
 1.24160 +    ** settings and return NULL
 1.24161 +    */
 1.24162 +    rc = SQLITE_OK;
 1.24163 +    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
 1.24164 +      if( aSyscall[i].pDefault ){
 1.24165 +        aSyscall[i].pCurrent = aSyscall[i].pDefault;
 1.24166 +      }
 1.24167 +    }
 1.24168 +  }else{
 1.24169 +    /* If zName is specified, operate on only the one system call
 1.24170 +    ** specified.
 1.24171 +    */
 1.24172 +    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
 1.24173 +      if( strcmp(zName, aSyscall[i].zName)==0 ){
 1.24174 +        if( aSyscall[i].pDefault==0 ){
 1.24175 +          aSyscall[i].pDefault = aSyscall[i].pCurrent;
 1.24176 +        }
 1.24177 +        rc = SQLITE_OK;
 1.24178 +        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
 1.24179 +        aSyscall[i].pCurrent = pNewFunc;
 1.24180 +        break;
 1.24181 +      }
 1.24182 +    }
 1.24183 +  }
 1.24184 +  return rc;
 1.24185 +}
 1.24186 +
 1.24187 +/*
 1.24188 +** Return the value of a system call.  Return NULL if zName is not a
 1.24189 +** recognized system call name.  NULL is also returned if the system call
 1.24190 +** is currently undefined.
 1.24191 +*/
 1.24192 +static sqlite3_syscall_ptr unixGetSystemCall(
 1.24193 +  sqlite3_vfs *pNotUsed,
 1.24194 +  const char *zName
 1.24195 +){
 1.24196 +  unsigned int i;
 1.24197 +
 1.24198 +  UNUSED_PARAMETER(pNotUsed);
 1.24199 +  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
 1.24200 +    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
 1.24201 +  }
 1.24202 +  return 0;
 1.24203 +}
 1.24204 +
 1.24205 +/*
 1.24206 +** Return the name of the first system call after zName.  If zName==NULL
 1.24207 +** then return the name of the first system call.  Return NULL if zName
 1.24208 +** is the last system call or if zName is not the name of a valid
 1.24209 +** system call.
 1.24210 +*/
 1.24211 +static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
 1.24212 +  int i = -1;
 1.24213 +
 1.24214 +  UNUSED_PARAMETER(p);
 1.24215 +  if( zName ){
 1.24216 +    for(i=0; i<ArraySize(aSyscall)-1; i++){
 1.24217 +      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
 1.24218 +    }
 1.24219 +  }
 1.24220 +  for(i++; i<ArraySize(aSyscall); i++){
 1.24221 +    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
 1.24222 +  }
 1.24223 +  return 0;
 1.24224 +}
 1.24225 +
 1.24226 +/*
 1.24227 +** Do not accept any file descriptor less than this value, in order to avoid
 1.24228 +** opening database file using file descriptors that are commonly used for 
 1.24229 +** standard input, output, and error.
 1.24230 +*/
 1.24231 +#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
 1.24232 +# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
 1.24233 +#endif
 1.24234 +
 1.24235 +/*
 1.24236 +** Invoke open().  Do so multiple times, until it either succeeds or
 1.24237 +** fails for some reason other than EINTR.
 1.24238 +**
 1.24239 +** If the file creation mode "m" is 0 then set it to the default for
 1.24240 +** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
 1.24241 +** 0644) as modified by the system umask.  If m is not 0, then
 1.24242 +** make the file creation mode be exactly m ignoring the umask.
 1.24243 +**
 1.24244 +** The m parameter will be non-zero only when creating -wal, -journal,
 1.24245 +** and -shm files.  We want those files to have *exactly* the same
 1.24246 +** permissions as their original database, unadulterated by the umask.
 1.24247 +** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
 1.24248 +** transaction crashes and leaves behind hot journals, then any
 1.24249 +** process that is able to write to the database will also be able to
 1.24250 +** recover the hot journals.
 1.24251 +*/
 1.24252 +static int robust_open(const char *z, int f, mode_t m){
 1.24253 +  int fd;
 1.24254 +  mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
 1.24255 +  while(1){
 1.24256 +#if defined(O_CLOEXEC)
 1.24257 +    fd = osOpen(z,f|O_CLOEXEC,m2);
 1.24258 +#else
 1.24259 +    fd = osOpen(z,f,m2);
 1.24260 +#endif
 1.24261 +    if( fd<0 ){
 1.24262 +      if( errno==EINTR ) continue;
 1.24263 +      break;
 1.24264 +    }
 1.24265 +    if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
 1.24266 +    osClose(fd);
 1.24267 +    sqlite3_log(SQLITE_WARNING, 
 1.24268 +                "attempt to open \"%s\" as file descriptor %d", z, fd);
 1.24269 +    fd = -1;
 1.24270 +    if( osOpen("/dev/null", f, m)<0 ) break;
 1.24271 +  }
 1.24272 +  if( fd>=0 ){
 1.24273 +    if( m!=0 ){
 1.24274 +      struct stat statbuf;
 1.24275 +      if( osFstat(fd, &statbuf)==0 
 1.24276 +       && statbuf.st_size==0
 1.24277 +       && (statbuf.st_mode&0777)!=m 
 1.24278 +      ){
 1.24279 +        osFchmod(fd, m);
 1.24280 +      }
 1.24281 +    }
 1.24282 +#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
 1.24283 +    osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
 1.24284 +#endif
 1.24285 +  }
 1.24286 +  return fd;
 1.24287 +}
 1.24288 +
 1.24289 +/*
 1.24290 +** Helper functions to obtain and relinquish the global mutex. The
 1.24291 +** global mutex is used to protect the unixInodeInfo and
 1.24292 +** vxworksFileId objects used by this file, all of which may be 
 1.24293 +** shared by multiple threads.
 1.24294 +**
 1.24295 +** Function unixMutexHeld() is used to assert() that the global mutex 
 1.24296 +** is held when required. This function is only used as part of assert() 
 1.24297 +** statements. e.g.
 1.24298 +**
 1.24299 +**   unixEnterMutex()
 1.24300 +**     assert( unixMutexHeld() );
 1.24301 +**   unixEnterLeave()
 1.24302 +*/
 1.24303 +static void unixEnterMutex(void){
 1.24304 +  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
 1.24305 +}
 1.24306 +static void unixLeaveMutex(void){
 1.24307 +  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
 1.24308 +}
 1.24309 +#ifdef SQLITE_DEBUG
 1.24310 +static int unixMutexHeld(void) {
 1.24311 +  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
 1.24312 +}
 1.24313 +#endif
 1.24314 +
 1.24315 +
 1.24316 +#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
 1.24317 +/*
 1.24318 +** Helper function for printing out trace information from debugging
 1.24319 +** binaries. This returns the string represetation of the supplied
 1.24320 +** integer lock-type.
 1.24321 +*/
 1.24322 +static const char *azFileLock(int eFileLock){
 1.24323 +  switch( eFileLock ){
 1.24324 +    case NO_LOCK: return "NONE";
 1.24325 +    case SHARED_LOCK: return "SHARED";
 1.24326 +    case RESERVED_LOCK: return "RESERVED";
 1.24327 +    case PENDING_LOCK: return "PENDING";
 1.24328 +    case EXCLUSIVE_LOCK: return "EXCLUSIVE";
 1.24329 +  }
 1.24330 +  return "ERROR";
 1.24331 +}
 1.24332 +#endif
 1.24333 +
 1.24334 +#ifdef SQLITE_LOCK_TRACE
 1.24335 +/*
 1.24336 +** Print out information about all locking operations.
 1.24337 +**
 1.24338 +** This routine is used for troubleshooting locks on multithreaded
 1.24339 +** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
 1.24340 +** command-line option on the compiler.  This code is normally
 1.24341 +** turned off.
 1.24342 +*/
 1.24343 +static int lockTrace(int fd, int op, struct flock *p){
 1.24344 +  char *zOpName, *zType;
 1.24345 +  int s;
 1.24346 +  int savedErrno;
 1.24347 +  if( op==F_GETLK ){
 1.24348 +    zOpName = "GETLK";
 1.24349 +  }else if( op==F_SETLK ){
 1.24350 +    zOpName = "SETLK";
 1.24351 +  }else{
 1.24352 +    s = osFcntl(fd, op, p);
 1.24353 +    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
 1.24354 +    return s;
 1.24355 +  }
 1.24356 +  if( p->l_type==F_RDLCK ){
 1.24357 +    zType = "RDLCK";
 1.24358 +  }else if( p->l_type==F_WRLCK ){
 1.24359 +    zType = "WRLCK";
 1.24360 +  }else if( p->l_type==F_UNLCK ){
 1.24361 +    zType = "UNLCK";
 1.24362 +  }else{
 1.24363 +    assert( 0 );
 1.24364 +  }
 1.24365 +  assert( p->l_whence==SEEK_SET );
 1.24366 +  s = osFcntl(fd, op, p);
 1.24367 +  savedErrno = errno;
 1.24368 +  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
 1.24369 +     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
 1.24370 +     (int)p->l_pid, s);
 1.24371 +  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
 1.24372 +    struct flock l2;
 1.24373 +    l2 = *p;
 1.24374 +    osFcntl(fd, F_GETLK, &l2);
 1.24375 +    if( l2.l_type==F_RDLCK ){
 1.24376 +      zType = "RDLCK";
 1.24377 +    }else if( l2.l_type==F_WRLCK ){
 1.24378 +      zType = "WRLCK";
 1.24379 +    }else if( l2.l_type==F_UNLCK ){
 1.24380 +      zType = "UNLCK";
 1.24381 +    }else{
 1.24382 +      assert( 0 );
 1.24383 +    }
 1.24384 +    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
 1.24385 +       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
 1.24386 +  }
 1.24387 +  errno = savedErrno;
 1.24388 +  return s;
 1.24389 +}
 1.24390 +#undef osFcntl
 1.24391 +#define osFcntl lockTrace
 1.24392 +#endif /* SQLITE_LOCK_TRACE */
 1.24393 +
 1.24394 +/*
 1.24395 +** Retry ftruncate() calls that fail due to EINTR
 1.24396 +*/
 1.24397 +static int robust_ftruncate(int h, sqlite3_int64 sz){
 1.24398 +  int rc;
 1.24399 +  do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
 1.24400 +  return rc;
 1.24401 +}
 1.24402 +
 1.24403 +/*
 1.24404 +** This routine translates a standard POSIX errno code into something
 1.24405 +** useful to the clients of the sqlite3 functions.  Specifically, it is
 1.24406 +** intended to translate a variety of "try again" errors into SQLITE_BUSY
 1.24407 +** and a variety of "please close the file descriptor NOW" errors into 
 1.24408 +** SQLITE_IOERR
 1.24409 +** 
 1.24410 +** Errors during initialization of locks, or file system support for locks,
 1.24411 +** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
 1.24412 +*/
 1.24413 +static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
 1.24414 +  switch (posixError) {
 1.24415 +#if 0
 1.24416 +  /* At one point this code was not commented out. In theory, this branch
 1.24417 +  ** should never be hit, as this function should only be called after
 1.24418 +  ** a locking-related function (i.e. fcntl()) has returned non-zero with
 1.24419 +  ** the value of errno as the first argument. Since a system call has failed,
 1.24420 +  ** errno should be non-zero.
 1.24421 +  **
 1.24422 +  ** Despite this, if errno really is zero, we still don't want to return
 1.24423 +  ** SQLITE_OK. The system call failed, and *some* SQLite error should be
 1.24424 +  ** propagated back to the caller. Commenting this branch out means errno==0
 1.24425 +  ** will be handled by the "default:" case below.
 1.24426 +  */
 1.24427 +  case 0: 
 1.24428 +    return SQLITE_OK;
 1.24429 +#endif
 1.24430 +
 1.24431 +  case EAGAIN:
 1.24432 +  case ETIMEDOUT:
 1.24433 +  case EBUSY:
 1.24434 +  case EINTR:
 1.24435 +  case ENOLCK:  
 1.24436 +    /* random NFS retry error, unless during file system support 
 1.24437 +     * introspection, in which it actually means what it says */
 1.24438 +    return SQLITE_BUSY;
 1.24439 +    
 1.24440 +  case EACCES: 
 1.24441 +    /* EACCES is like EAGAIN during locking operations, but not any other time*/
 1.24442 +    if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
 1.24443 +        (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
 1.24444 +        (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
 1.24445 +        (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
 1.24446 +      return SQLITE_BUSY;
 1.24447 +    }
 1.24448 +    /* else fall through */
 1.24449 +  case EPERM: 
 1.24450 +    return SQLITE_PERM;
 1.24451 +    
 1.24452 +  /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
 1.24453 +  ** this module never makes such a call. And the code in SQLite itself 
 1.24454 +  ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
 1.24455 +  ** this case is also commented out. If the system does set errno to EDEADLK,
 1.24456 +  ** the default SQLITE_IOERR_XXX code will be returned. */
 1.24457 +#if 0
 1.24458 +  case EDEADLK:
 1.24459 +    return SQLITE_IOERR_BLOCKED;
 1.24460 +#endif
 1.24461 +    
 1.24462 +#if EOPNOTSUPP!=ENOTSUP
 1.24463 +  case EOPNOTSUPP: 
 1.24464 +    /* something went terribly awry, unless during file system support 
 1.24465 +     * introspection, in which it actually means what it says */
 1.24466 +#endif
 1.24467 +#ifdef ENOTSUP
 1.24468 +  case ENOTSUP: 
 1.24469 +    /* invalid fd, unless during file system support introspection, in which 
 1.24470 +     * it actually means what it says */
 1.24471 +#endif
 1.24472 +  case EIO:
 1.24473 +  case EBADF:
 1.24474 +  case EINVAL:
 1.24475 +  case ENOTCONN:
 1.24476 +  case ENODEV:
 1.24477 +  case ENXIO:
 1.24478 +  case ENOENT:
 1.24479 +#ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
 1.24480 +  case ESTALE:
 1.24481 +#endif
 1.24482 +  case ENOSYS:
 1.24483 +    /* these should force the client to close the file and reconnect */
 1.24484 +    
 1.24485 +  default: 
 1.24486 +    return sqliteIOErr;
 1.24487 +  }
 1.24488 +}
 1.24489 +
 1.24490 +
 1.24491 +/******************************************************************************
 1.24492 +****************** Begin Unique File ID Utility Used By VxWorks ***************
 1.24493 +**
 1.24494 +** On most versions of unix, we can get a unique ID for a file by concatenating
 1.24495 +** the device number and the inode number.  But this does not work on VxWorks.
 1.24496 +** On VxWorks, a unique file id must be based on the canonical filename.
 1.24497 +**
 1.24498 +** A pointer to an instance of the following structure can be used as a
 1.24499 +** unique file ID in VxWorks.  Each instance of this structure contains
 1.24500 +** a copy of the canonical filename.  There is also a reference count.  
 1.24501 +** The structure is reclaimed when the number of pointers to it drops to
 1.24502 +** zero.
 1.24503 +**
 1.24504 +** There are never very many files open at one time and lookups are not
 1.24505 +** a performance-critical path, so it is sufficient to put these
 1.24506 +** structures on a linked list.
 1.24507 +*/
 1.24508 +struct vxworksFileId {
 1.24509 +  struct vxworksFileId *pNext;  /* Next in a list of them all */
 1.24510 +  int nRef;                     /* Number of references to this one */
 1.24511 +  int nName;                    /* Length of the zCanonicalName[] string */
 1.24512 +  char *zCanonicalName;         /* Canonical filename */
 1.24513 +};
 1.24514 +
 1.24515 +#if OS_VXWORKS
 1.24516 +/* 
 1.24517 +** All unique filenames are held on a linked list headed by this
 1.24518 +** variable:
 1.24519 +*/
 1.24520 +static struct vxworksFileId *vxworksFileList = 0;
 1.24521 +
 1.24522 +/*
 1.24523 +** Simplify a filename into its canonical form
 1.24524 +** by making the following changes:
 1.24525 +**
 1.24526 +**  * removing any trailing and duplicate /
 1.24527 +**  * convert /./ into just /
 1.24528 +**  * convert /A/../ where A is any simple name into just /
 1.24529 +**
 1.24530 +** Changes are made in-place.  Return the new name length.
 1.24531 +**
 1.24532 +** The original filename is in z[0..n-1].  Return the number of
 1.24533 +** characters in the simplified name.
 1.24534 +*/
 1.24535 +static int vxworksSimplifyName(char *z, int n){
 1.24536 +  int i, j;
 1.24537 +  while( n>1 && z[n-1]=='/' ){ n--; }
 1.24538 +  for(i=j=0; i<n; i++){
 1.24539 +    if( z[i]=='/' ){
 1.24540 +      if( z[i+1]=='/' ) continue;
 1.24541 +      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
 1.24542 +        i += 1;
 1.24543 +        continue;
 1.24544 +      }
 1.24545 +      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
 1.24546 +        while( j>0 && z[j-1]!='/' ){ j--; }
 1.24547 +        if( j>0 ){ j--; }
 1.24548 +        i += 2;
 1.24549 +        continue;
 1.24550 +      }
 1.24551 +    }
 1.24552 +    z[j++] = z[i];
 1.24553 +  }
 1.24554 +  z[j] = 0;
 1.24555 +  return j;
 1.24556 +}
 1.24557 +
 1.24558 +/*
 1.24559 +** Find a unique file ID for the given absolute pathname.  Return
 1.24560 +** a pointer to the vxworksFileId object.  This pointer is the unique
 1.24561 +** file ID.
 1.24562 +**
 1.24563 +** The nRef field of the vxworksFileId object is incremented before
 1.24564 +** the object is returned.  A new vxworksFileId object is created
 1.24565 +** and added to the global list if necessary.
 1.24566 +**
 1.24567 +** If a memory allocation error occurs, return NULL.
 1.24568 +*/
 1.24569 +static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
 1.24570 +  struct vxworksFileId *pNew;         /* search key and new file ID */
 1.24571 +  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
 1.24572 +  int n;                              /* Length of zAbsoluteName string */
 1.24573 +
 1.24574 +  assert( zAbsoluteName[0]=='/' );
 1.24575 +  n = (int)strlen(zAbsoluteName);
 1.24576 +  pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
 1.24577 +  if( pNew==0 ) return 0;
 1.24578 +  pNew->zCanonicalName = (char*)&pNew[1];
 1.24579 +  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
 1.24580 +  n = vxworksSimplifyName(pNew->zCanonicalName, n);
 1.24581 +
 1.24582 +  /* Search for an existing entry that matching the canonical name.
 1.24583 +  ** If found, increment the reference count and return a pointer to
 1.24584 +  ** the existing file ID.
 1.24585 +  */
 1.24586 +  unixEnterMutex();
 1.24587 +  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
 1.24588 +    if( pCandidate->nName==n 
 1.24589 +     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
 1.24590 +    ){
 1.24591 +       sqlite3_free(pNew);
 1.24592 +       pCandidate->nRef++;
 1.24593 +       unixLeaveMutex();
 1.24594 +       return pCandidate;
 1.24595 +    }
 1.24596 +  }
 1.24597 +
 1.24598 +  /* No match was found.  We will make a new file ID */
 1.24599 +  pNew->nRef = 1;
 1.24600 +  pNew->nName = n;
 1.24601 +  pNew->pNext = vxworksFileList;
 1.24602 +  vxworksFileList = pNew;
 1.24603 +  unixLeaveMutex();
 1.24604 +  return pNew;
 1.24605 +}
 1.24606 +
 1.24607 +/*
 1.24608 +** Decrement the reference count on a vxworksFileId object.  Free
 1.24609 +** the object when the reference count reaches zero.
 1.24610 +*/
 1.24611 +static void vxworksReleaseFileId(struct vxworksFileId *pId){
 1.24612 +  unixEnterMutex();
 1.24613 +  assert( pId->nRef>0 );
 1.24614 +  pId->nRef--;
 1.24615 +  if( pId->nRef==0 ){
 1.24616 +    struct vxworksFileId **pp;
 1.24617 +    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
 1.24618 +    assert( *pp==pId );
 1.24619 +    *pp = pId->pNext;
 1.24620 +    sqlite3_free(pId);
 1.24621 +  }
 1.24622 +  unixLeaveMutex();
 1.24623 +}
 1.24624 +#endif /* OS_VXWORKS */
 1.24625 +/*************** End of Unique File ID Utility Used By VxWorks ****************
 1.24626 +******************************************************************************/
 1.24627 +
 1.24628 +
 1.24629 +/******************************************************************************
 1.24630 +*************************** Posix Advisory Locking ****************************
 1.24631 +**
 1.24632 +** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
 1.24633 +** section 6.5.2.2 lines 483 through 490 specify that when a process
 1.24634 +** sets or clears a lock, that operation overrides any prior locks set
 1.24635 +** by the same process.  It does not explicitly say so, but this implies
 1.24636 +** that it overrides locks set by the same process using a different
 1.24637 +** file descriptor.  Consider this test case:
 1.24638 +**
 1.24639 +**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
 1.24640 +**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
 1.24641 +**
 1.24642 +** Suppose ./file1 and ./file2 are really the same file (because
 1.24643 +** one is a hard or symbolic link to the other) then if you set
 1.24644 +** an exclusive lock on fd1, then try to get an exclusive lock
 1.24645 +** on fd2, it works.  I would have expected the second lock to
 1.24646 +** fail since there was already a lock on the file due to fd1.
 1.24647 +** But not so.  Since both locks came from the same process, the
 1.24648 +** second overrides the first, even though they were on different
 1.24649 +** file descriptors opened on different file names.
 1.24650 +**
 1.24651 +** This means that we cannot use POSIX locks to synchronize file access
 1.24652 +** among competing threads of the same process.  POSIX locks will work fine
 1.24653 +** to synchronize access for threads in separate processes, but not
 1.24654 +** threads within the same process.
 1.24655 +**
 1.24656 +** To work around the problem, SQLite has to manage file locks internally
 1.24657 +** on its own.  Whenever a new database is opened, we have to find the
 1.24658 +** specific inode of the database file (the inode is determined by the
 1.24659 +** st_dev and st_ino fields of the stat structure that fstat() fills in)
 1.24660 +** and check for locks already existing on that inode.  When locks are
 1.24661 +** created or removed, we have to look at our own internal record of the
 1.24662 +** locks to see if another thread has previously set a lock on that same
 1.24663 +** inode.
 1.24664 +**
 1.24665 +** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
 1.24666 +** For VxWorks, we have to use the alternative unique ID system based on
 1.24667 +** canonical filename and implemented in the previous division.)
 1.24668 +**
 1.24669 +** The sqlite3_file structure for POSIX is no longer just an integer file
 1.24670 +** descriptor.  It is now a structure that holds the integer file
 1.24671 +** descriptor and a pointer to a structure that describes the internal
 1.24672 +** locks on the corresponding inode.  There is one locking structure
 1.24673 +** per inode, so if the same inode is opened twice, both unixFile structures
 1.24674 +** point to the same locking structure.  The locking structure keeps
 1.24675 +** a reference count (so we will know when to delete it) and a "cnt"
 1.24676 +** field that tells us its internal lock status.  cnt==0 means the
 1.24677 +** file is unlocked.  cnt==-1 means the file has an exclusive lock.
 1.24678 +** cnt>0 means there are cnt shared locks on the file.
 1.24679 +**
 1.24680 +** Any attempt to lock or unlock a file first checks the locking
 1.24681 +** structure.  The fcntl() system call is only invoked to set a 
 1.24682 +** POSIX lock if the internal lock structure transitions between
 1.24683 +** a locked and an unlocked state.
 1.24684 +**
 1.24685 +** But wait:  there are yet more problems with POSIX advisory locks.
 1.24686 +**
 1.24687 +** If you close a file descriptor that points to a file that has locks,
 1.24688 +** all locks on that file that are owned by the current process are
 1.24689 +** released.  To work around this problem, each unixInodeInfo object
 1.24690 +** maintains a count of the number of pending locks on tha inode.
 1.24691 +** When an attempt is made to close an unixFile, if there are
 1.24692 +** other unixFile open on the same inode that are holding locks, the call
 1.24693 +** to close() the file descriptor is deferred until all of the locks clear.
 1.24694 +** The unixInodeInfo structure keeps a list of file descriptors that need to
 1.24695 +** be closed and that list is walked (and cleared) when the last lock
 1.24696 +** clears.
 1.24697 +**
 1.24698 +** Yet another problem:  LinuxThreads do not play well with posix locks.
 1.24699 +**
 1.24700 +** Many older versions of linux use the LinuxThreads library which is
 1.24701 +** not posix compliant.  Under LinuxThreads, a lock created by thread
 1.24702 +** A cannot be modified or overridden by a different thread B.
 1.24703 +** Only thread A can modify the lock.  Locking behavior is correct
 1.24704 +** if the appliation uses the newer Native Posix Thread Library (NPTL)
 1.24705 +** on linux - with NPTL a lock created by thread A can override locks
 1.24706 +** in thread B.  But there is no way to know at compile-time which
 1.24707 +** threading library is being used.  So there is no way to know at
 1.24708 +** compile-time whether or not thread A can override locks on thread B.
 1.24709 +** One has to do a run-time check to discover the behavior of the
 1.24710 +** current process.
 1.24711 +**
 1.24712 +** SQLite used to support LinuxThreads.  But support for LinuxThreads
 1.24713 +** was dropped beginning with version 3.7.0.  SQLite will still work with
 1.24714 +** LinuxThreads provided that (1) there is no more than one connection 
 1.24715 +** per database file in the same process and (2) database connections
 1.24716 +** do not move across threads.
 1.24717 +*/
 1.24718 +
 1.24719 +/*
 1.24720 +** An instance of the following structure serves as the key used
 1.24721 +** to locate a particular unixInodeInfo object.
 1.24722 +*/
 1.24723 +struct unixFileId {
 1.24724 +  dev_t dev;                  /* Device number */
 1.24725 +#if OS_VXWORKS
 1.24726 +  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
 1.24727 +#else
 1.24728 +  ino_t ino;                  /* Inode number */
 1.24729 +#endif
 1.24730 +};
 1.24731 +
 1.24732 +/*
 1.24733 +** An instance of the following structure is allocated for each open
 1.24734 +** inode.  Or, on LinuxThreads, there is one of these structures for
 1.24735 +** each inode opened by each thread.
 1.24736 +**
 1.24737 +** A single inode can have multiple file descriptors, so each unixFile
 1.24738 +** structure contains a pointer to an instance of this object and this
 1.24739 +** object keeps a count of the number of unixFile pointing to it.
 1.24740 +*/
 1.24741 +struct unixInodeInfo {
 1.24742 +  struct unixFileId fileId;       /* The lookup key */
 1.24743 +  int nShared;                    /* Number of SHARED locks held */
 1.24744 +  unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
 1.24745 +  unsigned char bProcessLock;     /* An exclusive process lock is held */
 1.24746 +  int nRef;                       /* Number of pointers to this structure */
 1.24747 +  unixShmNode *pShmNode;          /* Shared memory associated with this inode */
 1.24748 +  int nLock;                      /* Number of outstanding file locks */
 1.24749 +  UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
 1.24750 +  unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
 1.24751 +  unixInodeInfo *pPrev;           /*    .... doubly linked */
 1.24752 +#if SQLITE_ENABLE_LOCKING_STYLE
 1.24753 +  unsigned long long sharedByte;  /* for AFP simulated shared lock */
 1.24754 +#endif
 1.24755 +#if OS_VXWORKS
 1.24756 +  sem_t *pSem;                    /* Named POSIX semaphore */
 1.24757 +  char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
 1.24758 +#endif
 1.24759 +};
 1.24760 +
 1.24761 +/*
 1.24762 +** A lists of all unixInodeInfo objects.
 1.24763 +*/
 1.24764 +static unixInodeInfo *inodeList = 0;
 1.24765 +
 1.24766 +/*
 1.24767 +**
 1.24768 +** This function - unixLogError_x(), is only ever called via the macro
 1.24769 +** unixLogError().
 1.24770 +**
 1.24771 +** It is invoked after an error occurs in an OS function and errno has been
 1.24772 +** set. It logs a message using sqlite3_log() containing the current value of
 1.24773 +** errno and, if possible, the human-readable equivalent from strerror() or
 1.24774 +** strerror_r().
 1.24775 +**
 1.24776 +** The first argument passed to the macro should be the error code that
 1.24777 +** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
 1.24778 +** The two subsequent arguments should be the name of the OS function that
 1.24779 +** failed (e.g. "unlink", "open") and the associated file-system path,
 1.24780 +** if any.
 1.24781 +*/
 1.24782 +#define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
 1.24783 +static int unixLogErrorAtLine(
 1.24784 +  int errcode,                    /* SQLite error code */
 1.24785 +  const char *zFunc,              /* Name of OS function that failed */
 1.24786 +  const char *zPath,              /* File path associated with error */
 1.24787 +  int iLine                       /* Source line number where error occurred */
 1.24788 +){
 1.24789 +  char *zErr;                     /* Message from strerror() or equivalent */
 1.24790 +  int iErrno = errno;             /* Saved syscall error number */
 1.24791 +
 1.24792 +  /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
 1.24793 +  ** the strerror() function to obtain the human-readable error message
 1.24794 +  ** equivalent to errno. Otherwise, use strerror_r().
 1.24795 +  */ 
 1.24796 +#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
 1.24797 +  char aErr[80];
 1.24798 +  memset(aErr, 0, sizeof(aErr));
 1.24799 +  zErr = aErr;
 1.24800 +
 1.24801 +  /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
 1.24802 +  ** assume that the system provides the GNU version of strerror_r() that
 1.24803 +  ** returns a pointer to a buffer containing the error message. That pointer 
 1.24804 +  ** may point to aErr[], or it may point to some static storage somewhere. 
 1.24805 +  ** Otherwise, assume that the system provides the POSIX version of 
 1.24806 +  ** strerror_r(), which always writes an error message into aErr[].
 1.24807 +  **
 1.24808 +  ** If the code incorrectly assumes that it is the POSIX version that is
 1.24809 +  ** available, the error message will often be an empty string. Not a
 1.24810 +  ** huge problem. Incorrectly concluding that the GNU version is available 
 1.24811 +  ** could lead to a segfault though.
 1.24812 +  */
 1.24813 +#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
 1.24814 +  zErr = 
 1.24815 +# endif
 1.24816 +  strerror_r(iErrno, aErr, sizeof(aErr)-1);
 1.24817 +
 1.24818 +#elif SQLITE_THREADSAFE
 1.24819 +  /* This is a threadsafe build, but strerror_r() is not available. */
 1.24820 +  zErr = "";
 1.24821 +#else
 1.24822 +  /* Non-threadsafe build, use strerror(). */
 1.24823 +  zErr = strerror(iErrno);
 1.24824 +#endif
 1.24825 +
 1.24826 +  if( zPath==0 ) zPath = "";
 1.24827 +  sqlite3_log(errcode,
 1.24828 +      "os_unix.c:%d: (%d) %s(%s) - %s",
 1.24829 +      iLine, iErrno, zFunc, zPath, zErr
 1.24830 +  );
 1.24831 +
 1.24832 +  return errcode;
 1.24833 +}
 1.24834 +
 1.24835 +/*
 1.24836 +** Close a file descriptor.
 1.24837 +**
 1.24838 +** We assume that close() almost always works, since it is only in a
 1.24839 +** very sick application or on a very sick platform that it might fail.
 1.24840 +** If it does fail, simply leak the file descriptor, but do log the
 1.24841 +** error.
 1.24842 +**
 1.24843 +** Note that it is not safe to retry close() after EINTR since the
 1.24844 +** file descriptor might have already been reused by another thread.
 1.24845 +** So we don't even try to recover from an EINTR.  Just log the error
 1.24846 +** and move on.
 1.24847 +*/
 1.24848 +static void robust_close(unixFile *pFile, int h, int lineno){
 1.24849 +  if( osClose(h) ){
 1.24850 +    unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
 1.24851 +                       pFile ? pFile->zPath : 0, lineno);
 1.24852 +  }
 1.24853 +}
 1.24854 +
 1.24855 +/*
 1.24856 +** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
 1.24857 +*/ 
 1.24858 +static void closePendingFds(unixFile *pFile){
 1.24859 +  unixInodeInfo *pInode = pFile->pInode;
 1.24860 +  UnixUnusedFd *p;
 1.24861 +  UnixUnusedFd *pNext;
 1.24862 +  for(p=pInode->pUnused; p; p=pNext){
 1.24863 +    pNext = p->pNext;
 1.24864 +    robust_close(pFile, p->fd, __LINE__);
 1.24865 +    sqlite3_free(p);
 1.24866 +  }
 1.24867 +  pInode->pUnused = 0;
 1.24868 +}
 1.24869 +
 1.24870 +/*
 1.24871 +** Release a unixInodeInfo structure previously allocated by findInodeInfo().
 1.24872 +**
 1.24873 +** The mutex entered using the unixEnterMutex() function must be held
 1.24874 +** when this function is called.
 1.24875 +*/
 1.24876 +static void releaseInodeInfo(unixFile *pFile){
 1.24877 +  unixInodeInfo *pInode = pFile->pInode;
 1.24878 +  assert( unixMutexHeld() );
 1.24879 +  if( ALWAYS(pInode) ){
 1.24880 +    pInode->nRef--;
 1.24881 +    if( pInode->nRef==0 ){
 1.24882 +      assert( pInode->pShmNode==0 );
 1.24883 +      closePendingFds(pFile);
 1.24884 +      if( pInode->pPrev ){
 1.24885 +        assert( pInode->pPrev->pNext==pInode );
 1.24886 +        pInode->pPrev->pNext = pInode->pNext;
 1.24887 +      }else{
 1.24888 +        assert( inodeList==pInode );
 1.24889 +        inodeList = pInode->pNext;
 1.24890 +      }
 1.24891 +      if( pInode->pNext ){
 1.24892 +        assert( pInode->pNext->pPrev==pInode );
 1.24893 +        pInode->pNext->pPrev = pInode->pPrev;
 1.24894 +      }
 1.24895 +      sqlite3_free(pInode);
 1.24896 +    }
 1.24897 +  }
 1.24898 +}
 1.24899 +
 1.24900 +/*
 1.24901 +** Given a file descriptor, locate the unixInodeInfo object that
 1.24902 +** describes that file descriptor.  Create a new one if necessary.  The
 1.24903 +** return value might be uninitialized if an error occurs.
 1.24904 +**
 1.24905 +** The mutex entered using the unixEnterMutex() function must be held
 1.24906 +** when this function is called.
 1.24907 +**
 1.24908 +** Return an appropriate error code.
 1.24909 +*/
 1.24910 +static int findInodeInfo(
 1.24911 +  unixFile *pFile,               /* Unix file with file desc used in the key */
 1.24912 +  unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
 1.24913 +){
 1.24914 +  int rc;                        /* System call return code */
 1.24915 +  int fd;                        /* The file descriptor for pFile */
 1.24916 +  struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
 1.24917 +  struct stat statbuf;           /* Low-level file information */
 1.24918 +  unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
 1.24919 +
 1.24920 +  assert( unixMutexHeld() );
 1.24921 +
 1.24922 +  /* Get low-level information about the file that we can used to
 1.24923 +  ** create a unique name for the file.
 1.24924 +  */
 1.24925 +  fd = pFile->h;
 1.24926 +  rc = osFstat(fd, &statbuf);
 1.24927 +  if( rc!=0 ){
 1.24928 +    pFile->lastErrno = errno;
 1.24929 +#ifdef EOVERFLOW
 1.24930 +    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
 1.24931 +#endif
 1.24932 +    return SQLITE_IOERR;
 1.24933 +  }
 1.24934 +
 1.24935 +#ifdef __APPLE__
 1.24936 +  /* On OS X on an msdos filesystem, the inode number is reported
 1.24937 +  ** incorrectly for zero-size files.  See ticket #3260.  To work
 1.24938 +  ** around this problem (we consider it a bug in OS X, not SQLite)
 1.24939 +  ** we always increase the file size to 1 by writing a single byte
 1.24940 +  ** prior to accessing the inode number.  The one byte written is
 1.24941 +  ** an ASCII 'S' character which also happens to be the first byte
 1.24942 +  ** in the header of every SQLite database.  In this way, if there
 1.24943 +  ** is a race condition such that another thread has already populated
 1.24944 +  ** the first page of the database, no damage is done.
 1.24945 +  */
 1.24946 +  if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
 1.24947 +    do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
 1.24948 +    if( rc!=1 ){
 1.24949 +      pFile->lastErrno = errno;
 1.24950 +      return SQLITE_IOERR;
 1.24951 +    }
 1.24952 +    rc = osFstat(fd, &statbuf);
 1.24953 +    if( rc!=0 ){
 1.24954 +      pFile->lastErrno = errno;
 1.24955 +      return SQLITE_IOERR;
 1.24956 +    }
 1.24957 +  }
 1.24958 +#endif
 1.24959 +
 1.24960 +  memset(&fileId, 0, sizeof(fileId));
 1.24961 +  fileId.dev = statbuf.st_dev;
 1.24962 +#if OS_VXWORKS
 1.24963 +  fileId.pId = pFile->pId;
 1.24964 +#else
 1.24965 +  fileId.ino = statbuf.st_ino;
 1.24966 +#endif
 1.24967 +  pInode = inodeList;
 1.24968 +  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
 1.24969 +    pInode = pInode->pNext;
 1.24970 +  }
 1.24971 +  if( pInode==0 ){
 1.24972 +    pInode = sqlite3_malloc( sizeof(*pInode) );
 1.24973 +    if( pInode==0 ){
 1.24974 +      return SQLITE_NOMEM;
 1.24975 +    }
 1.24976 +    memset(pInode, 0, sizeof(*pInode));
 1.24977 +    memcpy(&pInode->fileId, &fileId, sizeof(fileId));
 1.24978 +    pInode->nRef = 1;
 1.24979 +    pInode->pNext = inodeList;
 1.24980 +    pInode->pPrev = 0;
 1.24981 +    if( inodeList ) inodeList->pPrev = pInode;
 1.24982 +    inodeList = pInode;
 1.24983 +  }else{
 1.24984 +    pInode->nRef++;
 1.24985 +  }
 1.24986 +  *ppInode = pInode;
 1.24987 +  return SQLITE_OK;
 1.24988 +}
 1.24989 +
 1.24990 +/*
 1.24991 +** Return TRUE if pFile has been renamed or unlinked since it was first opened.
 1.24992 +*/
 1.24993 +static int fileHasMoved(unixFile *pFile){
 1.24994 +  struct stat buf;
 1.24995 +  return pFile->pInode!=0 &&
 1.24996 +         (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
 1.24997 +}
 1.24998 +
 1.24999 +
 1.25000 +/*
 1.25001 +** Check a unixFile that is a database.  Verify the following:
 1.25002 +**
 1.25003 +** (1) There is exactly one hard link on the file
 1.25004 +** (2) The file is not a symbolic link
 1.25005 +** (3) The file has not been renamed or unlinked
 1.25006 +**
 1.25007 +** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
 1.25008 +*/
 1.25009 +static void verifyDbFile(unixFile *pFile){
 1.25010 +  struct stat buf;
 1.25011 +  int rc;
 1.25012 +  if( pFile->ctrlFlags & UNIXFILE_WARNED ){
 1.25013 +    /* One or more of the following warnings have already been issued.  Do not
 1.25014 +    ** repeat them so as not to clutter the error log */
 1.25015 +    return;
 1.25016 +  }
 1.25017 +  rc = osFstat(pFile->h, &buf);
 1.25018 +  if( rc!=0 ){
 1.25019 +    sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
 1.25020 +    pFile->ctrlFlags |= UNIXFILE_WARNED;
 1.25021 +    return;
 1.25022 +  }
 1.25023 +  if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
 1.25024 +    sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
 1.25025 +    pFile->ctrlFlags |= UNIXFILE_WARNED;
 1.25026 +    return;
 1.25027 +  }
 1.25028 +  if( buf.st_nlink>1 ){
 1.25029 +    sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
 1.25030 +    pFile->ctrlFlags |= UNIXFILE_WARNED;
 1.25031 +    return;
 1.25032 +  }
 1.25033 +  if( fileHasMoved(pFile) ){
 1.25034 +    sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
 1.25035 +    pFile->ctrlFlags |= UNIXFILE_WARNED;
 1.25036 +    return;
 1.25037 +  }
 1.25038 +}
 1.25039 +
 1.25040 +
 1.25041 +/*
 1.25042 +** This routine checks if there is a RESERVED lock held on the specified
 1.25043 +** file by this or any other process. If such a lock is held, set *pResOut
 1.25044 +** to a non-zero value otherwise *pResOut is set to zero.  The return value
 1.25045 +** is set to SQLITE_OK unless an I/O error occurs during lock checking.
 1.25046 +*/
 1.25047 +static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
 1.25048 +  int rc = SQLITE_OK;
 1.25049 +  int reserved = 0;
 1.25050 +  unixFile *pFile = (unixFile*)id;
 1.25051 +
 1.25052 +  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
 1.25053 +
 1.25054 +  assert( pFile );
 1.25055 +  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
 1.25056 +
 1.25057 +  /* Check if a thread in this process holds such a lock */
 1.25058 +  if( pFile->pInode->eFileLock>SHARED_LOCK ){
 1.25059 +    reserved = 1;
 1.25060 +  }
 1.25061 +
 1.25062 +  /* Otherwise see if some other process holds it.
 1.25063 +  */
 1.25064 +#ifndef __DJGPP__
 1.25065 +  if( !reserved && !pFile->pInode->bProcessLock ){
 1.25066 +    struct flock lock;
 1.25067 +    lock.l_whence = SEEK_SET;
 1.25068 +    lock.l_start = RESERVED_BYTE;
 1.25069 +    lock.l_len = 1;
 1.25070 +    lock.l_type = F_WRLCK;
 1.25071 +    if( osFcntl(pFile->h, F_GETLK, &lock) ){
 1.25072 +      rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
 1.25073 +      pFile->lastErrno = errno;
 1.25074 +    } else if( lock.l_type!=F_UNLCK ){
 1.25075 +      reserved = 1;
 1.25076 +    }
 1.25077 +  }
 1.25078 +#endif
 1.25079 +  
 1.25080 +  unixLeaveMutex();
 1.25081 +  OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
 1.25082 +
 1.25083 +  *pResOut = reserved;
 1.25084 +  return rc;
 1.25085 +}
 1.25086 +
 1.25087 +/*
 1.25088 +** Attempt to set a system-lock on the file pFile.  The lock is 
 1.25089 +** described by pLock.
 1.25090 +**
 1.25091 +** If the pFile was opened read/write from unix-excl, then the only lock
 1.25092 +** ever obtained is an exclusive lock, and it is obtained exactly once
 1.25093 +** the first time any lock is attempted.  All subsequent system locking
 1.25094 +** operations become no-ops.  Locking operations still happen internally,
 1.25095 +** in order to coordinate access between separate database connections
 1.25096 +** within this process, but all of that is handled in memory and the
 1.25097 +** operating system does not participate.
 1.25098 +**
 1.25099 +** This function is a pass-through to fcntl(F_SETLK) if pFile is using
 1.25100 +** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
 1.25101 +** and is read-only.
 1.25102 +**
 1.25103 +** Zero is returned if the call completes successfully, or -1 if a call
 1.25104 +** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
 1.25105 +*/
 1.25106 +static int unixFileLock(unixFile *pFile, struct flock *pLock){
 1.25107 +  int rc;
 1.25108 +  unixInodeInfo *pInode = pFile->pInode;
 1.25109 +  assert( unixMutexHeld() );
 1.25110 +  assert( pInode!=0 );
 1.25111 +  if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
 1.25112 +   && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
 1.25113 +  ){
 1.25114 +    if( pInode->bProcessLock==0 ){
 1.25115 +      struct flock lock;
 1.25116 +      assert( pInode->nLock==0 );
 1.25117 +      lock.l_whence = SEEK_SET;
 1.25118 +      lock.l_start = SHARED_FIRST;
 1.25119 +      lock.l_len = SHARED_SIZE;
 1.25120 +      lock.l_type = F_WRLCK;
 1.25121 +      rc = osFcntl(pFile->h, F_SETLK, &lock);
 1.25122 +      if( rc<0 ) return rc;
 1.25123 +      pInode->bProcessLock = 1;
 1.25124 +      pInode->nLock++;
 1.25125 +    }else{
 1.25126 +      rc = 0;
 1.25127 +    }
 1.25128 +  }else{
 1.25129 +    rc = osFcntl(pFile->h, F_SETLK, pLock);
 1.25130 +  }
 1.25131 +  return rc;
 1.25132 +}
 1.25133 +
 1.25134 +/*
 1.25135 +** Lock the file with the lock specified by parameter eFileLock - one
 1.25136 +** of the following:
 1.25137 +**
 1.25138 +**     (1) SHARED_LOCK
 1.25139 +**     (2) RESERVED_LOCK
 1.25140 +**     (3) PENDING_LOCK
 1.25141 +**     (4) EXCLUSIVE_LOCK
 1.25142 +**
 1.25143 +** Sometimes when requesting one lock state, additional lock states
 1.25144 +** are inserted in between.  The locking might fail on one of the later
 1.25145 +** transitions leaving the lock state different from what it started but
 1.25146 +** still short of its goal.  The following chart shows the allowed
 1.25147 +** transitions and the inserted intermediate states:
 1.25148 +**
 1.25149 +**    UNLOCKED -> SHARED
 1.25150 +**    SHARED -> RESERVED
 1.25151 +**    SHARED -> (PENDING) -> EXCLUSIVE
 1.25152 +**    RESERVED -> (PENDING) -> EXCLUSIVE
 1.25153 +**    PENDING -> EXCLUSIVE
 1.25154 +**
 1.25155 +** This routine will only increase a lock.  Use the sqlite3OsUnlock()
 1.25156 +** routine to lower a locking level.
 1.25157 +*/
 1.25158 +static int unixLock(sqlite3_file *id, int eFileLock){
 1.25159 +  /* The following describes the implementation of the various locks and
 1.25160 +  ** lock transitions in terms of the POSIX advisory shared and exclusive
 1.25161 +  ** lock primitives (called read-locks and write-locks below, to avoid
 1.25162 +  ** confusion with SQLite lock names). The algorithms are complicated
 1.25163 +  ** slightly in order to be compatible with windows systems simultaneously
 1.25164 +  ** accessing the same database file, in case that is ever required.
 1.25165 +  **
 1.25166 +  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
 1.25167 +  ** byte', each single bytes at well known offsets, and the 'shared byte
 1.25168 +  ** range', a range of 510 bytes at a well known offset.
 1.25169 +  **
 1.25170 +  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
 1.25171 +  ** byte'.  If this is successful, a random byte from the 'shared byte
 1.25172 +  ** range' is read-locked and the lock on the 'pending byte' released.
 1.25173 +  **
 1.25174 +  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
 1.25175 +  ** A RESERVED lock is implemented by grabbing a write-lock on the
 1.25176 +  ** 'reserved byte'. 
 1.25177 +  **
 1.25178 +  ** A process may only obtain a PENDING lock after it has obtained a
 1.25179 +  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
 1.25180 +  ** on the 'pending byte'. This ensures that no new SHARED locks can be
 1.25181 +  ** obtained, but existing SHARED locks are allowed to persist. A process
 1.25182 +  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
 1.25183 +  ** This property is used by the algorithm for rolling back a journal file
 1.25184 +  ** after a crash.
 1.25185 +  **
 1.25186 +  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
 1.25187 +  ** implemented by obtaining a write-lock on the entire 'shared byte
 1.25188 +  ** range'. Since all other locks require a read-lock on one of the bytes
 1.25189 +  ** within this range, this ensures that no other locks are held on the
 1.25190 +  ** database. 
 1.25191 +  **
 1.25192 +  ** The reason a single byte cannot be used instead of the 'shared byte
 1.25193 +  ** range' is that some versions of windows do not support read-locks. By
 1.25194 +  ** locking a random byte from a range, concurrent SHARED locks may exist
 1.25195 +  ** even if the locking primitive used is always a write-lock.
 1.25196 +  */
 1.25197 +  int rc = SQLITE_OK;
 1.25198 +  unixFile *pFile = (unixFile*)id;
 1.25199 +  unixInodeInfo *pInode;
 1.25200 +  struct flock lock;
 1.25201 +  int tErrno = 0;
 1.25202 +
 1.25203 +  assert( pFile );
 1.25204 +  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
 1.25205 +      azFileLock(eFileLock), azFileLock(pFile->eFileLock),
 1.25206 +      azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
 1.25207 +
 1.25208 +  /* If there is already a lock of this type or more restrictive on the
 1.25209 +  ** unixFile, do nothing. Don't use the end_lock: exit path, as
 1.25210 +  ** unixEnterMutex() hasn't been called yet.
 1.25211 +  */
 1.25212 +  if( pFile->eFileLock>=eFileLock ){
 1.25213 +    OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
 1.25214 +            azFileLock(eFileLock)));
 1.25215 +    return SQLITE_OK;
 1.25216 +  }
 1.25217 +
 1.25218 +  /* Make sure the locking sequence is correct.
 1.25219 +  **  (1) We never move from unlocked to anything higher than shared lock.
 1.25220 +  **  (2) SQLite never explicitly requests a pendig lock.
 1.25221 +  **  (3) A shared lock is always held when a reserve lock is requested.
 1.25222 +  */
 1.25223 +  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
 1.25224 +  assert( eFileLock!=PENDING_LOCK );
 1.25225 +  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
 1.25226 +
 1.25227 +  /* This mutex is needed because pFile->pInode is shared across threads
 1.25228 +  */
 1.25229 +  unixEnterMutex();
 1.25230 +  pInode = pFile->pInode;
 1.25231 +
 1.25232 +  /* If some thread using this PID has a lock via a different unixFile*
 1.25233 +  ** handle that precludes the requested lock, return BUSY.
 1.25234 +  */
 1.25235 +  if( (pFile->eFileLock!=pInode->eFileLock && 
 1.25236 +          (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
 1.25237 +  ){
 1.25238 +    rc = SQLITE_BUSY;
 1.25239 +    goto end_lock;
 1.25240 +  }
 1.25241 +
 1.25242 +  /* If a SHARED lock is requested, and some thread using this PID already
 1.25243 +  ** has a SHARED or RESERVED lock, then increment reference counts and
 1.25244 +  ** return SQLITE_OK.
 1.25245 +  */
 1.25246 +  if( eFileLock==SHARED_LOCK && 
 1.25247 +      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
 1.25248 +    assert( eFileLock==SHARED_LOCK );
 1.25249 +    assert( pFile->eFileLock==0 );
 1.25250 +    assert( pInode->nShared>0 );
 1.25251 +    pFile->eFileLock = SHARED_LOCK;
 1.25252 +    pInode->nShared++;
 1.25253 +    pInode->nLock++;
 1.25254 +    goto end_lock;
 1.25255 +  }
 1.25256 +
 1.25257 +
 1.25258 +  /* A PENDING lock is needed before acquiring a SHARED lock and before
 1.25259 +  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
 1.25260 +  ** be released.
 1.25261 +  */
 1.25262 +  lock.l_len = 1L;
 1.25263 +  lock.l_whence = SEEK_SET;
 1.25264 +  if( eFileLock==SHARED_LOCK 
 1.25265 +      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
 1.25266 +  ){
 1.25267 +    lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
 1.25268 +    lock.l_start = PENDING_BYTE;
 1.25269 +    if( unixFileLock(pFile, &lock) ){
 1.25270 +      tErrno = errno;
 1.25271 +      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
 1.25272 +      if( rc!=SQLITE_BUSY ){
 1.25273 +        pFile->lastErrno = tErrno;
 1.25274 +      }
 1.25275 +      goto end_lock;
 1.25276 +    }
 1.25277 +  }
 1.25278 +
 1.25279 +
 1.25280 +  /* If control gets to this point, then actually go ahead and make
 1.25281 +  ** operating system calls for the specified lock.
 1.25282 +  */
 1.25283 +  if( eFileLock==SHARED_LOCK ){
 1.25284 +    assert( pInode->nShared==0 );
 1.25285 +    assert( pInode->eFileLock==0 );
 1.25286 +    assert( rc==SQLITE_OK );
 1.25287 +
 1.25288 +    /* Now get the read-lock */
 1.25289 +    lock.l_start = SHARED_FIRST;
 1.25290 +    lock.l_len = SHARED_SIZE;
 1.25291 +    if( unixFileLock(pFile, &lock) ){
 1.25292 +      tErrno = errno;
 1.25293 +      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
 1.25294 +    }
 1.25295 +
 1.25296 +    /* Drop the temporary PENDING lock */
 1.25297 +    lock.l_start = PENDING_BYTE;
 1.25298 +    lock.l_len = 1L;
 1.25299 +    lock.l_type = F_UNLCK;
 1.25300 +    if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
 1.25301 +      /* This could happen with a network mount */
 1.25302 +      tErrno = errno;
 1.25303 +      rc = SQLITE_IOERR_UNLOCK; 
 1.25304 +    }
 1.25305 +
 1.25306 +    if( rc ){
 1.25307 +      if( rc!=SQLITE_BUSY ){
 1.25308 +        pFile->lastErrno = tErrno;
 1.25309 +      }
 1.25310 +      goto end_lock;
 1.25311 +    }else{
 1.25312 +      pFile->eFileLock = SHARED_LOCK;
 1.25313 +      pInode->nLock++;
 1.25314 +      pInode->nShared = 1;
 1.25315 +    }
 1.25316 +  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
 1.25317 +    /* We are trying for an exclusive lock but another thread in this
 1.25318 +    ** same process is still holding a shared lock. */
 1.25319 +    rc = SQLITE_BUSY;
 1.25320 +  }else{
 1.25321 +    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
 1.25322 +    ** assumed that there is a SHARED or greater lock on the file
 1.25323 +    ** already.
 1.25324 +    */
 1.25325 +    assert( 0!=pFile->eFileLock );
 1.25326 +    lock.l_type = F_WRLCK;
 1.25327 +
 1.25328 +    assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
 1.25329 +    if( eFileLock==RESERVED_LOCK ){
 1.25330 +      lock.l_start = RESERVED_BYTE;
 1.25331 +      lock.l_len = 1L;
 1.25332 +    }else{
 1.25333 +      lock.l_start = SHARED_FIRST;
 1.25334 +      lock.l_len = SHARED_SIZE;
 1.25335 +    }
 1.25336 +
 1.25337 +    if( unixFileLock(pFile, &lock) ){
 1.25338 +      tErrno = errno;
 1.25339 +      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
 1.25340 +      if( rc!=SQLITE_BUSY ){
 1.25341 +        pFile->lastErrno = tErrno;
 1.25342 +      }
 1.25343 +    }
 1.25344 +  }
 1.25345 +  
 1.25346 +
 1.25347 +#ifdef SQLITE_DEBUG
 1.25348 +  /* Set up the transaction-counter change checking flags when
 1.25349 +  ** transitioning from a SHARED to a RESERVED lock.  The change
 1.25350 +  ** from SHARED to RESERVED marks the beginning of a normal
 1.25351 +  ** write operation (not a hot journal rollback).
 1.25352 +  */
 1.25353 +  if( rc==SQLITE_OK
 1.25354 +   && pFile->eFileLock<=SHARED_LOCK
 1.25355 +   && eFileLock==RESERVED_LOCK
 1.25356 +  ){
 1.25357 +    pFile->transCntrChng = 0;
 1.25358 +    pFile->dbUpdate = 0;
 1.25359 +    pFile->inNormalWrite = 1;
 1.25360 +  }
 1.25361 +#endif
 1.25362 +
 1.25363 +
 1.25364 +  if( rc==SQLITE_OK ){
 1.25365 +    pFile->eFileLock = eFileLock;
 1.25366 +    pInode->eFileLock = eFileLock;
 1.25367 +  }else if( eFileLock==EXCLUSIVE_LOCK ){
 1.25368 +    pFile->eFileLock = PENDING_LOCK;
 1.25369 +    pInode->eFileLock = PENDING_LOCK;
 1.25370 +  }
 1.25371 +
 1.25372 +end_lock:
 1.25373 +  unixLeaveMutex();
 1.25374 +  OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
 1.25375 +      rc==SQLITE_OK ? "ok" : "failed"));
 1.25376 +  return rc;
 1.25377 +}
 1.25378 +
 1.25379 +/*
 1.25380 +** Add the file descriptor used by file handle pFile to the corresponding
 1.25381 +** pUnused list.
 1.25382 +*/
 1.25383 +static void setPendingFd(unixFile *pFile){
 1.25384 +  unixInodeInfo *pInode = pFile->pInode;
 1.25385 +  UnixUnusedFd *p = pFile->pUnused;
 1.25386 +  p->pNext = pInode->pUnused;
 1.25387 +  pInode->pUnused = p;
 1.25388 +  pFile->h = -1;
 1.25389 +  pFile->pUnused = 0;
 1.25390 +}
 1.25391 +
 1.25392 +/*
 1.25393 +** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 1.25394 +** must be either NO_LOCK or SHARED_LOCK.
 1.25395 +**
 1.25396 +** If the locking level of the file descriptor is already at or below
 1.25397 +** the requested locking level, this routine is a no-op.
 1.25398 +** 
 1.25399 +** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
 1.25400 +** the byte range is divided into 2 parts and the first part is unlocked then
 1.25401 +** set to a read lock, then the other part is simply unlocked.  This works 
 1.25402 +** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
 1.25403 +** remove the write lock on a region when a read lock is set.
 1.25404 +*/
 1.25405 +static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
 1.25406 +  unixFile *pFile = (unixFile*)id;
 1.25407 +  unixInodeInfo *pInode;
 1.25408 +  struct flock lock;
 1.25409 +  int rc = SQLITE_OK;
 1.25410 +
 1.25411 +  assert( pFile );
 1.25412 +  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
 1.25413 +      pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
 1.25414 +      getpid()));
 1.25415 +
 1.25416 +  assert( eFileLock<=SHARED_LOCK );
 1.25417 +  if( pFile->eFileLock<=eFileLock ){
 1.25418 +    return SQLITE_OK;
 1.25419 +  }
 1.25420 +  unixEnterMutex();
 1.25421 +  pInode = pFile->pInode;
 1.25422 +  assert( pInode->nShared!=0 );
 1.25423 +  if( pFile->eFileLock>SHARED_LOCK ){
 1.25424 +    assert( pInode->eFileLock==pFile->eFileLock );
 1.25425 +
 1.25426 +#ifdef SQLITE_DEBUG
 1.25427 +    /* When reducing a lock such that other processes can start
 1.25428 +    ** reading the database file again, make sure that the
 1.25429 +    ** transaction counter was updated if any part of the database
 1.25430 +    ** file changed.  If the transaction counter is not updated,
 1.25431 +    ** other connections to the same file might not realize that
 1.25432 +    ** the file has changed and hence might not know to flush their
 1.25433 +    ** cache.  The use of a stale cache can lead to database corruption.
 1.25434 +    */
 1.25435 +    pFile->inNormalWrite = 0;
 1.25436 +#endif
 1.25437 +
 1.25438 +    /* downgrading to a shared lock on NFS involves clearing the write lock
 1.25439 +    ** before establishing the readlock - to avoid a race condition we downgrade
 1.25440 +    ** the lock in 2 blocks, so that part of the range will be covered by a 
 1.25441 +    ** write lock until the rest is covered by a read lock:
 1.25442 +    **  1:   [WWWWW]
 1.25443 +    **  2:   [....W]
 1.25444 +    **  3:   [RRRRW]
 1.25445 +    **  4:   [RRRR.]
 1.25446 +    */
 1.25447 +    if( eFileLock==SHARED_LOCK ){
 1.25448 +
 1.25449 +#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
 1.25450 +      (void)handleNFSUnlock;
 1.25451 +      assert( handleNFSUnlock==0 );
 1.25452 +#endif
 1.25453 +#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 1.25454 +      if( handleNFSUnlock ){
 1.25455 +        int tErrno;               /* Error code from system call errors */
 1.25456 +        off_t divSize = SHARED_SIZE - 1;
 1.25457 +        
 1.25458 +        lock.l_type = F_UNLCK;
 1.25459 +        lock.l_whence = SEEK_SET;
 1.25460 +        lock.l_start = SHARED_FIRST;
 1.25461 +        lock.l_len = divSize;
 1.25462 +        if( unixFileLock(pFile, &lock)==(-1) ){
 1.25463 +          tErrno = errno;
 1.25464 +          rc = SQLITE_IOERR_UNLOCK;
 1.25465 +          if( IS_LOCK_ERROR(rc) ){
 1.25466 +            pFile->lastErrno = tErrno;
 1.25467 +          }
 1.25468 +          goto end_unlock;
 1.25469 +        }
 1.25470 +        lock.l_type = F_RDLCK;
 1.25471 +        lock.l_whence = SEEK_SET;
 1.25472 +        lock.l_start = SHARED_FIRST;
 1.25473 +        lock.l_len = divSize;
 1.25474 +        if( unixFileLock(pFile, &lock)==(-1) ){
 1.25475 +          tErrno = errno;
 1.25476 +          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
 1.25477 +          if( IS_LOCK_ERROR(rc) ){
 1.25478 +            pFile->lastErrno = tErrno;
 1.25479 +          }
 1.25480 +          goto end_unlock;
 1.25481 +        }
 1.25482 +        lock.l_type = F_UNLCK;
 1.25483 +        lock.l_whence = SEEK_SET;
 1.25484 +        lock.l_start = SHARED_FIRST+divSize;
 1.25485 +        lock.l_len = SHARED_SIZE-divSize;
 1.25486 +        if( unixFileLock(pFile, &lock)==(-1) ){
 1.25487 +          tErrno = errno;
 1.25488 +          rc = SQLITE_IOERR_UNLOCK;
 1.25489 +          if( IS_LOCK_ERROR(rc) ){
 1.25490 +            pFile->lastErrno = tErrno;
 1.25491 +          }
 1.25492 +          goto end_unlock;
 1.25493 +        }
 1.25494 +      }else
 1.25495 +#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
 1.25496 +      {
 1.25497 +        lock.l_type = F_RDLCK;
 1.25498 +        lock.l_whence = SEEK_SET;
 1.25499 +        lock.l_start = SHARED_FIRST;
 1.25500 +        lock.l_len = SHARED_SIZE;
 1.25501 +        if( unixFileLock(pFile, &lock) ){
 1.25502 +          /* In theory, the call to unixFileLock() cannot fail because another
 1.25503 +          ** process is holding an incompatible lock. If it does, this 
 1.25504 +          ** indicates that the other process is not following the locking
 1.25505 +          ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
 1.25506 +          ** SQLITE_BUSY would confuse the upper layer (in practice it causes 
 1.25507 +          ** an assert to fail). */ 
 1.25508 +          rc = SQLITE_IOERR_RDLOCK;
 1.25509 +          pFile->lastErrno = errno;
 1.25510 +          goto end_unlock;
 1.25511 +        }
 1.25512 +      }
 1.25513 +    }
 1.25514 +    lock.l_type = F_UNLCK;
 1.25515 +    lock.l_whence = SEEK_SET;
 1.25516 +    lock.l_start = PENDING_BYTE;
 1.25517 +    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
 1.25518 +    if( unixFileLock(pFile, &lock)==0 ){
 1.25519 +      pInode->eFileLock = SHARED_LOCK;
 1.25520 +    }else{
 1.25521 +      rc = SQLITE_IOERR_UNLOCK;
 1.25522 +      pFile->lastErrno = errno;
 1.25523 +      goto end_unlock;
 1.25524 +    }
 1.25525 +  }
 1.25526 +  if( eFileLock==NO_LOCK ){
 1.25527 +    /* Decrement the shared lock counter.  Release the lock using an
 1.25528 +    ** OS call only when all threads in this same process have released
 1.25529 +    ** the lock.
 1.25530 +    */
 1.25531 +    pInode->nShared--;
 1.25532 +    if( pInode->nShared==0 ){
 1.25533 +      lock.l_type = F_UNLCK;
 1.25534 +      lock.l_whence = SEEK_SET;
 1.25535 +      lock.l_start = lock.l_len = 0L;
 1.25536 +      if( unixFileLock(pFile, &lock)==0 ){
 1.25537 +        pInode->eFileLock = NO_LOCK;
 1.25538 +      }else{
 1.25539 +        rc = SQLITE_IOERR_UNLOCK;
 1.25540 +        pFile->lastErrno = errno;
 1.25541 +        pInode->eFileLock = NO_LOCK;
 1.25542 +        pFile->eFileLock = NO_LOCK;
 1.25543 +      }
 1.25544 +    }
 1.25545 +
 1.25546 +    /* Decrement the count of locks against this same file.  When the
 1.25547 +    ** count reaches zero, close any other file descriptors whose close
 1.25548 +    ** was deferred because of outstanding locks.
 1.25549 +    */
 1.25550 +    pInode->nLock--;
 1.25551 +    assert( pInode->nLock>=0 );
 1.25552 +    if( pInode->nLock==0 ){
 1.25553 +      closePendingFds(pFile);
 1.25554 +    }
 1.25555 +  }
 1.25556 +
 1.25557 +end_unlock:
 1.25558 +  unixLeaveMutex();
 1.25559 +  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
 1.25560 +  return rc;
 1.25561 +}
 1.25562 +
 1.25563 +/*
 1.25564 +** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 1.25565 +** must be either NO_LOCK or SHARED_LOCK.
 1.25566 +**
 1.25567 +** If the locking level of the file descriptor is already at or below
 1.25568 +** the requested locking level, this routine is a no-op.
 1.25569 +*/
 1.25570 +static int unixUnlock(sqlite3_file *id, int eFileLock){
 1.25571 +#if SQLITE_MAX_MMAP_SIZE>0
 1.25572 +  assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
 1.25573 +#endif
 1.25574 +  return posixUnlock(id, eFileLock, 0);
 1.25575 +}
 1.25576 +
 1.25577 +#if SQLITE_MAX_MMAP_SIZE>0
 1.25578 +static int unixMapfile(unixFile *pFd, i64 nByte);
 1.25579 +static void unixUnmapfile(unixFile *pFd);
 1.25580 +#endif
 1.25581 +
 1.25582 +/*
 1.25583 +** This function performs the parts of the "close file" operation 
 1.25584 +** common to all locking schemes. It closes the directory and file
 1.25585 +** handles, if they are valid, and sets all fields of the unixFile
 1.25586 +** structure to 0.
 1.25587 +**
 1.25588 +** It is *not* necessary to hold the mutex when this routine is called,
 1.25589 +** even on VxWorks.  A mutex will be acquired on VxWorks by the
 1.25590 +** vxworksReleaseFileId() routine.
 1.25591 +*/
 1.25592 +static int closeUnixFile(sqlite3_file *id){
 1.25593 +  unixFile *pFile = (unixFile*)id;
 1.25594 +#if SQLITE_MAX_MMAP_SIZE>0
 1.25595 +  unixUnmapfile(pFile);
 1.25596 +#endif
 1.25597 +  if( pFile->h>=0 ){
 1.25598 +    robust_close(pFile, pFile->h, __LINE__);
 1.25599 +    pFile->h = -1;
 1.25600 +  }
 1.25601 +#if OS_VXWORKS
 1.25602 +  if( pFile->pId ){
 1.25603 +    if( pFile->ctrlFlags & UNIXFILE_DELETE ){
 1.25604 +      osUnlink(pFile->pId->zCanonicalName);
 1.25605 +    }
 1.25606 +    vxworksReleaseFileId(pFile->pId);
 1.25607 +    pFile->pId = 0;
 1.25608 +  }
 1.25609 +#endif
 1.25610 +  OSTRACE(("CLOSE   %-3d\n", pFile->h));
 1.25611 +  OpenCounter(-1);
 1.25612 +  sqlite3_free(pFile->pUnused);
 1.25613 +  memset(pFile, 0, sizeof(unixFile));
 1.25614 +  return SQLITE_OK;
 1.25615 +}
 1.25616 +
 1.25617 +/*
 1.25618 +** Close a file.
 1.25619 +*/
 1.25620 +static int unixClose(sqlite3_file *id){
 1.25621 +  int rc = SQLITE_OK;
 1.25622 +  unixFile *pFile = (unixFile *)id;
 1.25623 +  verifyDbFile(pFile);
 1.25624 +  unixUnlock(id, NO_LOCK);
 1.25625 +  unixEnterMutex();
 1.25626 +
 1.25627 +  /* unixFile.pInode is always valid here. Otherwise, a different close
 1.25628 +  ** routine (e.g. nolockClose()) would be called instead.
 1.25629 +  */
 1.25630 +  assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
 1.25631 +  if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
 1.25632 +    /* If there are outstanding locks, do not actually close the file just
 1.25633 +    ** yet because that would clear those locks.  Instead, add the file
 1.25634 +    ** descriptor to pInode->pUnused list.  It will be automatically closed 
 1.25635 +    ** when the last lock is cleared.
 1.25636 +    */
 1.25637 +    setPendingFd(pFile);
 1.25638 +  }
 1.25639 +  releaseInodeInfo(pFile);
 1.25640 +  rc = closeUnixFile(id);
 1.25641 +  unixLeaveMutex();
 1.25642 +  return rc;
 1.25643 +}
 1.25644 +
 1.25645 +/************** End of the posix advisory lock implementation *****************
 1.25646 +******************************************************************************/
 1.25647 +
 1.25648 +/******************************************************************************
 1.25649 +****************************** No-op Locking **********************************
 1.25650 +**
 1.25651 +** Of the various locking implementations available, this is by far the
 1.25652 +** simplest:  locking is ignored.  No attempt is made to lock the database
 1.25653 +** file for reading or writing.
 1.25654 +**
 1.25655 +** This locking mode is appropriate for use on read-only databases
 1.25656 +** (ex: databases that are burned into CD-ROM, for example.)  It can
 1.25657 +** also be used if the application employs some external mechanism to
 1.25658 +** prevent simultaneous access of the same database by two or more
 1.25659 +** database connections.  But there is a serious risk of database
 1.25660 +** corruption if this locking mode is used in situations where multiple
 1.25661 +** database connections are accessing the same database file at the same
 1.25662 +** time and one or more of those connections are writing.
 1.25663 +*/
 1.25664 +
 1.25665 +static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
 1.25666 +  UNUSED_PARAMETER(NotUsed);
 1.25667 +  *pResOut = 0;
 1.25668 +  return SQLITE_OK;
 1.25669 +}
 1.25670 +static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
 1.25671 +  UNUSED_PARAMETER2(NotUsed, NotUsed2);
 1.25672 +  return SQLITE_OK;
 1.25673 +}
 1.25674 +static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
 1.25675 +  UNUSED_PARAMETER2(NotUsed, NotUsed2);
 1.25676 +  return SQLITE_OK;
 1.25677 +}
 1.25678 +
 1.25679 +/*
 1.25680 +** Close the file.
 1.25681 +*/
 1.25682 +static int nolockClose(sqlite3_file *id) {
 1.25683 +  return closeUnixFile(id);
 1.25684 +}
 1.25685 +
 1.25686 +/******************* End of the no-op lock implementation *********************
 1.25687 +******************************************************************************/
 1.25688 +
 1.25689 +/******************************************************************************
 1.25690 +************************* Begin dot-file Locking ******************************
 1.25691 +**
 1.25692 +** The dotfile locking implementation uses the existence of separate lock
 1.25693 +** files (really a directory) to control access to the database.  This works
 1.25694 +** on just about every filesystem imaginable.  But there are serious downsides:
 1.25695 +**
 1.25696 +**    (1)  There is zero concurrency.  A single reader blocks all other
 1.25697 +**         connections from reading or writing the database.
 1.25698 +**
 1.25699 +**    (2)  An application crash or power loss can leave stale lock files
 1.25700 +**         sitting around that need to be cleared manually.
 1.25701 +**
 1.25702 +** Nevertheless, a dotlock is an appropriate locking mode for use if no
 1.25703 +** other locking strategy is available.
 1.25704 +**
 1.25705 +** Dotfile locking works by creating a subdirectory in the same directory as
 1.25706 +** the database and with the same name but with a ".lock" extension added.
 1.25707 +** The existence of a lock directory implies an EXCLUSIVE lock.  All other
 1.25708 +** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
 1.25709 +*/
 1.25710 +
 1.25711 +/*
 1.25712 +** The file suffix added to the data base filename in order to create the
 1.25713 +** lock directory.
 1.25714 +*/
 1.25715 +#define DOTLOCK_SUFFIX ".lock"
 1.25716 +
 1.25717 +/*
 1.25718 +** This routine checks if there is a RESERVED lock held on the specified
 1.25719 +** file by this or any other process. If such a lock is held, set *pResOut
 1.25720 +** to a non-zero value otherwise *pResOut is set to zero.  The return value
 1.25721 +** is set to SQLITE_OK unless an I/O error occurs during lock checking.
 1.25722 +**
 1.25723 +** In dotfile locking, either a lock exists or it does not.  So in this
 1.25724 +** variation of CheckReservedLock(), *pResOut is set to true if any lock
 1.25725 +** is held on the file and false if the file is unlocked.
 1.25726 +*/
 1.25727 +static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
 1.25728 +  int rc = SQLITE_OK;
 1.25729 +  int reserved = 0;
 1.25730 +  unixFile *pFile = (unixFile*)id;
 1.25731 +
 1.25732 +  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
 1.25733 +  
 1.25734 +  assert( pFile );
 1.25735 +
 1.25736 +  /* Check if a thread in this process holds such a lock */
 1.25737 +  if( pFile->eFileLock>SHARED_LOCK ){
 1.25738 +    /* Either this connection or some other connection in the same process
 1.25739 +    ** holds a lock on the file.  No need to check further. */
 1.25740 +    reserved = 1;
 1.25741 +  }else{
 1.25742 +    /* The lock is held if and only if the lockfile exists */
 1.25743 +    const char *zLockFile = (const char*)pFile->lockingContext;
 1.25744 +    reserved = osAccess(zLockFile, 0)==0;
 1.25745 +  }
 1.25746 +  OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
 1.25747 +  *pResOut = reserved;
 1.25748 +  return rc;
 1.25749 +}
 1.25750 +
 1.25751 +/*
 1.25752 +** Lock the file with the lock specified by parameter eFileLock - one
 1.25753 +** of the following:
 1.25754 +**
 1.25755 +**     (1) SHARED_LOCK
 1.25756 +**     (2) RESERVED_LOCK
 1.25757 +**     (3) PENDING_LOCK
 1.25758 +**     (4) EXCLUSIVE_LOCK
 1.25759 +**
 1.25760 +** Sometimes when requesting one lock state, additional lock states
 1.25761 +** are inserted in between.  The locking might fail on one of the later
 1.25762 +** transitions leaving the lock state different from what it started but
 1.25763 +** still short of its goal.  The following chart shows the allowed
 1.25764 +** transitions and the inserted intermediate states:
 1.25765 +**
 1.25766 +**    UNLOCKED -> SHARED
 1.25767 +**    SHARED -> RESERVED
 1.25768 +**    SHARED -> (PENDING) -> EXCLUSIVE
 1.25769 +**    RESERVED -> (PENDING) -> EXCLUSIVE
 1.25770 +**    PENDING -> EXCLUSIVE
 1.25771 +**
 1.25772 +** This routine will only increase a lock.  Use the sqlite3OsUnlock()
 1.25773 +** routine to lower a locking level.
 1.25774 +**
 1.25775 +** With dotfile locking, we really only support state (4): EXCLUSIVE.
 1.25776 +** But we track the other locking levels internally.
 1.25777 +*/
 1.25778 +static int dotlockLock(sqlite3_file *id, int eFileLock) {
 1.25779 +  unixFile *pFile = (unixFile*)id;
 1.25780 +  char *zLockFile = (char *)pFile->lockingContext;
 1.25781 +  int rc = SQLITE_OK;
 1.25782 +
 1.25783 +
 1.25784 +  /* If we have any lock, then the lock file already exists.  All we have
 1.25785 +  ** to do is adjust our internal record of the lock level.
 1.25786 +  */
 1.25787 +  if( pFile->eFileLock > NO_LOCK ){
 1.25788 +    pFile->eFileLock = eFileLock;
 1.25789 +    /* Always update the timestamp on the old file */
 1.25790 +#ifdef HAVE_UTIME
 1.25791 +    utime(zLockFile, NULL);
 1.25792 +#else
 1.25793 +    utimes(zLockFile, NULL);
 1.25794 +#endif
 1.25795 +    return SQLITE_OK;
 1.25796 +  }
 1.25797 +  
 1.25798 +  /* grab an exclusive lock */
 1.25799 +  rc = osMkdir(zLockFile, 0777);
 1.25800 +  if( rc<0 ){
 1.25801 +    /* failed to open/create the lock directory */
 1.25802 +    int tErrno = errno;
 1.25803 +    if( EEXIST == tErrno ){
 1.25804 +      rc = SQLITE_BUSY;
 1.25805 +    } else {
 1.25806 +      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
 1.25807 +      if( IS_LOCK_ERROR(rc) ){
 1.25808 +        pFile->lastErrno = tErrno;
 1.25809 +      }
 1.25810 +    }
 1.25811 +    return rc;
 1.25812 +  } 
 1.25813 +  
 1.25814 +  /* got it, set the type and return ok */
 1.25815 +  pFile->eFileLock = eFileLock;
 1.25816 +  return rc;
 1.25817 +}
 1.25818 +
 1.25819 +/*
 1.25820 +** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 1.25821 +** must be either NO_LOCK or SHARED_LOCK.
 1.25822 +**
 1.25823 +** If the locking level of the file descriptor is already at or below
 1.25824 +** the requested locking level, this routine is a no-op.
 1.25825 +**
 1.25826 +** When the locking level reaches NO_LOCK, delete the lock file.
 1.25827 +*/
 1.25828 +static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
 1.25829 +  unixFile *pFile = (unixFile*)id;
 1.25830 +  char *zLockFile = (char *)pFile->lockingContext;
 1.25831 +  int rc;
 1.25832 +
 1.25833 +  assert( pFile );
 1.25834 +  OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
 1.25835 +           pFile->eFileLock, getpid()));
 1.25836 +  assert( eFileLock<=SHARED_LOCK );
 1.25837 +  
 1.25838 +  /* no-op if possible */
 1.25839 +  if( pFile->eFileLock==eFileLock ){
 1.25840 +    return SQLITE_OK;
 1.25841 +  }
 1.25842 +
 1.25843 +  /* To downgrade to shared, simply update our internal notion of the
 1.25844 +  ** lock state.  No need to mess with the file on disk.
 1.25845 +  */
 1.25846 +  if( eFileLock==SHARED_LOCK ){
 1.25847 +    pFile->eFileLock = SHARED_LOCK;
 1.25848 +    return SQLITE_OK;
 1.25849 +  }
 1.25850 +  
 1.25851 +  /* To fully unlock the database, delete the lock file */
 1.25852 +  assert( eFileLock==NO_LOCK );
 1.25853 +  rc = osRmdir(zLockFile);
 1.25854 +  if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
 1.25855 +  if( rc<0 ){
 1.25856 +    int tErrno = errno;
 1.25857 +    rc = 0;
 1.25858 +    if( ENOENT != tErrno ){
 1.25859 +      rc = SQLITE_IOERR_UNLOCK;
 1.25860 +    }
 1.25861 +    if( IS_LOCK_ERROR(rc) ){
 1.25862 +      pFile->lastErrno = tErrno;
 1.25863 +    }
 1.25864 +    return rc; 
 1.25865 +  }
 1.25866 +  pFile->eFileLock = NO_LOCK;
 1.25867 +  return SQLITE_OK;
 1.25868 +}
 1.25869 +
 1.25870 +/*
 1.25871 +** Close a file.  Make sure the lock has been released before closing.
 1.25872 +*/
 1.25873 +static int dotlockClose(sqlite3_file *id) {
 1.25874 +  int rc = SQLITE_OK;
 1.25875 +  if( id ){
 1.25876 +    unixFile *pFile = (unixFile*)id;
 1.25877 +    dotlockUnlock(id, NO_LOCK);
 1.25878 +    sqlite3_free(pFile->lockingContext);
 1.25879 +    rc = closeUnixFile(id);
 1.25880 +  }
 1.25881 +  return rc;
 1.25882 +}
 1.25883 +/****************** End of the dot-file lock implementation *******************
 1.25884 +******************************************************************************/
 1.25885 +
 1.25886 +/******************************************************************************
 1.25887 +************************** Begin flock Locking ********************************
 1.25888 +**
 1.25889 +** Use the flock() system call to do file locking.
 1.25890 +**
 1.25891 +** flock() locking is like dot-file locking in that the various
 1.25892 +** fine-grain locking levels supported by SQLite are collapsed into
 1.25893 +** a single exclusive lock.  In other words, SHARED, RESERVED, and
 1.25894 +** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
 1.25895 +** still works when you do this, but concurrency is reduced since
 1.25896 +** only a single process can be reading the database at a time.
 1.25897 +**
 1.25898 +** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
 1.25899 +** compiling for VXWORKS.
 1.25900 +*/
 1.25901 +#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
 1.25902 +
 1.25903 +/*
 1.25904 +** Retry flock() calls that fail with EINTR
 1.25905 +*/
 1.25906 +#ifdef EINTR
 1.25907 +static int robust_flock(int fd, int op){
 1.25908 +  int rc;
 1.25909 +  do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
 1.25910 +  return rc;
 1.25911 +}
 1.25912 +#else
 1.25913 +# define robust_flock(a,b) flock(a,b)
 1.25914 +#endif
 1.25915 +     
 1.25916 +
 1.25917 +/*
 1.25918 +** This routine checks if there is a RESERVED lock held on the specified
 1.25919 +** file by this or any other process. If such a lock is held, set *pResOut
 1.25920 +** to a non-zero value otherwise *pResOut is set to zero.  The return value
 1.25921 +** is set to SQLITE_OK unless an I/O error occurs during lock checking.
 1.25922 +*/
 1.25923 +static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
 1.25924 +  int rc = SQLITE_OK;
 1.25925 +  int reserved = 0;
 1.25926 +  unixFile *pFile = (unixFile*)id;
 1.25927 +  
 1.25928 +  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
 1.25929 +  
 1.25930 +  assert( pFile );
 1.25931 +  
 1.25932 +  /* Check if a thread in this process holds such a lock */
 1.25933 +  if( pFile->eFileLock>SHARED_LOCK ){
 1.25934 +    reserved = 1;
 1.25935 +  }
 1.25936 +  
 1.25937 +  /* Otherwise see if some other process holds it. */
 1.25938 +  if( !reserved ){
 1.25939 +    /* attempt to get the lock */
 1.25940 +    int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
 1.25941 +    if( !lrc ){
 1.25942 +      /* got the lock, unlock it */
 1.25943 +      lrc = robust_flock(pFile->h, LOCK_UN);
 1.25944 +      if ( lrc ) {
 1.25945 +        int tErrno = errno;
 1.25946 +        /* unlock failed with an error */
 1.25947 +        lrc = SQLITE_IOERR_UNLOCK; 
 1.25948 +        if( IS_LOCK_ERROR(lrc) ){
 1.25949 +          pFile->lastErrno = tErrno;
 1.25950 +          rc = lrc;
 1.25951 +        }
 1.25952 +      }
 1.25953 +    } else {
 1.25954 +      int tErrno = errno;
 1.25955 +      reserved = 1;
 1.25956 +      /* someone else might have it reserved */
 1.25957 +      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
 1.25958 +      if( IS_LOCK_ERROR(lrc) ){
 1.25959 +        pFile->lastErrno = tErrno;
 1.25960 +        rc = lrc;
 1.25961 +      }
 1.25962 +    }
 1.25963 +  }
 1.25964 +  OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
 1.25965 +
 1.25966 +#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
 1.25967 +  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
 1.25968 +    rc = SQLITE_OK;
 1.25969 +    reserved=1;
 1.25970 +  }
 1.25971 +#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
 1.25972 +  *pResOut = reserved;
 1.25973 +  return rc;
 1.25974 +}
 1.25975 +
 1.25976 +/*
 1.25977 +** Lock the file with the lock specified by parameter eFileLock - one
 1.25978 +** of the following:
 1.25979 +**
 1.25980 +**     (1) SHARED_LOCK
 1.25981 +**     (2) RESERVED_LOCK
 1.25982 +**     (3) PENDING_LOCK
 1.25983 +**     (4) EXCLUSIVE_LOCK
 1.25984 +**
 1.25985 +** Sometimes when requesting one lock state, additional lock states
 1.25986 +** are inserted in between.  The locking might fail on one of the later
 1.25987 +** transitions leaving the lock state different from what it started but
 1.25988 +** still short of its goal.  The following chart shows the allowed
 1.25989 +** transitions and the inserted intermediate states:
 1.25990 +**
 1.25991 +**    UNLOCKED -> SHARED
 1.25992 +**    SHARED -> RESERVED
 1.25993 +**    SHARED -> (PENDING) -> EXCLUSIVE
 1.25994 +**    RESERVED -> (PENDING) -> EXCLUSIVE
 1.25995 +**    PENDING -> EXCLUSIVE
 1.25996 +**
 1.25997 +** flock() only really support EXCLUSIVE locks.  We track intermediate
 1.25998 +** lock states in the sqlite3_file structure, but all locks SHARED or
 1.25999 +** above are really EXCLUSIVE locks and exclude all other processes from
 1.26000 +** access the file.
 1.26001 +**
 1.26002 +** This routine will only increase a lock.  Use the sqlite3OsUnlock()
 1.26003 +** routine to lower a locking level.
 1.26004 +*/
 1.26005 +static int flockLock(sqlite3_file *id, int eFileLock) {
 1.26006 +  int rc = SQLITE_OK;
 1.26007 +  unixFile *pFile = (unixFile*)id;
 1.26008 +
 1.26009 +  assert( pFile );
 1.26010 +
 1.26011 +  /* if we already have a lock, it is exclusive.  
 1.26012 +  ** Just adjust level and punt on outta here. */
 1.26013 +  if (pFile->eFileLock > NO_LOCK) {
 1.26014 +    pFile->eFileLock = eFileLock;
 1.26015 +    return SQLITE_OK;
 1.26016 +  }
 1.26017 +  
 1.26018 +  /* grab an exclusive lock */
 1.26019 +  
 1.26020 +  if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
 1.26021 +    int tErrno = errno;
 1.26022 +    /* didn't get, must be busy */
 1.26023 +    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
 1.26024 +    if( IS_LOCK_ERROR(rc) ){
 1.26025 +      pFile->lastErrno = tErrno;
 1.26026 +    }
 1.26027 +  } else {
 1.26028 +    /* got it, set the type and return ok */
 1.26029 +    pFile->eFileLock = eFileLock;
 1.26030 +  }
 1.26031 +  OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
 1.26032 +           rc==SQLITE_OK ? "ok" : "failed"));
 1.26033 +#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
 1.26034 +  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
 1.26035 +    rc = SQLITE_BUSY;
 1.26036 +  }
 1.26037 +#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
 1.26038 +  return rc;
 1.26039 +}
 1.26040 +
 1.26041 +
 1.26042 +/*
 1.26043 +** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 1.26044 +** must be either NO_LOCK or SHARED_LOCK.
 1.26045 +**
 1.26046 +** If the locking level of the file descriptor is already at or below
 1.26047 +** the requested locking level, this routine is a no-op.
 1.26048 +*/
 1.26049 +static int flockUnlock(sqlite3_file *id, int eFileLock) {
 1.26050 +  unixFile *pFile = (unixFile*)id;
 1.26051 +  
 1.26052 +  assert( pFile );
 1.26053 +  OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
 1.26054 +           pFile->eFileLock, getpid()));
 1.26055 +  assert( eFileLock<=SHARED_LOCK );
 1.26056 +  
 1.26057 +  /* no-op if possible */
 1.26058 +  if( pFile->eFileLock==eFileLock ){
 1.26059 +    return SQLITE_OK;
 1.26060 +  }
 1.26061 +  
 1.26062 +  /* shared can just be set because we always have an exclusive */
 1.26063 +  if (eFileLock==SHARED_LOCK) {
 1.26064 +    pFile->eFileLock = eFileLock;
 1.26065 +    return SQLITE_OK;
 1.26066 +  }
 1.26067 +  
 1.26068 +  /* no, really, unlock. */
 1.26069 +  if( robust_flock(pFile->h, LOCK_UN) ){
 1.26070 +#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
 1.26071 +    return SQLITE_OK;
 1.26072 +#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
 1.26073 +    return SQLITE_IOERR_UNLOCK;
 1.26074 +  }else{
 1.26075 +    pFile->eFileLock = NO_LOCK;
 1.26076 +    return SQLITE_OK;
 1.26077 +  }
 1.26078 +}
 1.26079 +
 1.26080 +/*
 1.26081 +** Close a file.
 1.26082 +*/
 1.26083 +static int flockClose(sqlite3_file *id) {
 1.26084 +  int rc = SQLITE_OK;
 1.26085 +  if( id ){
 1.26086 +    flockUnlock(id, NO_LOCK);
 1.26087 +    rc = closeUnixFile(id);
 1.26088 +  }
 1.26089 +  return rc;
 1.26090 +}
 1.26091 +
 1.26092 +#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
 1.26093 +
 1.26094 +/******************* End of the flock lock implementation *********************
 1.26095 +******************************************************************************/
 1.26096 +
 1.26097 +/******************************************************************************
 1.26098 +************************ Begin Named Semaphore Locking ************************
 1.26099 +**
 1.26100 +** Named semaphore locking is only supported on VxWorks.
 1.26101 +**
 1.26102 +** Semaphore locking is like dot-lock and flock in that it really only
 1.26103 +** supports EXCLUSIVE locking.  Only a single process can read or write
 1.26104 +** the database file at a time.  This reduces potential concurrency, but
 1.26105 +** makes the lock implementation much easier.
 1.26106 +*/
 1.26107 +#if OS_VXWORKS
 1.26108 +
 1.26109 +/*
 1.26110 +** This routine checks if there is a RESERVED lock held on the specified
 1.26111 +** file by this or any other process. If such a lock is held, set *pResOut
 1.26112 +** to a non-zero value otherwise *pResOut is set to zero.  The return value
 1.26113 +** is set to SQLITE_OK unless an I/O error occurs during lock checking.
 1.26114 +*/
 1.26115 +static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
 1.26116 +  int rc = SQLITE_OK;
 1.26117 +  int reserved = 0;
 1.26118 +  unixFile *pFile = (unixFile*)id;
 1.26119 +
 1.26120 +  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
 1.26121 +  
 1.26122 +  assert( pFile );
 1.26123 +
 1.26124 +  /* Check if a thread in this process holds such a lock */
 1.26125 +  if( pFile->eFileLock>SHARED_LOCK ){
 1.26126 +    reserved = 1;
 1.26127 +  }
 1.26128 +  
 1.26129 +  /* Otherwise see if some other process holds it. */
 1.26130 +  if( !reserved ){
 1.26131 +    sem_t *pSem = pFile->pInode->pSem;
 1.26132 +    struct stat statBuf;
 1.26133 +
 1.26134 +    if( sem_trywait(pSem)==-1 ){
 1.26135 +      int tErrno = errno;
 1.26136 +      if( EAGAIN != tErrno ){
 1.26137 +        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
 1.26138 +        pFile->lastErrno = tErrno;
 1.26139 +      } else {
 1.26140 +        /* someone else has the lock when we are in NO_LOCK */
 1.26141 +        reserved = (pFile->eFileLock < SHARED_LOCK);
 1.26142 +      }
 1.26143 +    }else{
 1.26144 +      /* we could have it if we want it */
 1.26145 +      sem_post(pSem);
 1.26146 +    }
 1.26147 +  }
 1.26148 +  OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
 1.26149 +
 1.26150 +  *pResOut = reserved;
 1.26151 +  return rc;
 1.26152 +}
 1.26153 +
 1.26154 +/*
 1.26155 +** Lock the file with the lock specified by parameter eFileLock - one
 1.26156 +** of the following:
 1.26157 +**
 1.26158 +**     (1) SHARED_LOCK
 1.26159 +**     (2) RESERVED_LOCK
 1.26160 +**     (3) PENDING_LOCK
 1.26161 +**     (4) EXCLUSIVE_LOCK
 1.26162 +**
 1.26163 +** Sometimes when requesting one lock state, additional lock states
 1.26164 +** are inserted in between.  The locking might fail on one of the later
 1.26165 +** transitions leaving the lock state different from what it started but
 1.26166 +** still short of its goal.  The following chart shows the allowed
 1.26167 +** transitions and the inserted intermediate states:
 1.26168 +**
 1.26169 +**    UNLOCKED -> SHARED
 1.26170 +**    SHARED -> RESERVED
 1.26171 +**    SHARED -> (PENDING) -> EXCLUSIVE
 1.26172 +**    RESERVED -> (PENDING) -> EXCLUSIVE
 1.26173 +**    PENDING -> EXCLUSIVE
 1.26174 +**
 1.26175 +** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
 1.26176 +** lock states in the sqlite3_file structure, but all locks SHARED or
 1.26177 +** above are really EXCLUSIVE locks and exclude all other processes from
 1.26178 +** access the file.
 1.26179 +**
 1.26180 +** This routine will only increase a lock.  Use the sqlite3OsUnlock()
 1.26181 +** routine to lower a locking level.
 1.26182 +*/
 1.26183 +static int semLock(sqlite3_file *id, int eFileLock) {
 1.26184 +  unixFile *pFile = (unixFile*)id;
 1.26185 +  int fd;
 1.26186 +  sem_t *pSem = pFile->pInode->pSem;
 1.26187 +  int rc = SQLITE_OK;
 1.26188 +
 1.26189 +  /* if we already have a lock, it is exclusive.  
 1.26190 +  ** Just adjust level and punt on outta here. */
 1.26191 +  if (pFile->eFileLock > NO_LOCK) {
 1.26192 +    pFile->eFileLock = eFileLock;
 1.26193 +    rc = SQLITE_OK;
 1.26194 +    goto sem_end_lock;
 1.26195 +  }
 1.26196 +  
 1.26197 +  /* lock semaphore now but bail out when already locked. */
 1.26198 +  if( sem_trywait(pSem)==-1 ){
 1.26199 +    rc = SQLITE_BUSY;
 1.26200 +    goto sem_end_lock;
 1.26201 +  }
 1.26202 +
 1.26203 +  /* got it, set the type and return ok */
 1.26204 +  pFile->eFileLock = eFileLock;
 1.26205 +
 1.26206 + sem_end_lock:
 1.26207 +  return rc;
 1.26208 +}
 1.26209 +
 1.26210 +/*
 1.26211 +** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 1.26212 +** must be either NO_LOCK or SHARED_LOCK.
 1.26213 +**
 1.26214 +** If the locking level of the file descriptor is already at or below
 1.26215 +** the requested locking level, this routine is a no-op.
 1.26216 +*/
 1.26217 +static int semUnlock(sqlite3_file *id, int eFileLock) {
 1.26218 +  unixFile *pFile = (unixFile*)id;
 1.26219 +  sem_t *pSem = pFile->pInode->pSem;
 1.26220 +
 1.26221 +  assert( pFile );
 1.26222 +  assert( pSem );
 1.26223 +  OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
 1.26224 +           pFile->eFileLock, getpid()));
 1.26225 +  assert( eFileLock<=SHARED_LOCK );
 1.26226 +  
 1.26227 +  /* no-op if possible */
 1.26228 +  if( pFile->eFileLock==eFileLock ){
 1.26229 +    return SQLITE_OK;
 1.26230 +  }
 1.26231 +  
 1.26232 +  /* shared can just be set because we always have an exclusive */
 1.26233 +  if (eFileLock==SHARED_LOCK) {
 1.26234 +    pFile->eFileLock = eFileLock;
 1.26235 +    return SQLITE_OK;
 1.26236 +  }
 1.26237 +  
 1.26238 +  /* no, really unlock. */
 1.26239 +  if ( sem_post(pSem)==-1 ) {
 1.26240 +    int rc, tErrno = errno;
 1.26241 +    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
 1.26242 +    if( IS_LOCK_ERROR(rc) ){
 1.26243 +      pFile->lastErrno = tErrno;
 1.26244 +    }
 1.26245 +    return rc; 
 1.26246 +  }
 1.26247 +  pFile->eFileLock = NO_LOCK;
 1.26248 +  return SQLITE_OK;
 1.26249 +}
 1.26250 +
 1.26251 +/*
 1.26252 + ** Close a file.
 1.26253 + */
 1.26254 +static int semClose(sqlite3_file *id) {
 1.26255 +  if( id ){
 1.26256 +    unixFile *pFile = (unixFile*)id;
 1.26257 +    semUnlock(id, NO_LOCK);
 1.26258 +    assert( pFile );
 1.26259 +    unixEnterMutex();
 1.26260 +    releaseInodeInfo(pFile);
 1.26261 +    unixLeaveMutex();
 1.26262 +    closeUnixFile(id);
 1.26263 +  }
 1.26264 +  return SQLITE_OK;
 1.26265 +}
 1.26266 +
 1.26267 +#endif /* OS_VXWORKS */
 1.26268 +/*
 1.26269 +** Named semaphore locking is only available on VxWorks.
 1.26270 +**
 1.26271 +*************** End of the named semaphore lock implementation ****************
 1.26272 +******************************************************************************/
 1.26273 +
 1.26274 +
 1.26275 +/******************************************************************************
 1.26276 +*************************** Begin AFP Locking *********************************
 1.26277 +**
 1.26278 +** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
 1.26279 +** on Apple Macintosh computers - both OS9 and OSX.
 1.26280 +**
 1.26281 +** Third-party implementations of AFP are available.  But this code here
 1.26282 +** only works on OSX.
 1.26283 +*/
 1.26284 +
 1.26285 +#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 1.26286 +/*
 1.26287 +** The afpLockingContext structure contains all afp lock specific state
 1.26288 +*/
 1.26289 +typedef struct afpLockingContext afpLockingContext;
 1.26290 +struct afpLockingContext {
 1.26291 +  int reserved;
 1.26292 +  const char *dbPath;             /* Name of the open file */
 1.26293 +};
 1.26294 +
 1.26295 +struct ByteRangeLockPB2
 1.26296 +{
 1.26297 +  unsigned long long offset;        /* offset to first byte to lock */
 1.26298 +  unsigned long long length;        /* nbr of bytes to lock */
 1.26299 +  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
 1.26300 +  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
 1.26301 +  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
 1.26302 +  int fd;                           /* file desc to assoc this lock with */
 1.26303 +};
 1.26304 +
 1.26305 +#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
 1.26306 +
 1.26307 +/*
 1.26308 +** This is a utility for setting or clearing a bit-range lock on an
 1.26309 +** AFP filesystem.
 1.26310 +** 
 1.26311 +** Return SQLITE_OK on success, SQLITE_BUSY on failure.
 1.26312 +*/
 1.26313 +static int afpSetLock(
 1.26314 +  const char *path,              /* Name of the file to be locked or unlocked */
 1.26315 +  unixFile *pFile,               /* Open file descriptor on path */
 1.26316 +  unsigned long long offset,     /* First byte to be locked */
 1.26317 +  unsigned long long length,     /* Number of bytes to lock */
 1.26318 +  int setLockFlag                /* True to set lock.  False to clear lock */
 1.26319 +){
 1.26320 +  struct ByteRangeLockPB2 pb;
 1.26321 +  int err;
 1.26322 +  
 1.26323 +  pb.unLockFlag = setLockFlag ? 0 : 1;
 1.26324 +  pb.startEndFlag = 0;
 1.26325 +  pb.offset = offset;
 1.26326 +  pb.length = length; 
 1.26327 +  pb.fd = pFile->h;
 1.26328 +  
 1.26329 +  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
 1.26330 +    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
 1.26331 +    offset, length));
 1.26332 +  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
 1.26333 +  if ( err==-1 ) {
 1.26334 +    int rc;
 1.26335 +    int tErrno = errno;
 1.26336 +    OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
 1.26337 +             path, tErrno, strerror(tErrno)));
 1.26338 +#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
 1.26339 +    rc = SQLITE_BUSY;
 1.26340 +#else
 1.26341 +    rc = sqliteErrorFromPosixError(tErrno,
 1.26342 +                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
 1.26343 +#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
 1.26344 +    if( IS_LOCK_ERROR(rc) ){
 1.26345 +      pFile->lastErrno = tErrno;
 1.26346 +    }
 1.26347 +    return rc;
 1.26348 +  } else {
 1.26349 +    return SQLITE_OK;
 1.26350 +  }
 1.26351 +}
 1.26352 +
 1.26353 +/*
 1.26354 +** This routine checks if there is a RESERVED lock held on the specified
 1.26355 +** file by this or any other process. If such a lock is held, set *pResOut
 1.26356 +** to a non-zero value otherwise *pResOut is set to zero.  The return value
 1.26357 +** is set to SQLITE_OK unless an I/O error occurs during lock checking.
 1.26358 +*/
 1.26359 +static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
 1.26360 +  int rc = SQLITE_OK;
 1.26361 +  int reserved = 0;
 1.26362 +  unixFile *pFile = (unixFile*)id;
 1.26363 +  afpLockingContext *context;
 1.26364 +  
 1.26365 +  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
 1.26366 +  
 1.26367 +  assert( pFile );
 1.26368 +  context = (afpLockingContext *) pFile->lockingContext;
 1.26369 +  if( context->reserved ){
 1.26370 +    *pResOut = 1;
 1.26371 +    return SQLITE_OK;
 1.26372 +  }
 1.26373 +  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
 1.26374 +  
 1.26375 +  /* Check if a thread in this process holds such a lock */
 1.26376 +  if( pFile->pInode->eFileLock>SHARED_LOCK ){
 1.26377 +    reserved = 1;
 1.26378 +  }
 1.26379 +  
 1.26380 +  /* Otherwise see if some other process holds it.
 1.26381 +   */
 1.26382 +  if( !reserved ){
 1.26383 +    /* lock the RESERVED byte */
 1.26384 +    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
 1.26385 +    if( SQLITE_OK==lrc ){
 1.26386 +      /* if we succeeded in taking the reserved lock, unlock it to restore
 1.26387 +      ** the original state */
 1.26388 +      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
 1.26389 +    } else {
 1.26390 +      /* if we failed to get the lock then someone else must have it */
 1.26391 +      reserved = 1;
 1.26392 +    }
 1.26393 +    if( IS_LOCK_ERROR(lrc) ){
 1.26394 +      rc=lrc;
 1.26395 +    }
 1.26396 +  }
 1.26397 +  
 1.26398 +  unixLeaveMutex();
 1.26399 +  OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
 1.26400 +  
 1.26401 +  *pResOut = reserved;
 1.26402 +  return rc;
 1.26403 +}
 1.26404 +
 1.26405 +/*
 1.26406 +** Lock the file with the lock specified by parameter eFileLock - one
 1.26407 +** of the following:
 1.26408 +**
 1.26409 +**     (1) SHARED_LOCK
 1.26410 +**     (2) RESERVED_LOCK
 1.26411 +**     (3) PENDING_LOCK
 1.26412 +**     (4) EXCLUSIVE_LOCK
 1.26413 +**
 1.26414 +** Sometimes when requesting one lock state, additional lock states
 1.26415 +** are inserted in between.  The locking might fail on one of the later
 1.26416 +** transitions leaving the lock state different from what it started but
 1.26417 +** still short of its goal.  The following chart shows the allowed
 1.26418 +** transitions and the inserted intermediate states:
 1.26419 +**
 1.26420 +**    UNLOCKED -> SHARED
 1.26421 +**    SHARED -> RESERVED
 1.26422 +**    SHARED -> (PENDING) -> EXCLUSIVE
 1.26423 +**    RESERVED -> (PENDING) -> EXCLUSIVE
 1.26424 +**    PENDING -> EXCLUSIVE
 1.26425 +**
 1.26426 +** This routine will only increase a lock.  Use the sqlite3OsUnlock()
 1.26427 +** routine to lower a locking level.
 1.26428 +*/
 1.26429 +static int afpLock(sqlite3_file *id, int eFileLock){
 1.26430 +  int rc = SQLITE_OK;
 1.26431 +  unixFile *pFile = (unixFile*)id;
 1.26432 +  unixInodeInfo *pInode = pFile->pInode;
 1.26433 +  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
 1.26434 +  
 1.26435 +  assert( pFile );
 1.26436 +  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
 1.26437 +           azFileLock(eFileLock), azFileLock(pFile->eFileLock),
 1.26438 +           azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
 1.26439 +
 1.26440 +  /* If there is already a lock of this type or more restrictive on the
 1.26441 +  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
 1.26442 +  ** unixEnterMutex() hasn't been called yet.
 1.26443 +  */
 1.26444 +  if( pFile->eFileLock>=eFileLock ){
 1.26445 +    OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
 1.26446 +           azFileLock(eFileLock)));
 1.26447 +    return SQLITE_OK;
 1.26448 +  }
 1.26449 +
 1.26450 +  /* Make sure the locking sequence is correct
 1.26451 +  **  (1) We never move from unlocked to anything higher than shared lock.
 1.26452 +  **  (2) SQLite never explicitly requests a pendig lock.
 1.26453 +  **  (3) A shared lock is always held when a reserve lock is requested.
 1.26454 +  */
 1.26455 +  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
 1.26456 +  assert( eFileLock!=PENDING_LOCK );
 1.26457 +  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
 1.26458 +  
 1.26459 +  /* This mutex is needed because pFile->pInode is shared across threads
 1.26460 +  */
 1.26461 +  unixEnterMutex();
 1.26462 +  pInode = pFile->pInode;
 1.26463 +
 1.26464 +  /* If some thread using this PID has a lock via a different unixFile*
 1.26465 +  ** handle that precludes the requested lock, return BUSY.
 1.26466 +  */
 1.26467 +  if( (pFile->eFileLock!=pInode->eFileLock && 
 1.26468 +       (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
 1.26469 +     ){
 1.26470 +    rc = SQLITE_BUSY;
 1.26471 +    goto afp_end_lock;
 1.26472 +  }
 1.26473 +  
 1.26474 +  /* If a SHARED lock is requested, and some thread using this PID already
 1.26475 +  ** has a SHARED or RESERVED lock, then increment reference counts and
 1.26476 +  ** return SQLITE_OK.
 1.26477 +  */
 1.26478 +  if( eFileLock==SHARED_LOCK && 
 1.26479 +     (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
 1.26480 +    assert( eFileLock==SHARED_LOCK );
 1.26481 +    assert( pFile->eFileLock==0 );
 1.26482 +    assert( pInode->nShared>0 );
 1.26483 +    pFile->eFileLock = SHARED_LOCK;
 1.26484 +    pInode->nShared++;
 1.26485 +    pInode->nLock++;
 1.26486 +    goto afp_end_lock;
 1.26487 +  }
 1.26488 +    
 1.26489 +  /* A PENDING lock is needed before acquiring a SHARED lock and before
 1.26490 +  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
 1.26491 +  ** be released.
 1.26492 +  */
 1.26493 +  if( eFileLock==SHARED_LOCK 
 1.26494 +      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
 1.26495 +  ){
 1.26496 +    int failed;
 1.26497 +    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
 1.26498 +    if (failed) {
 1.26499 +      rc = failed;
 1.26500 +      goto afp_end_lock;
 1.26501 +    }
 1.26502 +  }
 1.26503 +  
 1.26504 +  /* If control gets to this point, then actually go ahead and make
 1.26505 +  ** operating system calls for the specified lock.
 1.26506 +  */
 1.26507 +  if( eFileLock==SHARED_LOCK ){
 1.26508 +    int lrc1, lrc2, lrc1Errno = 0;
 1.26509 +    long lk, mask;
 1.26510 +    
 1.26511 +    assert( pInode->nShared==0 );
 1.26512 +    assert( pInode->eFileLock==0 );
 1.26513 +        
 1.26514 +    mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
 1.26515 +    /* Now get the read-lock SHARED_LOCK */
 1.26516 +    /* note that the quality of the randomness doesn't matter that much */
 1.26517 +    lk = random(); 
 1.26518 +    pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
 1.26519 +    lrc1 = afpSetLock(context->dbPath, pFile, 
 1.26520 +          SHARED_FIRST+pInode->sharedByte, 1, 1);
 1.26521 +    if( IS_LOCK_ERROR(lrc1) ){
 1.26522 +      lrc1Errno = pFile->lastErrno;
 1.26523 +    }
 1.26524 +    /* Drop the temporary PENDING lock */
 1.26525 +    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
 1.26526 +    
 1.26527 +    if( IS_LOCK_ERROR(lrc1) ) {
 1.26528 +      pFile->lastErrno = lrc1Errno;
 1.26529 +      rc = lrc1;
 1.26530 +      goto afp_end_lock;
 1.26531 +    } else if( IS_LOCK_ERROR(lrc2) ){
 1.26532 +      rc = lrc2;
 1.26533 +      goto afp_end_lock;
 1.26534 +    } else if( lrc1 != SQLITE_OK ) {
 1.26535 +      rc = lrc1;
 1.26536 +    } else {
 1.26537 +      pFile->eFileLock = SHARED_LOCK;
 1.26538 +      pInode->nLock++;
 1.26539 +      pInode->nShared = 1;
 1.26540 +    }
 1.26541 +  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
 1.26542 +    /* We are trying for an exclusive lock but another thread in this
 1.26543 +     ** same process is still holding a shared lock. */
 1.26544 +    rc = SQLITE_BUSY;
 1.26545 +  }else{
 1.26546 +    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
 1.26547 +    ** assumed that there is a SHARED or greater lock on the file
 1.26548 +    ** already.
 1.26549 +    */
 1.26550 +    int failed = 0;
 1.26551 +    assert( 0!=pFile->eFileLock );
 1.26552 +    if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
 1.26553 +        /* Acquire a RESERVED lock */
 1.26554 +        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
 1.26555 +      if( !failed ){
 1.26556 +        context->reserved = 1;
 1.26557 +      }
 1.26558 +    }
 1.26559 +    if (!failed && eFileLock == EXCLUSIVE_LOCK) {
 1.26560 +      /* Acquire an EXCLUSIVE lock */
 1.26561 +        
 1.26562 +      /* Remove the shared lock before trying the range.  we'll need to 
 1.26563 +      ** reestablish the shared lock if we can't get the  afpUnlock
 1.26564 +      */
 1.26565 +      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
 1.26566 +                         pInode->sharedByte, 1, 0)) ){
 1.26567 +        int failed2 = SQLITE_OK;
 1.26568 +        /* now attemmpt to get the exclusive lock range */
 1.26569 +        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
 1.26570 +                               SHARED_SIZE, 1);
 1.26571 +        if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
 1.26572 +                       SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
 1.26573 +          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
 1.26574 +          ** a critical I/O error
 1.26575 +          */
 1.26576 +          rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
 1.26577 +               SQLITE_IOERR_LOCK;
 1.26578 +          goto afp_end_lock;
 1.26579 +        } 
 1.26580 +      }else{
 1.26581 +        rc = failed; 
 1.26582 +      }
 1.26583 +    }
 1.26584 +    if( failed ){
 1.26585 +      rc = failed;
 1.26586 +    }
 1.26587 +  }
 1.26588 +  
 1.26589 +  if( rc==SQLITE_OK ){
 1.26590 +    pFile->eFileLock = eFileLock;
 1.26591 +    pInode->eFileLock = eFileLock;
 1.26592 +  }else if( eFileLock==EXCLUSIVE_LOCK ){
 1.26593 +    pFile->eFileLock = PENDING_LOCK;
 1.26594 +    pInode->eFileLock = PENDING_LOCK;
 1.26595 +  }
 1.26596 +  
 1.26597 +afp_end_lock:
 1.26598 +  unixLeaveMutex();
 1.26599 +  OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
 1.26600 +         rc==SQLITE_OK ? "ok" : "failed"));
 1.26601 +  return rc;
 1.26602 +}
 1.26603 +
 1.26604 +/*
 1.26605 +** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 1.26606 +** must be either NO_LOCK or SHARED_LOCK.
 1.26607 +**
 1.26608 +** If the locking level of the file descriptor is already at or below
 1.26609 +** the requested locking level, this routine is a no-op.
 1.26610 +*/
 1.26611 +static int afpUnlock(sqlite3_file *id, int eFileLock) {
 1.26612 +  int rc = SQLITE_OK;
 1.26613 +  unixFile *pFile = (unixFile*)id;
 1.26614 +  unixInodeInfo *pInode;
 1.26615 +  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
 1.26616 +  int skipShared = 0;
 1.26617 +#ifdef SQLITE_TEST
 1.26618 +  int h = pFile->h;
 1.26619 +#endif
 1.26620 +
 1.26621 +  assert( pFile );
 1.26622 +  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
 1.26623 +           pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
 1.26624 +           getpid()));
 1.26625 +
 1.26626 +  assert( eFileLock<=SHARED_LOCK );
 1.26627 +  if( pFile->eFileLock<=eFileLock ){
 1.26628 +    return SQLITE_OK;
 1.26629 +  }
 1.26630 +  unixEnterMutex();
 1.26631 +  pInode = pFile->pInode;
 1.26632 +  assert( pInode->nShared!=0 );
 1.26633 +  if( pFile->eFileLock>SHARED_LOCK ){
 1.26634 +    assert( pInode->eFileLock==pFile->eFileLock );
 1.26635 +    SimulateIOErrorBenign(1);
 1.26636 +    SimulateIOError( h=(-1) )
 1.26637 +    SimulateIOErrorBenign(0);
 1.26638 +    
 1.26639 +#ifdef SQLITE_DEBUG
 1.26640 +    /* When reducing a lock such that other processes can start
 1.26641 +    ** reading the database file again, make sure that the
 1.26642 +    ** transaction counter was updated if any part of the database
 1.26643 +    ** file changed.  If the transaction counter is not updated,
 1.26644 +    ** other connections to the same file might not realize that
 1.26645 +    ** the file has changed and hence might not know to flush their
 1.26646 +    ** cache.  The use of a stale cache can lead to database corruption.
 1.26647 +    */
 1.26648 +    assert( pFile->inNormalWrite==0
 1.26649 +           || pFile->dbUpdate==0
 1.26650 +           || pFile->transCntrChng==1 );
 1.26651 +    pFile->inNormalWrite = 0;
 1.26652 +#endif
 1.26653 +    
 1.26654 +    if( pFile->eFileLock==EXCLUSIVE_LOCK ){
 1.26655 +      rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
 1.26656 +      if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
 1.26657 +        /* only re-establish the shared lock if necessary */
 1.26658 +        int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
 1.26659 +        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
 1.26660 +      } else {
 1.26661 +        skipShared = 1;
 1.26662 +      }
 1.26663 +    }
 1.26664 +    if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
 1.26665 +      rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
 1.26666 +    } 
 1.26667 +    if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
 1.26668 +      rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
 1.26669 +      if( !rc ){ 
 1.26670 +        context->reserved = 0; 
 1.26671 +      }
 1.26672 +    }
 1.26673 +    if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
 1.26674 +      pInode->eFileLock = SHARED_LOCK;
 1.26675 +    }
 1.26676 +  }
 1.26677 +  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
 1.26678 +
 1.26679 +    /* Decrement the shared lock counter.  Release the lock using an
 1.26680 +    ** OS call only when all threads in this same process have released
 1.26681 +    ** the lock.
 1.26682 +    */
 1.26683 +    unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
 1.26684 +    pInode->nShared--;
 1.26685 +    if( pInode->nShared==0 ){
 1.26686 +      SimulateIOErrorBenign(1);
 1.26687 +      SimulateIOError( h=(-1) )
 1.26688 +      SimulateIOErrorBenign(0);
 1.26689 +      if( !skipShared ){
 1.26690 +        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
 1.26691 +      }
 1.26692 +      if( !rc ){
 1.26693 +        pInode->eFileLock = NO_LOCK;
 1.26694 +        pFile->eFileLock = NO_LOCK;
 1.26695 +      }
 1.26696 +    }
 1.26697 +    if( rc==SQLITE_OK ){
 1.26698 +      pInode->nLock--;
 1.26699 +      assert( pInode->nLock>=0 );
 1.26700 +      if( pInode->nLock==0 ){
 1.26701 +        closePendingFds(pFile);
 1.26702 +      }
 1.26703 +    }
 1.26704 +  }
 1.26705 +  
 1.26706 +  unixLeaveMutex();
 1.26707 +  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
 1.26708 +  return rc;
 1.26709 +}
 1.26710 +
 1.26711 +/*
 1.26712 +** Close a file & cleanup AFP specific locking context 
 1.26713 +*/
 1.26714 +static int afpClose(sqlite3_file *id) {
 1.26715 +  int rc = SQLITE_OK;
 1.26716 +  if( id ){
 1.26717 +    unixFile *pFile = (unixFile*)id;
 1.26718 +    afpUnlock(id, NO_LOCK);
 1.26719 +    unixEnterMutex();
 1.26720 +    if( pFile->pInode && pFile->pInode->nLock ){
 1.26721 +      /* If there are outstanding locks, do not actually close the file just
 1.26722 +      ** yet because that would clear those locks.  Instead, add the file
 1.26723 +      ** descriptor to pInode->aPending.  It will be automatically closed when
 1.26724 +      ** the last lock is cleared.
 1.26725 +      */
 1.26726 +      setPendingFd(pFile);
 1.26727 +    }
 1.26728 +    releaseInodeInfo(pFile);
 1.26729 +    sqlite3_free(pFile->lockingContext);
 1.26730 +    rc = closeUnixFile(id);
 1.26731 +    unixLeaveMutex();
 1.26732 +  }
 1.26733 +  return rc;
 1.26734 +}
 1.26735 +
 1.26736 +#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
 1.26737 +/*
 1.26738 +** The code above is the AFP lock implementation.  The code is specific
 1.26739 +** to MacOSX and does not work on other unix platforms.  No alternative
 1.26740 +** is available.  If you don't compile for a mac, then the "unix-afp"
 1.26741 +** VFS is not available.
 1.26742 +**
 1.26743 +********************* End of the AFP lock implementation **********************
 1.26744 +******************************************************************************/
 1.26745 +
 1.26746 +/******************************************************************************
 1.26747 +*************************** Begin NFS Locking ********************************/
 1.26748 +
 1.26749 +#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 1.26750 +/*
 1.26751 + ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 1.26752 + ** must be either NO_LOCK or SHARED_LOCK.
 1.26753 + **
 1.26754 + ** If the locking level of the file descriptor is already at or below
 1.26755 + ** the requested locking level, this routine is a no-op.
 1.26756 + */
 1.26757 +static int nfsUnlock(sqlite3_file *id, int eFileLock){
 1.26758 +  return posixUnlock(id, eFileLock, 1);
 1.26759 +}
 1.26760 +
 1.26761 +#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
 1.26762 +/*
 1.26763 +** The code above is the NFS lock implementation.  The code is specific
 1.26764 +** to MacOSX and does not work on other unix platforms.  No alternative
 1.26765 +** is available.  
 1.26766 +**
 1.26767 +********************* End of the NFS lock implementation **********************
 1.26768 +******************************************************************************/
 1.26769 +
 1.26770 +/******************************************************************************
 1.26771 +**************** Non-locking sqlite3_file methods *****************************
 1.26772 +**
 1.26773 +** The next division contains implementations for all methods of the 
 1.26774 +** sqlite3_file object other than the locking methods.  The locking
 1.26775 +** methods were defined in divisions above (one locking method per
 1.26776 +** division).  Those methods that are common to all locking modes
 1.26777 +** are gather together into this division.
 1.26778 +*/
 1.26779 +
 1.26780 +/*
 1.26781 +** Seek to the offset passed as the second argument, then read cnt 
 1.26782 +** bytes into pBuf. Return the number of bytes actually read.
 1.26783 +**
 1.26784 +** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
 1.26785 +** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
 1.26786 +** one system to another.  Since SQLite does not define USE_PREAD
 1.26787 +** any any form by default, we will not attempt to define _XOPEN_SOURCE.
 1.26788 +** See tickets #2741 and #2681.
 1.26789 +**
 1.26790 +** To avoid stomping the errno value on a failed read the lastErrno value
 1.26791 +** is set before returning.
 1.26792 +*/
 1.26793 +static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
 1.26794 +  int got;
 1.26795 +  int prior = 0;
 1.26796 +#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
 1.26797 +  i64 newOffset;
 1.26798 +#endif
 1.26799 +  TIMER_START;
 1.26800 +  assert( cnt==(cnt&0x1ffff) );
 1.26801 +  assert( id->h>2 );
 1.26802 +  cnt &= 0x1ffff;
 1.26803 +  do{
 1.26804 +#if defined(USE_PREAD)
 1.26805 +    got = osPread(id->h, pBuf, cnt, offset);
 1.26806 +    SimulateIOError( got = -1 );
 1.26807 +#elif defined(USE_PREAD64)
 1.26808 +    got = osPread64(id->h, pBuf, cnt, offset);
 1.26809 +    SimulateIOError( got = -1 );
 1.26810 +#else
 1.26811 +    newOffset = lseek(id->h, offset, SEEK_SET);
 1.26812 +    SimulateIOError( newOffset-- );
 1.26813 +    if( newOffset!=offset ){
 1.26814 +      if( newOffset == -1 ){
 1.26815 +        ((unixFile*)id)->lastErrno = errno;
 1.26816 +      }else{
 1.26817 +        ((unixFile*)id)->lastErrno = 0;
 1.26818 +      }
 1.26819 +      return -1;
 1.26820 +    }
 1.26821 +    got = osRead(id->h, pBuf, cnt);
 1.26822 +#endif
 1.26823 +    if( got==cnt ) break;
 1.26824 +    if( got<0 ){
 1.26825 +      if( errno==EINTR ){ got = 1; continue; }
 1.26826 +      prior = 0;
 1.26827 +      ((unixFile*)id)->lastErrno = errno;
 1.26828 +      break;
 1.26829 +    }else if( got>0 ){
 1.26830 +      cnt -= got;
 1.26831 +      offset += got;
 1.26832 +      prior += got;
 1.26833 +      pBuf = (void*)(got + (char*)pBuf);
 1.26834 +    }
 1.26835 +  }while( got>0 );
 1.26836 +  TIMER_END;
 1.26837 +  OSTRACE(("READ    %-3d %5d %7lld %llu\n",
 1.26838 +            id->h, got+prior, offset-prior, TIMER_ELAPSED));
 1.26839 +  return got+prior;
 1.26840 +}
 1.26841 +
 1.26842 +/*
 1.26843 +** Read data from a file into a buffer.  Return SQLITE_OK if all
 1.26844 +** bytes were read successfully and SQLITE_IOERR if anything goes
 1.26845 +** wrong.
 1.26846 +*/
 1.26847 +static int unixRead(
 1.26848 +  sqlite3_file *id, 
 1.26849 +  void *pBuf, 
 1.26850 +  int amt,
 1.26851 +  sqlite3_int64 offset
 1.26852 +){
 1.26853 +  unixFile *pFile = (unixFile *)id;
 1.26854 +  int got;
 1.26855 +  assert( id );
 1.26856 +  assert( offset>=0 );
 1.26857 +  assert( amt>0 );
 1.26858 +
 1.26859 +  /* If this is a database file (not a journal, master-journal or temp
 1.26860 +  ** file), the bytes in the locking range should never be read or written. */
 1.26861 +#if 0
 1.26862 +  assert( pFile->pUnused==0
 1.26863 +       || offset>=PENDING_BYTE+512
 1.26864 +       || offset+amt<=PENDING_BYTE 
 1.26865 +  );
 1.26866 +#endif
 1.26867 +
 1.26868 +#if SQLITE_MAX_MMAP_SIZE>0
 1.26869 +  /* Deal with as much of this read request as possible by transfering
 1.26870 +  ** data from the memory mapping using memcpy().  */
 1.26871 +  if( offset<pFile->mmapSize ){
 1.26872 +    if( offset+amt <= pFile->mmapSize ){
 1.26873 +      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
 1.26874 +      return SQLITE_OK;
 1.26875 +    }else{
 1.26876 +      int nCopy = pFile->mmapSize - offset;
 1.26877 +      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
 1.26878 +      pBuf = &((u8 *)pBuf)[nCopy];
 1.26879 +      amt -= nCopy;
 1.26880 +      offset += nCopy;
 1.26881 +    }
 1.26882 +  }
 1.26883 +#endif
 1.26884 +
 1.26885 +  got = seekAndRead(pFile, offset, pBuf, amt);
 1.26886 +  if( got==amt ){
 1.26887 +    return SQLITE_OK;
 1.26888 +  }else if( got<0 ){
 1.26889 +    /* lastErrno set by seekAndRead */
 1.26890 +    return SQLITE_IOERR_READ;
 1.26891 +  }else{
 1.26892 +    pFile->lastErrno = 0; /* not a system error */
 1.26893 +    /* Unread parts of the buffer must be zero-filled */
 1.26894 +    memset(&((char*)pBuf)[got], 0, amt-got);
 1.26895 +    return SQLITE_IOERR_SHORT_READ;
 1.26896 +  }
 1.26897 +}
 1.26898 +
 1.26899 +/*
 1.26900 +** Attempt to seek the file-descriptor passed as the first argument to
 1.26901 +** absolute offset iOff, then attempt to write nBuf bytes of data from
 1.26902 +** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise, 
 1.26903 +** return the actual number of bytes written (which may be less than
 1.26904 +** nBuf).
 1.26905 +*/
 1.26906 +static int seekAndWriteFd(
 1.26907 +  int fd,                         /* File descriptor to write to */
 1.26908 +  i64 iOff,                       /* File offset to begin writing at */
 1.26909 +  const void *pBuf,               /* Copy data from this buffer to the file */
 1.26910 +  int nBuf,                       /* Size of buffer pBuf in bytes */
 1.26911 +  int *piErrno                    /* OUT: Error number if error occurs */
 1.26912 +){
 1.26913 +  int rc = 0;                     /* Value returned by system call */
 1.26914 +
 1.26915 +  assert( nBuf==(nBuf&0x1ffff) );
 1.26916 +  assert( fd>2 );
 1.26917 +  nBuf &= 0x1ffff;
 1.26918 +  TIMER_START;
 1.26919 +
 1.26920 +#if defined(USE_PREAD)
 1.26921 +  do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
 1.26922 +#elif defined(USE_PREAD64)
 1.26923 +  do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
 1.26924 +#else
 1.26925 +  do{
 1.26926 +    i64 iSeek = lseek(fd, iOff, SEEK_SET);
 1.26927 +    SimulateIOError( iSeek-- );
 1.26928 +
 1.26929 +    if( iSeek!=iOff ){
 1.26930 +      if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
 1.26931 +      return -1;
 1.26932 +    }
 1.26933 +    rc = osWrite(fd, pBuf, nBuf);
 1.26934 +  }while( rc<0 && errno==EINTR );
 1.26935 +#endif
 1.26936 +
 1.26937 +  TIMER_END;
 1.26938 +  OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
 1.26939 +
 1.26940 +  if( rc<0 && piErrno ) *piErrno = errno;
 1.26941 +  return rc;
 1.26942 +}
 1.26943 +
 1.26944 +
 1.26945 +/*
 1.26946 +** Seek to the offset in id->offset then read cnt bytes into pBuf.
 1.26947 +** Return the number of bytes actually read.  Update the offset.
 1.26948 +**
 1.26949 +** To avoid stomping the errno value on a failed write the lastErrno value
 1.26950 +** is set before returning.
 1.26951 +*/
 1.26952 +static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
 1.26953 +  return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
 1.26954 +}
 1.26955 +
 1.26956 +
 1.26957 +/*
 1.26958 +** Write data from a buffer into a file.  Return SQLITE_OK on success
 1.26959 +** or some other error code on failure.
 1.26960 +*/
 1.26961 +static int unixWrite(
 1.26962 +  sqlite3_file *id, 
 1.26963 +  const void *pBuf, 
 1.26964 +  int amt,
 1.26965 +  sqlite3_int64 offset 
 1.26966 +){
 1.26967 +  unixFile *pFile = (unixFile*)id;
 1.26968 +  int wrote = 0;
 1.26969 +  assert( id );
 1.26970 +  assert( amt>0 );
 1.26971 +
 1.26972 +  /* If this is a database file (not a journal, master-journal or temp
 1.26973 +  ** file), the bytes in the locking range should never be read or written. */
 1.26974 +#if 0
 1.26975 +  assert( pFile->pUnused==0
 1.26976 +       || offset>=PENDING_BYTE+512
 1.26977 +       || offset+amt<=PENDING_BYTE 
 1.26978 +  );
 1.26979 +#endif
 1.26980 +
 1.26981 +#ifdef SQLITE_DEBUG
 1.26982 +  /* If we are doing a normal write to a database file (as opposed to
 1.26983 +  ** doing a hot-journal rollback or a write to some file other than a
 1.26984 +  ** normal database file) then record the fact that the database
 1.26985 +  ** has changed.  If the transaction counter is modified, record that
 1.26986 +  ** fact too.
 1.26987 +  */
 1.26988 +  if( pFile->inNormalWrite ){
 1.26989 +    pFile->dbUpdate = 1;  /* The database has been modified */
 1.26990 +    if( offset<=24 && offset+amt>=27 ){
 1.26991 +      int rc;
 1.26992 +      char oldCntr[4];
 1.26993 +      SimulateIOErrorBenign(1);
 1.26994 +      rc = seekAndRead(pFile, 24, oldCntr, 4);
 1.26995 +      SimulateIOErrorBenign(0);
 1.26996 +      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
 1.26997 +        pFile->transCntrChng = 1;  /* The transaction counter has changed */
 1.26998 +      }
 1.26999 +    }
 1.27000 +  }
 1.27001 +#endif
 1.27002 +
 1.27003 +#if SQLITE_MAX_MMAP_SIZE>0
 1.27004 +  /* Deal with as much of this write request as possible by transfering
 1.27005 +  ** data from the memory mapping using memcpy().  */
 1.27006 +  if( offset<pFile->mmapSize ){
 1.27007 +    if( offset+amt <= pFile->mmapSize ){
 1.27008 +      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
 1.27009 +      return SQLITE_OK;
 1.27010 +    }else{
 1.27011 +      int nCopy = pFile->mmapSize - offset;
 1.27012 +      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
 1.27013 +      pBuf = &((u8 *)pBuf)[nCopy];
 1.27014 +      amt -= nCopy;
 1.27015 +      offset += nCopy;
 1.27016 +    }
 1.27017 +  }
 1.27018 +#endif
 1.27019 +
 1.27020 +  while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
 1.27021 +    amt -= wrote;
 1.27022 +    offset += wrote;
 1.27023 +    pBuf = &((char*)pBuf)[wrote];
 1.27024 +  }
 1.27025 +  SimulateIOError(( wrote=(-1), amt=1 ));
 1.27026 +  SimulateDiskfullError(( wrote=0, amt=1 ));
 1.27027 +
 1.27028 +  if( amt>0 ){
 1.27029 +    if( wrote<0 && pFile->lastErrno!=ENOSPC ){
 1.27030 +      /* lastErrno set by seekAndWrite */
 1.27031 +      return SQLITE_IOERR_WRITE;
 1.27032 +    }else{
 1.27033 +      pFile->lastErrno = 0; /* not a system error */
 1.27034 +      return SQLITE_FULL;
 1.27035 +    }
 1.27036 +  }
 1.27037 +
 1.27038 +  return SQLITE_OK;
 1.27039 +}
 1.27040 +
 1.27041 +#ifdef SQLITE_TEST
 1.27042 +/*
 1.27043 +** Count the number of fullsyncs and normal syncs.  This is used to test
 1.27044 +** that syncs and fullsyncs are occurring at the right times.
 1.27045 +*/
 1.27046 +SQLITE_API int sqlite3_sync_count = 0;
 1.27047 +SQLITE_API int sqlite3_fullsync_count = 0;
 1.27048 +#endif
 1.27049 +
 1.27050 +/*
 1.27051 +** We do not trust systems to provide a working fdatasync().  Some do.
 1.27052 +** Others do no.  To be safe, we will stick with the (slightly slower)
 1.27053 +** fsync(). If you know that your system does support fdatasync() correctly,
 1.27054 +** then simply compile with -Dfdatasync=fdatasync
 1.27055 +*/
 1.27056 +#if !defined(fdatasync)
 1.27057 +# define fdatasync fsync
 1.27058 +#endif
 1.27059 +
 1.27060 +/*
 1.27061 +** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
 1.27062 +** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
 1.27063 +** only available on Mac OS X.  But that could change.
 1.27064 +*/
 1.27065 +#ifdef F_FULLFSYNC
 1.27066 +# define HAVE_FULLFSYNC 1
 1.27067 +#else
 1.27068 +# define HAVE_FULLFSYNC 0
 1.27069 +#endif
 1.27070 +
 1.27071 +
 1.27072 +/*
 1.27073 +** The fsync() system call does not work as advertised on many
 1.27074 +** unix systems.  The following procedure is an attempt to make
 1.27075 +** it work better.
 1.27076 +**
 1.27077 +** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
 1.27078 +** for testing when we want to run through the test suite quickly.
 1.27079 +** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
 1.27080 +** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
 1.27081 +** or power failure will likely corrupt the database file.
 1.27082 +**
 1.27083 +** SQLite sets the dataOnly flag if the size of the file is unchanged.
 1.27084 +** The idea behind dataOnly is that it should only write the file content
 1.27085 +** to disk, not the inode.  We only set dataOnly if the file size is 
 1.27086 +** unchanged since the file size is part of the inode.  However, 
 1.27087 +** Ted Ts'o tells us that fdatasync() will also write the inode if the
 1.27088 +** file size has changed.  The only real difference between fdatasync()
 1.27089 +** and fsync(), Ted tells us, is that fdatasync() will not flush the
 1.27090 +** inode if the mtime or owner or other inode attributes have changed.
 1.27091 +** We only care about the file size, not the other file attributes, so
 1.27092 +** as far as SQLite is concerned, an fdatasync() is always adequate.
 1.27093 +** So, we always use fdatasync() if it is available, regardless of
 1.27094 +** the value of the dataOnly flag.
 1.27095 +*/
 1.27096 +static int full_fsync(int fd, int fullSync, int dataOnly){
 1.27097 +  int rc;
 1.27098 +
 1.27099 +  /* The following "ifdef/elif/else/" block has the same structure as
 1.27100 +  ** the one below. It is replicated here solely to avoid cluttering 
 1.27101 +  ** up the real code with the UNUSED_PARAMETER() macros.
 1.27102 +  */
 1.27103 +#ifdef SQLITE_NO_SYNC
 1.27104 +  UNUSED_PARAMETER(fd);
 1.27105 +  UNUSED_PARAMETER(fullSync);
 1.27106 +  UNUSED_PARAMETER(dataOnly);
 1.27107 +#elif HAVE_FULLFSYNC
 1.27108 +  UNUSED_PARAMETER(dataOnly);
 1.27109 +#else
 1.27110 +  UNUSED_PARAMETER(fullSync);
 1.27111 +  UNUSED_PARAMETER(dataOnly);
 1.27112 +#endif
 1.27113 +
 1.27114 +  /* Record the number of times that we do a normal fsync() and 
 1.27115 +  ** FULLSYNC.  This is used during testing to verify that this procedure
 1.27116 +  ** gets called with the correct arguments.
 1.27117 +  */
 1.27118 +#ifdef SQLITE_TEST
 1.27119 +  if( fullSync ) sqlite3_fullsync_count++;
 1.27120 +  sqlite3_sync_count++;
 1.27121 +#endif
 1.27122 +
 1.27123 +  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
 1.27124 +  ** no-op
 1.27125 +  */
 1.27126 +#ifdef SQLITE_NO_SYNC
 1.27127 +  rc = SQLITE_OK;
 1.27128 +#elif HAVE_FULLFSYNC
 1.27129 +  if( fullSync ){
 1.27130 +    rc = osFcntl(fd, F_FULLFSYNC, 0);
 1.27131 +  }else{
 1.27132 +    rc = 1;
 1.27133 +  }
 1.27134 +  /* If the FULLFSYNC failed, fall back to attempting an fsync().
 1.27135 +  ** It shouldn't be possible for fullfsync to fail on the local 
 1.27136 +  ** file system (on OSX), so failure indicates that FULLFSYNC
 1.27137 +  ** isn't supported for this file system. So, attempt an fsync 
 1.27138 +  ** and (for now) ignore the overhead of a superfluous fcntl call.  
 1.27139 +  ** It'd be better to detect fullfsync support once and avoid 
 1.27140 +  ** the fcntl call every time sync is called.
 1.27141 +  */
 1.27142 +  if( rc ) rc = fsync(fd);
 1.27143 +
 1.27144 +#elif defined(__APPLE__)
 1.27145 +  /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
 1.27146 +  ** so currently we default to the macro that redefines fdatasync to fsync
 1.27147 +  */
 1.27148 +  rc = fsync(fd);
 1.27149 +#else 
 1.27150 +  rc = fdatasync(fd);
 1.27151 +#if OS_VXWORKS
 1.27152 +  if( rc==-1 && errno==ENOTSUP ){
 1.27153 +    rc = fsync(fd);
 1.27154 +  }
 1.27155 +#endif /* OS_VXWORKS */
 1.27156 +#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
 1.27157 +
 1.27158 +  if( OS_VXWORKS && rc!= -1 ){
 1.27159 +    rc = 0;
 1.27160 +  }
 1.27161 +  return rc;
 1.27162 +}
 1.27163 +
 1.27164 +/*
 1.27165 +** Open a file descriptor to the directory containing file zFilename.
 1.27166 +** If successful, *pFd is set to the opened file descriptor and
 1.27167 +** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
 1.27168 +** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
 1.27169 +** value.
 1.27170 +**
 1.27171 +** The directory file descriptor is used for only one thing - to
 1.27172 +** fsync() a directory to make sure file creation and deletion events
 1.27173 +** are flushed to disk.  Such fsyncs are not needed on newer
 1.27174 +** journaling filesystems, but are required on older filesystems.
 1.27175 +**
 1.27176 +** This routine can be overridden using the xSetSysCall interface.
 1.27177 +** The ability to override this routine was added in support of the
 1.27178 +** chromium sandbox.  Opening a directory is a security risk (we are
 1.27179 +** told) so making it overrideable allows the chromium sandbox to
 1.27180 +** replace this routine with a harmless no-op.  To make this routine
 1.27181 +** a no-op, replace it with a stub that returns SQLITE_OK but leaves
 1.27182 +** *pFd set to a negative number.
 1.27183 +**
 1.27184 +** If SQLITE_OK is returned, the caller is responsible for closing
 1.27185 +** the file descriptor *pFd using close().
 1.27186 +*/
 1.27187 +static int openDirectory(const char *zFilename, int *pFd){
 1.27188 +  int ii;
 1.27189 +  int fd = -1;
 1.27190 +  char zDirname[MAX_PATHNAME+1];
 1.27191 +
 1.27192 +  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
 1.27193 +  for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
 1.27194 +  if( ii>0 ){
 1.27195 +    zDirname[ii] = '\0';
 1.27196 +    fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
 1.27197 +    if( fd>=0 ){
 1.27198 +      OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
 1.27199 +    }
 1.27200 +  }
 1.27201 +  *pFd = fd;
 1.27202 +  return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
 1.27203 +}
 1.27204 +
 1.27205 +/*
 1.27206 +** Make sure all writes to a particular file are committed to disk.
 1.27207 +**
 1.27208 +** If dataOnly==0 then both the file itself and its metadata (file
 1.27209 +** size, access time, etc) are synced.  If dataOnly!=0 then only the
 1.27210 +** file data is synced.
 1.27211 +**
 1.27212 +** Under Unix, also make sure that the directory entry for the file
 1.27213 +** has been created by fsync-ing the directory that contains the file.
 1.27214 +** If we do not do this and we encounter a power failure, the directory
 1.27215 +** entry for the journal might not exist after we reboot.  The next
 1.27216 +** SQLite to access the file will not know that the journal exists (because
 1.27217 +** the directory entry for the journal was never created) and the transaction
 1.27218 +** will not roll back - possibly leading to database corruption.
 1.27219 +*/
 1.27220 +static int unixSync(sqlite3_file *id, int flags){
 1.27221 +  int rc;
 1.27222 +  unixFile *pFile = (unixFile*)id;
 1.27223 +
 1.27224 +  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
 1.27225 +  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
 1.27226 +
 1.27227 +  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
 1.27228 +  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
 1.27229 +      || (flags&0x0F)==SQLITE_SYNC_FULL
 1.27230 +  );
 1.27231 +
 1.27232 +  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
 1.27233 +  ** line is to test that doing so does not cause any problems.
 1.27234 +  */
 1.27235 +  SimulateDiskfullError( return SQLITE_FULL );
 1.27236 +
 1.27237 +  assert( pFile );
 1.27238 +  OSTRACE(("SYNC    %-3d\n", pFile->h));
 1.27239 +  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
 1.27240 +  SimulateIOError( rc=1 );
 1.27241 +  if( rc ){
 1.27242 +    pFile->lastErrno = errno;
 1.27243 +    return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
 1.27244 +  }
 1.27245 +
 1.27246 +  /* Also fsync the directory containing the file if the DIRSYNC flag
 1.27247 +  ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
 1.27248 +  ** are unable to fsync a directory, so ignore errors on the fsync.
 1.27249 +  */
 1.27250 +  if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
 1.27251 +    int dirfd;
 1.27252 +    OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
 1.27253 +            HAVE_FULLFSYNC, isFullsync));
 1.27254 +    rc = osOpenDirectory(pFile->zPath, &dirfd);
 1.27255 +    if( rc==SQLITE_OK && dirfd>=0 ){
 1.27256 +      full_fsync(dirfd, 0, 0);
 1.27257 +      robust_close(pFile, dirfd, __LINE__);
 1.27258 +    }else if( rc==SQLITE_CANTOPEN ){
 1.27259 +      rc = SQLITE_OK;
 1.27260 +    }
 1.27261 +    pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
 1.27262 +  }
 1.27263 +  return rc;
 1.27264 +}
 1.27265 +
 1.27266 +/*
 1.27267 +** Truncate an open file to a specified size
 1.27268 +*/
 1.27269 +static int unixTruncate(sqlite3_file *id, i64 nByte){
 1.27270 +  unixFile *pFile = (unixFile *)id;
 1.27271 +  int rc;
 1.27272 +  assert( pFile );
 1.27273 +  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
 1.27274 +
 1.27275 +  /* If the user has configured a chunk-size for this file, truncate the
 1.27276 +  ** file so that it consists of an integer number of chunks (i.e. the
 1.27277 +  ** actual file size after the operation may be larger than the requested
 1.27278 +  ** size).
 1.27279 +  */
 1.27280 +  if( pFile->szChunk>0 ){
 1.27281 +    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
 1.27282 +  }
 1.27283 +
 1.27284 +  rc = robust_ftruncate(pFile->h, (off_t)nByte);
 1.27285 +  if( rc ){
 1.27286 +    pFile->lastErrno = errno;
 1.27287 +    return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
 1.27288 +  }else{
 1.27289 +#ifdef SQLITE_DEBUG
 1.27290 +    /* If we are doing a normal write to a database file (as opposed to
 1.27291 +    ** doing a hot-journal rollback or a write to some file other than a
 1.27292 +    ** normal database file) and we truncate the file to zero length,
 1.27293 +    ** that effectively updates the change counter.  This might happen
 1.27294 +    ** when restoring a database using the backup API from a zero-length
 1.27295 +    ** source.
 1.27296 +    */
 1.27297 +    if( pFile->inNormalWrite && nByte==0 ){
 1.27298 +      pFile->transCntrChng = 1;
 1.27299 +    }
 1.27300 +#endif
 1.27301 +
 1.27302 +#if SQLITE_MAX_MMAP_SIZE>0
 1.27303 +    /* If the file was just truncated to a size smaller than the currently
 1.27304 +    ** mapped region, reduce the effective mapping size as well. SQLite will
 1.27305 +    ** use read() and write() to access data beyond this point from now on.  
 1.27306 +    */
 1.27307 +    if( nByte<pFile->mmapSize ){
 1.27308 +      pFile->mmapSize = nByte;
 1.27309 +    }
 1.27310 +#endif
 1.27311 +
 1.27312 +    return SQLITE_OK;
 1.27313 +  }
 1.27314 +}
 1.27315 +
 1.27316 +/*
 1.27317 +** Determine the current size of a file in bytes
 1.27318 +*/
 1.27319 +static int unixFileSize(sqlite3_file *id, i64 *pSize){
 1.27320 +  int rc;
 1.27321 +  struct stat buf;
 1.27322 +  assert( id );
 1.27323 +  rc = osFstat(((unixFile*)id)->h, &buf);
 1.27324 +  SimulateIOError( rc=1 );
 1.27325 +  if( rc!=0 ){
 1.27326 +    ((unixFile*)id)->lastErrno = errno;
 1.27327 +    return SQLITE_IOERR_FSTAT;
 1.27328 +  }
 1.27329 +  *pSize = buf.st_size;
 1.27330 +
 1.27331 +  /* When opening a zero-size database, the findInodeInfo() procedure
 1.27332 +  ** writes a single byte into that file in order to work around a bug
 1.27333 +  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
 1.27334 +  ** layers, we need to report this file size as zero even though it is
 1.27335 +  ** really 1.   Ticket #3260.
 1.27336 +  */
 1.27337 +  if( *pSize==1 ) *pSize = 0;
 1.27338 +
 1.27339 +
 1.27340 +  return SQLITE_OK;
 1.27341 +}
 1.27342 +
 1.27343 +#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
 1.27344 +/*
 1.27345 +** Handler for proxy-locking file-control verbs.  Defined below in the
 1.27346 +** proxying locking division.
 1.27347 +*/
 1.27348 +static int proxyFileControl(sqlite3_file*,int,void*);
 1.27349 +#endif
 1.27350 +
 1.27351 +/* 
 1.27352 +** This function is called to handle the SQLITE_FCNTL_SIZE_HINT 
 1.27353 +** file-control operation.  Enlarge the database to nBytes in size
 1.27354 +** (rounded up to the next chunk-size).  If the database is already
 1.27355 +** nBytes or larger, this routine is a no-op.
 1.27356 +*/
 1.27357 +static int fcntlSizeHint(unixFile *pFile, i64 nByte){
 1.27358 +  if( pFile->szChunk>0 ){
 1.27359 +    i64 nSize;                    /* Required file size */
 1.27360 +    struct stat buf;              /* Used to hold return values of fstat() */
 1.27361 +   
 1.27362 +    if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
 1.27363 +
 1.27364 +    nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
 1.27365 +    if( nSize>(i64)buf.st_size ){
 1.27366 +
 1.27367 +#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
 1.27368 +      /* The code below is handling the return value of osFallocate() 
 1.27369 +      ** correctly. posix_fallocate() is defined to "returns zero on success, 
 1.27370 +      ** or an error number on  failure". See the manpage for details. */
 1.27371 +      int err;
 1.27372 +      do{
 1.27373 +        err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
 1.27374 +      }while( err==EINTR );
 1.27375 +      if( err ) return SQLITE_IOERR_WRITE;
 1.27376 +#else
 1.27377 +      /* If the OS does not have posix_fallocate(), fake it. First use
 1.27378 +      ** ftruncate() to set the file size, then write a single byte to
 1.27379 +      ** the last byte in each block within the extended region. This
 1.27380 +      ** is the same technique used by glibc to implement posix_fallocate()
 1.27381 +      ** on systems that do not have a real fallocate() system call.
 1.27382 +      */
 1.27383 +      int nBlk = buf.st_blksize;  /* File-system block size */
 1.27384 +      i64 iWrite;                 /* Next offset to write to */
 1.27385 +
 1.27386 +      if( robust_ftruncate(pFile->h, nSize) ){
 1.27387 +        pFile->lastErrno = errno;
 1.27388 +        return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
 1.27389 +      }
 1.27390 +      iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
 1.27391 +      while( iWrite<nSize ){
 1.27392 +        int nWrite = seekAndWrite(pFile, iWrite, "", 1);
 1.27393 +        if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
 1.27394 +        iWrite += nBlk;
 1.27395 +      }
 1.27396 +#endif
 1.27397 +    }
 1.27398 +  }
 1.27399 +
 1.27400 +#if SQLITE_MAX_MMAP_SIZE>0
 1.27401 +  if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
 1.27402 +    int rc;
 1.27403 +    if( pFile->szChunk<=0 ){
 1.27404 +      if( robust_ftruncate(pFile->h, nByte) ){
 1.27405 +        pFile->lastErrno = errno;
 1.27406 +        return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
 1.27407 +      }
 1.27408 +    }
 1.27409 +
 1.27410 +    rc = unixMapfile(pFile, nByte);
 1.27411 +    return rc;
 1.27412 +  }
 1.27413 +#endif
 1.27414 +
 1.27415 +  return SQLITE_OK;
 1.27416 +}
 1.27417 +
 1.27418 +/*
 1.27419 +** If *pArg is inititially negative then this is a query.  Set *pArg to
 1.27420 +** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
 1.27421 +**
 1.27422 +** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
 1.27423 +*/
 1.27424 +static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
 1.27425 +  if( *pArg<0 ){
 1.27426 +    *pArg = (pFile->ctrlFlags & mask)!=0;
 1.27427 +  }else if( (*pArg)==0 ){
 1.27428 +    pFile->ctrlFlags &= ~mask;
 1.27429 +  }else{
 1.27430 +    pFile->ctrlFlags |= mask;
 1.27431 +  }
 1.27432 +}
 1.27433 +
 1.27434 +/* Forward declaration */
 1.27435 +static int unixGetTempname(int nBuf, char *zBuf);
 1.27436 +
 1.27437 +/*
 1.27438 +** Information and control of an open file handle.
 1.27439 +*/
 1.27440 +static int unixFileControl(sqlite3_file *id, int op, void *pArg){
 1.27441 +  unixFile *pFile = (unixFile*)id;
 1.27442 +  switch( op ){
 1.27443 +    case SQLITE_FCNTL_LOCKSTATE: {
 1.27444 +      *(int*)pArg = pFile->eFileLock;
 1.27445 +      return SQLITE_OK;
 1.27446 +    }
 1.27447 +    case SQLITE_LAST_ERRNO: {
 1.27448 +      *(int*)pArg = pFile->lastErrno;
 1.27449 +      return SQLITE_OK;
 1.27450 +    }
 1.27451 +    case SQLITE_FCNTL_CHUNK_SIZE: {
 1.27452 +      pFile->szChunk = *(int *)pArg;
 1.27453 +      return SQLITE_OK;
 1.27454 +    }
 1.27455 +    case SQLITE_FCNTL_SIZE_HINT: {
 1.27456 +      int rc;
 1.27457 +      SimulateIOErrorBenign(1);
 1.27458 +      rc = fcntlSizeHint(pFile, *(i64 *)pArg);
 1.27459 +      SimulateIOErrorBenign(0);
 1.27460 +      return rc;
 1.27461 +    }
 1.27462 +    case SQLITE_FCNTL_PERSIST_WAL: {
 1.27463 +      unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
 1.27464 +      return SQLITE_OK;
 1.27465 +    }
 1.27466 +    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
 1.27467 +      unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
 1.27468 +      return SQLITE_OK;
 1.27469 +    }
 1.27470 +    case SQLITE_FCNTL_VFSNAME: {
 1.27471 +      *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
 1.27472 +      return SQLITE_OK;
 1.27473 +    }
 1.27474 +    case SQLITE_FCNTL_TEMPFILENAME: {
 1.27475 +      char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
 1.27476 +      if( zTFile ){
 1.27477 +        unixGetTempname(pFile->pVfs->mxPathname, zTFile);
 1.27478 +        *(char**)pArg = zTFile;
 1.27479 +      }
 1.27480 +      return SQLITE_OK;
 1.27481 +    }
 1.27482 +    case SQLITE_FCNTL_HAS_MOVED: {
 1.27483 +      *(int*)pArg = fileHasMoved(pFile);
 1.27484 +      return SQLITE_OK;
 1.27485 +    }
 1.27486 +#if SQLITE_MAX_MMAP_SIZE>0
 1.27487 +    case SQLITE_FCNTL_MMAP_SIZE: {
 1.27488 +      i64 newLimit = *(i64*)pArg;
 1.27489 +      int rc = SQLITE_OK;
 1.27490 +      if( newLimit>sqlite3GlobalConfig.mxMmap ){
 1.27491 +        newLimit = sqlite3GlobalConfig.mxMmap;
 1.27492 +      }
 1.27493 +      *(i64*)pArg = pFile->mmapSizeMax;
 1.27494 +      if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
 1.27495 +        pFile->mmapSizeMax = newLimit;
 1.27496 +        if( pFile->mmapSize>0 ){
 1.27497 +          unixUnmapfile(pFile);
 1.27498 +          rc = unixMapfile(pFile, -1);
 1.27499 +        }
 1.27500 +      }
 1.27501 +      return rc;
 1.27502 +    }
 1.27503 +#endif
 1.27504 +#ifdef SQLITE_DEBUG
 1.27505 +    /* The pager calls this method to signal that it has done
 1.27506 +    ** a rollback and that the database is therefore unchanged and
 1.27507 +    ** it hence it is OK for the transaction change counter to be
 1.27508 +    ** unchanged.
 1.27509 +    */
 1.27510 +    case SQLITE_FCNTL_DB_UNCHANGED: {
 1.27511 +      ((unixFile*)id)->dbUpdate = 0;
 1.27512 +      return SQLITE_OK;
 1.27513 +    }
 1.27514 +#endif
 1.27515 +#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
 1.27516 +    case SQLITE_SET_LOCKPROXYFILE:
 1.27517 +    case SQLITE_GET_LOCKPROXYFILE: {
 1.27518 +      return proxyFileControl(id,op,pArg);
 1.27519 +    }
 1.27520 +#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
 1.27521 +  }
 1.27522 +  return SQLITE_NOTFOUND;
 1.27523 +}
 1.27524 +
 1.27525 +/*
 1.27526 +** Return the sector size in bytes of the underlying block device for
 1.27527 +** the specified file. This is almost always 512 bytes, but may be
 1.27528 +** larger for some devices.
 1.27529 +**
 1.27530 +** SQLite code assumes this function cannot fail. It also assumes that
 1.27531 +** if two files are created in the same file-system directory (i.e.
 1.27532 +** a database and its journal file) that the sector size will be the
 1.27533 +** same for both.
 1.27534 +*/
 1.27535 +#ifndef __QNXNTO__ 
 1.27536 +static int unixSectorSize(sqlite3_file *NotUsed){
 1.27537 +  UNUSED_PARAMETER(NotUsed);
 1.27538 +  return SQLITE_DEFAULT_SECTOR_SIZE;
 1.27539 +}
 1.27540 +#endif
 1.27541 +
 1.27542 +/*
 1.27543 +** The following version of unixSectorSize() is optimized for QNX.
 1.27544 +*/
 1.27545 +#ifdef __QNXNTO__
 1.27546 +#include <sys/dcmd_blk.h>
 1.27547 +#include <sys/statvfs.h>
 1.27548 +static int unixSectorSize(sqlite3_file *id){
 1.27549 +  unixFile *pFile = (unixFile*)id;
 1.27550 +  if( pFile->sectorSize == 0 ){
 1.27551 +    struct statvfs fsInfo;
 1.27552 +       
 1.27553 +    /* Set defaults for non-supported filesystems */
 1.27554 +    pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
 1.27555 +    pFile->deviceCharacteristics = 0;
 1.27556 +    if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
 1.27557 +      return pFile->sectorSize;
 1.27558 +    }
 1.27559 +
 1.27560 +    if( !strcmp(fsInfo.f_basetype, "tmp") ) {
 1.27561 +      pFile->sectorSize = fsInfo.f_bsize;
 1.27562 +      pFile->deviceCharacteristics =
 1.27563 +        SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
 1.27564 +        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
 1.27565 +                                      ** the write succeeds */
 1.27566 +        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
 1.27567 +                                      ** so it is ordered */
 1.27568 +        0;
 1.27569 +    }else if( strstr(fsInfo.f_basetype, "etfs") ){
 1.27570 +      pFile->sectorSize = fsInfo.f_bsize;
 1.27571 +      pFile->deviceCharacteristics =
 1.27572 +        /* etfs cluster size writes are atomic */
 1.27573 +        (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
 1.27574 +        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
 1.27575 +                                      ** the write succeeds */
 1.27576 +        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
 1.27577 +                                      ** so it is ordered */
 1.27578 +        0;
 1.27579 +    }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
 1.27580 +      pFile->sectorSize = fsInfo.f_bsize;
 1.27581 +      pFile->deviceCharacteristics =
 1.27582 +        SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
 1.27583 +        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
 1.27584 +                                      ** the write succeeds */
 1.27585 +        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
 1.27586 +                                      ** so it is ordered */
 1.27587 +        0;
 1.27588 +    }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
 1.27589 +      pFile->sectorSize = fsInfo.f_bsize;
 1.27590 +      pFile->deviceCharacteristics =
 1.27591 +        /* full bitset of atomics from max sector size and smaller */
 1.27592 +        ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
 1.27593 +        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
 1.27594 +                                      ** so it is ordered */
 1.27595 +        0;
 1.27596 +    }else if( strstr(fsInfo.f_basetype, "dos") ){
 1.27597 +      pFile->sectorSize = fsInfo.f_bsize;
 1.27598 +      pFile->deviceCharacteristics =
 1.27599 +        /* full bitset of atomics from max sector size and smaller */
 1.27600 +        ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
 1.27601 +        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
 1.27602 +                                      ** so it is ordered */
 1.27603 +        0;
 1.27604 +    }else{
 1.27605 +      pFile->deviceCharacteristics =
 1.27606 +        SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
 1.27607 +        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
 1.27608 +                                      ** the write succeeds */
 1.27609 +        0;
 1.27610 +    }
 1.27611 +  }
 1.27612 +  /* Last chance verification.  If the sector size isn't a multiple of 512
 1.27613 +  ** then it isn't valid.*/
 1.27614 +  if( pFile->sectorSize % 512 != 0 ){
 1.27615 +    pFile->deviceCharacteristics = 0;
 1.27616 +    pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
 1.27617 +  }
 1.27618 +  return pFile->sectorSize;
 1.27619 +}
 1.27620 +#endif /* __QNXNTO__ */
 1.27621 +
 1.27622 +/*
 1.27623 +** Return the device characteristics for the file.
 1.27624 +**
 1.27625 +** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
 1.27626 +** However, that choice is contraversial since technically the underlying
 1.27627 +** file system does not always provide powersafe overwrites.  (In other
 1.27628 +** words, after a power-loss event, parts of the file that were never
 1.27629 +** written might end up being altered.)  However, non-PSOW behavior is very,
 1.27630 +** very rare.  And asserting PSOW makes a large reduction in the amount
 1.27631 +** of required I/O for journaling, since a lot of padding is eliminated.
 1.27632 +**  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
 1.27633 +** available to turn it off and URI query parameter available to turn it off.
 1.27634 +*/
 1.27635 +static int unixDeviceCharacteristics(sqlite3_file *id){
 1.27636 +  unixFile *p = (unixFile*)id;
 1.27637 +  int rc = 0;
 1.27638 +#ifdef __QNXNTO__
 1.27639 +  if( p->sectorSize==0 ) unixSectorSize(id);
 1.27640 +  rc = p->deviceCharacteristics;
 1.27641 +#endif
 1.27642 +  if( p->ctrlFlags & UNIXFILE_PSOW ){
 1.27643 +    rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
 1.27644 +  }
 1.27645 +  return rc;
 1.27646 +}
 1.27647 +
 1.27648 +#ifndef SQLITE_OMIT_WAL
 1.27649 +
 1.27650 +
 1.27651 +/*
 1.27652 +** Object used to represent an shared memory buffer.  
 1.27653 +**
 1.27654 +** When multiple threads all reference the same wal-index, each thread
 1.27655 +** has its own unixShm object, but they all point to a single instance
 1.27656 +** of this unixShmNode object.  In other words, each wal-index is opened
 1.27657 +** only once per process.
 1.27658 +**
 1.27659 +** Each unixShmNode object is connected to a single unixInodeInfo object.
 1.27660 +** We could coalesce this object into unixInodeInfo, but that would mean
 1.27661 +** every open file that does not use shared memory (in other words, most
 1.27662 +** open files) would have to carry around this extra information.  So
 1.27663 +** the unixInodeInfo object contains a pointer to this unixShmNode object
 1.27664 +** and the unixShmNode object is created only when needed.
 1.27665 +**
 1.27666 +** unixMutexHeld() must be true when creating or destroying
 1.27667 +** this object or while reading or writing the following fields:
 1.27668 +**
 1.27669 +**      nRef
 1.27670 +**
 1.27671 +** The following fields are read-only after the object is created:
 1.27672 +** 
 1.27673 +**      fid
 1.27674 +**      zFilename
 1.27675 +**
 1.27676 +** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
 1.27677 +** unixMutexHeld() is true when reading or writing any other field
 1.27678 +** in this structure.
 1.27679 +*/
 1.27680 +struct unixShmNode {
 1.27681 +  unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
 1.27682 +  sqlite3_mutex *mutex;      /* Mutex to access this object */
 1.27683 +  char *zFilename;           /* Name of the mmapped file */
 1.27684 +  int h;                     /* Open file descriptor */
 1.27685 +  int szRegion;              /* Size of shared-memory regions */
 1.27686 +  u16 nRegion;               /* Size of array apRegion */
 1.27687 +  u8 isReadonly;             /* True if read-only */
 1.27688 +  char **apRegion;           /* Array of mapped shared-memory regions */
 1.27689 +  int nRef;                  /* Number of unixShm objects pointing to this */
 1.27690 +  unixShm *pFirst;           /* All unixShm objects pointing to this */
 1.27691 +#ifdef SQLITE_DEBUG
 1.27692 +  u8 exclMask;               /* Mask of exclusive locks held */
 1.27693 +  u8 sharedMask;             /* Mask of shared locks held */
 1.27694 +  u8 nextShmId;              /* Next available unixShm.id value */
 1.27695 +#endif
 1.27696 +};
 1.27697 +
 1.27698 +/*
 1.27699 +** Structure used internally by this VFS to record the state of an
 1.27700 +** open shared memory connection.
 1.27701 +**
 1.27702 +** The following fields are initialized when this object is created and
 1.27703 +** are read-only thereafter:
 1.27704 +**
 1.27705 +**    unixShm.pFile
 1.27706 +**    unixShm.id
 1.27707 +**
 1.27708 +** All other fields are read/write.  The unixShm.pFile->mutex must be held
 1.27709 +** while accessing any read/write fields.
 1.27710 +*/
 1.27711 +struct unixShm {
 1.27712 +  unixShmNode *pShmNode;     /* The underlying unixShmNode object */
 1.27713 +  unixShm *pNext;            /* Next unixShm with the same unixShmNode */
 1.27714 +  u8 hasMutex;               /* True if holding the unixShmNode mutex */
 1.27715 +  u8 id;                     /* Id of this connection within its unixShmNode */
 1.27716 +  u16 sharedMask;            /* Mask of shared locks held */
 1.27717 +  u16 exclMask;              /* Mask of exclusive locks held */
 1.27718 +};
 1.27719 +
 1.27720 +/*
 1.27721 +** Constants used for locking
 1.27722 +*/
 1.27723 +#define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
 1.27724 +#define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
 1.27725 +
 1.27726 +/*
 1.27727 +** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
 1.27728 +**
 1.27729 +** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
 1.27730 +** otherwise.
 1.27731 +*/
 1.27732 +static int unixShmSystemLock(
 1.27733 +  unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
 1.27734 +  int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
 1.27735 +  int ofst,              /* First byte of the locking range */
 1.27736 +  int n                  /* Number of bytes to lock */
 1.27737 +){
 1.27738 +  struct flock f;       /* The posix advisory locking structure */
 1.27739 +  int rc = SQLITE_OK;   /* Result code form fcntl() */
 1.27740 +
 1.27741 +  /* Access to the unixShmNode object is serialized by the caller */
 1.27742 +  assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
 1.27743 +
 1.27744 +  /* Shared locks never span more than one byte */
 1.27745 +  assert( n==1 || lockType!=F_RDLCK );
 1.27746 +
 1.27747 +  /* Locks are within range */
 1.27748 +  assert( n>=1 && n<SQLITE_SHM_NLOCK );
 1.27749 +
 1.27750 +  if( pShmNode->h>=0 ){
 1.27751 +    /* Initialize the locking parameters */
 1.27752 +    memset(&f, 0, sizeof(f));
 1.27753 +    f.l_type = lockType;
 1.27754 +    f.l_whence = SEEK_SET;
 1.27755 +    f.l_start = ofst;
 1.27756 +    f.l_len = n;
 1.27757 +
 1.27758 +    rc = osFcntl(pShmNode->h, F_SETLK, &f);
 1.27759 +    rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
 1.27760 +  }
 1.27761 +
 1.27762 +  /* Update the global lock state and do debug tracing */
 1.27763 +#ifdef SQLITE_DEBUG
 1.27764 +  { u16 mask;
 1.27765 +  OSTRACE(("SHM-LOCK "));
 1.27766 +  mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
 1.27767 +  if( rc==SQLITE_OK ){
 1.27768 +    if( lockType==F_UNLCK ){
 1.27769 +      OSTRACE(("unlock %d ok", ofst));
 1.27770 +      pShmNode->exclMask &= ~mask;
 1.27771 +      pShmNode->sharedMask &= ~mask;
 1.27772 +    }else if( lockType==F_RDLCK ){
 1.27773 +      OSTRACE(("read-lock %d ok", ofst));
 1.27774 +      pShmNode->exclMask &= ~mask;
 1.27775 +      pShmNode->sharedMask |= mask;
 1.27776 +    }else{
 1.27777 +      assert( lockType==F_WRLCK );
 1.27778 +      OSTRACE(("write-lock %d ok", ofst));
 1.27779 +      pShmNode->exclMask |= mask;
 1.27780 +      pShmNode->sharedMask &= ~mask;
 1.27781 +    }
 1.27782 +  }else{
 1.27783 +    if( lockType==F_UNLCK ){
 1.27784 +      OSTRACE(("unlock %d failed", ofst));
 1.27785 +    }else if( lockType==F_RDLCK ){
 1.27786 +      OSTRACE(("read-lock failed"));
 1.27787 +    }else{
 1.27788 +      assert( lockType==F_WRLCK );
 1.27789 +      OSTRACE(("write-lock %d failed", ofst));
 1.27790 +    }
 1.27791 +  }
 1.27792 +  OSTRACE((" - afterwards %03x,%03x\n",
 1.27793 +           pShmNode->sharedMask, pShmNode->exclMask));
 1.27794 +  }
 1.27795 +#endif
 1.27796 +
 1.27797 +  return rc;        
 1.27798 +}
 1.27799 +
 1.27800 +
 1.27801 +/*
 1.27802 +** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
 1.27803 +**
 1.27804 +** This is not a VFS shared-memory method; it is a utility function called
 1.27805 +** by VFS shared-memory methods.
 1.27806 +*/
 1.27807 +static void unixShmPurge(unixFile *pFd){
 1.27808 +  unixShmNode *p = pFd->pInode->pShmNode;
 1.27809 +  assert( unixMutexHeld() );
 1.27810 +  if( p && p->nRef==0 ){
 1.27811 +    int i;
 1.27812 +    assert( p->pInode==pFd->pInode );
 1.27813 +    sqlite3_mutex_free(p->mutex);
 1.27814 +    for(i=0; i<p->nRegion; i++){
 1.27815 +      if( p->h>=0 ){
 1.27816 +        osMunmap(p->apRegion[i], p->szRegion);
 1.27817 +      }else{
 1.27818 +        sqlite3_free(p->apRegion[i]);
 1.27819 +      }
 1.27820 +    }
 1.27821 +    sqlite3_free(p->apRegion);
 1.27822 +    if( p->h>=0 ){
 1.27823 +      robust_close(pFd, p->h, __LINE__);
 1.27824 +      p->h = -1;
 1.27825 +    }
 1.27826 +    p->pInode->pShmNode = 0;
 1.27827 +    sqlite3_free(p);
 1.27828 +  }
 1.27829 +}
 1.27830 +
 1.27831 +/*
 1.27832 +** Open a shared-memory area associated with open database file pDbFd.  
 1.27833 +** This particular implementation uses mmapped files.
 1.27834 +**
 1.27835 +** The file used to implement shared-memory is in the same directory
 1.27836 +** as the open database file and has the same name as the open database
 1.27837 +** file with the "-shm" suffix added.  For example, if the database file
 1.27838 +** is "/home/user1/config.db" then the file that is created and mmapped
 1.27839 +** for shared memory will be called "/home/user1/config.db-shm".  
 1.27840 +**
 1.27841 +** Another approach to is to use files in /dev/shm or /dev/tmp or an
 1.27842 +** some other tmpfs mount. But if a file in a different directory
 1.27843 +** from the database file is used, then differing access permissions
 1.27844 +** or a chroot() might cause two different processes on the same
 1.27845 +** database to end up using different files for shared memory - 
 1.27846 +** meaning that their memory would not really be shared - resulting
 1.27847 +** in database corruption.  Nevertheless, this tmpfs file usage
 1.27848 +** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
 1.27849 +** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
 1.27850 +** option results in an incompatible build of SQLite;  builds of SQLite
 1.27851 +** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
 1.27852 +** same database file at the same time, database corruption will likely
 1.27853 +** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
 1.27854 +** "unsupported" and may go away in a future SQLite release.
 1.27855 +**
 1.27856 +** When opening a new shared-memory file, if no other instances of that
 1.27857 +** file are currently open, in this process or in other processes, then
 1.27858 +** the file must be truncated to zero length or have its header cleared.
 1.27859 +**
 1.27860 +** If the original database file (pDbFd) is using the "unix-excl" VFS
 1.27861 +** that means that an exclusive lock is held on the database file and
 1.27862 +** that no other processes are able to read or write the database.  In
 1.27863 +** that case, we do not really need shared memory.  No shared memory
 1.27864 +** file is created.  The shared memory will be simulated with heap memory.
 1.27865 +*/
 1.27866 +static int unixOpenSharedMemory(unixFile *pDbFd){
 1.27867 +  struct unixShm *p = 0;          /* The connection to be opened */
 1.27868 +  struct unixShmNode *pShmNode;   /* The underlying mmapped file */
 1.27869 +  int rc;                         /* Result code */
 1.27870 +  unixInodeInfo *pInode;          /* The inode of fd */
 1.27871 +  char *zShmFilename;             /* Name of the file used for SHM */
 1.27872 +  int nShmFilename;               /* Size of the SHM filename in bytes */
 1.27873 +
 1.27874 +  /* Allocate space for the new unixShm object. */
 1.27875 +  p = sqlite3_malloc( sizeof(*p) );
 1.27876 +  if( p==0 ) return SQLITE_NOMEM;
 1.27877 +  memset(p, 0, sizeof(*p));
 1.27878 +  assert( pDbFd->pShm==0 );
 1.27879 +
 1.27880 +  /* Check to see if a unixShmNode object already exists. Reuse an existing
 1.27881 +  ** one if present. Create a new one if necessary.
 1.27882 +  */
 1.27883 +  unixEnterMutex();
 1.27884 +  pInode = pDbFd->pInode;
 1.27885 +  pShmNode = pInode->pShmNode;
 1.27886 +  if( pShmNode==0 ){
 1.27887 +    struct stat sStat;                 /* fstat() info for database file */
 1.27888 +
 1.27889 +    /* Call fstat() to figure out the permissions on the database file. If
 1.27890 +    ** a new *-shm file is created, an attempt will be made to create it
 1.27891 +    ** with the same permissions.
 1.27892 +    */
 1.27893 +    if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
 1.27894 +      rc = SQLITE_IOERR_FSTAT;
 1.27895 +      goto shm_open_err;
 1.27896 +    }
 1.27897 +
 1.27898 +#ifdef SQLITE_SHM_DIRECTORY
 1.27899 +    nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
 1.27900 +#else
 1.27901 +    nShmFilename = 6 + (int)strlen(pDbFd->zPath);
 1.27902 +#endif
 1.27903 +    pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
 1.27904 +    if( pShmNode==0 ){
 1.27905 +      rc = SQLITE_NOMEM;
 1.27906 +      goto shm_open_err;
 1.27907 +    }
 1.27908 +    memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
 1.27909 +    zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
 1.27910 +#ifdef SQLITE_SHM_DIRECTORY
 1.27911 +    sqlite3_snprintf(nShmFilename, zShmFilename, 
 1.27912 +                     SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
 1.27913 +                     (u32)sStat.st_ino, (u32)sStat.st_dev);
 1.27914 +#else
 1.27915 +    sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
 1.27916 +    sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
 1.27917 +#endif
 1.27918 +    pShmNode->h = -1;
 1.27919 +    pDbFd->pInode->pShmNode = pShmNode;
 1.27920 +    pShmNode->pInode = pDbFd->pInode;
 1.27921 +    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
 1.27922 +    if( pShmNode->mutex==0 ){
 1.27923 +      rc = SQLITE_NOMEM;
 1.27924 +      goto shm_open_err;
 1.27925 +    }
 1.27926 +
 1.27927 +    if( pInode->bProcessLock==0 ){
 1.27928 +      int openFlags = O_RDWR | O_CREAT;
 1.27929 +      if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
 1.27930 +        openFlags = O_RDONLY;
 1.27931 +        pShmNode->isReadonly = 1;
 1.27932 +      }
 1.27933 +      pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
 1.27934 +      if( pShmNode->h<0 ){
 1.27935 +        rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
 1.27936 +        goto shm_open_err;
 1.27937 +      }
 1.27938 +
 1.27939 +      /* If this process is running as root, make sure that the SHM file
 1.27940 +      ** is owned by the same user that owns the original database.  Otherwise,
 1.27941 +      ** the original owner will not be able to connect.
 1.27942 +      */
 1.27943 +      osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
 1.27944 +  
 1.27945 +      /* Check to see if another process is holding the dead-man switch.
 1.27946 +      ** If not, truncate the file to zero length. 
 1.27947 +      */
 1.27948 +      rc = SQLITE_OK;
 1.27949 +      if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
 1.27950 +        if( robust_ftruncate(pShmNode->h, 0) ){
 1.27951 +          rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
 1.27952 +        }
 1.27953 +      }
 1.27954 +      if( rc==SQLITE_OK ){
 1.27955 +        rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
 1.27956 +      }
 1.27957 +      if( rc ) goto shm_open_err;
 1.27958 +    }
 1.27959 +  }
 1.27960 +
 1.27961 +  /* Make the new connection a child of the unixShmNode */
 1.27962 +  p->pShmNode = pShmNode;
 1.27963 +#ifdef SQLITE_DEBUG
 1.27964 +  p->id = pShmNode->nextShmId++;
 1.27965 +#endif
 1.27966 +  pShmNode->nRef++;
 1.27967 +  pDbFd->pShm = p;
 1.27968 +  unixLeaveMutex();
 1.27969 +
 1.27970 +  /* The reference count on pShmNode has already been incremented under
 1.27971 +  ** the cover of the unixEnterMutex() mutex and the pointer from the
 1.27972 +  ** new (struct unixShm) object to the pShmNode has been set. All that is
 1.27973 +  ** left to do is to link the new object into the linked list starting
 1.27974 +  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
 1.27975 +  ** mutex.
 1.27976 +  */
 1.27977 +  sqlite3_mutex_enter(pShmNode->mutex);
 1.27978 +  p->pNext = pShmNode->pFirst;
 1.27979 +  pShmNode->pFirst = p;
 1.27980 +  sqlite3_mutex_leave(pShmNode->mutex);
 1.27981 +  return SQLITE_OK;
 1.27982 +
 1.27983 +  /* Jump here on any error */
 1.27984 +shm_open_err:
 1.27985 +  unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
 1.27986 +  sqlite3_free(p);
 1.27987 +  unixLeaveMutex();
 1.27988 +  return rc;
 1.27989 +}
 1.27990 +
 1.27991 +/*
 1.27992 +** This function is called to obtain a pointer to region iRegion of the 
 1.27993 +** shared-memory associated with the database file fd. Shared-memory regions 
 1.27994 +** are numbered starting from zero. Each shared-memory region is szRegion 
 1.27995 +** bytes in size.
 1.27996 +**
 1.27997 +** If an error occurs, an error code is returned and *pp is set to NULL.
 1.27998 +**
 1.27999 +** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
 1.28000 +** region has not been allocated (by any client, including one running in a
 1.28001 +** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
 1.28002 +** bExtend is non-zero and the requested shared-memory region has not yet 
 1.28003 +** been allocated, it is allocated by this function.
 1.28004 +**
 1.28005 +** If the shared-memory region has already been allocated or is allocated by
 1.28006 +** this call as described above, then it is mapped into this processes 
 1.28007 +** address space (if it is not already), *pp is set to point to the mapped 
 1.28008 +** memory and SQLITE_OK returned.
 1.28009 +*/
 1.28010 +static int unixShmMap(
 1.28011 +  sqlite3_file *fd,               /* Handle open on database file */
 1.28012 +  int iRegion,                    /* Region to retrieve */
 1.28013 +  int szRegion,                   /* Size of regions */
 1.28014 +  int bExtend,                    /* True to extend file if necessary */
 1.28015 +  void volatile **pp              /* OUT: Mapped memory */
 1.28016 +){
 1.28017 +  unixFile *pDbFd = (unixFile*)fd;
 1.28018 +  unixShm *p;
 1.28019 +  unixShmNode *pShmNode;
 1.28020 +  int rc = SQLITE_OK;
 1.28021 +
 1.28022 +  /* If the shared-memory file has not yet been opened, open it now. */
 1.28023 +  if( pDbFd->pShm==0 ){
 1.28024 +    rc = unixOpenSharedMemory(pDbFd);
 1.28025 +    if( rc!=SQLITE_OK ) return rc;
 1.28026 +  }
 1.28027 +
 1.28028 +  p = pDbFd->pShm;
 1.28029 +  pShmNode = p->pShmNode;
 1.28030 +  sqlite3_mutex_enter(pShmNode->mutex);
 1.28031 +  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
 1.28032 +  assert( pShmNode->pInode==pDbFd->pInode );
 1.28033 +  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
 1.28034 +  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
 1.28035 +
 1.28036 +  if( pShmNode->nRegion<=iRegion ){
 1.28037 +    char **apNew;                      /* New apRegion[] array */
 1.28038 +    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
 1.28039 +    struct stat sStat;                 /* Used by fstat() */
 1.28040 +
 1.28041 +    pShmNode->szRegion = szRegion;
 1.28042 +
 1.28043 +    if( pShmNode->h>=0 ){
 1.28044 +      /* The requested region is not mapped into this processes address space.
 1.28045 +      ** Check to see if it has been allocated (i.e. if the wal-index file is
 1.28046 +      ** large enough to contain the requested region).
 1.28047 +      */
 1.28048 +      if( osFstat(pShmNode->h, &sStat) ){
 1.28049 +        rc = SQLITE_IOERR_SHMSIZE;
 1.28050 +        goto shmpage_out;
 1.28051 +      }
 1.28052 +  
 1.28053 +      if( sStat.st_size<nByte ){
 1.28054 +        /* The requested memory region does not exist. If bExtend is set to
 1.28055 +        ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
 1.28056 +        */
 1.28057 +        if( !bExtend ){
 1.28058 +          goto shmpage_out;
 1.28059 +        }
 1.28060 +
 1.28061 +        /* Alternatively, if bExtend is true, extend the file. Do this by
 1.28062 +        ** writing a single byte to the end of each (OS) page being
 1.28063 +        ** allocated or extended. Technically, we need only write to the
 1.28064 +        ** last page in order to extend the file. But writing to all new
 1.28065 +        ** pages forces the OS to allocate them immediately, which reduces
 1.28066 +        ** the chances of SIGBUS while accessing the mapped region later on.
 1.28067 +        */
 1.28068 +        else{
 1.28069 +          static const int pgsz = 4096;
 1.28070 +          int iPg;
 1.28071 +
 1.28072 +          /* Write to the last byte of each newly allocated or extended page */
 1.28073 +          assert( (nByte % pgsz)==0 );
 1.28074 +          for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
 1.28075 +            if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
 1.28076 +              const char *zFile = pShmNode->zFilename;
 1.28077 +              rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
 1.28078 +              goto shmpage_out;
 1.28079 +            }
 1.28080 +          }
 1.28081 +        }
 1.28082 +      }
 1.28083 +    }
 1.28084 +
 1.28085 +    /* Map the requested memory region into this processes address space. */
 1.28086 +    apNew = (char **)sqlite3_realloc(
 1.28087 +        pShmNode->apRegion, (iRegion+1)*sizeof(char *)
 1.28088 +    );
 1.28089 +    if( !apNew ){
 1.28090 +      rc = SQLITE_IOERR_NOMEM;
 1.28091 +      goto shmpage_out;
 1.28092 +    }
 1.28093 +    pShmNode->apRegion = apNew;
 1.28094 +    while(pShmNode->nRegion<=iRegion){
 1.28095 +      void *pMem;
 1.28096 +      if( pShmNode->h>=0 ){
 1.28097 +        pMem = osMmap(0, szRegion,
 1.28098 +            pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, 
 1.28099 +            MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
 1.28100 +        );
 1.28101 +        if( pMem==MAP_FAILED ){
 1.28102 +          rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
 1.28103 +          goto shmpage_out;
 1.28104 +        }
 1.28105 +      }else{
 1.28106 +        pMem = sqlite3_malloc(szRegion);
 1.28107 +        if( pMem==0 ){
 1.28108 +          rc = SQLITE_NOMEM;
 1.28109 +          goto shmpage_out;
 1.28110 +        }
 1.28111 +        memset(pMem, 0, szRegion);
 1.28112 +      }
 1.28113 +      pShmNode->apRegion[pShmNode->nRegion] = pMem;
 1.28114 +      pShmNode->nRegion++;
 1.28115 +    }
 1.28116 +  }
 1.28117 +
 1.28118 +shmpage_out:
 1.28119 +  if( pShmNode->nRegion>iRegion ){
 1.28120 +    *pp = pShmNode->apRegion[iRegion];
 1.28121 +  }else{
 1.28122 +    *pp = 0;
 1.28123 +  }
 1.28124 +  if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
 1.28125 +  sqlite3_mutex_leave(pShmNode->mutex);
 1.28126 +  return rc;
 1.28127 +}
 1.28128 +
 1.28129 +/*
 1.28130 +** Change the lock state for a shared-memory segment.
 1.28131 +**
 1.28132 +** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
 1.28133 +** different here than in posix.  In xShmLock(), one can go from unlocked
 1.28134 +** to shared and back or from unlocked to exclusive and back.  But one may
 1.28135 +** not go from shared to exclusive or from exclusive to shared.
 1.28136 +*/
 1.28137 +static int unixShmLock(
 1.28138 +  sqlite3_file *fd,          /* Database file holding the shared memory */
 1.28139 +  int ofst,                  /* First lock to acquire or release */
 1.28140 +  int n,                     /* Number of locks to acquire or release */
 1.28141 +  int flags                  /* What to do with the lock */
 1.28142 +){
 1.28143 +  unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
 1.28144 +  unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
 1.28145 +  unixShm *pX;                          /* For looping over all siblings */
 1.28146 +  unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
 1.28147 +  int rc = SQLITE_OK;                   /* Result code */
 1.28148 +  u16 mask;                             /* Mask of locks to take or release */
 1.28149 +
 1.28150 +  assert( pShmNode==pDbFd->pInode->pShmNode );
 1.28151 +  assert( pShmNode->pInode==pDbFd->pInode );
 1.28152 +  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
 1.28153 +  assert( n>=1 );
 1.28154 +  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
 1.28155 +       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
 1.28156 +       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
 1.28157 +       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
 1.28158 +  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
 1.28159 +  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
 1.28160 +  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
 1.28161 +
 1.28162 +  mask = (1<<(ofst+n)) - (1<<ofst);
 1.28163 +  assert( n>1 || mask==(1<<ofst) );
 1.28164 +  sqlite3_mutex_enter(pShmNode->mutex);
 1.28165 +  if( flags & SQLITE_SHM_UNLOCK ){
 1.28166 +    u16 allMask = 0; /* Mask of locks held by siblings */
 1.28167 +
 1.28168 +    /* See if any siblings hold this same lock */
 1.28169 +    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
 1.28170 +      if( pX==p ) continue;
 1.28171 +      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
 1.28172 +      allMask |= pX->sharedMask;
 1.28173 +    }
 1.28174 +
 1.28175 +    /* Unlock the system-level locks */
 1.28176 +    if( (mask & allMask)==0 ){
 1.28177 +      rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
 1.28178 +    }else{
 1.28179 +      rc = SQLITE_OK;
 1.28180 +    }
 1.28181 +
 1.28182 +    /* Undo the local locks */
 1.28183 +    if( rc==SQLITE_OK ){
 1.28184 +      p->exclMask &= ~mask;
 1.28185 +      p->sharedMask &= ~mask;
 1.28186 +    } 
 1.28187 +  }else if( flags & SQLITE_SHM_SHARED ){
 1.28188 +    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
 1.28189 +
 1.28190 +    /* Find out which shared locks are already held by sibling connections.
 1.28191 +    ** If any sibling already holds an exclusive lock, go ahead and return
 1.28192 +    ** SQLITE_BUSY.
 1.28193 +    */
 1.28194 +    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
 1.28195 +      if( (pX->exclMask & mask)!=0 ){
 1.28196 +        rc = SQLITE_BUSY;
 1.28197 +        break;
 1.28198 +      }
 1.28199 +      allShared |= pX->sharedMask;
 1.28200 +    }
 1.28201 +
 1.28202 +    /* Get shared locks at the system level, if necessary */
 1.28203 +    if( rc==SQLITE_OK ){
 1.28204 +      if( (allShared & mask)==0 ){
 1.28205 +        rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
 1.28206 +      }else{
 1.28207 +        rc = SQLITE_OK;
 1.28208 +      }
 1.28209 +    }
 1.28210 +
 1.28211 +    /* Get the local shared locks */
 1.28212 +    if( rc==SQLITE_OK ){
 1.28213 +      p->sharedMask |= mask;
 1.28214 +    }
 1.28215 +  }else{
 1.28216 +    /* Make sure no sibling connections hold locks that will block this
 1.28217 +    ** lock.  If any do, return SQLITE_BUSY right away.
 1.28218 +    */
 1.28219 +    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
 1.28220 +      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
 1.28221 +        rc = SQLITE_BUSY;
 1.28222 +        break;
 1.28223 +      }
 1.28224 +    }
 1.28225 +  
 1.28226 +    /* Get the exclusive locks at the system level.  Then if successful
 1.28227 +    ** also mark the local connection as being locked.
 1.28228 +    */
 1.28229 +    if( rc==SQLITE_OK ){
 1.28230 +      rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
 1.28231 +      if( rc==SQLITE_OK ){
 1.28232 +        assert( (p->sharedMask & mask)==0 );
 1.28233 +        p->exclMask |= mask;
 1.28234 +      }
 1.28235 +    }
 1.28236 +  }
 1.28237 +  sqlite3_mutex_leave(pShmNode->mutex);
 1.28238 +  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
 1.28239 +           p->id, getpid(), p->sharedMask, p->exclMask));
 1.28240 +  return rc;
 1.28241 +}
 1.28242 +
 1.28243 +/*
 1.28244 +** Implement a memory barrier or memory fence on shared memory.  
 1.28245 +**
 1.28246 +** All loads and stores begun before the barrier must complete before
 1.28247 +** any load or store begun after the barrier.
 1.28248 +*/
 1.28249 +static void unixShmBarrier(
 1.28250 +  sqlite3_file *fd                /* Database file holding the shared memory */
 1.28251 +){
 1.28252 +  UNUSED_PARAMETER(fd);
 1.28253 +  unixEnterMutex();
 1.28254 +  unixLeaveMutex();
 1.28255 +}
 1.28256 +
 1.28257 +/*
 1.28258 +** Close a connection to shared-memory.  Delete the underlying 
 1.28259 +** storage if deleteFlag is true.
 1.28260 +**
 1.28261 +** If there is no shared memory associated with the connection then this
 1.28262 +** routine is a harmless no-op.
 1.28263 +*/
 1.28264 +static int unixShmUnmap(
 1.28265 +  sqlite3_file *fd,               /* The underlying database file */
 1.28266 +  int deleteFlag                  /* Delete shared-memory if true */
 1.28267 +){
 1.28268 +  unixShm *p;                     /* The connection to be closed */
 1.28269 +  unixShmNode *pShmNode;          /* The underlying shared-memory file */
 1.28270 +  unixShm **pp;                   /* For looping over sibling connections */
 1.28271 +  unixFile *pDbFd;                /* The underlying database file */
 1.28272 +
 1.28273 +  pDbFd = (unixFile*)fd;
 1.28274 +  p = pDbFd->pShm;
 1.28275 +  if( p==0 ) return SQLITE_OK;
 1.28276 +  pShmNode = p->pShmNode;
 1.28277 +
 1.28278 +  assert( pShmNode==pDbFd->pInode->pShmNode );
 1.28279 +  assert( pShmNode->pInode==pDbFd->pInode );
 1.28280 +
 1.28281 +  /* Remove connection p from the set of connections associated
 1.28282 +  ** with pShmNode */
 1.28283 +  sqlite3_mutex_enter(pShmNode->mutex);
 1.28284 +  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
 1.28285 +  *pp = p->pNext;
 1.28286 +
 1.28287 +  /* Free the connection p */
 1.28288 +  sqlite3_free(p);
 1.28289 +  pDbFd->pShm = 0;
 1.28290 +  sqlite3_mutex_leave(pShmNode->mutex);
 1.28291 +
 1.28292 +  /* If pShmNode->nRef has reached 0, then close the underlying
 1.28293 +  ** shared-memory file, too */
 1.28294 +  unixEnterMutex();
 1.28295 +  assert( pShmNode->nRef>0 );
 1.28296 +  pShmNode->nRef--;
 1.28297 +  if( pShmNode->nRef==0 ){
 1.28298 +    if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
 1.28299 +    unixShmPurge(pDbFd);
 1.28300 +  }
 1.28301 +  unixLeaveMutex();
 1.28302 +
 1.28303 +  return SQLITE_OK;
 1.28304 +}
 1.28305 +
 1.28306 +
 1.28307 +#else
 1.28308 +# define unixShmMap     0
 1.28309 +# define unixShmLock    0
 1.28310 +# define unixShmBarrier 0
 1.28311 +# define unixShmUnmap   0
 1.28312 +#endif /* #ifndef SQLITE_OMIT_WAL */
 1.28313 +
 1.28314 +#if SQLITE_MAX_MMAP_SIZE>0
 1.28315 +/*
 1.28316 +** If it is currently memory mapped, unmap file pFd.
 1.28317 +*/
 1.28318 +static void unixUnmapfile(unixFile *pFd){
 1.28319 +  assert( pFd->nFetchOut==0 );
 1.28320 +  if( pFd->pMapRegion ){
 1.28321 +    osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
 1.28322 +    pFd->pMapRegion = 0;
 1.28323 +    pFd->mmapSize = 0;
 1.28324 +    pFd->mmapSizeActual = 0;
 1.28325 +  }
 1.28326 +}
 1.28327 +
 1.28328 +/*
 1.28329 +** Return the system page size.
 1.28330 +*/
 1.28331 +static int unixGetPagesize(void){
 1.28332 +#if HAVE_MREMAP
 1.28333 +  return 512;
 1.28334 +#elif defined(_BSD_SOURCE)
 1.28335 +  return getpagesize();
 1.28336 +#else
 1.28337 +  return (int)sysconf(_SC_PAGESIZE);
 1.28338 +#endif
 1.28339 +}
 1.28340 +
 1.28341 +/*
 1.28342 +** Attempt to set the size of the memory mapping maintained by file 
 1.28343 +** descriptor pFd to nNew bytes. Any existing mapping is discarded.
 1.28344 +**
 1.28345 +** If successful, this function sets the following variables:
 1.28346 +**
 1.28347 +**       unixFile.pMapRegion
 1.28348 +**       unixFile.mmapSize
 1.28349 +**       unixFile.mmapSizeActual
 1.28350 +**
 1.28351 +** If unsuccessful, an error message is logged via sqlite3_log() and
 1.28352 +** the three variables above are zeroed. In this case SQLite should
 1.28353 +** continue accessing the database using the xRead() and xWrite()
 1.28354 +** methods.
 1.28355 +*/
 1.28356 +static void unixRemapfile(
 1.28357 +  unixFile *pFd,                  /* File descriptor object */
 1.28358 +  i64 nNew                        /* Required mapping size */
 1.28359 +){
 1.28360 +  const char *zErr = "mmap";
 1.28361 +  int h = pFd->h;                      /* File descriptor open on db file */
 1.28362 +  u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */
 1.28363 +  i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */
 1.28364 +  u8 *pNew = 0;                        /* Location of new mapping */
 1.28365 +  int flags = PROT_READ;               /* Flags to pass to mmap() */
 1.28366 +
 1.28367 +  assert( pFd->nFetchOut==0 );
 1.28368 +  assert( nNew>pFd->mmapSize );
 1.28369 +  assert( nNew<=pFd->mmapSizeMax );
 1.28370 +  assert( nNew>0 );
 1.28371 +  assert( pFd->mmapSizeActual>=pFd->mmapSize );
 1.28372 +  assert( MAP_FAILED!=0 );
 1.28373 +
 1.28374 +  if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
 1.28375 +
 1.28376 +  if( pOrig ){
 1.28377 +    const int szSyspage = unixGetPagesize();
 1.28378 +    i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
 1.28379 +    u8 *pReq = &pOrig[nReuse];
 1.28380 +
 1.28381 +    /* Unmap any pages of the existing mapping that cannot be reused. */
 1.28382 +    if( nReuse!=nOrig ){
 1.28383 +      osMunmap(pReq, nOrig-nReuse);
 1.28384 +    }
 1.28385 +
 1.28386 +#if HAVE_MREMAP
 1.28387 +    pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
 1.28388 +    zErr = "mremap";
 1.28389 +#else
 1.28390 +    pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
 1.28391 +    if( pNew!=MAP_FAILED ){
 1.28392 +      if( pNew!=pReq ){
 1.28393 +        osMunmap(pNew, nNew - nReuse);
 1.28394 +        pNew = 0;
 1.28395 +      }else{
 1.28396 +        pNew = pOrig;
 1.28397 +      }
 1.28398 +    }
 1.28399 +#endif
 1.28400 +
 1.28401 +    /* The attempt to extend the existing mapping failed. Free it. */
 1.28402 +    if( pNew==MAP_FAILED || pNew==0 ){
 1.28403 +      osMunmap(pOrig, nReuse);
 1.28404 +    }
 1.28405 +  }
 1.28406 +
 1.28407 +  /* If pNew is still NULL, try to create an entirely new mapping. */
 1.28408 +  if( pNew==0 ){
 1.28409 +    pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
 1.28410 +  }
 1.28411 +
 1.28412 +  if( pNew==MAP_FAILED ){
 1.28413 +    pNew = 0;
 1.28414 +    nNew = 0;
 1.28415 +    unixLogError(SQLITE_OK, zErr, pFd->zPath);
 1.28416 +
 1.28417 +    /* If the mmap() above failed, assume that all subsequent mmap() calls
 1.28418 +    ** will probably fail too. Fall back to using xRead/xWrite exclusively
 1.28419 +    ** in this case.  */
 1.28420 +    pFd->mmapSizeMax = 0;
 1.28421 +  }
 1.28422 +  pFd->pMapRegion = (void *)pNew;
 1.28423 +  pFd->mmapSize = pFd->mmapSizeActual = nNew;
 1.28424 +}
 1.28425 +
 1.28426 +/*
 1.28427 +** Memory map or remap the file opened by file-descriptor pFd (if the file
 1.28428 +** is already mapped, the existing mapping is replaced by the new). Or, if 
 1.28429 +** there already exists a mapping for this file, and there are still 
 1.28430 +** outstanding xFetch() references to it, this function is a no-op.
 1.28431 +**
 1.28432 +** If parameter nByte is non-negative, then it is the requested size of 
 1.28433 +** the mapping to create. Otherwise, if nByte is less than zero, then the 
 1.28434 +** requested size is the size of the file on disk. The actual size of the
 1.28435 +** created mapping is either the requested size or the value configured 
 1.28436 +** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
 1.28437 +**
 1.28438 +** SQLITE_OK is returned if no error occurs (even if the mapping is not
 1.28439 +** recreated as a result of outstanding references) or an SQLite error
 1.28440 +** code otherwise.
 1.28441 +*/
 1.28442 +static int unixMapfile(unixFile *pFd, i64 nByte){
 1.28443 +  i64 nMap = nByte;
 1.28444 +  int rc;
 1.28445 +
 1.28446 +  assert( nMap>=0 || pFd->nFetchOut==0 );
 1.28447 +  if( pFd->nFetchOut>0 ) return SQLITE_OK;
 1.28448 +
 1.28449 +  if( nMap<0 ){
 1.28450 +    struct stat statbuf;          /* Low-level file information */
 1.28451 +    rc = osFstat(pFd->h, &statbuf);
 1.28452 +    if( rc!=SQLITE_OK ){
 1.28453 +      return SQLITE_IOERR_FSTAT;
 1.28454 +    }
 1.28455 +    nMap = statbuf.st_size;
 1.28456 +  }
 1.28457 +  if( nMap>pFd->mmapSizeMax ){
 1.28458 +    nMap = pFd->mmapSizeMax;
 1.28459 +  }
 1.28460 +
 1.28461 +  if( nMap!=pFd->mmapSize ){
 1.28462 +    if( nMap>0 ){
 1.28463 +      unixRemapfile(pFd, nMap);
 1.28464 +    }else{
 1.28465 +      unixUnmapfile(pFd);
 1.28466 +    }
 1.28467 +  }
 1.28468 +
 1.28469 +  return SQLITE_OK;
 1.28470 +}
 1.28471 +#endif /* SQLITE_MAX_MMAP_SIZE>0 */
 1.28472 +
 1.28473 +/*
 1.28474 +** If possible, return a pointer to a mapping of file fd starting at offset
 1.28475 +** iOff. The mapping must be valid for at least nAmt bytes.
 1.28476 +**
 1.28477 +** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
 1.28478 +** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
 1.28479 +** Finally, if an error does occur, return an SQLite error code. The final
 1.28480 +** value of *pp is undefined in this case.
 1.28481 +**
 1.28482 +** If this function does return a pointer, the caller must eventually 
 1.28483 +** release the reference by calling unixUnfetch().
 1.28484 +*/
 1.28485 +static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
 1.28486 +#if SQLITE_MAX_MMAP_SIZE>0
 1.28487 +  unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
 1.28488 +#endif
 1.28489 +  *pp = 0;
 1.28490 +
 1.28491 +#if SQLITE_MAX_MMAP_SIZE>0
 1.28492 +  if( pFd->mmapSizeMax>0 ){
 1.28493 +    if( pFd->pMapRegion==0 ){
 1.28494 +      int rc = unixMapfile(pFd, -1);
 1.28495 +      if( rc!=SQLITE_OK ) return rc;
 1.28496 +    }
 1.28497 +    if( pFd->mmapSize >= iOff+nAmt ){
 1.28498 +      *pp = &((u8 *)pFd->pMapRegion)[iOff];
 1.28499 +      pFd->nFetchOut++;
 1.28500 +    }
 1.28501 +  }
 1.28502 +#endif
 1.28503 +  return SQLITE_OK;
 1.28504 +}
 1.28505 +
 1.28506 +/*
 1.28507 +** If the third argument is non-NULL, then this function releases a 
 1.28508 +** reference obtained by an earlier call to unixFetch(). The second
 1.28509 +** argument passed to this function must be the same as the corresponding
 1.28510 +** argument that was passed to the unixFetch() invocation. 
 1.28511 +**
 1.28512 +** Or, if the third argument is NULL, then this function is being called 
 1.28513 +** to inform the VFS layer that, according to POSIX, any existing mapping 
 1.28514 +** may now be invalid and should be unmapped.
 1.28515 +*/
 1.28516 +static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
 1.28517 +#if SQLITE_MAX_MMAP_SIZE>0
 1.28518 +  unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
 1.28519 +  UNUSED_PARAMETER(iOff);
 1.28520 +
 1.28521 +  /* If p==0 (unmap the entire file) then there must be no outstanding 
 1.28522 +  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
 1.28523 +  ** then there must be at least one outstanding.  */
 1.28524 +  assert( (p==0)==(pFd->nFetchOut==0) );
 1.28525 +
 1.28526 +  /* If p!=0, it must match the iOff value. */
 1.28527 +  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
 1.28528 +
 1.28529 +  if( p ){
 1.28530 +    pFd->nFetchOut--;
 1.28531 +  }else{
 1.28532 +    unixUnmapfile(pFd);
 1.28533 +  }
 1.28534 +
 1.28535 +  assert( pFd->nFetchOut>=0 );
 1.28536 +#else
 1.28537 +  UNUSED_PARAMETER(fd);
 1.28538 +  UNUSED_PARAMETER(p);
 1.28539 +  UNUSED_PARAMETER(iOff);
 1.28540 +#endif
 1.28541 +  return SQLITE_OK;
 1.28542 +}
 1.28543 +
 1.28544 +/*
 1.28545 +** Here ends the implementation of all sqlite3_file methods.
 1.28546 +**
 1.28547 +********************** End sqlite3_file Methods *******************************
 1.28548 +******************************************************************************/
 1.28549 +
 1.28550 +/*
 1.28551 +** This division contains definitions of sqlite3_io_methods objects that
 1.28552 +** implement various file locking strategies.  It also contains definitions
 1.28553 +** of "finder" functions.  A finder-function is used to locate the appropriate
 1.28554 +** sqlite3_io_methods object for a particular database file.  The pAppData
 1.28555 +** field of the sqlite3_vfs VFS objects are initialized to be pointers to
 1.28556 +** the correct finder-function for that VFS.
 1.28557 +**
 1.28558 +** Most finder functions return a pointer to a fixed sqlite3_io_methods
 1.28559 +** object.  The only interesting finder-function is autolockIoFinder, which
 1.28560 +** looks at the filesystem type and tries to guess the best locking
 1.28561 +** strategy from that.
 1.28562 +**
 1.28563 +** For finder-funtion F, two objects are created:
 1.28564 +**
 1.28565 +**    (1) The real finder-function named "FImpt()".
 1.28566 +**
 1.28567 +**    (2) A constant pointer to this function named just "F".
 1.28568 +**
 1.28569 +**
 1.28570 +** A pointer to the F pointer is used as the pAppData value for VFS
 1.28571 +** objects.  We have to do this instead of letting pAppData point
 1.28572 +** directly at the finder-function since C90 rules prevent a void*
 1.28573 +** from be cast into a function pointer.
 1.28574 +**
 1.28575 +**
 1.28576 +** Each instance of this macro generates two objects:
 1.28577 +**
 1.28578 +**   *  A constant sqlite3_io_methods object call METHOD that has locking
 1.28579 +**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
 1.28580 +**
 1.28581 +**   *  An I/O method finder function called FINDER that returns a pointer
 1.28582 +**      to the METHOD object in the previous bullet.
 1.28583 +*/
 1.28584 +#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
 1.28585 +static const sqlite3_io_methods METHOD = {                                   \
 1.28586 +   VERSION,                    /* iVersion */                                \
 1.28587 +   CLOSE,                      /* xClose */                                  \
 1.28588 +   unixRead,                   /* xRead */                                   \
 1.28589 +   unixWrite,                  /* xWrite */                                  \
 1.28590 +   unixTruncate,               /* xTruncate */                               \
 1.28591 +   unixSync,                   /* xSync */                                   \
 1.28592 +   unixFileSize,               /* xFileSize */                               \
 1.28593 +   LOCK,                       /* xLock */                                   \
 1.28594 +   UNLOCK,                     /* xUnlock */                                 \
 1.28595 +   CKLOCK,                     /* xCheckReservedLock */                      \
 1.28596 +   unixFileControl,            /* xFileControl */                            \
 1.28597 +   unixSectorSize,             /* xSectorSize */                             \
 1.28598 +   unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
 1.28599 +   unixShmMap,                 /* xShmMap */                                 \
 1.28600 +   unixShmLock,                /* xShmLock */                                \
 1.28601 +   unixShmBarrier,             /* xShmBarrier */                             \
 1.28602 +   unixShmUnmap,               /* xShmUnmap */                               \
 1.28603 +   unixFetch,                  /* xFetch */                                  \
 1.28604 +   unixUnfetch,                /* xUnfetch */                                \
 1.28605 +};                                                                           \
 1.28606 +static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
 1.28607 +  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
 1.28608 +  return &METHOD;                                                            \
 1.28609 +}                                                                            \
 1.28610 +static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
 1.28611 +    = FINDER##Impl;
 1.28612 +
 1.28613 +/*
 1.28614 +** Here are all of the sqlite3_io_methods objects for each of the
 1.28615 +** locking strategies.  Functions that return pointers to these methods
 1.28616 +** are also created.
 1.28617 +*/
 1.28618 +IOMETHODS(
 1.28619 +  posixIoFinder,            /* Finder function name */
 1.28620 +  posixIoMethods,           /* sqlite3_io_methods object name */
 1.28621 +  3,                        /* shared memory and mmap are enabled */
 1.28622 +  unixClose,                /* xClose method */
 1.28623 +  unixLock,                 /* xLock method */
 1.28624 +  unixUnlock,               /* xUnlock method */
 1.28625 +  unixCheckReservedLock     /* xCheckReservedLock method */
 1.28626 +)
 1.28627 +IOMETHODS(
 1.28628 +  nolockIoFinder,           /* Finder function name */
 1.28629 +  nolockIoMethods,          /* sqlite3_io_methods object name */
 1.28630 +  1,                        /* shared memory is disabled */
 1.28631 +  nolockClose,              /* xClose method */
 1.28632 +  nolockLock,               /* xLock method */
 1.28633 +  nolockUnlock,             /* xUnlock method */
 1.28634 +  nolockCheckReservedLock   /* xCheckReservedLock method */
 1.28635 +)
 1.28636 +IOMETHODS(
 1.28637 +  dotlockIoFinder,          /* Finder function name */
 1.28638 +  dotlockIoMethods,         /* sqlite3_io_methods object name */
 1.28639 +  1,                        /* shared memory is disabled */
 1.28640 +  dotlockClose,             /* xClose method */
 1.28641 +  dotlockLock,              /* xLock method */
 1.28642 +  dotlockUnlock,            /* xUnlock method */
 1.28643 +  dotlockCheckReservedLock  /* xCheckReservedLock method */
 1.28644 +)
 1.28645 +
 1.28646 +#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
 1.28647 +IOMETHODS(
 1.28648 +  flockIoFinder,            /* Finder function name */
 1.28649 +  flockIoMethods,           /* sqlite3_io_methods object name */
 1.28650 +  1,                        /* shared memory is disabled */
 1.28651 +  flockClose,               /* xClose method */
 1.28652 +  flockLock,                /* xLock method */
 1.28653 +  flockUnlock,              /* xUnlock method */
 1.28654 +  flockCheckReservedLock    /* xCheckReservedLock method */
 1.28655 +)
 1.28656 +#endif
 1.28657 +
 1.28658 +#if OS_VXWORKS
 1.28659 +IOMETHODS(
 1.28660 +  semIoFinder,              /* Finder function name */
 1.28661 +  semIoMethods,             /* sqlite3_io_methods object name */
 1.28662 +  1,                        /* shared memory is disabled */
 1.28663 +  semClose,                 /* xClose method */
 1.28664 +  semLock,                  /* xLock method */
 1.28665 +  semUnlock,                /* xUnlock method */
 1.28666 +  semCheckReservedLock      /* xCheckReservedLock method */
 1.28667 +)
 1.28668 +#endif
 1.28669 +
 1.28670 +#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 1.28671 +IOMETHODS(
 1.28672 +  afpIoFinder,              /* Finder function name */
 1.28673 +  afpIoMethods,             /* sqlite3_io_methods object name */
 1.28674 +  1,                        /* shared memory is disabled */
 1.28675 +  afpClose,                 /* xClose method */
 1.28676 +  afpLock,                  /* xLock method */
 1.28677 +  afpUnlock,                /* xUnlock method */
 1.28678 +  afpCheckReservedLock      /* xCheckReservedLock method */
 1.28679 +)
 1.28680 +#endif
 1.28681 +
 1.28682 +/*
 1.28683 +** The proxy locking method is a "super-method" in the sense that it
 1.28684 +** opens secondary file descriptors for the conch and lock files and
 1.28685 +** it uses proxy, dot-file, AFP, and flock() locking methods on those
 1.28686 +** secondary files.  For this reason, the division that implements
 1.28687 +** proxy locking is located much further down in the file.  But we need
 1.28688 +** to go ahead and define the sqlite3_io_methods and finder function
 1.28689 +** for proxy locking here.  So we forward declare the I/O methods.
 1.28690 +*/
 1.28691 +#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 1.28692 +static int proxyClose(sqlite3_file*);
 1.28693 +static int proxyLock(sqlite3_file*, int);
 1.28694 +static int proxyUnlock(sqlite3_file*, int);
 1.28695 +static int proxyCheckReservedLock(sqlite3_file*, int*);
 1.28696 +IOMETHODS(
 1.28697 +  proxyIoFinder,            /* Finder function name */
 1.28698 +  proxyIoMethods,           /* sqlite3_io_methods object name */
 1.28699 +  1,                        /* shared memory is disabled */
 1.28700 +  proxyClose,               /* xClose method */
 1.28701 +  proxyLock,                /* xLock method */
 1.28702 +  proxyUnlock,              /* xUnlock method */
 1.28703 +  proxyCheckReservedLock    /* xCheckReservedLock method */
 1.28704 +)
 1.28705 +#endif
 1.28706 +
 1.28707 +/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
 1.28708 +#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 1.28709 +IOMETHODS(
 1.28710 +  nfsIoFinder,               /* Finder function name */
 1.28711 +  nfsIoMethods,              /* sqlite3_io_methods object name */
 1.28712 +  1,                         /* shared memory is disabled */
 1.28713 +  unixClose,                 /* xClose method */
 1.28714 +  unixLock,                  /* xLock method */
 1.28715 +  nfsUnlock,                 /* xUnlock method */
 1.28716 +  unixCheckReservedLock      /* xCheckReservedLock method */
 1.28717 +)
 1.28718 +#endif
 1.28719 +
 1.28720 +#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 1.28721 +/* 
 1.28722 +** This "finder" function attempts to determine the best locking strategy 
 1.28723 +** for the database file "filePath".  It then returns the sqlite3_io_methods
 1.28724 +** object that implements that strategy.
 1.28725 +**
 1.28726 +** This is for MacOSX only.
 1.28727 +*/
 1.28728 +static const sqlite3_io_methods *autolockIoFinderImpl(
 1.28729 +  const char *filePath,    /* name of the database file */
 1.28730 +  unixFile *pNew           /* open file object for the database file */
 1.28731 +){
 1.28732 +  static const struct Mapping {
 1.28733 +    const char *zFilesystem;              /* Filesystem type name */
 1.28734 +    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
 1.28735 +  } aMap[] = {
 1.28736 +    { "hfs",    &posixIoMethods },
 1.28737 +    { "ufs",    &posixIoMethods },
 1.28738 +    { "afpfs",  &afpIoMethods },
 1.28739 +    { "smbfs",  &afpIoMethods },
 1.28740 +    { "webdav", &nolockIoMethods },
 1.28741 +    { 0, 0 }
 1.28742 +  };
 1.28743 +  int i;
 1.28744 +  struct statfs fsInfo;
 1.28745 +  struct flock lockInfo;
 1.28746 +
 1.28747 +  if( !filePath ){
 1.28748 +    /* If filePath==NULL that means we are dealing with a transient file
 1.28749 +    ** that does not need to be locked. */
 1.28750 +    return &nolockIoMethods;
 1.28751 +  }
 1.28752 +  if( statfs(filePath, &fsInfo) != -1 ){
 1.28753 +    if( fsInfo.f_flags & MNT_RDONLY ){
 1.28754 +      return &nolockIoMethods;
 1.28755 +    }
 1.28756 +    for(i=0; aMap[i].zFilesystem; i++){
 1.28757 +      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
 1.28758 +        return aMap[i].pMethods;
 1.28759 +      }
 1.28760 +    }
 1.28761 +  }
 1.28762 +
 1.28763 +  /* Default case. Handles, amongst others, "nfs".
 1.28764 +  ** Test byte-range lock using fcntl(). If the call succeeds, 
 1.28765 +  ** assume that the file-system supports POSIX style locks. 
 1.28766 +  */
 1.28767 +  lockInfo.l_len = 1;
 1.28768 +  lockInfo.l_start = 0;
 1.28769 +  lockInfo.l_whence = SEEK_SET;
 1.28770 +  lockInfo.l_type = F_RDLCK;
 1.28771 +  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
 1.28772 +    if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
 1.28773 +      return &nfsIoMethods;
 1.28774 +    } else {
 1.28775 +      return &posixIoMethods;
 1.28776 +    }
 1.28777 +  }else{
 1.28778 +    return &dotlockIoMethods;
 1.28779 +  }
 1.28780 +}
 1.28781 +static const sqlite3_io_methods 
 1.28782 +  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
 1.28783 +
 1.28784 +#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
 1.28785 +
 1.28786 +#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
 1.28787 +/* 
 1.28788 +** This "finder" function attempts to determine the best locking strategy 
 1.28789 +** for the database file "filePath".  It then returns the sqlite3_io_methods
 1.28790 +** object that implements that strategy.
 1.28791 +**
 1.28792 +** This is for VXWorks only.
 1.28793 +*/
 1.28794 +static const sqlite3_io_methods *autolockIoFinderImpl(
 1.28795 +  const char *filePath,    /* name of the database file */
 1.28796 +  unixFile *pNew           /* the open file object */
 1.28797 +){
 1.28798 +  struct flock lockInfo;
 1.28799 +
 1.28800 +  if( !filePath ){
 1.28801 +    /* If filePath==NULL that means we are dealing with a transient file
 1.28802 +    ** that does not need to be locked. */
 1.28803 +    return &nolockIoMethods;
 1.28804 +  }
 1.28805 +
 1.28806 +  /* Test if fcntl() is supported and use POSIX style locks.
 1.28807 +  ** Otherwise fall back to the named semaphore method.
 1.28808 +  */
 1.28809 +  lockInfo.l_len = 1;
 1.28810 +  lockInfo.l_start = 0;
 1.28811 +  lockInfo.l_whence = SEEK_SET;
 1.28812 +  lockInfo.l_type = F_RDLCK;
 1.28813 +  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
 1.28814 +    return &posixIoMethods;
 1.28815 +  }else{
 1.28816 +    return &semIoMethods;
 1.28817 +  }
 1.28818 +}
 1.28819 +static const sqlite3_io_methods 
 1.28820 +  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
 1.28821 +
 1.28822 +#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
 1.28823 +
 1.28824 +/*
 1.28825 +** An abstract type for a pointer to a IO method finder function:
 1.28826 +*/
 1.28827 +typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
 1.28828 +
 1.28829 +
 1.28830 +/****************************************************************************
 1.28831 +**************************** sqlite3_vfs methods ****************************
 1.28832 +**
 1.28833 +** This division contains the implementation of methods on the
 1.28834 +** sqlite3_vfs object.
 1.28835 +*/
 1.28836 +
 1.28837 +/*
 1.28838 +** Initialize the contents of the unixFile structure pointed to by pId.
 1.28839 +*/
 1.28840 +static int fillInUnixFile(
 1.28841 +  sqlite3_vfs *pVfs,      /* Pointer to vfs object */
 1.28842 +  int h,                  /* Open file descriptor of file being opened */
 1.28843 +  sqlite3_file *pId,      /* Write to the unixFile structure here */
 1.28844 +  const char *zFilename,  /* Name of the file being opened */
 1.28845 +  int ctrlFlags           /* Zero or more UNIXFILE_* values */
 1.28846 +){
 1.28847 +  const sqlite3_io_methods *pLockingStyle;
 1.28848 +  unixFile *pNew = (unixFile *)pId;
 1.28849 +  int rc = SQLITE_OK;
 1.28850 +
 1.28851 +  assert( pNew->pInode==NULL );
 1.28852 +
 1.28853 +  /* Usually the path zFilename should not be a relative pathname. The
 1.28854 +  ** exception is when opening the proxy "conch" file in builds that
 1.28855 +  ** include the special Apple locking styles.
 1.28856 +  */
 1.28857 +#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 1.28858 +  assert( zFilename==0 || zFilename[0]=='/' 
 1.28859 +    || pVfs->pAppData==(void*)&autolockIoFinder );
 1.28860 +#else
 1.28861 +  assert( zFilename==0 || zFilename[0]=='/' );
 1.28862 +#endif
 1.28863 +
 1.28864 +  /* No locking occurs in temporary files */
 1.28865 +  assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
 1.28866 +
 1.28867 +  OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
 1.28868 +  pNew->h = h;
 1.28869 +  pNew->pVfs = pVfs;
 1.28870 +  pNew->zPath = zFilename;
 1.28871 +  pNew->ctrlFlags = (u8)ctrlFlags;
 1.28872 +#if SQLITE_MAX_MMAP_SIZE>0
 1.28873 +  pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
 1.28874 +#endif
 1.28875 +  if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
 1.28876 +                           "psow", SQLITE_POWERSAFE_OVERWRITE) ){
 1.28877 +    pNew->ctrlFlags |= UNIXFILE_PSOW;
 1.28878 +  }
 1.28879 +  if( strcmp(pVfs->zName,"unix-excl")==0 ){
 1.28880 +    pNew->ctrlFlags |= UNIXFILE_EXCL;
 1.28881 +  }
 1.28882 +
 1.28883 +#if OS_VXWORKS
 1.28884 +  pNew->pId = vxworksFindFileId(zFilename);
 1.28885 +  if( pNew->pId==0 ){
 1.28886 +    ctrlFlags |= UNIXFILE_NOLOCK;
 1.28887 +    rc = SQLITE_NOMEM;
 1.28888 +  }
 1.28889 +#endif
 1.28890 +
 1.28891 +  if( ctrlFlags & UNIXFILE_NOLOCK ){
 1.28892 +    pLockingStyle = &nolockIoMethods;
 1.28893 +  }else{
 1.28894 +    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
 1.28895 +#if SQLITE_ENABLE_LOCKING_STYLE
 1.28896 +    /* Cache zFilename in the locking context (AFP and dotlock override) for
 1.28897 +    ** proxyLock activation is possible (remote proxy is based on db name)
 1.28898 +    ** zFilename remains valid until file is closed, to support */
 1.28899 +    pNew->lockingContext = (void*)zFilename;
 1.28900 +#endif
 1.28901 +  }
 1.28902 +
 1.28903 +  if( pLockingStyle == &posixIoMethods
 1.28904 +#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 1.28905 +    || pLockingStyle == &nfsIoMethods
 1.28906 +#endif
 1.28907 +  ){
 1.28908 +    unixEnterMutex();
 1.28909 +    rc = findInodeInfo(pNew, &pNew->pInode);
 1.28910 +    if( rc!=SQLITE_OK ){
 1.28911 +      /* If an error occurred in findInodeInfo(), close the file descriptor
 1.28912 +      ** immediately, before releasing the mutex. findInodeInfo() may fail
 1.28913 +      ** in two scenarios:
 1.28914 +      **
 1.28915 +      **   (a) A call to fstat() failed.
 1.28916 +      **   (b) A malloc failed.
 1.28917 +      **
 1.28918 +      ** Scenario (b) may only occur if the process is holding no other
 1.28919 +      ** file descriptors open on the same file. If there were other file
 1.28920 +      ** descriptors on this file, then no malloc would be required by
 1.28921 +      ** findInodeInfo(). If this is the case, it is quite safe to close
 1.28922 +      ** handle h - as it is guaranteed that no posix locks will be released
 1.28923 +      ** by doing so.
 1.28924 +      **
 1.28925 +      ** If scenario (a) caused the error then things are not so safe. The
 1.28926 +      ** implicit assumption here is that if fstat() fails, things are in
 1.28927 +      ** such bad shape that dropping a lock or two doesn't matter much.
 1.28928 +      */
 1.28929 +      robust_close(pNew, h, __LINE__);
 1.28930 +      h = -1;
 1.28931 +    }
 1.28932 +    unixLeaveMutex();
 1.28933 +  }
 1.28934 +
 1.28935 +#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
 1.28936 +  else if( pLockingStyle == &afpIoMethods ){
 1.28937 +    /* AFP locking uses the file path so it needs to be included in
 1.28938 +    ** the afpLockingContext.
 1.28939 +    */
 1.28940 +    afpLockingContext *pCtx;
 1.28941 +    pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
 1.28942 +    if( pCtx==0 ){
 1.28943 +      rc = SQLITE_NOMEM;
 1.28944 +    }else{
 1.28945 +      /* NB: zFilename exists and remains valid until the file is closed
 1.28946 +      ** according to requirement F11141.  So we do not need to make a
 1.28947 +      ** copy of the filename. */
 1.28948 +      pCtx->dbPath = zFilename;
 1.28949 +      pCtx->reserved = 0;
 1.28950 +      srandomdev();
 1.28951 +      unixEnterMutex();
 1.28952 +      rc = findInodeInfo(pNew, &pNew->pInode);
 1.28953 +      if( rc!=SQLITE_OK ){
 1.28954 +        sqlite3_free(pNew->lockingContext);
 1.28955 +        robust_close(pNew, h, __LINE__);
 1.28956 +        h = -1;
 1.28957 +      }
 1.28958 +      unixLeaveMutex();        
 1.28959 +    }
 1.28960 +  }
 1.28961 +#endif
 1.28962 +
 1.28963 +  else if( pLockingStyle == &dotlockIoMethods ){
 1.28964 +    /* Dotfile locking uses the file path so it needs to be included in
 1.28965 +    ** the dotlockLockingContext 
 1.28966 +    */
 1.28967 +    char *zLockFile;
 1.28968 +    int nFilename;
 1.28969 +    assert( zFilename!=0 );
 1.28970 +    nFilename = (int)strlen(zFilename) + 6;
 1.28971 +    zLockFile = (char *)sqlite3_malloc(nFilename);
 1.28972 +    if( zLockFile==0 ){
 1.28973 +      rc = SQLITE_NOMEM;
 1.28974 +    }else{
 1.28975 +      sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
 1.28976 +    }
 1.28977 +    pNew->lockingContext = zLockFile;
 1.28978 +  }
 1.28979 +
 1.28980 +#if OS_VXWORKS
 1.28981 +  else if( pLockingStyle == &semIoMethods ){
 1.28982 +    /* Named semaphore locking uses the file path so it needs to be
 1.28983 +    ** included in the semLockingContext
 1.28984 +    */
 1.28985 +    unixEnterMutex();
 1.28986 +    rc = findInodeInfo(pNew, &pNew->pInode);
 1.28987 +    if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
 1.28988 +      char *zSemName = pNew->pInode->aSemName;
 1.28989 +      int n;
 1.28990 +      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
 1.28991 +                       pNew->pId->zCanonicalName);
 1.28992 +      for( n=1; zSemName[n]; n++ )
 1.28993 +        if( zSemName[n]=='/' ) zSemName[n] = '_';
 1.28994 +      pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
 1.28995 +      if( pNew->pInode->pSem == SEM_FAILED ){
 1.28996 +        rc = SQLITE_NOMEM;
 1.28997 +        pNew->pInode->aSemName[0] = '\0';
 1.28998 +      }
 1.28999 +    }
 1.29000 +    unixLeaveMutex();
 1.29001 +  }
 1.29002 +#endif
 1.29003 +  
 1.29004 +  pNew->lastErrno = 0;
 1.29005 +#if OS_VXWORKS
 1.29006 +  if( rc!=SQLITE_OK ){
 1.29007 +    if( h>=0 ) robust_close(pNew, h, __LINE__);
 1.29008 +    h = -1;
 1.29009 +    osUnlink(zFilename);
 1.29010 +    pNew->ctrlFlags |= UNIXFILE_DELETE;
 1.29011 +  }
 1.29012 +#endif
 1.29013 +  if( rc!=SQLITE_OK ){
 1.29014 +    if( h>=0 ) robust_close(pNew, h, __LINE__);
 1.29015 +  }else{
 1.29016 +    pNew->pMethod = pLockingStyle;
 1.29017 +    OpenCounter(+1);
 1.29018 +    verifyDbFile(pNew);
 1.29019 +  }
 1.29020 +  return rc;
 1.29021 +}
 1.29022 +
 1.29023 +/*
 1.29024 +** Return the name of a directory in which to put temporary files.
 1.29025 +** If no suitable temporary file directory can be found, return NULL.
 1.29026 +*/
 1.29027 +static const char *unixTempFileDir(void){
 1.29028 +  static const char *azDirs[] = {
 1.29029 +     0,
 1.29030 +     0,
 1.29031 +     0,
 1.29032 +     "/var/tmp",
 1.29033 +     "/usr/tmp",
 1.29034 +     "/tmp",
 1.29035 +     0        /* List terminator */
 1.29036 +  };
 1.29037 +  unsigned int i;
 1.29038 +  struct stat buf;
 1.29039 +  const char *zDir = 0;
 1.29040 +
 1.29041 +  azDirs[0] = sqlite3_temp_directory;
 1.29042 +  if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
 1.29043 +  if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
 1.29044 +  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
 1.29045 +    if( zDir==0 ) continue;
 1.29046 +    if( osStat(zDir, &buf) ) continue;
 1.29047 +    if( !S_ISDIR(buf.st_mode) ) continue;
 1.29048 +    if( osAccess(zDir, 07) ) continue;
 1.29049 +    break;
 1.29050 +  }
 1.29051 +  return zDir;
 1.29052 +}
 1.29053 +
 1.29054 +/*
 1.29055 +** Create a temporary file name in zBuf.  zBuf must be allocated
 1.29056 +** by the calling process and must be big enough to hold at least
 1.29057 +** pVfs->mxPathname bytes.
 1.29058 +*/
 1.29059 +static int unixGetTempname(int nBuf, char *zBuf){
 1.29060 +  static const unsigned char zChars[] =
 1.29061 +    "abcdefghijklmnopqrstuvwxyz"
 1.29062 +    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 1.29063 +    "0123456789";
 1.29064 +  unsigned int i, j;
 1.29065 +  const char *zDir;
 1.29066 +
 1.29067 +  /* It's odd to simulate an io-error here, but really this is just
 1.29068 +  ** using the io-error infrastructure to test that SQLite handles this
 1.29069 +  ** function failing. 
 1.29070 +  */
 1.29071 +  SimulateIOError( return SQLITE_IOERR );
 1.29072 +
 1.29073 +  zDir = unixTempFileDir();
 1.29074 +  if( zDir==0 ) zDir = ".";
 1.29075 +
 1.29076 +  /* Check that the output buffer is large enough for the temporary file 
 1.29077 +  ** name. If it is not, return SQLITE_ERROR.
 1.29078 +  */
 1.29079 +  if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
 1.29080 +    return SQLITE_ERROR;
 1.29081 +  }
 1.29082 +
 1.29083 +  do{
 1.29084 +    sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
 1.29085 +    j = (int)strlen(zBuf);
 1.29086 +    sqlite3_randomness(15, &zBuf[j]);
 1.29087 +    for(i=0; i<15; i++, j++){
 1.29088 +      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
 1.29089 +    }
 1.29090 +    zBuf[j] = 0;
 1.29091 +    zBuf[j+1] = 0;
 1.29092 +  }while( osAccess(zBuf,0)==0 );
 1.29093 +  return SQLITE_OK;
 1.29094 +}
 1.29095 +
 1.29096 +#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
 1.29097 +/*
 1.29098 +** Routine to transform a unixFile into a proxy-locking unixFile.
 1.29099 +** Implementation in the proxy-lock division, but used by unixOpen()
 1.29100 +** if SQLITE_PREFER_PROXY_LOCKING is defined.
 1.29101 +*/
 1.29102 +static int proxyTransformUnixFile(unixFile*, const char*);
 1.29103 +#endif
 1.29104 +
 1.29105 +/*
 1.29106 +** Search for an unused file descriptor that was opened on the database 
 1.29107 +** file (not a journal or master-journal file) identified by pathname
 1.29108 +** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
 1.29109 +** argument to this function.
 1.29110 +**
 1.29111 +** Such a file descriptor may exist if a database connection was closed
 1.29112 +** but the associated file descriptor could not be closed because some
 1.29113 +** other file descriptor open on the same file is holding a file-lock.
 1.29114 +** Refer to comments in the unixClose() function and the lengthy comment
 1.29115 +** describing "Posix Advisory Locking" at the start of this file for 
 1.29116 +** further details. Also, ticket #4018.
 1.29117 +**
 1.29118 +** If a suitable file descriptor is found, then it is returned. If no
 1.29119 +** such file descriptor is located, -1 is returned.
 1.29120 +*/
 1.29121 +static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
 1.29122 +  UnixUnusedFd *pUnused = 0;
 1.29123 +
 1.29124 +  /* Do not search for an unused file descriptor on vxworks. Not because
 1.29125 +  ** vxworks would not benefit from the change (it might, we're not sure),
 1.29126 +  ** but because no way to test it is currently available. It is better 
 1.29127 +  ** not to risk breaking vxworks support for the sake of such an obscure 
 1.29128 +  ** feature.  */
 1.29129 +#if !OS_VXWORKS
 1.29130 +  struct stat sStat;                   /* Results of stat() call */
 1.29131 +
 1.29132 +  /* A stat() call may fail for various reasons. If this happens, it is
 1.29133 +  ** almost certain that an open() call on the same path will also fail.
 1.29134 +  ** For this reason, if an error occurs in the stat() call here, it is
 1.29135 +  ** ignored and -1 is returned. The caller will try to open a new file
 1.29136 +  ** descriptor on the same path, fail, and return an error to SQLite.
 1.29137 +  **
 1.29138 +  ** Even if a subsequent open() call does succeed, the consequences of
 1.29139 +  ** not searching for a resusable file descriptor are not dire.  */
 1.29140 +  if( 0==osStat(zPath, &sStat) ){
 1.29141 +    unixInodeInfo *pInode;
 1.29142 +
 1.29143 +    unixEnterMutex();
 1.29144 +    pInode = inodeList;
 1.29145 +    while( pInode && (pInode->fileId.dev!=sStat.st_dev
 1.29146 +                     || pInode->fileId.ino!=sStat.st_ino) ){
 1.29147 +       pInode = pInode->pNext;
 1.29148 +    }
 1.29149 +    if( pInode ){
 1.29150 +      UnixUnusedFd **pp;
 1.29151 +      for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
 1.29152 +      pUnused = *pp;
 1.29153 +      if( pUnused ){
 1.29154 +        *pp = pUnused->pNext;
 1.29155 +      }
 1.29156 +    }
 1.29157 +    unixLeaveMutex();
 1.29158 +  }
 1.29159 +#endif    /* if !OS_VXWORKS */
 1.29160 +  return pUnused;
 1.29161 +}
 1.29162 +
 1.29163 +/*
 1.29164 +** This function is called by unixOpen() to determine the unix permissions
 1.29165 +** to create new files with. If no error occurs, then SQLITE_OK is returned
 1.29166 +** and a value suitable for passing as the third argument to open(2) is
 1.29167 +** written to *pMode. If an IO error occurs, an SQLite error code is 
 1.29168 +** returned and the value of *pMode is not modified.
 1.29169 +**
 1.29170 +** In most cases cases, this routine sets *pMode to 0, which will become
 1.29171 +** an indication to robust_open() to create the file using
 1.29172 +** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
 1.29173 +** But if the file being opened is a WAL or regular journal file, then 
 1.29174 +** this function queries the file-system for the permissions on the 
 1.29175 +** corresponding database file and sets *pMode to this value. Whenever 
 1.29176 +** possible, WAL and journal files are created using the same permissions 
 1.29177 +** as the associated database file.
 1.29178 +**
 1.29179 +** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
 1.29180 +** original filename is unavailable.  But 8_3_NAMES is only used for
 1.29181 +** FAT filesystems and permissions do not matter there, so just use
 1.29182 +** the default permissions.
 1.29183 +*/
 1.29184 +static int findCreateFileMode(
 1.29185 +  const char *zPath,              /* Path of file (possibly) being created */
 1.29186 +  int flags,                      /* Flags passed as 4th argument to xOpen() */
 1.29187 +  mode_t *pMode,                  /* OUT: Permissions to open file with */
 1.29188 +  uid_t *pUid,                    /* OUT: uid to set on the file */
 1.29189 +  gid_t *pGid                     /* OUT: gid to set on the file */
 1.29190 +){
 1.29191 +  int rc = SQLITE_OK;             /* Return Code */
 1.29192 +  *pMode = 0;
 1.29193 +  *pUid = 0;
 1.29194 +  *pGid = 0;
 1.29195 +  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
 1.29196 +    char zDb[MAX_PATHNAME+1];     /* Database file path */
 1.29197 +    int nDb;                      /* Number of valid bytes in zDb */
 1.29198 +    struct stat sStat;            /* Output of stat() on database file */
 1.29199 +
 1.29200 +    /* zPath is a path to a WAL or journal file. The following block derives
 1.29201 +    ** the path to the associated database file from zPath. This block handles
 1.29202 +    ** the following naming conventions:
 1.29203 +    **
 1.29204 +    **   "<path to db>-journal"
 1.29205 +    **   "<path to db>-wal"
 1.29206 +    **   "<path to db>-journalNN"
 1.29207 +    **   "<path to db>-walNN"
 1.29208 +    **
 1.29209 +    ** where NN is a decimal number. The NN naming schemes are 
 1.29210 +    ** used by the test_multiplex.c module.
 1.29211 +    */
 1.29212 +    nDb = sqlite3Strlen30(zPath) - 1; 
 1.29213 +#ifdef SQLITE_ENABLE_8_3_NAMES
 1.29214 +    while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
 1.29215 +    if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
 1.29216 +#else
 1.29217 +    while( zPath[nDb]!='-' ){
 1.29218 +      assert( nDb>0 );
 1.29219 +      assert( zPath[nDb]!='\n' );
 1.29220 +      nDb--;
 1.29221 +    }
 1.29222 +#endif
 1.29223 +    memcpy(zDb, zPath, nDb);
 1.29224 +    zDb[nDb] = '\0';
 1.29225 +
 1.29226 +    if( 0==osStat(zDb, &sStat) ){
 1.29227 +      *pMode = sStat.st_mode & 0777;
 1.29228 +      *pUid = sStat.st_uid;
 1.29229 +      *pGid = sStat.st_gid;
 1.29230 +    }else{
 1.29231 +      rc = SQLITE_IOERR_FSTAT;
 1.29232 +    }
 1.29233 +  }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
 1.29234 +    *pMode = 0600;
 1.29235 +  }
 1.29236 +  return rc;
 1.29237 +}
 1.29238 +
 1.29239 +/*
 1.29240 +** Open the file zPath.
 1.29241 +** 
 1.29242 +** Previously, the SQLite OS layer used three functions in place of this
 1.29243 +** one:
 1.29244 +**
 1.29245 +**     sqlite3OsOpenReadWrite();
 1.29246 +**     sqlite3OsOpenReadOnly();
 1.29247 +**     sqlite3OsOpenExclusive();
 1.29248 +**
 1.29249 +** These calls correspond to the following combinations of flags:
 1.29250 +**
 1.29251 +**     ReadWrite() ->     (READWRITE | CREATE)
 1.29252 +**     ReadOnly()  ->     (READONLY) 
 1.29253 +**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
 1.29254 +**
 1.29255 +** The old OpenExclusive() accepted a boolean argument - "delFlag". If
 1.29256 +** true, the file was configured to be automatically deleted when the
 1.29257 +** file handle closed. To achieve the same effect using this new 
 1.29258 +** interface, add the DELETEONCLOSE flag to those specified above for 
 1.29259 +** OpenExclusive().
 1.29260 +*/
 1.29261 +static int unixOpen(
 1.29262 +  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
 1.29263 +  const char *zPath,           /* Pathname of file to be opened */
 1.29264 +  sqlite3_file *pFile,         /* The file descriptor to be filled in */
 1.29265 +  int flags,                   /* Input flags to control the opening */
 1.29266 +  int *pOutFlags               /* Output flags returned to SQLite core */
 1.29267 +){
 1.29268 +  unixFile *p = (unixFile *)pFile;
 1.29269 +  int fd = -1;                   /* File descriptor returned by open() */
 1.29270 +  int openFlags = 0;             /* Flags to pass to open() */
 1.29271 +  int eType = flags&0xFFFFFF00;  /* Type of file to open */
 1.29272 +  int noLock;                    /* True to omit locking primitives */
 1.29273 +  int rc = SQLITE_OK;            /* Function Return Code */
 1.29274 +  int ctrlFlags = 0;             /* UNIXFILE_* flags */
 1.29275 +
 1.29276 +  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
 1.29277 +  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
 1.29278 +  int isCreate     = (flags & SQLITE_OPEN_CREATE);
 1.29279 +  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
 1.29280 +  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
 1.29281 +#if SQLITE_ENABLE_LOCKING_STYLE
 1.29282 +  int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
 1.29283 +#endif
 1.29284 +#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
 1.29285 +  struct statfs fsInfo;
 1.29286 +#endif
 1.29287 +
 1.29288 +  /* If creating a master or main-file journal, this function will open
 1.29289 +  ** a file-descriptor on the directory too. The first time unixSync()
 1.29290 +  ** is called the directory file descriptor will be fsync()ed and close()d.
 1.29291 +  */
 1.29292 +  int syncDir = (isCreate && (
 1.29293 +        eType==SQLITE_OPEN_MASTER_JOURNAL 
 1.29294 +     || eType==SQLITE_OPEN_MAIN_JOURNAL 
 1.29295 +     || eType==SQLITE_OPEN_WAL
 1.29296 +  ));
 1.29297 +
 1.29298 +  /* If argument zPath is a NULL pointer, this function is required to open
 1.29299 +  ** a temporary file. Use this buffer to store the file name in.
 1.29300 +  */
 1.29301 +  char zTmpname[MAX_PATHNAME+2];
 1.29302 +  const char *zName = zPath;
 1.29303 +
 1.29304 +  /* Check the following statements are true: 
 1.29305 +  **
 1.29306 +  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
 1.29307 +  **   (b) if CREATE is set, then READWRITE must also be set, and
 1.29308 +  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
 1.29309 +  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
 1.29310 +  */
 1.29311 +  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
 1.29312 +  assert(isCreate==0 || isReadWrite);
 1.29313 +  assert(isExclusive==0 || isCreate);
 1.29314 +  assert(isDelete==0 || isCreate);
 1.29315 +
 1.29316 +  /* The main DB, main journal, WAL file and master journal are never 
 1.29317 +  ** automatically deleted. Nor are they ever temporary files.  */
 1.29318 +  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
 1.29319 +  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
 1.29320 +  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
 1.29321 +  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
 1.29322 +
 1.29323 +  /* Assert that the upper layer has set one of the "file-type" flags. */
 1.29324 +  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
 1.29325 +       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
 1.29326 +       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
 1.29327 +       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
 1.29328 +  );
 1.29329 +
 1.29330 +  /* Detect a pid change and reset the PRNG.  There is a race condition
 1.29331 +  ** here such that two or more threads all trying to open databases at
 1.29332 +  ** the same instant might all reset the PRNG.  But multiple resets
 1.29333 +  ** are harmless.
 1.29334 +  */
 1.29335 +  if( randomnessPid!=getpid() ){
 1.29336 +    randomnessPid = getpid();
 1.29337 +    sqlite3_randomness(0,0);
 1.29338 +  }
 1.29339 +
 1.29340 +  memset(p, 0, sizeof(unixFile));
 1.29341 +
 1.29342 +  if( eType==SQLITE_OPEN_MAIN_DB ){
 1.29343 +    UnixUnusedFd *pUnused;
 1.29344 +    pUnused = findReusableFd(zName, flags);
 1.29345 +    if( pUnused ){
 1.29346 +      fd = pUnused->fd;
 1.29347 +    }else{
 1.29348 +      pUnused = sqlite3_malloc(sizeof(*pUnused));
 1.29349 +      if( !pUnused ){
 1.29350 +        return SQLITE_NOMEM;
 1.29351 +      }
 1.29352 +    }
 1.29353 +    p->pUnused = pUnused;
 1.29354 +
 1.29355 +    /* Database filenames are double-zero terminated if they are not
 1.29356 +    ** URIs with parameters.  Hence, they can always be passed into
 1.29357 +    ** sqlite3_uri_parameter(). */
 1.29358 +    assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
 1.29359 +
 1.29360 +  }else if( !zName ){
 1.29361 +    /* If zName is NULL, the upper layer is requesting a temp file. */
 1.29362 +    assert(isDelete && !syncDir);
 1.29363 +    rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
 1.29364 +    if( rc!=SQLITE_OK ){
 1.29365 +      return rc;
 1.29366 +    }
 1.29367 +    zName = zTmpname;
 1.29368 +
 1.29369 +    /* Generated temporary filenames are always double-zero terminated
 1.29370 +    ** for use by sqlite3_uri_parameter(). */
 1.29371 +    assert( zName[strlen(zName)+1]==0 );
 1.29372 +  }
 1.29373 +
 1.29374 +  /* Determine the value of the flags parameter passed to POSIX function
 1.29375 +  ** open(). These must be calculated even if open() is not called, as
 1.29376 +  ** they may be stored as part of the file handle and used by the 
 1.29377 +  ** 'conch file' locking functions later on.  */
 1.29378 +  if( isReadonly )  openFlags |= O_RDONLY;
 1.29379 +  if( isReadWrite ) openFlags |= O_RDWR;
 1.29380 +  if( isCreate )    openFlags |= O_CREAT;
 1.29381 +  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
 1.29382 +  openFlags |= (O_LARGEFILE|O_BINARY);
 1.29383 +
 1.29384 +  if( fd<0 ){
 1.29385 +    mode_t openMode;              /* Permissions to create file with */
 1.29386 +    uid_t uid;                    /* Userid for the file */
 1.29387 +    gid_t gid;                    /* Groupid for the file */
 1.29388 +    rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
 1.29389 +    if( rc!=SQLITE_OK ){
 1.29390 +      assert( !p->pUnused );
 1.29391 +      assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
 1.29392 +      return rc;
 1.29393 +    }
 1.29394 +    fd = robust_open(zName, openFlags, openMode);
 1.29395 +    OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
 1.29396 +    if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
 1.29397 +      /* Failed to open the file for read/write access. Try read-only. */
 1.29398 +      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
 1.29399 +      openFlags &= ~(O_RDWR|O_CREAT);
 1.29400 +      flags |= SQLITE_OPEN_READONLY;
 1.29401 +      openFlags |= O_RDONLY;
 1.29402 +      isReadonly = 1;
 1.29403 +      fd = robust_open(zName, openFlags, openMode);
 1.29404 +    }
 1.29405 +    if( fd<0 ){
 1.29406 +      rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
 1.29407 +      goto open_finished;
 1.29408 +    }
 1.29409 +
 1.29410 +    /* If this process is running as root and if creating a new rollback
 1.29411 +    ** journal or WAL file, set the ownership of the journal or WAL to be
 1.29412 +    ** the same as the original database.
 1.29413 +    */
 1.29414 +    if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
 1.29415 +      osFchown(fd, uid, gid);
 1.29416 +    }
 1.29417 +  }
 1.29418 +  assert( fd>=0 );
 1.29419 +  if( pOutFlags ){
 1.29420 +    *pOutFlags = flags;
 1.29421 +  }
 1.29422 +
 1.29423 +  if( p->pUnused ){
 1.29424 +    p->pUnused->fd = fd;
 1.29425 +    p->pUnused->flags = flags;
 1.29426 +  }
 1.29427 +
 1.29428 +  if( isDelete ){
 1.29429 +#if OS_VXWORKS
 1.29430 +    zPath = zName;
 1.29431 +#else
 1.29432 +    osUnlink(zName);
 1.29433 +#endif
 1.29434 +  }
 1.29435 +#if SQLITE_ENABLE_LOCKING_STYLE
 1.29436 +  else{
 1.29437 +    p->openFlags = openFlags;
 1.29438 +  }
 1.29439 +#endif
 1.29440 +
 1.29441 +  noLock = eType!=SQLITE_OPEN_MAIN_DB;
 1.29442 +
 1.29443 +  
 1.29444 +#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
 1.29445 +  if( fstatfs(fd, &fsInfo) == -1 ){
 1.29446 +    ((unixFile*)pFile)->lastErrno = errno;
 1.29447 +    robust_close(p, fd, __LINE__);
 1.29448 +    return SQLITE_IOERR_ACCESS;
 1.29449 +  }
 1.29450 +  if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
 1.29451 +    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
 1.29452 +  }
 1.29453 +#endif
 1.29454 +
 1.29455 +  /* Set up appropriate ctrlFlags */
 1.29456 +  if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
 1.29457 +  if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
 1.29458 +  if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
 1.29459 +  if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
 1.29460 +  if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
 1.29461 +
 1.29462 +#if SQLITE_ENABLE_LOCKING_STYLE
 1.29463 +#if SQLITE_PREFER_PROXY_LOCKING
 1.29464 +  isAutoProxy = 1;
 1.29465 +#endif
 1.29466 +  if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
 1.29467 +    char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
 1.29468 +    int useProxy = 0;
 1.29469 +
 1.29470 +    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
 1.29471 +    ** never use proxy, NULL means use proxy for non-local files only.  */
 1.29472 +    if( envforce!=NULL ){
 1.29473 +      useProxy = atoi(envforce)>0;
 1.29474 +    }else{
 1.29475 +      if( statfs(zPath, &fsInfo) == -1 ){
 1.29476 +        /* In theory, the close(fd) call is sub-optimal. If the file opened
 1.29477 +        ** with fd is a database file, and there are other connections open
 1.29478 +        ** on that file that are currently holding advisory locks on it,
 1.29479 +        ** then the call to close() will cancel those locks. In practice,
 1.29480 +        ** we're assuming that statfs() doesn't fail very often. At least
 1.29481 +        ** not while other file descriptors opened by the same process on
 1.29482 +        ** the same file are working.  */
 1.29483 +        p->lastErrno = errno;
 1.29484 +        robust_close(p, fd, __LINE__);
 1.29485 +        rc = SQLITE_IOERR_ACCESS;
 1.29486 +        goto open_finished;
 1.29487 +      }
 1.29488 +      useProxy = !(fsInfo.f_flags&MNT_LOCAL);
 1.29489 +    }
 1.29490 +    if( useProxy ){
 1.29491 +      rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
 1.29492 +      if( rc==SQLITE_OK ){
 1.29493 +        rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
 1.29494 +        if( rc!=SQLITE_OK ){
 1.29495 +          /* Use unixClose to clean up the resources added in fillInUnixFile 
 1.29496 +          ** and clear all the structure's references.  Specifically, 
 1.29497 +          ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
 1.29498 +          */
 1.29499 +          unixClose(pFile);
 1.29500 +          return rc;
 1.29501 +        }
 1.29502 +      }
 1.29503 +      goto open_finished;
 1.29504 +    }
 1.29505 +  }
 1.29506 +#endif
 1.29507 +  
 1.29508 +  rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
 1.29509 +
 1.29510 +open_finished:
 1.29511 +  if( rc!=SQLITE_OK ){
 1.29512 +    sqlite3_free(p->pUnused);
 1.29513 +  }
 1.29514 +  return rc;
 1.29515 +}
 1.29516 +
 1.29517 +
 1.29518 +/*
 1.29519 +** Delete the file at zPath. If the dirSync argument is true, fsync()
 1.29520 +** the directory after deleting the file.
 1.29521 +*/
 1.29522 +static int unixDelete(
 1.29523 +  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
 1.29524 +  const char *zPath,        /* Name of file to be deleted */
 1.29525 +  int dirSync               /* If true, fsync() directory after deleting file */
 1.29526 +){
 1.29527 +  int rc = SQLITE_OK;
 1.29528 +  UNUSED_PARAMETER(NotUsed);
 1.29529 +  SimulateIOError(return SQLITE_IOERR_DELETE);
 1.29530 +  if( osUnlink(zPath)==(-1) ){
 1.29531 +    if( errno==ENOENT ){
 1.29532 +      rc = SQLITE_IOERR_DELETE_NOENT;
 1.29533 +    }else{
 1.29534 +      rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
 1.29535 +    }
 1.29536 +    return rc;
 1.29537 +  }
 1.29538 +#ifndef SQLITE_DISABLE_DIRSYNC
 1.29539 +  if( (dirSync & 1)!=0 ){
 1.29540 +    int fd;
 1.29541 +    rc = osOpenDirectory(zPath, &fd);
 1.29542 +    if( rc==SQLITE_OK ){
 1.29543 +#if OS_VXWORKS
 1.29544 +      if( fsync(fd)==-1 )
 1.29545 +#else
 1.29546 +      if( fsync(fd) )
 1.29547 +#endif
 1.29548 +      {
 1.29549 +        rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
 1.29550 +      }
 1.29551 +      robust_close(0, fd, __LINE__);
 1.29552 +    }else if( rc==SQLITE_CANTOPEN ){
 1.29553 +      rc = SQLITE_OK;
 1.29554 +    }
 1.29555 +  }
 1.29556 +#endif
 1.29557 +  return rc;
 1.29558 +}
 1.29559 +
 1.29560 +/*
 1.29561 +** Test the existence of or access permissions of file zPath. The
 1.29562 +** test performed depends on the value of flags:
 1.29563 +**
 1.29564 +**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
 1.29565 +**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
 1.29566 +**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
 1.29567 +**
 1.29568 +** Otherwise return 0.
 1.29569 +*/
 1.29570 +static int unixAccess(
 1.29571 +  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
 1.29572 +  const char *zPath,      /* Path of the file to examine */
 1.29573 +  int flags,              /* What do we want to learn about the zPath file? */
 1.29574 +  int *pResOut            /* Write result boolean here */
 1.29575 +){
 1.29576 +  int amode = 0;
 1.29577 +  UNUSED_PARAMETER(NotUsed);
 1.29578 +  SimulateIOError( return SQLITE_IOERR_ACCESS; );
 1.29579 +  switch( flags ){
 1.29580 +    case SQLITE_ACCESS_EXISTS:
 1.29581 +      amode = F_OK;
 1.29582 +      break;
 1.29583 +    case SQLITE_ACCESS_READWRITE:
 1.29584 +      amode = W_OK|R_OK;
 1.29585 +      break;
 1.29586 +    case SQLITE_ACCESS_READ:
 1.29587 +      amode = R_OK;
 1.29588 +      break;
 1.29589 +
 1.29590 +    default:
 1.29591 +      assert(!"Invalid flags argument");
 1.29592 +  }
 1.29593 +  *pResOut = (osAccess(zPath, amode)==0);
 1.29594 +  if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
 1.29595 +    struct stat buf;
 1.29596 +    if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
 1.29597 +      *pResOut = 0;
 1.29598 +    }
 1.29599 +  }
 1.29600 +  return SQLITE_OK;
 1.29601 +}
 1.29602 +
 1.29603 +
 1.29604 +/*
 1.29605 +** Turn a relative pathname into a full pathname. The relative path
 1.29606 +** is stored as a nul-terminated string in the buffer pointed to by
 1.29607 +** zPath. 
 1.29608 +**
 1.29609 +** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
 1.29610 +** (in this case, MAX_PATHNAME bytes). The full-path is written to
 1.29611 +** this buffer before returning.
 1.29612 +*/
 1.29613 +static int unixFullPathname(
 1.29614 +  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
 1.29615 +  const char *zPath,            /* Possibly relative input path */
 1.29616 +  int nOut,                     /* Size of output buffer in bytes */
 1.29617 +  char *zOut                    /* Output buffer */
 1.29618 +){
 1.29619 +
 1.29620 +  /* It's odd to simulate an io-error here, but really this is just
 1.29621 +  ** using the io-error infrastructure to test that SQLite handles this
 1.29622 +  ** function failing. This function could fail if, for example, the
 1.29623 +  ** current working directory has been unlinked.
 1.29624 +  */
 1.29625 +  SimulateIOError( return SQLITE_ERROR );
 1.29626 +
 1.29627 +  assert( pVfs->mxPathname==MAX_PATHNAME );
 1.29628 +  UNUSED_PARAMETER(pVfs);
 1.29629 +
 1.29630 +  zOut[nOut-1] = '\0';
 1.29631 +  if( zPath[0]=='/' ){
 1.29632 +    sqlite3_snprintf(nOut, zOut, "%s", zPath);
 1.29633 +  }else{
 1.29634 +    int nCwd;
 1.29635 +    if( osGetcwd(zOut, nOut-1)==0 ){
 1.29636 +      return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
 1.29637 +    }
 1.29638 +    nCwd = (int)strlen(zOut);
 1.29639 +    sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
 1.29640 +  }
 1.29641 +  return SQLITE_OK;
 1.29642 +}
 1.29643 +
 1.29644 +
 1.29645 +#ifndef SQLITE_OMIT_LOAD_EXTENSION
 1.29646 +/*
 1.29647 +** Interfaces for opening a shared library, finding entry points
 1.29648 +** within the shared library, and closing the shared library.
 1.29649 +*/
 1.29650 +#include <dlfcn.h>
 1.29651 +static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
 1.29652 +  UNUSED_PARAMETER(NotUsed);
 1.29653 +  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
 1.29654 +}
 1.29655 +
 1.29656 +/*
 1.29657 +** SQLite calls this function immediately after a call to unixDlSym() or
 1.29658 +** unixDlOpen() fails (returns a null pointer). If a more detailed error
 1.29659 +** message is available, it is written to zBufOut. If no error message
 1.29660 +** is available, zBufOut is left unmodified and SQLite uses a default
 1.29661 +** error message.
 1.29662 +*/
 1.29663 +static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
 1.29664 +  const char *zErr;
 1.29665 +  UNUSED_PARAMETER(NotUsed);
 1.29666 +  unixEnterMutex();
 1.29667 +  zErr = dlerror();
 1.29668 +  if( zErr ){
 1.29669 +    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
 1.29670 +  }
 1.29671 +  unixLeaveMutex();
 1.29672 +}
 1.29673 +static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
 1.29674 +  /* 
 1.29675 +  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
 1.29676 +  ** cast into a pointer to a function.  And yet the library dlsym() routine
 1.29677 +  ** returns a void* which is really a pointer to a function.  So how do we
 1.29678 +  ** use dlsym() with -pedantic-errors?
 1.29679 +  **
 1.29680 +  ** Variable x below is defined to be a pointer to a function taking
 1.29681 +  ** parameters void* and const char* and returning a pointer to a function.
 1.29682 +  ** We initialize x by assigning it a pointer to the dlsym() function.
 1.29683 +  ** (That assignment requires a cast.)  Then we call the function that
 1.29684 +  ** x points to.  
 1.29685 +  **
 1.29686 +  ** This work-around is unlikely to work correctly on any system where
 1.29687 +  ** you really cannot cast a function pointer into void*.  But then, on the
 1.29688 +  ** other hand, dlsym() will not work on such a system either, so we have
 1.29689 +  ** not really lost anything.
 1.29690 +  */
 1.29691 +  void (*(*x)(void*,const char*))(void);
 1.29692 +  UNUSED_PARAMETER(NotUsed);
 1.29693 +  x = (void(*(*)(void*,const char*))(void))dlsym;
 1.29694 +  return (*x)(p, zSym);
 1.29695 +}
 1.29696 +static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
 1.29697 +  UNUSED_PARAMETER(NotUsed);
 1.29698 +  dlclose(pHandle);
 1.29699 +}
 1.29700 +#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
 1.29701 +  #define unixDlOpen  0
 1.29702 +  #define unixDlError 0
 1.29703 +  #define unixDlSym   0
 1.29704 +  #define unixDlClose 0
 1.29705 +#endif
 1.29706 +
 1.29707 +/*
 1.29708 +** Write nBuf bytes of random data to the supplied buffer zBuf.
 1.29709 +*/
 1.29710 +static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
 1.29711 +  UNUSED_PARAMETER(NotUsed);
 1.29712 +  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
 1.29713 +
 1.29714 +  /* We have to initialize zBuf to prevent valgrind from reporting
 1.29715 +  ** errors.  The reports issued by valgrind are incorrect - we would
 1.29716 +  ** prefer that the randomness be increased by making use of the
 1.29717 +  ** uninitialized space in zBuf - but valgrind errors tend to worry
 1.29718 +  ** some users.  Rather than argue, it seems easier just to initialize
 1.29719 +  ** the whole array and silence valgrind, even if that means less randomness
 1.29720 +  ** in the random seed.
 1.29721 +  **
 1.29722 +  ** When testing, initializing zBuf[] to zero is all we do.  That means
 1.29723 +  ** that we always use the same random number sequence.  This makes the
 1.29724 +  ** tests repeatable.
 1.29725 +  */
 1.29726 +  memset(zBuf, 0, nBuf);
 1.29727 +  randomnessPid = getpid();  
 1.29728 +#if !defined(SQLITE_TEST)
 1.29729 +  {
 1.29730 +    int fd, got;
 1.29731 +    fd = robust_open("/dev/urandom", O_RDONLY, 0);
 1.29732 +    if( fd<0 ){
 1.29733 +      time_t t;
 1.29734 +      time(&t);
 1.29735 +      memcpy(zBuf, &t, sizeof(t));
 1.29736 +      memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
 1.29737 +      assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
 1.29738 +      nBuf = sizeof(t) + sizeof(randomnessPid);
 1.29739 +    }else{
 1.29740 +      do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
 1.29741 +      robust_close(0, fd, __LINE__);
 1.29742 +    }
 1.29743 +  }
 1.29744 +#endif
 1.29745 +  return nBuf;
 1.29746 +}
 1.29747 +
 1.29748 +
 1.29749 +/*
 1.29750 +** Sleep for a little while.  Return the amount of time slept.
 1.29751 +** The argument is the number of microseconds we want to sleep.
 1.29752 +** The return value is the number of microseconds of sleep actually
 1.29753 +** requested from the underlying operating system, a number which
 1.29754 +** might be greater than or equal to the argument, but not less
 1.29755 +** than the argument.
 1.29756 +*/
 1.29757 +static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
 1.29758 +#if OS_VXWORKS
 1.29759 +  struct timespec sp;
 1.29760 +
 1.29761 +  sp.tv_sec = microseconds / 1000000;
 1.29762 +  sp.tv_nsec = (microseconds % 1000000) * 1000;
 1.29763 +  nanosleep(&sp, NULL);
 1.29764 +  UNUSED_PARAMETER(NotUsed);
 1.29765 +  return microseconds;
 1.29766 +#elif defined(HAVE_USLEEP) && HAVE_USLEEP
 1.29767 +  usleep(microseconds);
 1.29768 +  UNUSED_PARAMETER(NotUsed);
 1.29769 +  return microseconds;
 1.29770 +#else
 1.29771 +  int seconds = (microseconds+999999)/1000000;
 1.29772 +  sleep(seconds);
 1.29773 +  UNUSED_PARAMETER(NotUsed);
 1.29774 +  return seconds*1000000;
 1.29775 +#endif
 1.29776 +}
 1.29777 +
 1.29778 +/*
 1.29779 +** The following variable, if set to a non-zero value, is interpreted as
 1.29780 +** the number of seconds since 1970 and is used to set the result of
 1.29781 +** sqlite3OsCurrentTime() during testing.
 1.29782 +*/
 1.29783 +#ifdef SQLITE_TEST
 1.29784 +SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
 1.29785 +#endif
 1.29786 +
 1.29787 +/*
 1.29788 +** Find the current time (in Universal Coordinated Time).  Write into *piNow
 1.29789 +** the current time and date as a Julian Day number times 86_400_000.  In
 1.29790 +** other words, write into *piNow the number of milliseconds since the Julian
 1.29791 +** epoch of noon in Greenwich on November 24, 4714 B.C according to the
 1.29792 +** proleptic Gregorian calendar.
 1.29793 +**
 1.29794 +** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date 
 1.29795 +** cannot be found.
 1.29796 +*/
 1.29797 +static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
 1.29798 +  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
 1.29799 +  int rc = SQLITE_OK;
 1.29800 +#if defined(NO_GETTOD)
 1.29801 +  time_t t;
 1.29802 +  time(&t);
 1.29803 +  *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
 1.29804 +#elif OS_VXWORKS
 1.29805 +  struct timespec sNow;
 1.29806 +  clock_gettime(CLOCK_REALTIME, &sNow);
 1.29807 +  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
 1.29808 +#else
 1.29809 +  struct timeval sNow;
 1.29810 +  if( gettimeofday(&sNow, 0)==0 ){
 1.29811 +    *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
 1.29812 +  }else{
 1.29813 +    rc = SQLITE_ERROR;
 1.29814 +  }
 1.29815 +#endif
 1.29816 +
 1.29817 +#ifdef SQLITE_TEST
 1.29818 +  if( sqlite3_current_time ){
 1.29819 +    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
 1.29820 +  }
 1.29821 +#endif
 1.29822 +  UNUSED_PARAMETER(NotUsed);
 1.29823 +  return rc;
 1.29824 +}
 1.29825 +
 1.29826 +/*
 1.29827 +** Find the current time (in Universal Coordinated Time).  Write the
 1.29828 +** current time and date as a Julian Day number into *prNow and
 1.29829 +** return 0.  Return 1 if the time and date cannot be found.
 1.29830 +*/
 1.29831 +static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
 1.29832 +  sqlite3_int64 i = 0;
 1.29833 +  int rc;
 1.29834 +  UNUSED_PARAMETER(NotUsed);
 1.29835 +  rc = unixCurrentTimeInt64(0, &i);
 1.29836 +  *prNow = i/86400000.0;
 1.29837 +  return rc;
 1.29838 +}
 1.29839 +
 1.29840 +/*
 1.29841 +** We added the xGetLastError() method with the intention of providing
 1.29842 +** better low-level error messages when operating-system problems come up
 1.29843 +** during SQLite operation.  But so far, none of that has been implemented
 1.29844 +** in the core.  So this routine is never called.  For now, it is merely
 1.29845 +** a place-holder.
 1.29846 +*/
 1.29847 +static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
 1.29848 +  UNUSED_PARAMETER(NotUsed);
 1.29849 +  UNUSED_PARAMETER(NotUsed2);
 1.29850 +  UNUSED_PARAMETER(NotUsed3);
 1.29851 +  return 0;
 1.29852 +}
 1.29853 +
 1.29854 +
 1.29855 +/*
 1.29856 +************************ End of sqlite3_vfs methods ***************************
 1.29857 +******************************************************************************/
 1.29858 +
 1.29859 +/******************************************************************************
 1.29860 +************************** Begin Proxy Locking ********************************
 1.29861 +**
 1.29862 +** Proxy locking is a "uber-locking-method" in this sense:  It uses the
 1.29863 +** other locking methods on secondary lock files.  Proxy locking is a
 1.29864 +** meta-layer over top of the primitive locking implemented above.  For
 1.29865 +** this reason, the division that implements of proxy locking is deferred
 1.29866 +** until late in the file (here) after all of the other I/O methods have
 1.29867 +** been defined - so that the primitive locking methods are available
 1.29868 +** as services to help with the implementation of proxy locking.
 1.29869 +**
 1.29870 +****
 1.29871 +**
 1.29872 +** The default locking schemes in SQLite use byte-range locks on the
 1.29873 +** database file to coordinate safe, concurrent access by multiple readers
 1.29874 +** and writers [http://sqlite.org/lockingv3.html].  The five file locking
 1.29875 +** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
 1.29876 +** as POSIX read & write locks over fixed set of locations (via fsctl),
 1.29877 +** on AFP and SMB only exclusive byte-range locks are available via fsctl
 1.29878 +** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
 1.29879 +** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
 1.29880 +** address in the shared range is taken for a SHARED lock, the entire
 1.29881 +** shared range is taken for an EXCLUSIVE lock):
 1.29882 +**
 1.29883 +**      PENDING_BYTE        0x40000000
 1.29884 +**      RESERVED_BYTE       0x40000001
 1.29885 +**      SHARED_RANGE        0x40000002 -> 0x40000200
 1.29886 +**
 1.29887 +** This works well on the local file system, but shows a nearly 100x
 1.29888 +** slowdown in read performance on AFP because the AFP client disables
 1.29889 +** the read cache when byte-range locks are present.  Enabling the read
 1.29890 +** cache exposes a cache coherency problem that is present on all OS X
 1.29891 +** supported network file systems.  NFS and AFP both observe the
 1.29892 +** close-to-open semantics for ensuring cache coherency
 1.29893 +** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
 1.29894 +** address the requirements for concurrent database access by multiple
 1.29895 +** readers and writers
 1.29896 +** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
 1.29897 +**
 1.29898 +** To address the performance and cache coherency issues, proxy file locking
 1.29899 +** changes the way database access is controlled by limiting access to a
 1.29900 +** single host at a time and moving file locks off of the database file
 1.29901 +** and onto a proxy file on the local file system.  
 1.29902 +**
 1.29903 +**
 1.29904 +** Using proxy locks
 1.29905 +** -----------------
 1.29906 +**
 1.29907 +** C APIs
 1.29908 +**
 1.29909 +**  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
 1.29910 +**                       <proxy_path> | ":auto:");
 1.29911 +**  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
 1.29912 +**
 1.29913 +**
 1.29914 +** SQL pragmas
 1.29915 +**
 1.29916 +**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
 1.29917 +**  PRAGMA [database.]lock_proxy_file
 1.29918 +**
 1.29919 +** Specifying ":auto:" means that if there is a conch file with a matching
 1.29920 +** host ID in it, the proxy path in the conch file will be used, otherwise
 1.29921 +** a proxy path based on the user's temp dir
 1.29922 +** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
 1.29923 +** actual proxy file name is generated from the name and path of the
 1.29924 +** database file.  For example:
 1.29925 +**
 1.29926 +**       For database path "/Users/me/foo.db" 
 1.29927 +**       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
 1.29928 +**
 1.29929 +** Once a lock proxy is configured for a database connection, it can not
 1.29930 +** be removed, however it may be switched to a different proxy path via
 1.29931 +** the above APIs (assuming the conch file is not being held by another
 1.29932 +** connection or process). 
 1.29933 +**
 1.29934 +**
 1.29935 +** How proxy locking works
 1.29936 +** -----------------------
 1.29937 +**
 1.29938 +** Proxy file locking relies primarily on two new supporting files: 
 1.29939 +**
 1.29940 +**   *  conch file to limit access to the database file to a single host
 1.29941 +**      at a time
 1.29942 +**
 1.29943 +**   *  proxy file to act as a proxy for the advisory locks normally
 1.29944 +**      taken on the database
 1.29945 +**
 1.29946 +** The conch file - to use a proxy file, sqlite must first "hold the conch"
 1.29947 +** by taking an sqlite-style shared lock on the conch file, reading the
 1.29948 +** contents and comparing the host's unique host ID (see below) and lock
 1.29949 +** proxy path against the values stored in the conch.  The conch file is
 1.29950 +** stored in the same directory as the database file and the file name
 1.29951 +** is patterned after the database file name as ".<databasename>-conch".
 1.29952 +** If the conch file does not exist, or it's contents do not match the
 1.29953 +** host ID and/or proxy path, then the lock is escalated to an exclusive
 1.29954 +** lock and the conch file contents is updated with the host ID and proxy
 1.29955 +** path and the lock is downgraded to a shared lock again.  If the conch
 1.29956 +** is held by another process (with a shared lock), the exclusive lock
 1.29957 +** will fail and SQLITE_BUSY is returned.
 1.29958 +**
 1.29959 +** The proxy file - a single-byte file used for all advisory file locks
 1.29960 +** normally taken on the database file.   This allows for safe sharing
 1.29961 +** of the database file for multiple readers and writers on the same
 1.29962 +** host (the conch ensures that they all use the same local lock file).
 1.29963 +**
 1.29964 +** Requesting the lock proxy does not immediately take the conch, it is
 1.29965 +** only taken when the first request to lock database file is made.  
 1.29966 +** This matches the semantics of the traditional locking behavior, where
 1.29967 +** opening a connection to a database file does not take a lock on it.
 1.29968 +** The shared lock and an open file descriptor are maintained until 
 1.29969 +** the connection to the database is closed. 
 1.29970 +**
 1.29971 +** The proxy file and the lock file are never deleted so they only need
 1.29972 +** to be created the first time they are used.
 1.29973 +**
 1.29974 +** Configuration options
 1.29975 +** ---------------------
 1.29976 +**
 1.29977 +**  SQLITE_PREFER_PROXY_LOCKING
 1.29978 +**
 1.29979 +**       Database files accessed on non-local file systems are
 1.29980 +**       automatically configured for proxy locking, lock files are
 1.29981 +**       named automatically using the same logic as
 1.29982 +**       PRAGMA lock_proxy_file=":auto:"
 1.29983 +**    
 1.29984 +**  SQLITE_PROXY_DEBUG
 1.29985 +**
 1.29986 +**       Enables the logging of error messages during host id file
 1.29987 +**       retrieval and creation
 1.29988 +**
 1.29989 +**  LOCKPROXYDIR
 1.29990 +**
 1.29991 +**       Overrides the default directory used for lock proxy files that
 1.29992 +**       are named automatically via the ":auto:" setting
 1.29993 +**
 1.29994 +**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
 1.29995 +**
 1.29996 +**       Permissions to use when creating a directory for storing the
 1.29997 +**       lock proxy files, only used when LOCKPROXYDIR is not set.
 1.29998 +**    
 1.29999 +**    
 1.30000 +** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
 1.30001 +** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
 1.30002 +** force proxy locking to be used for every database file opened, and 0
 1.30003 +** will force automatic proxy locking to be disabled for all database
 1.30004 +** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
 1.30005 +** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
 1.30006 +*/
 1.30007 +
 1.30008 +/*
 1.30009 +** Proxy locking is only available on MacOSX 
 1.30010 +*/
 1.30011 +#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 1.30012 +
 1.30013 +/*
 1.30014 +** The proxyLockingContext has the path and file structures for the remote 
 1.30015 +** and local proxy files in it
 1.30016 +*/
 1.30017 +typedef struct proxyLockingContext proxyLockingContext;
 1.30018 +struct proxyLockingContext {
 1.30019 +  unixFile *conchFile;         /* Open conch file */
 1.30020 +  char *conchFilePath;         /* Name of the conch file */
 1.30021 +  unixFile *lockProxy;         /* Open proxy lock file */
 1.30022 +  char *lockProxyPath;         /* Name of the proxy lock file */
 1.30023 +  char *dbPath;                /* Name of the open file */
 1.30024 +  int conchHeld;               /* 1 if the conch is held, -1 if lockless */
 1.30025 +  void *oldLockingContext;     /* Original lockingcontext to restore on close */
 1.30026 +  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
 1.30027 +};
 1.30028 +
 1.30029 +/* 
 1.30030 +** The proxy lock file path for the database at dbPath is written into lPath, 
 1.30031 +** which must point to valid, writable memory large enough for a maxLen length
 1.30032 +** file path. 
 1.30033 +*/
 1.30034 +static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
 1.30035 +  int len;
 1.30036 +  int dbLen;
 1.30037 +  int i;
 1.30038 +
 1.30039 +#ifdef LOCKPROXYDIR
 1.30040 +  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
 1.30041 +#else
 1.30042 +# ifdef _CS_DARWIN_USER_TEMP_DIR
 1.30043 +  {
 1.30044 +    if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
 1.30045 +      OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
 1.30046 +               lPath, errno, getpid()));
 1.30047 +      return SQLITE_IOERR_LOCK;
 1.30048 +    }
 1.30049 +    len = strlcat(lPath, "sqliteplocks", maxLen);    
 1.30050 +  }
 1.30051 +# else
 1.30052 +  len = strlcpy(lPath, "/tmp/", maxLen);
 1.30053 +# endif
 1.30054 +#endif
 1.30055 +
 1.30056 +  if( lPath[len-1]!='/' ){
 1.30057 +    len = strlcat(lPath, "/", maxLen);
 1.30058 +  }
 1.30059 +  
 1.30060 +  /* transform the db path to a unique cache name */
 1.30061 +  dbLen = (int)strlen(dbPath);
 1.30062 +  for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
 1.30063 +    char c = dbPath[i];
 1.30064 +    lPath[i+len] = (c=='/')?'_':c;
 1.30065 +  }
 1.30066 +  lPath[i+len]='\0';
 1.30067 +  strlcat(lPath, ":auto:", maxLen);
 1.30068 +  OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
 1.30069 +  return SQLITE_OK;
 1.30070 +}
 1.30071 +
 1.30072 +/* 
 1.30073 + ** Creates the lock file and any missing directories in lockPath
 1.30074 + */
 1.30075 +static int proxyCreateLockPath(const char *lockPath){
 1.30076 +  int i, len;
 1.30077 +  char buf[MAXPATHLEN];
 1.30078 +  int start = 0;
 1.30079 +  
 1.30080 +  assert(lockPath!=NULL);
 1.30081 +  /* try to create all the intermediate directories */
 1.30082 +  len = (int)strlen(lockPath);
 1.30083 +  buf[0] = lockPath[0];
 1.30084 +  for( i=1; i<len; i++ ){
 1.30085 +    if( lockPath[i] == '/' && (i - start > 0) ){
 1.30086 +      /* only mkdir if leaf dir != "." or "/" or ".." */
 1.30087 +      if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
 1.30088 +         || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
 1.30089 +        buf[i]='\0';
 1.30090 +        if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
 1.30091 +          int err=errno;
 1.30092 +          if( err!=EEXIST ) {
 1.30093 +            OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
 1.30094 +                     "'%s' proxy lock path=%s pid=%d\n",
 1.30095 +                     buf, strerror(err), lockPath, getpid()));
 1.30096 +            return err;
 1.30097 +          }
 1.30098 +        }
 1.30099 +      }
 1.30100 +      start=i+1;
 1.30101 +    }
 1.30102 +    buf[i] = lockPath[i];
 1.30103 +  }
 1.30104 +  OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
 1.30105 +  return 0;
 1.30106 +}
 1.30107 +
 1.30108 +/*
 1.30109 +** Create a new VFS file descriptor (stored in memory obtained from
 1.30110 +** sqlite3_malloc) and open the file named "path" in the file descriptor.
 1.30111 +**
 1.30112 +** The caller is responsible not only for closing the file descriptor
 1.30113 +** but also for freeing the memory associated with the file descriptor.
 1.30114 +*/
 1.30115 +static int proxyCreateUnixFile(
 1.30116 +    const char *path,        /* path for the new unixFile */
 1.30117 +    unixFile **ppFile,       /* unixFile created and returned by ref */
 1.30118 +    int islockfile           /* if non zero missing dirs will be created */
 1.30119 +) {
 1.30120 +  int fd = -1;
 1.30121 +  unixFile *pNew;
 1.30122 +  int rc = SQLITE_OK;
 1.30123 +  int openFlags = O_RDWR | O_CREAT;
 1.30124 +  sqlite3_vfs dummyVfs;
 1.30125 +  int terrno = 0;
 1.30126 +  UnixUnusedFd *pUnused = NULL;
 1.30127 +
 1.30128 +  /* 1. first try to open/create the file
 1.30129 +  ** 2. if that fails, and this is a lock file (not-conch), try creating
 1.30130 +  ** the parent directories and then try again.
 1.30131 +  ** 3. if that fails, try to open the file read-only
 1.30132 +  ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
 1.30133 +  */
 1.30134 +  pUnused = findReusableFd(path, openFlags);
 1.30135 +  if( pUnused ){
 1.30136 +    fd = pUnused->fd;
 1.30137 +  }else{
 1.30138 +    pUnused = sqlite3_malloc(sizeof(*pUnused));
 1.30139 +    if( !pUnused ){
 1.30140 +      return SQLITE_NOMEM;
 1.30141 +    }
 1.30142 +  }
 1.30143 +  if( fd<0 ){
 1.30144 +    fd = robust_open(path, openFlags, 0);
 1.30145 +    terrno = errno;
 1.30146 +    if( fd<0 && errno==ENOENT && islockfile ){
 1.30147 +      if( proxyCreateLockPath(path) == SQLITE_OK ){
 1.30148 +        fd = robust_open(path, openFlags, 0);
 1.30149 +      }
 1.30150 +    }
 1.30151 +  }
 1.30152 +  if( fd<0 ){
 1.30153 +    openFlags = O_RDONLY;
 1.30154 +    fd = robust_open(path, openFlags, 0);
 1.30155 +    terrno = errno;
 1.30156 +  }
 1.30157 +  if( fd<0 ){
 1.30158 +    if( islockfile ){
 1.30159 +      return SQLITE_BUSY;
 1.30160 +    }
 1.30161 +    switch (terrno) {
 1.30162 +      case EACCES:
 1.30163 +        return SQLITE_PERM;
 1.30164 +      case EIO: 
 1.30165 +        return SQLITE_IOERR_LOCK; /* even though it is the conch */
 1.30166 +      default:
 1.30167 +        return SQLITE_CANTOPEN_BKPT;
 1.30168 +    }
 1.30169 +  }
 1.30170 +  
 1.30171 +  pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
 1.30172 +  if( pNew==NULL ){
 1.30173 +    rc = SQLITE_NOMEM;
 1.30174 +    goto end_create_proxy;
 1.30175 +  }
 1.30176 +  memset(pNew, 0, sizeof(unixFile));
 1.30177 +  pNew->openFlags = openFlags;
 1.30178 +  memset(&dummyVfs, 0, sizeof(dummyVfs));
 1.30179 +  dummyVfs.pAppData = (void*)&autolockIoFinder;
 1.30180 +  dummyVfs.zName = "dummy";
 1.30181 +  pUnused->fd = fd;
 1.30182 +  pUnused->flags = openFlags;
 1.30183 +  pNew->pUnused = pUnused;
 1.30184 +  
 1.30185 +  rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
 1.30186 +  if( rc==SQLITE_OK ){
 1.30187 +    *ppFile = pNew;
 1.30188 +    return SQLITE_OK;
 1.30189 +  }
 1.30190 +end_create_proxy:    
 1.30191 +  robust_close(pNew, fd, __LINE__);
 1.30192 +  sqlite3_free(pNew);
 1.30193 +  sqlite3_free(pUnused);
 1.30194 +  return rc;
 1.30195 +}
 1.30196 +
 1.30197 +#ifdef SQLITE_TEST
 1.30198 +/* simulate multiple hosts by creating unique hostid file paths */
 1.30199 +SQLITE_API int sqlite3_hostid_num = 0;
 1.30200 +#endif
 1.30201 +
 1.30202 +#define PROXY_HOSTIDLEN    16  /* conch file host id length */
 1.30203 +
 1.30204 +/* Not always defined in the headers as it ought to be */
 1.30205 +extern int gethostuuid(uuid_t id, const struct timespec *wait);
 1.30206 +
 1.30207 +/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
 1.30208 +** bytes of writable memory.
 1.30209 +*/
 1.30210 +static int proxyGetHostID(unsigned char *pHostID, int *pError){
 1.30211 +  assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
 1.30212 +  memset(pHostID, 0, PROXY_HOSTIDLEN);
 1.30213 +#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
 1.30214 +               && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
 1.30215 +  {
 1.30216 +    static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
 1.30217 +    if( gethostuuid(pHostID, &timeout) ){
 1.30218 +      int err = errno;
 1.30219 +      if( pError ){
 1.30220 +        *pError = err;
 1.30221 +      }
 1.30222 +      return SQLITE_IOERR;
 1.30223 +    }
 1.30224 +  }
 1.30225 +#else
 1.30226 +  UNUSED_PARAMETER(pError);
 1.30227 +#endif
 1.30228 +#ifdef SQLITE_TEST
 1.30229 +  /* simulate multiple hosts by creating unique hostid file paths */
 1.30230 +  if( sqlite3_hostid_num != 0){
 1.30231 +    pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
 1.30232 +  }
 1.30233 +#endif
 1.30234 +  
 1.30235 +  return SQLITE_OK;
 1.30236 +}
 1.30237 +
 1.30238 +/* The conch file contains the header, host id and lock file path
 1.30239 + */
 1.30240 +#define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
 1.30241 +#define PROXY_HEADERLEN    1   /* conch file header length */
 1.30242 +#define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
 1.30243 +#define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
 1.30244 +
 1.30245 +/* 
 1.30246 +** Takes an open conch file, copies the contents to a new path and then moves 
 1.30247 +** it back.  The newly created file's file descriptor is assigned to the
 1.30248 +** conch file structure and finally the original conch file descriptor is 
 1.30249 +** closed.  Returns zero if successful.
 1.30250 +*/
 1.30251 +static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
 1.30252 +  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
 1.30253 +  unixFile *conchFile = pCtx->conchFile;
 1.30254 +  char tPath[MAXPATHLEN];
 1.30255 +  char buf[PROXY_MAXCONCHLEN];
 1.30256 +  char *cPath = pCtx->conchFilePath;
 1.30257 +  size_t readLen = 0;
 1.30258 +  size_t pathLen = 0;
 1.30259 +  char errmsg[64] = "";
 1.30260 +  int fd = -1;
 1.30261 +  int rc = -1;
 1.30262 +  UNUSED_PARAMETER(myHostID);
 1.30263 +
 1.30264 +  /* create a new path by replace the trailing '-conch' with '-break' */
 1.30265 +  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
 1.30266 +  if( pathLen>MAXPATHLEN || pathLen<6 || 
 1.30267 +     (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
 1.30268 +    sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
 1.30269 +    goto end_breaklock;
 1.30270 +  }
 1.30271 +  /* read the conch content */
 1.30272 +  readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
 1.30273 +  if( readLen<PROXY_PATHINDEX ){
 1.30274 +    sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
 1.30275 +    goto end_breaklock;
 1.30276 +  }
 1.30277 +  /* write it out to the temporary break file */
 1.30278 +  fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
 1.30279 +  if( fd<0 ){
 1.30280 +    sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
 1.30281 +    goto end_breaklock;
 1.30282 +  }
 1.30283 +  if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
 1.30284 +    sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
 1.30285 +    goto end_breaklock;
 1.30286 +  }
 1.30287 +  if( rename(tPath, cPath) ){
 1.30288 +    sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
 1.30289 +    goto end_breaklock;
 1.30290 +  }
 1.30291 +  rc = 0;
 1.30292 +  fprintf(stderr, "broke stale lock on %s\n", cPath);
 1.30293 +  robust_close(pFile, conchFile->h, __LINE__);
 1.30294 +  conchFile->h = fd;
 1.30295 +  conchFile->openFlags = O_RDWR | O_CREAT;
 1.30296 +
 1.30297 +end_breaklock:
 1.30298 +  if( rc ){
 1.30299 +    if( fd>=0 ){
 1.30300 +      osUnlink(tPath);
 1.30301 +      robust_close(pFile, fd, __LINE__);
 1.30302 +    }
 1.30303 +    fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
 1.30304 +  }
 1.30305 +  return rc;
 1.30306 +}
 1.30307 +
 1.30308 +/* Take the requested lock on the conch file and break a stale lock if the 
 1.30309 +** host id matches.
 1.30310 +*/
 1.30311 +static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
 1.30312 +  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
 1.30313 +  unixFile *conchFile = pCtx->conchFile;
 1.30314 +  int rc = SQLITE_OK;
 1.30315 +  int nTries = 0;
 1.30316 +  struct timespec conchModTime;
 1.30317 +  
 1.30318 +  memset(&conchModTime, 0, sizeof(conchModTime));
 1.30319 +  do {
 1.30320 +    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
 1.30321 +    nTries ++;
 1.30322 +    if( rc==SQLITE_BUSY ){
 1.30323 +      /* If the lock failed (busy):
 1.30324 +       * 1st try: get the mod time of the conch, wait 0.5s and try again. 
 1.30325 +       * 2nd try: fail if the mod time changed or host id is different, wait 
 1.30326 +       *           10 sec and try again
 1.30327 +       * 3rd try: break the lock unless the mod time has changed.
 1.30328 +       */
 1.30329 +      struct stat buf;
 1.30330 +      if( osFstat(conchFile->h, &buf) ){
 1.30331 +        pFile->lastErrno = errno;
 1.30332 +        return SQLITE_IOERR_LOCK;
 1.30333 +      }
 1.30334 +      
 1.30335 +      if( nTries==1 ){
 1.30336 +        conchModTime = buf.st_mtimespec;
 1.30337 +        usleep(500000); /* wait 0.5 sec and try the lock again*/
 1.30338 +        continue;  
 1.30339 +      }
 1.30340 +
 1.30341 +      assert( nTries>1 );
 1.30342 +      if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
 1.30343 +         conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
 1.30344 +        return SQLITE_BUSY;
 1.30345 +      }
 1.30346 +      
 1.30347 +      if( nTries==2 ){  
 1.30348 +        char tBuf[PROXY_MAXCONCHLEN];
 1.30349 +        int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
 1.30350 +        if( len<0 ){
 1.30351 +          pFile->lastErrno = errno;
 1.30352 +          return SQLITE_IOERR_LOCK;
 1.30353 +        }
 1.30354 +        if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
 1.30355 +          /* don't break the lock if the host id doesn't match */
 1.30356 +          if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
 1.30357 +            return SQLITE_BUSY;
 1.30358 +          }
 1.30359 +        }else{
 1.30360 +          /* don't break the lock on short read or a version mismatch */
 1.30361 +          return SQLITE_BUSY;
 1.30362 +        }
 1.30363 +        usleep(10000000); /* wait 10 sec and try the lock again */
 1.30364 +        continue; 
 1.30365 +      }
 1.30366 +      
 1.30367 +      assert( nTries==3 );
 1.30368 +      if( 0==proxyBreakConchLock(pFile, myHostID) ){
 1.30369 +        rc = SQLITE_OK;
 1.30370 +        if( lockType==EXCLUSIVE_LOCK ){
 1.30371 +          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);          
 1.30372 +        }
 1.30373 +        if( !rc ){
 1.30374 +          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
 1.30375 +        }
 1.30376 +      }
 1.30377 +    }
 1.30378 +  } while( rc==SQLITE_BUSY && nTries<3 );
 1.30379 +  
 1.30380 +  return rc;
 1.30381 +}
 1.30382 +
 1.30383 +/* Takes the conch by taking a shared lock and read the contents conch, if 
 1.30384 +** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
 1.30385 +** lockPath means that the lockPath in the conch file will be used if the 
 1.30386 +** host IDs match, or a new lock path will be generated automatically 
 1.30387 +** and written to the conch file.
 1.30388 +*/
 1.30389 +static int proxyTakeConch(unixFile *pFile){
 1.30390 +  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
 1.30391 +  
 1.30392 +  if( pCtx->conchHeld!=0 ){
 1.30393 +    return SQLITE_OK;
 1.30394 +  }else{
 1.30395 +    unixFile *conchFile = pCtx->conchFile;
 1.30396 +    uuid_t myHostID;
 1.30397 +    int pError = 0;
 1.30398 +    char readBuf[PROXY_MAXCONCHLEN];
 1.30399 +    char lockPath[MAXPATHLEN];
 1.30400 +    char *tempLockPath = NULL;
 1.30401 +    int rc = SQLITE_OK;
 1.30402 +    int createConch = 0;
 1.30403 +    int hostIdMatch = 0;
 1.30404 +    int readLen = 0;
 1.30405 +    int tryOldLockPath = 0;
 1.30406 +    int forceNewLockPath = 0;
 1.30407 +    
 1.30408 +    OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
 1.30409 +             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
 1.30410 +
 1.30411 +    rc = proxyGetHostID(myHostID, &pError);
 1.30412 +    if( (rc&0xff)==SQLITE_IOERR ){
 1.30413 +      pFile->lastErrno = pError;
 1.30414 +      goto end_takeconch;
 1.30415 +    }
 1.30416 +    rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
 1.30417 +    if( rc!=SQLITE_OK ){
 1.30418 +      goto end_takeconch;
 1.30419 +    }
 1.30420 +    /* read the existing conch file */
 1.30421 +    readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
 1.30422 +    if( readLen<0 ){
 1.30423 +      /* I/O error: lastErrno set by seekAndRead */
 1.30424 +      pFile->lastErrno = conchFile->lastErrno;
 1.30425 +      rc = SQLITE_IOERR_READ;
 1.30426 +      goto end_takeconch;
 1.30427 +    }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
 1.30428 +             readBuf[0]!=(char)PROXY_CONCHVERSION ){
 1.30429 +      /* a short read or version format mismatch means we need to create a new 
 1.30430 +      ** conch file. 
 1.30431 +      */
 1.30432 +      createConch = 1;
 1.30433 +    }
 1.30434 +    /* if the host id matches and the lock path already exists in the conch
 1.30435 +    ** we'll try to use the path there, if we can't open that path, we'll 
 1.30436 +    ** retry with a new auto-generated path 
 1.30437 +    */
 1.30438 +    do { /* in case we need to try again for an :auto: named lock file */
 1.30439 +
 1.30440 +      if( !createConch && !forceNewLockPath ){
 1.30441 +        hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
 1.30442 +                                  PROXY_HOSTIDLEN);
 1.30443 +        /* if the conch has data compare the contents */
 1.30444 +        if( !pCtx->lockProxyPath ){
 1.30445 +          /* for auto-named local lock file, just check the host ID and we'll
 1.30446 +           ** use the local lock file path that's already in there
 1.30447 +           */
 1.30448 +          if( hostIdMatch ){
 1.30449 +            size_t pathLen = (readLen - PROXY_PATHINDEX);
 1.30450 +            
 1.30451 +            if( pathLen>=MAXPATHLEN ){
 1.30452 +              pathLen=MAXPATHLEN-1;
 1.30453 +            }
 1.30454 +            memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
 1.30455 +            lockPath[pathLen] = 0;
 1.30456 +            tempLockPath = lockPath;
 1.30457 +            tryOldLockPath = 1;
 1.30458 +            /* create a copy of the lock path if the conch is taken */
 1.30459 +            goto end_takeconch;
 1.30460 +          }
 1.30461 +        }else if( hostIdMatch
 1.30462 +               && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
 1.30463 +                           readLen-PROXY_PATHINDEX)
 1.30464 +        ){
 1.30465 +          /* conch host and lock path match */
 1.30466 +          goto end_takeconch; 
 1.30467 +        }
 1.30468 +      }
 1.30469 +      
 1.30470 +      /* if the conch isn't writable and doesn't match, we can't take it */
 1.30471 +      if( (conchFile->openFlags&O_RDWR) == 0 ){
 1.30472 +        rc = SQLITE_BUSY;
 1.30473 +        goto end_takeconch;
 1.30474 +      }
 1.30475 +      
 1.30476 +      /* either the conch didn't match or we need to create a new one */
 1.30477 +      if( !pCtx->lockProxyPath ){
 1.30478 +        proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
 1.30479 +        tempLockPath = lockPath;
 1.30480 +        /* create a copy of the lock path _only_ if the conch is taken */
 1.30481 +      }
 1.30482 +      
 1.30483 +      /* update conch with host and path (this will fail if other process
 1.30484 +      ** has a shared lock already), if the host id matches, use the big
 1.30485 +      ** stick.
 1.30486 +      */
 1.30487 +      futimes(conchFile->h, NULL);
 1.30488 +      if( hostIdMatch && !createConch ){
 1.30489 +        if( conchFile->pInode && conchFile->pInode->nShared>1 ){
 1.30490 +          /* We are trying for an exclusive lock but another thread in this
 1.30491 +           ** same process is still holding a shared lock. */
 1.30492 +          rc = SQLITE_BUSY;
 1.30493 +        } else {          
 1.30494 +          rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
 1.30495 +        }
 1.30496 +      }else{
 1.30497 +        rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
 1.30498 +      }
 1.30499 +      if( rc==SQLITE_OK ){
 1.30500 +        char writeBuffer[PROXY_MAXCONCHLEN];
 1.30501 +        int writeSize = 0;
 1.30502 +        
 1.30503 +        writeBuffer[0] = (char)PROXY_CONCHVERSION;
 1.30504 +        memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
 1.30505 +        if( pCtx->lockProxyPath!=NULL ){
 1.30506 +          strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
 1.30507 +        }else{
 1.30508 +          strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
 1.30509 +        }
 1.30510 +        writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
 1.30511 +        robust_ftruncate(conchFile->h, writeSize);
 1.30512 +        rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
 1.30513 +        fsync(conchFile->h);
 1.30514 +        /* If we created a new conch file (not just updated the contents of a 
 1.30515 +         ** valid conch file), try to match the permissions of the database 
 1.30516 +         */
 1.30517 +        if( rc==SQLITE_OK && createConch ){
 1.30518 +          struct stat buf;
 1.30519 +          int err = osFstat(pFile->h, &buf);
 1.30520 +          if( err==0 ){
 1.30521 +            mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
 1.30522 +                                        S_IROTH|S_IWOTH);
 1.30523 +            /* try to match the database file R/W permissions, ignore failure */
 1.30524 +#ifndef SQLITE_PROXY_DEBUG
 1.30525 +            osFchmod(conchFile->h, cmode);
 1.30526 +#else
 1.30527 +            do{
 1.30528 +              rc = osFchmod(conchFile->h, cmode);
 1.30529 +            }while( rc==(-1) && errno==EINTR );
 1.30530 +            if( rc!=0 ){
 1.30531 +              int code = errno;
 1.30532 +              fprintf(stderr, "fchmod %o FAILED with %d %s\n",
 1.30533 +                      cmode, code, strerror(code));
 1.30534 +            } else {
 1.30535 +              fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
 1.30536 +            }
 1.30537 +          }else{
 1.30538 +            int code = errno;
 1.30539 +            fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
 1.30540 +                    err, code, strerror(code));
 1.30541 +#endif
 1.30542 +          }
 1.30543 +        }
 1.30544 +      }
 1.30545 +      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
 1.30546 +      
 1.30547 +    end_takeconch:
 1.30548 +      OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
 1.30549 +      if( rc==SQLITE_OK && pFile->openFlags ){
 1.30550 +        int fd;
 1.30551 +        if( pFile->h>=0 ){
 1.30552 +          robust_close(pFile, pFile->h, __LINE__);
 1.30553 +        }
 1.30554 +        pFile->h = -1;
 1.30555 +        fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
 1.30556 +        OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
 1.30557 +        if( fd>=0 ){
 1.30558 +          pFile->h = fd;
 1.30559 +        }else{
 1.30560 +          rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
 1.30561 +           during locking */
 1.30562 +        }
 1.30563 +      }
 1.30564 +      if( rc==SQLITE_OK && !pCtx->lockProxy ){
 1.30565 +        char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
 1.30566 +        rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
 1.30567 +        if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
 1.30568 +          /* we couldn't create the proxy lock file with the old lock file path
 1.30569 +           ** so try again via auto-naming 
 1.30570 +           */
 1.30571 +          forceNewLockPath = 1;
 1.30572 +          tryOldLockPath = 0;
 1.30573 +          continue; /* go back to the do {} while start point, try again */
 1.30574 +        }
 1.30575 +      }
 1.30576 +      if( rc==SQLITE_OK ){
 1.30577 +        /* Need to make a copy of path if we extracted the value
 1.30578 +         ** from the conch file or the path was allocated on the stack
 1.30579 +         */
 1.30580 +        if( tempLockPath ){
 1.30581 +          pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
 1.30582 +          if( !pCtx->lockProxyPath ){
 1.30583 +            rc = SQLITE_NOMEM;
 1.30584 +          }
 1.30585 +        }
 1.30586 +      }
 1.30587 +      if( rc==SQLITE_OK ){
 1.30588 +        pCtx->conchHeld = 1;
 1.30589 +        
 1.30590 +        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
 1.30591 +          afpLockingContext *afpCtx;
 1.30592 +          afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
 1.30593 +          afpCtx->dbPath = pCtx->lockProxyPath;
 1.30594 +        }
 1.30595 +      } else {
 1.30596 +        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
 1.30597 +      }
 1.30598 +      OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
 1.30599 +               rc==SQLITE_OK?"ok":"failed"));
 1.30600 +      return rc;
 1.30601 +    } while (1); /* in case we need to retry the :auto: lock file - 
 1.30602 +                 ** we should never get here except via the 'continue' call. */
 1.30603 +  }
 1.30604 +}
 1.30605 +
 1.30606 +/*
 1.30607 +** If pFile holds a lock on a conch file, then release that lock.
 1.30608 +*/
 1.30609 +static int proxyReleaseConch(unixFile *pFile){
 1.30610 +  int rc = SQLITE_OK;         /* Subroutine return code */
 1.30611 +  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
 1.30612 +  unixFile *conchFile;        /* Name of the conch file */
 1.30613 +
 1.30614 +  pCtx = (proxyLockingContext *)pFile->lockingContext;
 1.30615 +  conchFile = pCtx->conchFile;
 1.30616 +  OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
 1.30617 +           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
 1.30618 +           getpid()));
 1.30619 +  if( pCtx->conchHeld>0 ){
 1.30620 +    rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
 1.30621 +  }
 1.30622 +  pCtx->conchHeld = 0;
 1.30623 +  OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
 1.30624 +           (rc==SQLITE_OK ? "ok" : "failed")));
 1.30625 +  return rc;
 1.30626 +}
 1.30627 +
 1.30628 +/*
 1.30629 +** Given the name of a database file, compute the name of its conch file.
 1.30630 +** Store the conch filename in memory obtained from sqlite3_malloc().
 1.30631 +** Make *pConchPath point to the new name.  Return SQLITE_OK on success
 1.30632 +** or SQLITE_NOMEM if unable to obtain memory.
 1.30633 +**
 1.30634 +** The caller is responsible for ensuring that the allocated memory
 1.30635 +** space is eventually freed.
 1.30636 +**
 1.30637 +** *pConchPath is set to NULL if a memory allocation error occurs.
 1.30638 +*/
 1.30639 +static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
 1.30640 +  int i;                        /* Loop counter */
 1.30641 +  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
 1.30642 +  char *conchPath;              /* buffer in which to construct conch name */
 1.30643 +
 1.30644 +  /* Allocate space for the conch filename and initialize the name to
 1.30645 +  ** the name of the original database file. */  
 1.30646 +  *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
 1.30647 +  if( conchPath==0 ){
 1.30648 +    return SQLITE_NOMEM;
 1.30649 +  }
 1.30650 +  memcpy(conchPath, dbPath, len+1);
 1.30651 +  
 1.30652 +  /* now insert a "." before the last / character */
 1.30653 +  for( i=(len-1); i>=0; i-- ){
 1.30654 +    if( conchPath[i]=='/' ){
 1.30655 +      i++;
 1.30656 +      break;
 1.30657 +    }
 1.30658 +  }
 1.30659 +  conchPath[i]='.';
 1.30660 +  while ( i<len ){
 1.30661 +    conchPath[i+1]=dbPath[i];
 1.30662 +    i++;
 1.30663 +  }
 1.30664 +
 1.30665 +  /* append the "-conch" suffix to the file */
 1.30666 +  memcpy(&conchPath[i+1], "-conch", 7);
 1.30667 +  assert( (int)strlen(conchPath) == len+7 );
 1.30668 +
 1.30669 +  return SQLITE_OK;
 1.30670 +}
 1.30671 +
 1.30672 +
 1.30673 +/* Takes a fully configured proxy locking-style unix file and switches
 1.30674 +** the local lock file path 
 1.30675 +*/
 1.30676 +static int switchLockProxyPath(unixFile *pFile, const char *path) {
 1.30677 +  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
 1.30678 +  char *oldPath = pCtx->lockProxyPath;
 1.30679 +  int rc = SQLITE_OK;
 1.30680 +
 1.30681 +  if( pFile->eFileLock!=NO_LOCK ){
 1.30682 +    return SQLITE_BUSY;
 1.30683 +  }  
 1.30684 +
 1.30685 +  /* nothing to do if the path is NULL, :auto: or matches the existing path */
 1.30686 +  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
 1.30687 +    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
 1.30688 +    return SQLITE_OK;
 1.30689 +  }else{
 1.30690 +    unixFile *lockProxy = pCtx->lockProxy;
 1.30691 +    pCtx->lockProxy=NULL;
 1.30692 +    pCtx->conchHeld = 0;
 1.30693 +    if( lockProxy!=NULL ){
 1.30694 +      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
 1.30695 +      if( rc ) return rc;
 1.30696 +      sqlite3_free(lockProxy);
 1.30697 +    }
 1.30698 +    sqlite3_free(oldPath);
 1.30699 +    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
 1.30700 +  }
 1.30701 +  
 1.30702 +  return rc;
 1.30703 +}
 1.30704 +
 1.30705 +/*
 1.30706 +** pFile is a file that has been opened by a prior xOpen call.  dbPath
 1.30707 +** is a string buffer at least MAXPATHLEN+1 characters in size.
 1.30708 +**
 1.30709 +** This routine find the filename associated with pFile and writes it
 1.30710 +** int dbPath.
 1.30711 +*/
 1.30712 +static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
 1.30713 +#if defined(__APPLE__)
 1.30714 +  if( pFile->pMethod == &afpIoMethods ){
 1.30715 +    /* afp style keeps a reference to the db path in the filePath field 
 1.30716 +    ** of the struct */
 1.30717 +    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
 1.30718 +    strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
 1.30719 +  } else
 1.30720 +#endif
 1.30721 +  if( pFile->pMethod == &dotlockIoMethods ){
 1.30722 +    /* dot lock style uses the locking context to store the dot lock
 1.30723 +    ** file path */
 1.30724 +    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
 1.30725 +    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
 1.30726 +  }else{
 1.30727 +    /* all other styles use the locking context to store the db file path */
 1.30728 +    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
 1.30729 +    strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
 1.30730 +  }
 1.30731 +  return SQLITE_OK;
 1.30732 +}
 1.30733 +
 1.30734 +/*
 1.30735 +** Takes an already filled in unix file and alters it so all file locking 
 1.30736 +** will be performed on the local proxy lock file.  The following fields
 1.30737 +** are preserved in the locking context so that they can be restored and 
 1.30738 +** the unix structure properly cleaned up at close time:
 1.30739 +**  ->lockingContext
 1.30740 +**  ->pMethod
 1.30741 +*/
 1.30742 +static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
 1.30743 +  proxyLockingContext *pCtx;
 1.30744 +  char dbPath[MAXPATHLEN+1];       /* Name of the database file */
 1.30745 +  char *lockPath=NULL;
 1.30746 +  int rc = SQLITE_OK;
 1.30747 +  
 1.30748 +  if( pFile->eFileLock!=NO_LOCK ){
 1.30749 +    return SQLITE_BUSY;
 1.30750 +  }
 1.30751 +  proxyGetDbPathForUnixFile(pFile, dbPath);
 1.30752 +  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
 1.30753 +    lockPath=NULL;
 1.30754 +  }else{
 1.30755 +    lockPath=(char *)path;
 1.30756 +  }
 1.30757 +  
 1.30758 +  OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
 1.30759 +           (lockPath ? lockPath : ":auto:"), getpid()));
 1.30760 +
 1.30761 +  pCtx = sqlite3_malloc( sizeof(*pCtx) );
 1.30762 +  if( pCtx==0 ){
 1.30763 +    return SQLITE_NOMEM;
 1.30764 +  }
 1.30765 +  memset(pCtx, 0, sizeof(*pCtx));
 1.30766 +
 1.30767 +  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
 1.30768 +  if( rc==SQLITE_OK ){
 1.30769 +    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
 1.30770 +    if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
 1.30771 +      /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
 1.30772 +      ** (c) the file system is read-only, then enable no-locking access.
 1.30773 +      ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
 1.30774 +      ** that openFlags will have only one of O_RDONLY or O_RDWR.
 1.30775 +      */
 1.30776 +      struct statfs fsInfo;
 1.30777 +      struct stat conchInfo;
 1.30778 +      int goLockless = 0;
 1.30779 +
 1.30780 +      if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
 1.30781 +        int err = errno;
 1.30782 +        if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
 1.30783 +          goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
 1.30784 +        }
 1.30785 +      }
 1.30786 +      if( goLockless ){
 1.30787 +        pCtx->conchHeld = -1; /* read only FS/ lockless */
 1.30788 +        rc = SQLITE_OK;
 1.30789 +      }
 1.30790 +    }
 1.30791 +  }  
 1.30792 +  if( rc==SQLITE_OK && lockPath ){
 1.30793 +    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
 1.30794 +  }
 1.30795 +
 1.30796 +  if( rc==SQLITE_OK ){
 1.30797 +    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
 1.30798 +    if( pCtx->dbPath==NULL ){
 1.30799 +      rc = SQLITE_NOMEM;
 1.30800 +    }
 1.30801 +  }
 1.30802 +  if( rc==SQLITE_OK ){
 1.30803 +    /* all memory is allocated, proxys are created and assigned, 
 1.30804 +    ** switch the locking context and pMethod then return.
 1.30805 +    */
 1.30806 +    pCtx->oldLockingContext = pFile->lockingContext;
 1.30807 +    pFile->lockingContext = pCtx;
 1.30808 +    pCtx->pOldMethod = pFile->pMethod;
 1.30809 +    pFile->pMethod = &proxyIoMethods;
 1.30810 +  }else{
 1.30811 +    if( pCtx->conchFile ){ 
 1.30812 +      pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
 1.30813 +      sqlite3_free(pCtx->conchFile);
 1.30814 +    }
 1.30815 +    sqlite3DbFree(0, pCtx->lockProxyPath);
 1.30816 +    sqlite3_free(pCtx->conchFilePath); 
 1.30817 +    sqlite3_free(pCtx);
 1.30818 +  }
 1.30819 +  OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
 1.30820 +           (rc==SQLITE_OK ? "ok" : "failed")));
 1.30821 +  return rc;
 1.30822 +}
 1.30823 +
 1.30824 +
 1.30825 +/*
 1.30826 +** This routine handles sqlite3_file_control() calls that are specific
 1.30827 +** to proxy locking.
 1.30828 +*/
 1.30829 +static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
 1.30830 +  switch( op ){
 1.30831 +    case SQLITE_GET_LOCKPROXYFILE: {
 1.30832 +      unixFile *pFile = (unixFile*)id;
 1.30833 +      if( pFile->pMethod == &proxyIoMethods ){
 1.30834 +        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
 1.30835 +        proxyTakeConch(pFile);
 1.30836 +        if( pCtx->lockProxyPath ){
 1.30837 +          *(const char **)pArg = pCtx->lockProxyPath;
 1.30838 +        }else{
 1.30839 +          *(const char **)pArg = ":auto: (not held)";
 1.30840 +        }
 1.30841 +      } else {
 1.30842 +        *(const char **)pArg = NULL;
 1.30843 +      }
 1.30844 +      return SQLITE_OK;
 1.30845 +    }
 1.30846 +    case SQLITE_SET_LOCKPROXYFILE: {
 1.30847 +      unixFile *pFile = (unixFile*)id;
 1.30848 +      int rc = SQLITE_OK;
 1.30849 +      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
 1.30850 +      if( pArg==NULL || (const char *)pArg==0 ){
 1.30851 +        if( isProxyStyle ){
 1.30852 +          /* turn off proxy locking - not supported */
 1.30853 +          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
 1.30854 +        }else{
 1.30855 +          /* turn off proxy locking - already off - NOOP */
 1.30856 +          rc = SQLITE_OK;
 1.30857 +        }
 1.30858 +      }else{
 1.30859 +        const char *proxyPath = (const char *)pArg;
 1.30860 +        if( isProxyStyle ){
 1.30861 +          proxyLockingContext *pCtx = 
 1.30862 +            (proxyLockingContext*)pFile->lockingContext;
 1.30863 +          if( !strcmp(pArg, ":auto:") 
 1.30864 +           || (pCtx->lockProxyPath &&
 1.30865 +               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
 1.30866 +          ){
 1.30867 +            rc = SQLITE_OK;
 1.30868 +          }else{
 1.30869 +            rc = switchLockProxyPath(pFile, proxyPath);
 1.30870 +          }
 1.30871 +        }else{
 1.30872 +          /* turn on proxy file locking */
 1.30873 +          rc = proxyTransformUnixFile(pFile, proxyPath);
 1.30874 +        }
 1.30875 +      }
 1.30876 +      return rc;
 1.30877 +    }
 1.30878 +    default: {
 1.30879 +      assert( 0 );  /* The call assures that only valid opcodes are sent */
 1.30880 +    }
 1.30881 +  }
 1.30882 +  /*NOTREACHED*/
 1.30883 +  return SQLITE_ERROR;
 1.30884 +}
 1.30885 +
 1.30886 +/*
 1.30887 +** Within this division (the proxying locking implementation) the procedures
 1.30888 +** above this point are all utilities.  The lock-related methods of the
 1.30889 +** proxy-locking sqlite3_io_method object follow.
 1.30890 +*/
 1.30891 +
 1.30892 +
 1.30893 +/*
 1.30894 +** This routine checks if there is a RESERVED lock held on the specified
 1.30895 +** file by this or any other process. If such a lock is held, set *pResOut
 1.30896 +** to a non-zero value otherwise *pResOut is set to zero.  The return value
 1.30897 +** is set to SQLITE_OK unless an I/O error occurs during lock checking.
 1.30898 +*/
 1.30899 +static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
 1.30900 +  unixFile *pFile = (unixFile*)id;
 1.30901 +  int rc = proxyTakeConch(pFile);
 1.30902 +  if( rc==SQLITE_OK ){
 1.30903 +    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
 1.30904 +    if( pCtx->conchHeld>0 ){
 1.30905 +      unixFile *proxy = pCtx->lockProxy;
 1.30906 +      return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
 1.30907 +    }else{ /* conchHeld < 0 is lockless */
 1.30908 +      pResOut=0;
 1.30909 +    }
 1.30910 +  }
 1.30911 +  return rc;
 1.30912 +}
 1.30913 +
 1.30914 +/*
 1.30915 +** Lock the file with the lock specified by parameter eFileLock - one
 1.30916 +** of the following:
 1.30917 +**
 1.30918 +**     (1) SHARED_LOCK
 1.30919 +**     (2) RESERVED_LOCK
 1.30920 +**     (3) PENDING_LOCK
 1.30921 +**     (4) EXCLUSIVE_LOCK
 1.30922 +**
 1.30923 +** Sometimes when requesting one lock state, additional lock states
 1.30924 +** are inserted in between.  The locking might fail on one of the later
 1.30925 +** transitions leaving the lock state different from what it started but
 1.30926 +** still short of its goal.  The following chart shows the allowed
 1.30927 +** transitions and the inserted intermediate states:
 1.30928 +**
 1.30929 +**    UNLOCKED -> SHARED
 1.30930 +**    SHARED -> RESERVED
 1.30931 +**    SHARED -> (PENDING) -> EXCLUSIVE
 1.30932 +**    RESERVED -> (PENDING) -> EXCLUSIVE
 1.30933 +**    PENDING -> EXCLUSIVE
 1.30934 +**
 1.30935 +** This routine will only increase a lock.  Use the sqlite3OsUnlock()
 1.30936 +** routine to lower a locking level.
 1.30937 +*/
 1.30938 +static int proxyLock(sqlite3_file *id, int eFileLock) {
 1.30939 +  unixFile *pFile = (unixFile*)id;
 1.30940 +  int rc = proxyTakeConch(pFile);
 1.30941 +  if( rc==SQLITE_OK ){
 1.30942 +    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
 1.30943 +    if( pCtx->conchHeld>0 ){
 1.30944 +      unixFile *proxy = pCtx->lockProxy;
 1.30945 +      rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
 1.30946 +      pFile->eFileLock = proxy->eFileLock;
 1.30947 +    }else{
 1.30948 +      /* conchHeld < 0 is lockless */
 1.30949 +    }
 1.30950 +  }
 1.30951 +  return rc;
 1.30952 +}
 1.30953 +
 1.30954 +
 1.30955 +/*
 1.30956 +** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 1.30957 +** must be either NO_LOCK or SHARED_LOCK.
 1.30958 +**
 1.30959 +** If the locking level of the file descriptor is already at or below
 1.30960 +** the requested locking level, this routine is a no-op.
 1.30961 +*/
 1.30962 +static int proxyUnlock(sqlite3_file *id, int eFileLock) {
 1.30963 +  unixFile *pFile = (unixFile*)id;
 1.30964 +  int rc = proxyTakeConch(pFile);
 1.30965 +  if( rc==SQLITE_OK ){
 1.30966 +    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
 1.30967 +    if( pCtx->conchHeld>0 ){
 1.30968 +      unixFile *proxy = pCtx->lockProxy;
 1.30969 +      rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
 1.30970 +      pFile->eFileLock = proxy->eFileLock;
 1.30971 +    }else{
 1.30972 +      /* conchHeld < 0 is lockless */
 1.30973 +    }
 1.30974 +  }
 1.30975 +  return rc;
 1.30976 +}
 1.30977 +
 1.30978 +/*
 1.30979 +** Close a file that uses proxy locks.
 1.30980 +*/
 1.30981 +static int proxyClose(sqlite3_file *id) {
 1.30982 +  if( id ){
 1.30983 +    unixFile *pFile = (unixFile*)id;
 1.30984 +    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
 1.30985 +    unixFile *lockProxy = pCtx->lockProxy;
 1.30986 +    unixFile *conchFile = pCtx->conchFile;
 1.30987 +    int rc = SQLITE_OK;
 1.30988 +    
 1.30989 +    if( lockProxy ){
 1.30990 +      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
 1.30991 +      if( rc ) return rc;
 1.30992 +      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
 1.30993 +      if( rc ) return rc;
 1.30994 +      sqlite3_free(lockProxy);
 1.30995 +      pCtx->lockProxy = 0;
 1.30996 +    }
 1.30997 +    if( conchFile ){
 1.30998 +      if( pCtx->conchHeld ){
 1.30999 +        rc = proxyReleaseConch(pFile);
 1.31000 +        if( rc ) return rc;
 1.31001 +      }
 1.31002 +      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
 1.31003 +      if( rc ) return rc;
 1.31004 +      sqlite3_free(conchFile);
 1.31005 +    }
 1.31006 +    sqlite3DbFree(0, pCtx->lockProxyPath);
 1.31007 +    sqlite3_free(pCtx->conchFilePath);
 1.31008 +    sqlite3DbFree(0, pCtx->dbPath);
 1.31009 +    /* restore the original locking context and pMethod then close it */
 1.31010 +    pFile->lockingContext = pCtx->oldLockingContext;
 1.31011 +    pFile->pMethod = pCtx->pOldMethod;
 1.31012 +    sqlite3_free(pCtx);
 1.31013 +    return pFile->pMethod->xClose(id);
 1.31014 +  }
 1.31015 +  return SQLITE_OK;
 1.31016 +}
 1.31017 +
 1.31018 +
 1.31019 +
 1.31020 +#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
 1.31021 +/*
 1.31022 +** The proxy locking style is intended for use with AFP filesystems.
 1.31023 +** And since AFP is only supported on MacOSX, the proxy locking is also
 1.31024 +** restricted to MacOSX.
 1.31025 +** 
 1.31026 +**
 1.31027 +******************* End of the proxy lock implementation **********************
 1.31028 +******************************************************************************/
 1.31029 +
 1.31030 +/*
 1.31031 +** Initialize the operating system interface.
 1.31032 +**
 1.31033 +** This routine registers all VFS implementations for unix-like operating
 1.31034 +** systems.  This routine, and the sqlite3_os_end() routine that follows,
 1.31035 +** should be the only routines in this file that are visible from other
 1.31036 +** files.
 1.31037 +**
 1.31038 +** This routine is called once during SQLite initialization and by a
 1.31039 +** single thread.  The memory allocation and mutex subsystems have not
 1.31040 +** necessarily been initialized when this routine is called, and so they
 1.31041 +** should not be used.
 1.31042 +*/
 1.31043 +SQLITE_API int sqlite3_os_init(void){ 
 1.31044 +  /* 
 1.31045 +  ** The following macro defines an initializer for an sqlite3_vfs object.
 1.31046 +  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
 1.31047 +  ** to the "finder" function.  (pAppData is a pointer to a pointer because
 1.31048 +  ** silly C90 rules prohibit a void* from being cast to a function pointer
 1.31049 +  ** and so we have to go through the intermediate pointer to avoid problems
 1.31050 +  ** when compiling with -pedantic-errors on GCC.)
 1.31051 +  **
 1.31052 +  ** The FINDER parameter to this macro is the name of the pointer to the
 1.31053 +  ** finder-function.  The finder-function returns a pointer to the
 1.31054 +  ** sqlite_io_methods object that implements the desired locking
 1.31055 +  ** behaviors.  See the division above that contains the IOMETHODS
 1.31056 +  ** macro for addition information on finder-functions.
 1.31057 +  **
 1.31058 +  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
 1.31059 +  ** object.  But the "autolockIoFinder" available on MacOSX does a little
 1.31060 +  ** more than that; it looks at the filesystem type that hosts the 
 1.31061 +  ** database file and tries to choose an locking method appropriate for
 1.31062 +  ** that filesystem time.
 1.31063 +  */
 1.31064 +  #define UNIXVFS(VFSNAME, FINDER) {                        \
 1.31065 +    3,                    /* iVersion */                    \
 1.31066 +    sizeof(unixFile),     /* szOsFile */                    \
 1.31067 +    MAX_PATHNAME,         /* mxPathname */                  \
 1.31068 +    0,                    /* pNext */                       \
 1.31069 +    VFSNAME,              /* zName */                       \
 1.31070 +    (void*)&FINDER,       /* pAppData */                    \
 1.31071 +    unixOpen,             /* xOpen */                       \
 1.31072 +    unixDelete,           /* xDelete */                     \
 1.31073 +    unixAccess,           /* xAccess */                     \
 1.31074 +    unixFullPathname,     /* xFullPathname */               \
 1.31075 +    unixDlOpen,           /* xDlOpen */                     \
 1.31076 +    unixDlError,          /* xDlError */                    \
 1.31077 +    unixDlSym,            /* xDlSym */                      \
 1.31078 +    unixDlClose,          /* xDlClose */                    \
 1.31079 +    unixRandomness,       /* xRandomness */                 \
 1.31080 +    unixSleep,            /* xSleep */                      \
 1.31081 +    unixCurrentTime,      /* xCurrentTime */                \
 1.31082 +    unixGetLastError,     /* xGetLastError */               \
 1.31083 +    unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
 1.31084 +    unixSetSystemCall,    /* xSetSystemCall */              \
 1.31085 +    unixGetSystemCall,    /* xGetSystemCall */              \
 1.31086 +    unixNextSystemCall,   /* xNextSystemCall */             \
 1.31087 +  }
 1.31088 +
 1.31089 +  /*
 1.31090 +  ** All default VFSes for unix are contained in the following array.
 1.31091 +  **
 1.31092 +  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
 1.31093 +  ** by the SQLite core when the VFS is registered.  So the following
 1.31094 +  ** array cannot be const.
 1.31095 +  */
 1.31096 +  static sqlite3_vfs aVfs[] = {
 1.31097 +#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
 1.31098 +    UNIXVFS("unix",          autolockIoFinder ),
 1.31099 +#else
 1.31100 +    UNIXVFS("unix",          posixIoFinder ),
 1.31101 +#endif
 1.31102 +    UNIXVFS("unix-none",     nolockIoFinder ),
 1.31103 +    UNIXVFS("unix-dotfile",  dotlockIoFinder ),
 1.31104 +    UNIXVFS("unix-excl",     posixIoFinder ),
 1.31105 +#if OS_VXWORKS
 1.31106 +    UNIXVFS("unix-namedsem", semIoFinder ),
 1.31107 +#endif
 1.31108 +#if SQLITE_ENABLE_LOCKING_STYLE
 1.31109 +    UNIXVFS("unix-posix",    posixIoFinder ),
 1.31110 +#if !OS_VXWORKS
 1.31111 +    UNIXVFS("unix-flock",    flockIoFinder ),
 1.31112 +#endif
 1.31113 +#endif
 1.31114 +#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
 1.31115 +    UNIXVFS("unix-afp",      afpIoFinder ),
 1.31116 +    UNIXVFS("unix-nfs",      nfsIoFinder ),
 1.31117 +    UNIXVFS("unix-proxy",    proxyIoFinder ),
 1.31118 +#endif
 1.31119 +  };
 1.31120 +  unsigned int i;          /* Loop counter */
 1.31121 +
 1.31122 +  /* Double-check that the aSyscall[] array has been constructed
 1.31123 +  ** correctly.  See ticket [bb3a86e890c8e96ab] */
 1.31124 +  assert( ArraySize(aSyscall)==24 );
 1.31125 +
 1.31126 +  /* Register all VFSes defined in the aVfs[] array */
 1.31127 +  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
 1.31128 +    sqlite3_vfs_register(&aVfs[i], i==0);
 1.31129 +  }
 1.31130 +  return SQLITE_OK; 
 1.31131 +}
 1.31132 +
 1.31133 +/*
 1.31134 +** Shutdown the operating system interface.
 1.31135 +**
 1.31136 +** Some operating systems might need to do some cleanup in this routine,
 1.31137 +** to release dynamically allocated objects.  But not on unix.
 1.31138 +** This routine is a no-op for unix.
 1.31139 +*/
 1.31140 +SQLITE_API int sqlite3_os_end(void){ 
 1.31141 +  return SQLITE_OK; 
 1.31142 +}
 1.31143 + 
 1.31144 +#endif /* SQLITE_OS_UNIX */
 1.31145 +
 1.31146 +/************** End of os_unix.c *********************************************/
 1.31147 +/************** Begin file os_win.c ******************************************/
 1.31148 +/*
 1.31149 +** 2004 May 22
 1.31150 +**
 1.31151 +** The author disclaims copyright to this source code.  In place of
 1.31152 +** a legal notice, here is a blessing:
 1.31153 +**
 1.31154 +**    May you do good and not evil.
 1.31155 +**    May you find forgiveness for yourself and forgive others.
 1.31156 +**    May you share freely, never taking more than you give.
 1.31157 +**
 1.31158 +******************************************************************************
 1.31159 +**
 1.31160 +** This file contains code that is specific to Windows.
 1.31161 +*/
 1.31162 +#if SQLITE_OS_WIN               /* This file is used for Windows only */
 1.31163 +
 1.31164 +#ifdef __CYGWIN__
 1.31165 +# include <sys/cygwin.h>
 1.31166 +# include <errno.h> /* amalgamator: keep */
 1.31167 +#endif
 1.31168 +
 1.31169 +/*
 1.31170 +** Include code that is common to all os_*.c files
 1.31171 +*/
 1.31172 +/************** Include os_common.h in the middle of os_win.c ****************/
 1.31173 +/************** Begin file os_common.h ***************************************/
 1.31174 +/*
 1.31175 +** 2004 May 22
 1.31176 +**
 1.31177 +** The author disclaims copyright to this source code.  In place of
 1.31178 +** a legal notice, here is a blessing:
 1.31179 +**
 1.31180 +**    May you do good and not evil.
 1.31181 +**    May you find forgiveness for yourself and forgive others.
 1.31182 +**    May you share freely, never taking more than you give.
 1.31183 +**
 1.31184 +******************************************************************************
 1.31185 +**
 1.31186 +** This file contains macros and a little bit of code that is common to
 1.31187 +** all of the platform-specific files (os_*.c) and is #included into those
 1.31188 +** files.
 1.31189 +**
 1.31190 +** This file should be #included by the os_*.c files only.  It is not a
 1.31191 +** general purpose header file.
 1.31192 +*/
 1.31193 +#ifndef _OS_COMMON_H_
 1.31194 +#define _OS_COMMON_H_
 1.31195 +
 1.31196 +/*
 1.31197 +** At least two bugs have slipped in because we changed the MEMORY_DEBUG
 1.31198 +** macro to SQLITE_DEBUG and some older makefiles have not yet made the
 1.31199 +** switch.  The following code should catch this problem at compile-time.
 1.31200 +*/
 1.31201 +#ifdef MEMORY_DEBUG
 1.31202 +# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
 1.31203 +#endif
 1.31204 +
 1.31205 +#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
 1.31206 +# ifndef SQLITE_DEBUG_OS_TRACE
 1.31207 +#   define SQLITE_DEBUG_OS_TRACE 0
 1.31208 +# endif
 1.31209 +  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
 1.31210 +# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
 1.31211 +#else
 1.31212 +# define OSTRACE(X)
 1.31213 +#endif
 1.31214 +
 1.31215 +/*
 1.31216 +** Macros for performance tracing.  Normally turned off.  Only works
 1.31217 +** on i486 hardware.
 1.31218 +*/
 1.31219 +#ifdef SQLITE_PERFORMANCE_TRACE
 1.31220 +
 1.31221 +/* 
 1.31222 +** hwtime.h contains inline assembler code for implementing 
 1.31223 +** high-performance timing routines.
 1.31224 +*/
 1.31225 +/************** Include hwtime.h in the middle of os_common.h ****************/
 1.31226 +/************** Begin file hwtime.h ******************************************/
 1.31227 +/*
 1.31228 +** 2008 May 27
 1.31229 +**
 1.31230 +** The author disclaims copyright to this source code.  In place of
 1.31231 +** a legal notice, here is a blessing:
 1.31232 +**
 1.31233 +**    May you do good and not evil.
 1.31234 +**    May you find forgiveness for yourself and forgive others.
 1.31235 +**    May you share freely, never taking more than you give.
 1.31236 +**
 1.31237 +******************************************************************************
 1.31238 +**
 1.31239 +** This file contains inline asm code for retrieving "high-performance"
 1.31240 +** counters for x86 class CPUs.
 1.31241 +*/
 1.31242 +#ifndef _HWTIME_H_
 1.31243 +#define _HWTIME_H_
 1.31244 +
 1.31245 +/*
 1.31246 +** The following routine only works on pentium-class (or newer) processors.
 1.31247 +** It uses the RDTSC opcode to read the cycle count value out of the
 1.31248 +** processor and returns that value.  This can be used for high-res
 1.31249 +** profiling.
 1.31250 +*/
 1.31251 +#if (defined(__GNUC__) || defined(_MSC_VER)) && \
 1.31252 +      (defined(i386) || defined(__i386__) || defined(_M_IX86))
 1.31253 +
 1.31254 +  #if defined(__GNUC__)
 1.31255 +
 1.31256 +  __inline__ sqlite_uint64 sqlite3Hwtime(void){
 1.31257 +     unsigned int lo, hi;
 1.31258 +     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
 1.31259 +     return (sqlite_uint64)hi << 32 | lo;
 1.31260 +  }
 1.31261 +
 1.31262 +  #elif defined(_MSC_VER)
 1.31263 +
 1.31264 +  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
 1.31265 +     __asm {
 1.31266 +        rdtsc
 1.31267 +        ret       ; return value at EDX:EAX
 1.31268 +     }
 1.31269 +  }
 1.31270 +
 1.31271 +  #endif
 1.31272 +
 1.31273 +#elif (defined(__GNUC__) && defined(__x86_64__))
 1.31274 +
 1.31275 +  __inline__ sqlite_uint64 sqlite3Hwtime(void){
 1.31276 +      unsigned long val;
 1.31277 +      __asm__ __volatile__ ("rdtsc" : "=A" (val));
 1.31278 +      return val;
 1.31279 +  }
 1.31280 + 
 1.31281 +#elif (defined(__GNUC__) && defined(__ppc__))
 1.31282 +
 1.31283 +  __inline__ sqlite_uint64 sqlite3Hwtime(void){
 1.31284 +      unsigned long long retval;
 1.31285 +      unsigned long junk;
 1.31286 +      __asm__ __volatile__ ("\n\
 1.31287 +          1:      mftbu   %1\n\
 1.31288 +                  mftb    %L0\n\
 1.31289 +                  mftbu   %0\n\
 1.31290 +                  cmpw    %0,%1\n\
 1.31291 +                  bne     1b"
 1.31292 +                  : "=r" (retval), "=r" (junk));
 1.31293 +      return retval;
 1.31294 +  }
 1.31295 +
 1.31296 +#else
 1.31297 +
 1.31298 +  #error Need implementation of sqlite3Hwtime() for your platform.
 1.31299 +
 1.31300 +  /*
 1.31301 +  ** To compile without implementing sqlite3Hwtime() for your platform,
 1.31302 +  ** you can remove the above #error and use the following
 1.31303 +  ** stub function.  You will lose timing support for many
 1.31304 +  ** of the debugging and testing utilities, but it should at
 1.31305 +  ** least compile and run.
 1.31306 +  */
 1.31307 +SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
 1.31308 +
 1.31309 +#endif
 1.31310 +
 1.31311 +#endif /* !defined(_HWTIME_H_) */
 1.31312 +
 1.31313 +/************** End of hwtime.h **********************************************/
 1.31314 +/************** Continuing where we left off in os_common.h ******************/
 1.31315 +
 1.31316 +static sqlite_uint64 g_start;
 1.31317 +static sqlite_uint64 g_elapsed;
 1.31318 +#define TIMER_START       g_start=sqlite3Hwtime()
 1.31319 +#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
 1.31320 +#define TIMER_ELAPSED     g_elapsed
 1.31321 +#else
 1.31322 +#define TIMER_START
 1.31323 +#define TIMER_END
 1.31324 +#define TIMER_ELAPSED     ((sqlite_uint64)0)
 1.31325 +#endif
 1.31326 +
 1.31327 +/*
 1.31328 +** If we compile with the SQLITE_TEST macro set, then the following block
 1.31329 +** of code will give us the ability to simulate a disk I/O error.  This
 1.31330 +** is used for testing the I/O recovery logic.
 1.31331 +*/
 1.31332 +#ifdef SQLITE_TEST
 1.31333 +SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
 1.31334 +SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
 1.31335 +SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
 1.31336 +SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
 1.31337 +SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
 1.31338 +SQLITE_API int sqlite3_diskfull_pending = 0;
 1.31339 +SQLITE_API int sqlite3_diskfull = 0;
 1.31340 +#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
 1.31341 +#define SimulateIOError(CODE)  \
 1.31342 +  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
 1.31343 +       || sqlite3_io_error_pending-- == 1 )  \
 1.31344 +              { local_ioerr(); CODE; }
 1.31345 +static void local_ioerr(){
 1.31346 +  IOTRACE(("IOERR\n"));
 1.31347 +  sqlite3_io_error_hit++;
 1.31348 +  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
 1.31349 +}
 1.31350 +#define SimulateDiskfullError(CODE) \
 1.31351 +   if( sqlite3_diskfull_pending ){ \
 1.31352 +     if( sqlite3_diskfull_pending == 1 ){ \
 1.31353 +       local_ioerr(); \
 1.31354 +       sqlite3_diskfull = 1; \
 1.31355 +       sqlite3_io_error_hit = 1; \
 1.31356 +       CODE; \
 1.31357 +     }else{ \
 1.31358 +       sqlite3_diskfull_pending--; \
 1.31359 +     } \
 1.31360 +   }
 1.31361 +#else
 1.31362 +#define SimulateIOErrorBenign(X)
 1.31363 +#define SimulateIOError(A)
 1.31364 +#define SimulateDiskfullError(A)
 1.31365 +#endif
 1.31366 +
 1.31367 +/*
 1.31368 +** When testing, keep a count of the number of open files.
 1.31369 +*/
 1.31370 +#ifdef SQLITE_TEST
 1.31371 +SQLITE_API int sqlite3_open_file_count = 0;
 1.31372 +#define OpenCounter(X)  sqlite3_open_file_count+=(X)
 1.31373 +#else
 1.31374 +#define OpenCounter(X)
 1.31375 +#endif
 1.31376 +
 1.31377 +#endif /* !defined(_OS_COMMON_H_) */
 1.31378 +
 1.31379 +/************** End of os_common.h *******************************************/
 1.31380 +/************** Continuing where we left off in os_win.c *********************/
 1.31381 +
 1.31382 +/*
 1.31383 +** Compiling and using WAL mode requires several APIs that are only
 1.31384 +** available in Windows platforms based on the NT kernel.
 1.31385 +*/
 1.31386 +#if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
 1.31387 +#  error "WAL mode requires support from the Windows NT kernel, compile\
 1.31388 + with SQLITE_OMIT_WAL."
 1.31389 +#endif
 1.31390 +
 1.31391 +/*
 1.31392 +** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
 1.31393 +** based on the sub-platform)?
 1.31394 +*/
 1.31395 +#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
 1.31396 +#  define SQLITE_WIN32_HAS_ANSI
 1.31397 +#endif
 1.31398 +
 1.31399 +/*
 1.31400 +** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
 1.31401 +** based on the sub-platform)?
 1.31402 +*/
 1.31403 +#if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
 1.31404 +    !defined(SQLITE_WIN32_NO_WIDE)
 1.31405 +#  define SQLITE_WIN32_HAS_WIDE
 1.31406 +#endif
 1.31407 +
 1.31408 +/*
 1.31409 +** Make sure at least one set of Win32 APIs is available.
 1.31410 +*/
 1.31411 +#if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
 1.31412 +#  error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
 1.31413 + must be defined."
 1.31414 +#endif
 1.31415 +
 1.31416 +/*
 1.31417 +** Define the required Windows SDK version constants if they are not
 1.31418 +** already available.
 1.31419 +*/
 1.31420 +#ifndef NTDDI_WIN8
 1.31421 +#  define NTDDI_WIN8                        0x06020000
 1.31422 +#endif
 1.31423 +
 1.31424 +#ifndef NTDDI_WINBLUE
 1.31425 +#  define NTDDI_WINBLUE                     0x06030000
 1.31426 +#endif
 1.31427 +
 1.31428 +/*
 1.31429 +** Check if the GetVersionEx[AW] functions should be considered deprecated
 1.31430 +** and avoid using them in that case.  It should be noted here that if the
 1.31431 +** value of the SQLITE_WIN32_GETVERSIONEX pre-processor macro is zero
 1.31432 +** (whether via this block or via being manually specified), that implies
 1.31433 +** the underlying operating system will always be based on the Windows NT
 1.31434 +** Kernel.
 1.31435 +*/
 1.31436 +#ifndef SQLITE_WIN32_GETVERSIONEX
 1.31437 +#  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
 1.31438 +#    define SQLITE_WIN32_GETVERSIONEX   0
 1.31439 +#  else
 1.31440 +#    define SQLITE_WIN32_GETVERSIONEX   1
 1.31441 +#  endif
 1.31442 +#endif
 1.31443 +
 1.31444 +/*
 1.31445 +** This constant should already be defined (in the "WinDef.h" SDK file).
 1.31446 +*/
 1.31447 +#ifndef MAX_PATH
 1.31448 +#  define MAX_PATH                      (260)
 1.31449 +#endif
 1.31450 +
 1.31451 +/*
 1.31452 +** Maximum pathname length (in chars) for Win32.  This should normally be
 1.31453 +** MAX_PATH.
 1.31454 +*/
 1.31455 +#ifndef SQLITE_WIN32_MAX_PATH_CHARS
 1.31456 +#  define SQLITE_WIN32_MAX_PATH_CHARS   (MAX_PATH)
 1.31457 +#endif
 1.31458 +
 1.31459 +/*
 1.31460 +** This constant should already be defined (in the "WinNT.h" SDK file).
 1.31461 +*/
 1.31462 +#ifndef UNICODE_STRING_MAX_CHARS
 1.31463 +#  define UNICODE_STRING_MAX_CHARS      (32767)
 1.31464 +#endif
 1.31465 +
 1.31466 +/*
 1.31467 +** Maximum pathname length (in chars) for WinNT.  This should normally be
 1.31468 +** UNICODE_STRING_MAX_CHARS.
 1.31469 +*/
 1.31470 +#ifndef SQLITE_WINNT_MAX_PATH_CHARS
 1.31471 +#  define SQLITE_WINNT_MAX_PATH_CHARS   (UNICODE_STRING_MAX_CHARS)
 1.31472 +#endif
 1.31473 +
 1.31474 +/*
 1.31475 +** Maximum pathname length (in bytes) for Win32.  The MAX_PATH macro is in
 1.31476 +** characters, so we allocate 4 bytes per character assuming worst-case of
 1.31477 +** 4-bytes-per-character for UTF8.
 1.31478 +*/
 1.31479 +#ifndef SQLITE_WIN32_MAX_PATH_BYTES
 1.31480 +#  define SQLITE_WIN32_MAX_PATH_BYTES   (SQLITE_WIN32_MAX_PATH_CHARS*4)
 1.31481 +#endif
 1.31482 +
 1.31483 +/*
 1.31484 +** Maximum pathname length (in bytes) for WinNT.  This should normally be
 1.31485 +** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
 1.31486 +*/
 1.31487 +#ifndef SQLITE_WINNT_MAX_PATH_BYTES
 1.31488 +#  define SQLITE_WINNT_MAX_PATH_BYTES   \
 1.31489 +                            (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
 1.31490 +#endif
 1.31491 +
 1.31492 +/*
 1.31493 +** Maximum error message length (in chars) for WinRT.
 1.31494 +*/
 1.31495 +#ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
 1.31496 +#  define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
 1.31497 +#endif
 1.31498 +
 1.31499 +/*
 1.31500 +** Returns non-zero if the character should be treated as a directory
 1.31501 +** separator.
 1.31502 +*/
 1.31503 +#ifndef winIsDirSep
 1.31504 +#  define winIsDirSep(a)                (((a) == '/') || ((a) == '\\'))
 1.31505 +#endif
 1.31506 +
 1.31507 +/*
 1.31508 +** This macro is used when a local variable is set to a value that is
 1.31509 +** [sometimes] not used by the code (e.g. via conditional compilation).
 1.31510 +*/
 1.31511 +#ifndef UNUSED_VARIABLE_VALUE
 1.31512 +#  define UNUSED_VARIABLE_VALUE(x) (void)(x)
 1.31513 +#endif
 1.31514 +
 1.31515 +/*
 1.31516 +** Returns the character that should be used as the directory separator.
 1.31517 +*/
 1.31518 +#ifndef winGetDirSep
 1.31519 +#  define winGetDirSep()                '\\'
 1.31520 +#endif
 1.31521 +
 1.31522 +/*
 1.31523 +** Do we need to manually define the Win32 file mapping APIs for use with WAL
 1.31524 +** mode (e.g. these APIs are available in the Windows CE SDK; however, they
 1.31525 +** are not present in the header file)?
 1.31526 +*/
 1.31527 +#if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
 1.31528 +/*
 1.31529 +** Two of the file mapping APIs are different under WinRT.  Figure out which
 1.31530 +** set we need.
 1.31531 +*/
 1.31532 +#if SQLITE_OS_WINRT
 1.31533 +WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
 1.31534 +        LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
 1.31535 +
 1.31536 +WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
 1.31537 +#else
 1.31538 +#if defined(SQLITE_WIN32_HAS_ANSI)
 1.31539 +WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
 1.31540 +        DWORD, DWORD, DWORD, LPCSTR);
 1.31541 +#endif /* defined(SQLITE_WIN32_HAS_ANSI) */
 1.31542 +
 1.31543 +#if defined(SQLITE_WIN32_HAS_WIDE)
 1.31544 +WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
 1.31545 +        DWORD, DWORD, DWORD, LPCWSTR);
 1.31546 +#endif /* defined(SQLITE_WIN32_HAS_WIDE) */
 1.31547 +
 1.31548 +WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
 1.31549 +#endif /* SQLITE_OS_WINRT */
 1.31550 +
 1.31551 +/*
 1.31552 +** This file mapping API is common to both Win32 and WinRT.
 1.31553 +*/
 1.31554 +WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
 1.31555 +#endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
 1.31556 +
 1.31557 +/*
 1.31558 +** Some Microsoft compilers lack this definition.
 1.31559 +*/
 1.31560 +#ifndef INVALID_FILE_ATTRIBUTES
 1.31561 +# define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
 1.31562 +#endif
 1.31563 +
 1.31564 +#ifndef FILE_FLAG_MASK
 1.31565 +# define FILE_FLAG_MASK          (0xFF3C0000)
 1.31566 +#endif
 1.31567 +
 1.31568 +#ifndef FILE_ATTRIBUTE_MASK
 1.31569 +# define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
 1.31570 +#endif
 1.31571 +
 1.31572 +#ifndef SQLITE_OMIT_WAL
 1.31573 +/* Forward references to structures used for WAL */
 1.31574 +typedef struct winShm winShm;           /* A connection to shared-memory */
 1.31575 +typedef struct winShmNode winShmNode;   /* A region of shared-memory */
 1.31576 +#endif
 1.31577 +
 1.31578 +/*
 1.31579 +** WinCE lacks native support for file locking so we have to fake it
 1.31580 +** with some code of our own.
 1.31581 +*/
 1.31582 +#if SQLITE_OS_WINCE
 1.31583 +typedef struct winceLock {
 1.31584 +  int nReaders;       /* Number of reader locks obtained */
 1.31585 +  BOOL bPending;      /* Indicates a pending lock has been obtained */
 1.31586 +  BOOL bReserved;     /* Indicates a reserved lock has been obtained */
 1.31587 +  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
 1.31588 +} winceLock;
 1.31589 +#endif
 1.31590 +
 1.31591 +/*
 1.31592 +** The winFile structure is a subclass of sqlite3_file* specific to the win32
 1.31593 +** portability layer.
 1.31594 +*/
 1.31595 +typedef struct winFile winFile;
 1.31596 +struct winFile {
 1.31597 +  const sqlite3_io_methods *pMethod; /*** Must be first ***/
 1.31598 +  sqlite3_vfs *pVfs;      /* The VFS used to open this file */
 1.31599 +  HANDLE h;               /* Handle for accessing the file */
 1.31600 +  u8 locktype;            /* Type of lock currently held on this file */
 1.31601 +  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
 1.31602 +  u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
 1.31603 +  DWORD lastErrno;        /* The Windows errno from the last I/O error */
 1.31604 +#ifndef SQLITE_OMIT_WAL
 1.31605 +  winShm *pShm;           /* Instance of shared memory on this file */
 1.31606 +#endif
 1.31607 +  const char *zPath;      /* Full pathname of this file */
 1.31608 +  int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
 1.31609 +#if SQLITE_OS_WINCE
 1.31610 +  LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
 1.31611 +  HANDLE hMutex;          /* Mutex used to control access to shared lock */  
 1.31612 +  HANDLE hShared;         /* Shared memory segment used for locking */
 1.31613 +  winceLock local;        /* Locks obtained by this instance of winFile */
 1.31614 +  winceLock *shared;      /* Global shared lock memory for the file  */
 1.31615 +#endif
 1.31616 +#if SQLITE_MAX_MMAP_SIZE>0
 1.31617 +  int nFetchOut;                /* Number of outstanding xFetch references */
 1.31618 +  HANDLE hMap;                  /* Handle for accessing memory mapping */
 1.31619 +  void *pMapRegion;             /* Area memory mapped */
 1.31620 +  sqlite3_int64 mmapSize;       /* Usable size of mapped region */
 1.31621 +  sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
 1.31622 +  sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
 1.31623 +#endif
 1.31624 +};
 1.31625 +
 1.31626 +/*
 1.31627 +** Allowed values for winFile.ctrlFlags
 1.31628 +*/
 1.31629 +#define WINFILE_RDONLY          0x02   /* Connection is read only */
 1.31630 +#define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
 1.31631 +#define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
 1.31632 +
 1.31633 +/*
 1.31634 + * The size of the buffer used by sqlite3_win32_write_debug().
 1.31635 + */
 1.31636 +#ifndef SQLITE_WIN32_DBG_BUF_SIZE
 1.31637 +#  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
 1.31638 +#endif
 1.31639 +
 1.31640 +/*
 1.31641 + * The value used with sqlite3_win32_set_directory() to specify that
 1.31642 + * the data directory should be changed.
 1.31643 + */
 1.31644 +#ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
 1.31645 +#  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
 1.31646 +#endif
 1.31647 +
 1.31648 +/*
 1.31649 + * The value used with sqlite3_win32_set_directory() to specify that
 1.31650 + * the temporary directory should be changed.
 1.31651 + */
 1.31652 +#ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
 1.31653 +#  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
 1.31654 +#endif
 1.31655 +
 1.31656 +/*
 1.31657 + * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
 1.31658 + * various Win32 API heap functions instead of our own.
 1.31659 + */
 1.31660 +#ifdef SQLITE_WIN32_MALLOC
 1.31661 +
 1.31662 +/*
 1.31663 + * If this is non-zero, an isolated heap will be created by the native Win32
 1.31664 + * allocator subsystem; otherwise, the default process heap will be used.  This
 1.31665 + * setting has no effect when compiling for WinRT.  By default, this is enabled
 1.31666 + * and an isolated heap will be created to store all allocated data.
 1.31667 + *
 1.31668 + ******************************************************************************
 1.31669 + * WARNING: It is important to note that when this setting is non-zero and the
 1.31670 + *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
 1.31671 + *          function), all data that was allocated using the isolated heap will
 1.31672 + *          be freed immediately and any attempt to access any of that freed
 1.31673 + *          data will almost certainly result in an immediate access violation.
 1.31674 + ******************************************************************************
 1.31675 + */
 1.31676 +#ifndef SQLITE_WIN32_HEAP_CREATE
 1.31677 +#  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
 1.31678 +#endif
 1.31679 +
 1.31680 +/*
 1.31681 + * The initial size of the Win32-specific heap.  This value may be zero.
 1.31682 + */
 1.31683 +#ifndef SQLITE_WIN32_HEAP_INIT_SIZE
 1.31684 +#  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
 1.31685 +                                       (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
 1.31686 +#endif
 1.31687 +
 1.31688 +/*
 1.31689 + * The maximum size of the Win32-specific heap.  This value may be zero.
 1.31690 + */
 1.31691 +#ifndef SQLITE_WIN32_HEAP_MAX_SIZE
 1.31692 +#  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
 1.31693 +#endif
 1.31694 +
 1.31695 +/*
 1.31696 + * The extra flags to use in calls to the Win32 heap APIs.  This value may be
 1.31697 + * zero for the default behavior.
 1.31698 + */
 1.31699 +#ifndef SQLITE_WIN32_HEAP_FLAGS
 1.31700 +#  define SQLITE_WIN32_HEAP_FLAGS     (0)
 1.31701 +#endif
 1.31702 +
 1.31703 +
 1.31704 +/*
 1.31705 +** The winMemData structure stores information required by the Win32-specific
 1.31706 +** sqlite3_mem_methods implementation.
 1.31707 +*/
 1.31708 +typedef struct winMemData winMemData;
 1.31709 +struct winMemData {
 1.31710 +#ifndef NDEBUG
 1.31711 +  u32 magic1;   /* Magic number to detect structure corruption. */
 1.31712 +#endif
 1.31713 +  HANDLE hHeap; /* The handle to our heap. */
 1.31714 +  BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
 1.31715 +#ifndef NDEBUG
 1.31716 +  u32 magic2;   /* Magic number to detect structure corruption. */
 1.31717 +#endif
 1.31718 +};
 1.31719 +
 1.31720 +#ifndef NDEBUG
 1.31721 +#define WINMEM_MAGIC1     0x42b2830b
 1.31722 +#define WINMEM_MAGIC2     0xbd4d7cf4
 1.31723 +#endif
 1.31724 +
 1.31725 +static struct winMemData win_mem_data = {
 1.31726 +#ifndef NDEBUG
 1.31727 +  WINMEM_MAGIC1,
 1.31728 +#endif
 1.31729 +  NULL, FALSE
 1.31730 +#ifndef NDEBUG
 1.31731 +  ,WINMEM_MAGIC2
 1.31732 +#endif
 1.31733 +};
 1.31734 +
 1.31735 +#ifndef NDEBUG
 1.31736 +#define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
 1.31737 +#define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
 1.31738 +#define winMemAssertMagic()  winMemAssertMagic1(); winMemAssertMagic2();
 1.31739 +#else
 1.31740 +#define winMemAssertMagic()
 1.31741 +#endif
 1.31742 +
 1.31743 +#define winMemGetDataPtr()  &win_mem_data
 1.31744 +#define winMemGetHeap()     win_mem_data.hHeap
 1.31745 +#define winMemGetOwned()    win_mem_data.bOwned
 1.31746 +
 1.31747 +static void *winMemMalloc(int nBytes);
 1.31748 +static void winMemFree(void *pPrior);
 1.31749 +static void *winMemRealloc(void *pPrior, int nBytes);
 1.31750 +static int winMemSize(void *p);
 1.31751 +static int winMemRoundup(int n);
 1.31752 +static int winMemInit(void *pAppData);
 1.31753 +static void winMemShutdown(void *pAppData);
 1.31754 +
 1.31755 +SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
 1.31756 +#endif /* SQLITE_WIN32_MALLOC */
 1.31757 +
 1.31758 +/*
 1.31759 +** The following variable is (normally) set once and never changes
 1.31760 +** thereafter.  It records whether the operating system is Win9x
 1.31761 +** or WinNT.
 1.31762 +**
 1.31763 +** 0:   Operating system unknown.
 1.31764 +** 1:   Operating system is Win9x.
 1.31765 +** 2:   Operating system is WinNT.
 1.31766 +**
 1.31767 +** In order to facilitate testing on a WinNT system, the test fixture
 1.31768 +** can manually set this value to 1 to emulate Win98 behavior.
 1.31769 +*/
 1.31770 +#ifdef SQLITE_TEST
 1.31771 +SQLITE_API int sqlite3_os_type = 0;
 1.31772 +#elif !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
 1.31773 +      defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_HAS_WIDE)
 1.31774 +static int sqlite3_os_type = 0;
 1.31775 +#endif
 1.31776 +
 1.31777 +#ifndef SYSCALL
 1.31778 +#  define SYSCALL sqlite3_syscall_ptr
 1.31779 +#endif
 1.31780 +
 1.31781 +/*
 1.31782 +** This function is not available on Windows CE or WinRT.
 1.31783 + */
 1.31784 +
 1.31785 +#if SQLITE_OS_WINCE || SQLITE_OS_WINRT
 1.31786 +#  define osAreFileApisANSI()       1
 1.31787 +#endif
 1.31788 +
 1.31789 +/*
 1.31790 +** Many system calls are accessed through pointer-to-functions so that
 1.31791 +** they may be overridden at runtime to facilitate fault injection during
 1.31792 +** testing and sandboxing.  The following array holds the names and pointers
 1.31793 +** to all overrideable system calls.
 1.31794 +*/
 1.31795 +static struct win_syscall {
 1.31796 +  const char *zName;            /* Name of the system call */
 1.31797 +  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
 1.31798 +  sqlite3_syscall_ptr pDefault; /* Default value */
 1.31799 +} aSyscall[] = {
 1.31800 +#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
 1.31801 +  { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
 1.31802 +#else
 1.31803 +  { "AreFileApisANSI",         (SYSCALL)0,                       0 },
 1.31804 +#endif
 1.31805 +
 1.31806 +#ifndef osAreFileApisANSI
 1.31807 +#define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
 1.31808 +#endif
 1.31809 +
 1.31810 +#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
 1.31811 +  { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
 1.31812 +#else
 1.31813 +  { "CharLowerW",              (SYSCALL)0,                       0 },
 1.31814 +#endif
 1.31815 +
 1.31816 +#define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
 1.31817 +
 1.31818 +#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
 1.31819 +  { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
 1.31820 +#else
 1.31821 +  { "CharUpperW",              (SYSCALL)0,                       0 },
 1.31822 +#endif
 1.31823 +
 1.31824 +#define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
 1.31825 +
 1.31826 +  { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
 1.31827 +
 1.31828 +#define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
 1.31829 +
 1.31830 +#if defined(SQLITE_WIN32_HAS_ANSI)
 1.31831 +  { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
 1.31832 +#else
 1.31833 +  { "CreateFileA",             (SYSCALL)0,                       0 },
 1.31834 +#endif
 1.31835 +
 1.31836 +#define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
 1.31837 +        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
 1.31838 +
 1.31839 +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
 1.31840 +  { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
 1.31841 +#else
 1.31842 +  { "CreateFileW",             (SYSCALL)0,                       0 },
 1.31843 +#endif
 1.31844 +
 1.31845 +#define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
 1.31846 +        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
 1.31847 +
 1.31848 +#if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
 1.31849 +        !defined(SQLITE_OMIT_WAL))
 1.31850 +  { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
 1.31851 +#else
 1.31852 +  { "CreateFileMappingA",      (SYSCALL)0,                       0 },
 1.31853 +#endif
 1.31854 +
 1.31855 +#define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
 1.31856 +        DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
 1.31857 +
 1.31858 +#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
 1.31859 +        !defined(SQLITE_OMIT_WAL))
 1.31860 +  { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
 1.31861 +#else
 1.31862 +  { "CreateFileMappingW",      (SYSCALL)0,                       0 },
 1.31863 +#endif
 1.31864 +
 1.31865 +#define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
 1.31866 +        DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
 1.31867 +
 1.31868 +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
 1.31869 +  { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
 1.31870 +#else
 1.31871 +  { "CreateMutexW",            (SYSCALL)0,                       0 },
 1.31872 +#endif
 1.31873 +
 1.31874 +#define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
 1.31875 +        LPCWSTR))aSyscall[8].pCurrent)
 1.31876 +
 1.31877 +#if defined(SQLITE_WIN32_HAS_ANSI)
 1.31878 +  { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
 1.31879 +#else
 1.31880 +  { "DeleteFileA",             (SYSCALL)0,                       0 },
 1.31881 +#endif
 1.31882 +
 1.31883 +#define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
 1.31884 +
 1.31885 +#if defined(SQLITE_WIN32_HAS_WIDE)
 1.31886 +  { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
 1.31887 +#else
 1.31888 +  { "DeleteFileW",             (SYSCALL)0,                       0 },
 1.31889 +#endif
 1.31890 +
 1.31891 +#define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
 1.31892 +
 1.31893 +#if SQLITE_OS_WINCE
 1.31894 +  { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
 1.31895 +#else
 1.31896 +  { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
 1.31897 +#endif
 1.31898 +
 1.31899 +#define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
 1.31900 +        LPFILETIME))aSyscall[11].pCurrent)
 1.31901 +
 1.31902 +#if SQLITE_OS_WINCE
 1.31903 +  { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
 1.31904 +#else
 1.31905 +  { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
 1.31906 +#endif
 1.31907 +
 1.31908 +#define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
 1.31909 +        LPSYSTEMTIME))aSyscall[12].pCurrent)
 1.31910 +
 1.31911 +  { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
 1.31912 +
 1.31913 +#define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
 1.31914 +
 1.31915 +#if defined(SQLITE_WIN32_HAS_ANSI)
 1.31916 +  { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
 1.31917 +#else
 1.31918 +  { "FormatMessageA",          (SYSCALL)0,                       0 },
 1.31919 +#endif
 1.31920 +
 1.31921 +#define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
 1.31922 +        DWORD,va_list*))aSyscall[14].pCurrent)
 1.31923 +
 1.31924 +#if defined(SQLITE_WIN32_HAS_WIDE)
 1.31925 +  { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
 1.31926 +#else
 1.31927 +  { "FormatMessageW",          (SYSCALL)0,                       0 },
 1.31928 +#endif
 1.31929 +
 1.31930 +#define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
 1.31931 +        DWORD,va_list*))aSyscall[15].pCurrent)
 1.31932 +
 1.31933 +#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
 1.31934 +  { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
 1.31935 +#else
 1.31936 +  { "FreeLibrary",             (SYSCALL)0,                       0 },
 1.31937 +#endif
 1.31938 +
 1.31939 +#define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
 1.31940 +
 1.31941 +  { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
 1.31942 +
 1.31943 +#define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
 1.31944 +
 1.31945 +#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
 1.31946 +  { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
 1.31947 +#else
 1.31948 +  { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
 1.31949 +#endif
 1.31950 +
 1.31951 +#define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
 1.31952 +        LPDWORD))aSyscall[18].pCurrent)
 1.31953 +
 1.31954 +#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
 1.31955 +  { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
 1.31956 +#else
 1.31957 +  { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
 1.31958 +#endif
 1.31959 +
 1.31960 +#define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
 1.31961 +        LPDWORD))aSyscall[19].pCurrent)
 1.31962 +
 1.31963 +#if defined(SQLITE_WIN32_HAS_ANSI)
 1.31964 +  { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
 1.31965 +#else
 1.31966 +  { "GetFileAttributesA",      (SYSCALL)0,                       0 },
 1.31967 +#endif
 1.31968 +
 1.31969 +#define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
 1.31970 +
 1.31971 +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
 1.31972 +  { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
 1.31973 +#else
 1.31974 +  { "GetFileAttributesW",      (SYSCALL)0,                       0 },
 1.31975 +#endif
 1.31976 +
 1.31977 +#define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
 1.31978 +
 1.31979 +#if defined(SQLITE_WIN32_HAS_WIDE)
 1.31980 +  { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
 1.31981 +#else
 1.31982 +  { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
 1.31983 +#endif
 1.31984 +
 1.31985 +#define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
 1.31986 +        LPVOID))aSyscall[22].pCurrent)
 1.31987 +
 1.31988 +#if !SQLITE_OS_WINRT
 1.31989 +  { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
 1.31990 +#else
 1.31991 +  { "GetFileSize",             (SYSCALL)0,                       0 },
 1.31992 +#endif
 1.31993 +
 1.31994 +#define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
 1.31995 +
 1.31996 +#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
 1.31997 +  { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
 1.31998 +#else
 1.31999 +  { "GetFullPathNameA",        (SYSCALL)0,                       0 },
 1.32000 +#endif
 1.32001 +
 1.32002 +#define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
 1.32003 +        LPSTR*))aSyscall[24].pCurrent)
 1.32004 +
 1.32005 +#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
 1.32006 +  { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
 1.32007 +#else
 1.32008 +  { "GetFullPathNameW",        (SYSCALL)0,                       0 },
 1.32009 +#endif
 1.32010 +
 1.32011 +#define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
 1.32012 +        LPWSTR*))aSyscall[25].pCurrent)
 1.32013 +
 1.32014 +  { "GetLastError",            (SYSCALL)GetLastError,            0 },
 1.32015 +
 1.32016 +#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
 1.32017 +
 1.32018 +#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
 1.32019 +#if SQLITE_OS_WINCE
 1.32020 +  /* The GetProcAddressA() routine is only available on Windows CE. */
 1.32021 +  { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
 1.32022 +#else
 1.32023 +  /* All other Windows platforms expect GetProcAddress() to take
 1.32024 +  ** an ANSI string regardless of the _UNICODE setting */
 1.32025 +  { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
 1.32026 +#endif
 1.32027 +#else
 1.32028 +  { "GetProcAddressA",         (SYSCALL)0,                       0 },
 1.32029 +#endif
 1.32030 +
 1.32031 +#define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
 1.32032 +        LPCSTR))aSyscall[27].pCurrent)
 1.32033 +
 1.32034 +#if !SQLITE_OS_WINRT
 1.32035 +  { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
 1.32036 +#else
 1.32037 +  { "GetSystemInfo",           (SYSCALL)0,                       0 },
 1.32038 +#endif
 1.32039 +
 1.32040 +#define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
 1.32041 +
 1.32042 +  { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
 1.32043 +
 1.32044 +#define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
 1.32045 +
 1.32046 +#if !SQLITE_OS_WINCE
 1.32047 +  { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
 1.32048 +#else
 1.32049 +  { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
 1.32050 +#endif
 1.32051 +
 1.32052 +#define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
 1.32053 +        LPFILETIME))aSyscall[30].pCurrent)
 1.32054 +
 1.32055 +#if defined(SQLITE_WIN32_HAS_ANSI)
 1.32056 +  { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
 1.32057 +#else
 1.32058 +  { "GetTempPathA",            (SYSCALL)0,                       0 },
 1.32059 +#endif
 1.32060 +
 1.32061 +#define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
 1.32062 +
 1.32063 +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
 1.32064 +  { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
 1.32065 +#else
 1.32066 +  { "GetTempPathW",            (SYSCALL)0,                       0 },
 1.32067 +#endif
 1.32068 +
 1.32069 +#define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
 1.32070 +
 1.32071 +#if !SQLITE_OS_WINRT
 1.32072 +  { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
 1.32073 +#else
 1.32074 +  { "GetTickCount",            (SYSCALL)0,                       0 },
 1.32075 +#endif
 1.32076 +
 1.32077 +#define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
 1.32078 +
 1.32079 +#if defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_GETVERSIONEX) && \
 1.32080 +        SQLITE_WIN32_GETVERSIONEX
 1.32081 +  { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
 1.32082 +#else
 1.32083 +  { "GetVersionExA",           (SYSCALL)0,                       0 },
 1.32084 +#endif
 1.32085 +
 1.32086 +#define osGetVersionExA ((BOOL(WINAPI*)( \
 1.32087 +        LPOSVERSIONINFOA))aSyscall[34].pCurrent)
 1.32088 +
 1.32089 +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
 1.32090 +        defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
 1.32091 +  { "GetVersionExW",           (SYSCALL)GetVersionExW,           0 },
 1.32092 +#else
 1.32093 +  { "GetVersionExW",           (SYSCALL)0,                       0 },
 1.32094 +#endif
 1.32095 +
 1.32096 +#define osGetVersionExW ((BOOL(WINAPI*)( \
 1.32097 +        LPOSVERSIONINFOW))aSyscall[35].pCurrent)
 1.32098 +
 1.32099 +  { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
 1.32100 +
 1.32101 +#define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
 1.32102 +        SIZE_T))aSyscall[36].pCurrent)
 1.32103 +
 1.32104 +#if !SQLITE_OS_WINRT
 1.32105 +  { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
 1.32106 +#else
 1.32107 +  { "HeapCreate",              (SYSCALL)0,                       0 },
 1.32108 +#endif
 1.32109 +
 1.32110 +#define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
 1.32111 +        SIZE_T))aSyscall[37].pCurrent)
 1.32112 +
 1.32113 +#if !SQLITE_OS_WINRT
 1.32114 +  { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
 1.32115 +#else
 1.32116 +  { "HeapDestroy",             (SYSCALL)0,                       0 },
 1.32117 +#endif
 1.32118 +
 1.32119 +#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
 1.32120 +
 1.32121 +  { "HeapFree",                (SYSCALL)HeapFree,                0 },
 1.32122 +
 1.32123 +#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
 1.32124 +
 1.32125 +  { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
 1.32126 +
 1.32127 +#define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
 1.32128 +        SIZE_T))aSyscall[40].pCurrent)
 1.32129 +
 1.32130 +  { "HeapSize",                (SYSCALL)HeapSize,                0 },
 1.32131 +
 1.32132 +#define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
 1.32133 +        LPCVOID))aSyscall[41].pCurrent)
 1.32134 +
 1.32135 +#if !SQLITE_OS_WINRT
 1.32136 +  { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
 1.32137 +#else
 1.32138 +  { "HeapValidate",            (SYSCALL)0,                       0 },
 1.32139 +#endif
 1.32140 +
 1.32141 +#define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
 1.32142 +        LPCVOID))aSyscall[42].pCurrent)
 1.32143 +
 1.32144 +#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
 1.32145 +  { "HeapCompact",             (SYSCALL)HeapCompact,             0 },
 1.32146 +#else
 1.32147 +  { "HeapCompact",             (SYSCALL)0,                       0 },
 1.32148 +#endif
 1.32149 +
 1.32150 +#define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
 1.32151 +
 1.32152 +#if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
 1.32153 +  { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
 1.32154 +#else
 1.32155 +  { "LoadLibraryA",            (SYSCALL)0,                       0 },
 1.32156 +#endif
 1.32157 +
 1.32158 +#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
 1.32159 +
 1.32160 +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
 1.32161 +        !defined(SQLITE_OMIT_LOAD_EXTENSION)
 1.32162 +  { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
 1.32163 +#else
 1.32164 +  { "LoadLibraryW",            (SYSCALL)0,                       0 },
 1.32165 +#endif
 1.32166 +
 1.32167 +#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
 1.32168 +
 1.32169 +#if !SQLITE_OS_WINRT
 1.32170 +  { "LocalFree",               (SYSCALL)LocalFree,               0 },
 1.32171 +#else
 1.32172 +  { "LocalFree",               (SYSCALL)0,                       0 },
 1.32173 +#endif
 1.32174 +
 1.32175 +#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
 1.32176 +
 1.32177 +#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
 1.32178 +  { "LockFile",                (SYSCALL)LockFile,                0 },
 1.32179 +#else
 1.32180 +  { "LockFile",                (SYSCALL)0,                       0 },
 1.32181 +#endif
 1.32182 +
 1.32183 +#ifndef osLockFile
 1.32184 +#define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
 1.32185 +        DWORD))aSyscall[47].pCurrent)
 1.32186 +#endif
 1.32187 +
 1.32188 +#if !SQLITE_OS_WINCE
 1.32189 +  { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
 1.32190 +#else
 1.32191 +  { "LockFileEx",              (SYSCALL)0,                       0 },
 1.32192 +#endif
 1.32193 +
 1.32194 +#ifndef osLockFileEx
 1.32195 +#define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
 1.32196 +        LPOVERLAPPED))aSyscall[48].pCurrent)
 1.32197 +#endif
 1.32198 +
 1.32199 +#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
 1.32200 +  { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
 1.32201 +#else
 1.32202 +  { "MapViewOfFile",           (SYSCALL)0,                       0 },
 1.32203 +#endif
 1.32204 +
 1.32205 +#define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
 1.32206 +        SIZE_T))aSyscall[49].pCurrent)
 1.32207 +
 1.32208 +  { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
 1.32209 +
 1.32210 +#define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
 1.32211 +        int))aSyscall[50].pCurrent)
 1.32212 +
 1.32213 +  { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
 1.32214 +
 1.32215 +#define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
 1.32216 +        LARGE_INTEGER*))aSyscall[51].pCurrent)
 1.32217 +
 1.32218 +  { "ReadFile",                (SYSCALL)ReadFile,                0 },
 1.32219 +
 1.32220 +#define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
 1.32221 +        LPOVERLAPPED))aSyscall[52].pCurrent)
 1.32222 +
 1.32223 +  { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
 1.32224 +
 1.32225 +#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
 1.32226 +
 1.32227 +#if !SQLITE_OS_WINRT
 1.32228 +  { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
 1.32229 +#else
 1.32230 +  { "SetFilePointer",          (SYSCALL)0,                       0 },
 1.32231 +#endif
 1.32232 +
 1.32233 +#define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
 1.32234 +        DWORD))aSyscall[54].pCurrent)
 1.32235 +
 1.32236 +#if !SQLITE_OS_WINRT
 1.32237 +  { "Sleep",                   (SYSCALL)Sleep,                   0 },
 1.32238 +#else
 1.32239 +  { "Sleep",                   (SYSCALL)0,                       0 },
 1.32240 +#endif
 1.32241 +
 1.32242 +#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
 1.32243 +
 1.32244 +  { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
 1.32245 +
 1.32246 +#define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
 1.32247 +        LPFILETIME))aSyscall[56].pCurrent)
 1.32248 +
 1.32249 +#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
 1.32250 +  { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
 1.32251 +#else
 1.32252 +  { "UnlockFile",              (SYSCALL)0,                       0 },
 1.32253 +#endif
 1.32254 +
 1.32255 +#ifndef osUnlockFile
 1.32256 +#define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
 1.32257 +        DWORD))aSyscall[57].pCurrent)
 1.32258 +#endif
 1.32259 +
 1.32260 +#if !SQLITE_OS_WINCE
 1.32261 +  { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
 1.32262 +#else
 1.32263 +  { "UnlockFileEx",            (SYSCALL)0,                       0 },
 1.32264 +#endif
 1.32265 +
 1.32266 +#define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
 1.32267 +        LPOVERLAPPED))aSyscall[58].pCurrent)
 1.32268 +
 1.32269 +#if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
 1.32270 +  { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
 1.32271 +#else
 1.32272 +  { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
 1.32273 +#endif
 1.32274 +
 1.32275 +#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
 1.32276 +
 1.32277 +  { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
 1.32278 +
 1.32279 +#define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
 1.32280 +        LPCSTR,LPBOOL))aSyscall[60].pCurrent)
 1.32281 +
 1.32282 +  { "WriteFile",               (SYSCALL)WriteFile,               0 },
 1.32283 +
 1.32284 +#define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
 1.32285 +        LPOVERLAPPED))aSyscall[61].pCurrent)
 1.32286 +
 1.32287 +#if SQLITE_OS_WINRT
 1.32288 +  { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
 1.32289 +#else
 1.32290 +  { "CreateEventExW",          (SYSCALL)0,                       0 },
 1.32291 +#endif
 1.32292 +
 1.32293 +#define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
 1.32294 +        DWORD,DWORD))aSyscall[62].pCurrent)
 1.32295 +
 1.32296 +#if !SQLITE_OS_WINRT
 1.32297 +  { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
 1.32298 +#else
 1.32299 +  { "WaitForSingleObject",     (SYSCALL)0,                       0 },
 1.32300 +#endif
 1.32301 +
 1.32302 +#define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
 1.32303 +        DWORD))aSyscall[63].pCurrent)
 1.32304 +
 1.32305 +#if SQLITE_OS_WINRT
 1.32306 +  { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
 1.32307 +#else
 1.32308 +  { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
 1.32309 +#endif
 1.32310 +
 1.32311 +#define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
 1.32312 +        BOOL))aSyscall[64].pCurrent)
 1.32313 +
 1.32314 +#if SQLITE_OS_WINRT
 1.32315 +  { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
 1.32316 +#else
 1.32317 +  { "SetFilePointerEx",        (SYSCALL)0,                       0 },
 1.32318 +#endif
 1.32319 +
 1.32320 +#define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
 1.32321 +        PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
 1.32322 +
 1.32323 +#if SQLITE_OS_WINRT
 1.32324 +  { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
 1.32325 +#else
 1.32326 +  { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
 1.32327 +#endif
 1.32328 +
 1.32329 +#define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
 1.32330 +        FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
 1.32331 +
 1.32332 +#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
 1.32333 +  { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
 1.32334 +#else
 1.32335 +  { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
 1.32336 +#endif
 1.32337 +
 1.32338 +#define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
 1.32339 +        SIZE_T))aSyscall[67].pCurrent)
 1.32340 +
 1.32341 +#if SQLITE_OS_WINRT
 1.32342 +  { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
 1.32343 +#else
 1.32344 +  { "CreateFile2",             (SYSCALL)0,                       0 },
 1.32345 +#endif
 1.32346 +
 1.32347 +#define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
 1.32348 +        LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
 1.32349 +
 1.32350 +#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
 1.32351 +  { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
 1.32352 +#else
 1.32353 +  { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
 1.32354 +#endif
 1.32355 +
 1.32356 +#define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
 1.32357 +        DWORD))aSyscall[69].pCurrent)
 1.32358 +
 1.32359 +#if SQLITE_OS_WINRT
 1.32360 +  { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
 1.32361 +#else
 1.32362 +  { "GetTickCount64",          (SYSCALL)0,                       0 },
 1.32363 +#endif
 1.32364 +
 1.32365 +#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
 1.32366 +
 1.32367 +#if SQLITE_OS_WINRT
 1.32368 +  { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
 1.32369 +#else
 1.32370 +  { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
 1.32371 +#endif
 1.32372 +
 1.32373 +#define osGetNativeSystemInfo ((VOID(WINAPI*)( \
 1.32374 +        LPSYSTEM_INFO))aSyscall[71].pCurrent)
 1.32375 +
 1.32376 +#if defined(SQLITE_WIN32_HAS_ANSI)
 1.32377 +  { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
 1.32378 +#else
 1.32379 +  { "OutputDebugStringA",      (SYSCALL)0,                       0 },
 1.32380 +#endif
 1.32381 +
 1.32382 +#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
 1.32383 +
 1.32384 +#if defined(SQLITE_WIN32_HAS_WIDE)
 1.32385 +  { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
 1.32386 +#else
 1.32387 +  { "OutputDebugStringW",      (SYSCALL)0,                       0 },
 1.32388 +#endif
 1.32389 +
 1.32390 +#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
 1.32391 +
 1.32392 +  { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
 1.32393 +
 1.32394 +#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
 1.32395 +
 1.32396 +#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
 1.32397 +  { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
 1.32398 +#else
 1.32399 +  { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
 1.32400 +#endif
 1.32401 +
 1.32402 +#define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
 1.32403 +        LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
 1.32404 +
 1.32405 +}; /* End of the overrideable system calls */
 1.32406 +
 1.32407 +/*
 1.32408 +** This is the xSetSystemCall() method of sqlite3_vfs for all of the
 1.32409 +** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
 1.32410 +** system call pointer, or SQLITE_NOTFOUND if there is no configurable
 1.32411 +** system call named zName.
 1.32412 +*/
 1.32413 +static int winSetSystemCall(
 1.32414 +  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
 1.32415 +  const char *zName,            /* Name of system call to override */
 1.32416 +  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
 1.32417 +){
 1.32418 +  unsigned int i;
 1.32419 +  int rc = SQLITE_NOTFOUND;
 1.32420 +
 1.32421 +  UNUSED_PARAMETER(pNotUsed);
 1.32422 +  if( zName==0 ){
 1.32423 +    /* If no zName is given, restore all system calls to their default
 1.32424 +    ** settings and return NULL
 1.32425 +    */
 1.32426 +    rc = SQLITE_OK;
 1.32427 +    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
 1.32428 +      if( aSyscall[i].pDefault ){
 1.32429 +        aSyscall[i].pCurrent = aSyscall[i].pDefault;
 1.32430 +      }
 1.32431 +    }
 1.32432 +  }else{
 1.32433 +    /* If zName is specified, operate on only the one system call
 1.32434 +    ** specified.
 1.32435 +    */
 1.32436 +    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
 1.32437 +      if( strcmp(zName, aSyscall[i].zName)==0 ){
 1.32438 +        if( aSyscall[i].pDefault==0 ){
 1.32439 +          aSyscall[i].pDefault = aSyscall[i].pCurrent;
 1.32440 +        }
 1.32441 +        rc = SQLITE_OK;
 1.32442 +        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
 1.32443 +        aSyscall[i].pCurrent = pNewFunc;
 1.32444 +        break;
 1.32445 +      }
 1.32446 +    }
 1.32447 +  }
 1.32448 +  return rc;
 1.32449 +}
 1.32450 +
 1.32451 +/*
 1.32452 +** Return the value of a system call.  Return NULL if zName is not a
 1.32453 +** recognized system call name.  NULL is also returned if the system call
 1.32454 +** is currently undefined.
 1.32455 +*/
 1.32456 +static sqlite3_syscall_ptr winGetSystemCall(
 1.32457 +  sqlite3_vfs *pNotUsed,
 1.32458 +  const char *zName
 1.32459 +){
 1.32460 +  unsigned int i;
 1.32461 +
 1.32462 +  UNUSED_PARAMETER(pNotUsed);
 1.32463 +  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
 1.32464 +    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
 1.32465 +  }
 1.32466 +  return 0;
 1.32467 +}
 1.32468 +
 1.32469 +/*
 1.32470 +** Return the name of the first system call after zName.  If zName==NULL
 1.32471 +** then return the name of the first system call.  Return NULL if zName
 1.32472 +** is the last system call or if zName is not the name of a valid
 1.32473 +** system call.
 1.32474 +*/
 1.32475 +static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
 1.32476 +  int i = -1;
 1.32477 +
 1.32478 +  UNUSED_PARAMETER(p);
 1.32479 +  if( zName ){
 1.32480 +    for(i=0; i<ArraySize(aSyscall)-1; i++){
 1.32481 +      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
 1.32482 +    }
 1.32483 +  }
 1.32484 +  for(i++; i<ArraySize(aSyscall); i++){
 1.32485 +    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
 1.32486 +  }
 1.32487 +  return 0;
 1.32488 +}
 1.32489 +
 1.32490 +#ifdef SQLITE_WIN32_MALLOC
 1.32491 +/*
 1.32492 +** If a Win32 native heap has been configured, this function will attempt to
 1.32493 +** compact it.  Upon success, SQLITE_OK will be returned.  Upon failure, one
 1.32494 +** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned.  The
 1.32495 +** "pnLargest" argument, if non-zero, will be used to return the size of the
 1.32496 +** largest committed free block in the heap, in bytes.
 1.32497 +*/
 1.32498 +SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
 1.32499 +  int rc = SQLITE_OK;
 1.32500 +  UINT nLargest = 0;
 1.32501 +  HANDLE hHeap;
 1.32502 +
 1.32503 +  winMemAssertMagic();
 1.32504 +  hHeap = winMemGetHeap();
 1.32505 +  assert( hHeap!=0 );
 1.32506 +  assert( hHeap!=INVALID_HANDLE_VALUE );
 1.32507 +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 1.32508 +  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
 1.32509 +#endif
 1.32510 +#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
 1.32511 +  if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
 1.32512 +    DWORD lastErrno = osGetLastError();
 1.32513 +    if( lastErrno==NO_ERROR ){
 1.32514 +      sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
 1.32515 +                  (void*)hHeap);
 1.32516 +      rc = SQLITE_NOMEM;
 1.32517 +    }else{
 1.32518 +      sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
 1.32519 +                  osGetLastError(), (void*)hHeap);
 1.32520 +      rc = SQLITE_ERROR;
 1.32521 +    }
 1.32522 +  }
 1.32523 +#else
 1.32524 +  sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
 1.32525 +              (void*)hHeap);
 1.32526 +  rc = SQLITE_NOTFOUND;
 1.32527 +#endif
 1.32528 +  if( pnLargest ) *pnLargest = nLargest;
 1.32529 +  return rc;
 1.32530 +}
 1.32531 +
 1.32532 +/*
 1.32533 +** If a Win32 native heap has been configured, this function will attempt to
 1.32534 +** destroy and recreate it.  If the Win32 native heap is not isolated and/or
 1.32535 +** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
 1.32536 +** be returned and no changes will be made to the Win32 native heap.
 1.32537 +*/
 1.32538 +SQLITE_API int sqlite3_win32_reset_heap(){
 1.32539 +  int rc;
 1.32540 +  MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
 1.32541 +  MUTEX_LOGIC( sqlite3_mutex *pMem; )    /* The memsys static mutex */
 1.32542 +  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
 1.32543 +  MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
 1.32544 +  sqlite3_mutex_enter(pMaster);
 1.32545 +  sqlite3_mutex_enter(pMem);
 1.32546 +  winMemAssertMagic();
 1.32547 +  if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
 1.32548 +    /*
 1.32549 +    ** At this point, there should be no outstanding memory allocations on
 1.32550 +    ** the heap.  Also, since both the master and memsys locks are currently
 1.32551 +    ** being held by us, no other function (i.e. from another thread) should
 1.32552 +    ** be able to even access the heap.  Attempt to destroy and recreate our
 1.32553 +    ** isolated Win32 native heap now.
 1.32554 +    */
 1.32555 +    assert( winMemGetHeap()!=NULL );
 1.32556 +    assert( winMemGetOwned() );
 1.32557 +    assert( sqlite3_memory_used()==0 );
 1.32558 +    winMemShutdown(winMemGetDataPtr());
 1.32559 +    assert( winMemGetHeap()==NULL );
 1.32560 +    assert( !winMemGetOwned() );
 1.32561 +    assert( sqlite3_memory_used()==0 );
 1.32562 +    rc = winMemInit(winMemGetDataPtr());
 1.32563 +    assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
 1.32564 +    assert( rc!=SQLITE_OK || winMemGetOwned() );
 1.32565 +    assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
 1.32566 +  }else{
 1.32567 +    /*
 1.32568 +    ** The Win32 native heap cannot be modified because it may be in use.
 1.32569 +    */
 1.32570 +    rc = SQLITE_BUSY;
 1.32571 +  }
 1.32572 +  sqlite3_mutex_leave(pMem);
 1.32573 +  sqlite3_mutex_leave(pMaster);
 1.32574 +  return rc;
 1.32575 +}
 1.32576 +#endif /* SQLITE_WIN32_MALLOC */
 1.32577 +
 1.32578 +/*
 1.32579 +** This function outputs the specified (ANSI) string to the Win32 debugger
 1.32580 +** (if available).
 1.32581 +*/
 1.32582 +
 1.32583 +SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
 1.32584 +  char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
 1.32585 +  int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
 1.32586 +  if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
 1.32587 +  assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
 1.32588 +#if defined(SQLITE_WIN32_HAS_ANSI)
 1.32589 +  if( nMin>0 ){
 1.32590 +    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
 1.32591 +    memcpy(zDbgBuf, zBuf, nMin);
 1.32592 +    osOutputDebugStringA(zDbgBuf);
 1.32593 +  }else{
 1.32594 +    osOutputDebugStringA(zBuf);
 1.32595 +  }
 1.32596 +#elif defined(SQLITE_WIN32_HAS_WIDE)
 1.32597 +  memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
 1.32598 +  if ( osMultiByteToWideChar(
 1.32599 +          osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
 1.32600 +          nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
 1.32601 +    return;
 1.32602 +  }
 1.32603 +  osOutputDebugStringW((LPCWSTR)zDbgBuf);
 1.32604 +#else
 1.32605 +  if( nMin>0 ){
 1.32606 +    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
 1.32607 +    memcpy(zDbgBuf, zBuf, nMin);
 1.32608 +    fprintf(stderr, "%s", zDbgBuf);
 1.32609 +  }else{
 1.32610 +    fprintf(stderr, "%s", zBuf);
 1.32611 +  }
 1.32612 +#endif
 1.32613 +}
 1.32614 +
 1.32615 +/*
 1.32616 +** The following routine suspends the current thread for at least ms
 1.32617 +** milliseconds.  This is equivalent to the Win32 Sleep() interface.
 1.32618 +*/
 1.32619 +#if SQLITE_OS_WINRT
 1.32620 +static HANDLE sleepObj = NULL;
 1.32621 +#endif
 1.32622 +
 1.32623 +SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
 1.32624 +#if SQLITE_OS_WINRT
 1.32625 +  if ( sleepObj==NULL ){
 1.32626 +    sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
 1.32627 +                                SYNCHRONIZE);
 1.32628 +  }
 1.32629 +  assert( sleepObj!=NULL );
 1.32630 +  osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
 1.32631 +#else
 1.32632 +  osSleep(milliseconds);
 1.32633 +#endif
 1.32634 +}
 1.32635 +
 1.32636 +/*
 1.32637 +** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
 1.32638 +** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
 1.32639 +**
 1.32640 +** Here is an interesting observation:  Win95, Win98, and WinME lack
 1.32641 +** the LockFileEx() API.  But we can still statically link against that
 1.32642 +** API as long as we don't call it when running Win95/98/ME.  A call to
 1.32643 +** this routine is used to determine if the host is Win95/98/ME or
 1.32644 +** WinNT/2K/XP so that we will know whether or not we can safely call
 1.32645 +** the LockFileEx() API.
 1.32646 +*/
 1.32647 +
 1.32648 +#if !defined(SQLITE_WIN32_GETVERSIONEX) || !SQLITE_WIN32_GETVERSIONEX
 1.32649 +# define osIsNT()  (1)
 1.32650 +#elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
 1.32651 +# define osIsNT()  (1)
 1.32652 +#elif !defined(SQLITE_WIN32_HAS_WIDE)
 1.32653 +# define osIsNT()  (0)
 1.32654 +#else
 1.32655 +  static int osIsNT(void){
 1.32656 +    if( sqlite3_os_type==0 ){
 1.32657 +#if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WIN8
 1.32658 +      OSVERSIONINFOW sInfo;
 1.32659 +      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
 1.32660 +      osGetVersionExW(&sInfo);
 1.32661 +#else
 1.32662 +      OSVERSIONINFOA sInfo;
 1.32663 +      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
 1.32664 +      osGetVersionExA(&sInfo);
 1.32665 +#endif
 1.32666 +      sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
 1.32667 +    }
 1.32668 +    return sqlite3_os_type==2;
 1.32669 +  }
 1.32670 +#endif
 1.32671 +
 1.32672 +#ifdef SQLITE_WIN32_MALLOC
 1.32673 +/*
 1.32674 +** Allocate nBytes of memory.
 1.32675 +*/
 1.32676 +static void *winMemMalloc(int nBytes){
 1.32677 +  HANDLE hHeap;
 1.32678 +  void *p;
 1.32679 +
 1.32680 +  winMemAssertMagic();
 1.32681 +  hHeap = winMemGetHeap();
 1.32682 +  assert( hHeap!=0 );
 1.32683 +  assert( hHeap!=INVALID_HANDLE_VALUE );
 1.32684 +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 1.32685 +  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
 1.32686 +#endif
 1.32687 +  assert( nBytes>=0 );
 1.32688 +  p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
 1.32689 +  if( !p ){
 1.32690 +    sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
 1.32691 +                nBytes, osGetLastError(), (void*)hHeap);
 1.32692 +  }
 1.32693 +  return p;
 1.32694 +}
 1.32695 +
 1.32696 +/*
 1.32697 +** Free memory.
 1.32698 +*/
 1.32699 +static void winMemFree(void *pPrior){
 1.32700 +  HANDLE hHeap;
 1.32701 +
 1.32702 +  winMemAssertMagic();
 1.32703 +  hHeap = winMemGetHeap();
 1.32704 +  assert( hHeap!=0 );
 1.32705 +  assert( hHeap!=INVALID_HANDLE_VALUE );
 1.32706 +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 1.32707 +  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
 1.32708 +#endif
 1.32709 +  if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
 1.32710 +  if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
 1.32711 +    sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
 1.32712 +                pPrior, osGetLastError(), (void*)hHeap);
 1.32713 +  }
 1.32714 +}
 1.32715 +
 1.32716 +/*
 1.32717 +** Change the size of an existing memory allocation
 1.32718 +*/
 1.32719 +static void *winMemRealloc(void *pPrior, int nBytes){
 1.32720 +  HANDLE hHeap;
 1.32721 +  void *p;
 1.32722 +
 1.32723 +  winMemAssertMagic();
 1.32724 +  hHeap = winMemGetHeap();
 1.32725 +  assert( hHeap!=0 );
 1.32726 +  assert( hHeap!=INVALID_HANDLE_VALUE );
 1.32727 +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 1.32728 +  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
 1.32729 +#endif
 1.32730 +  assert( nBytes>=0 );
 1.32731 +  if( !pPrior ){
 1.32732 +    p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
 1.32733 +  }else{
 1.32734 +    p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
 1.32735 +  }
 1.32736 +  if( !p ){
 1.32737 +    sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
 1.32738 +                pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
 1.32739 +                (void*)hHeap);
 1.32740 +  }
 1.32741 +  return p;
 1.32742 +}
 1.32743 +
 1.32744 +/*
 1.32745 +** Return the size of an outstanding allocation, in bytes.
 1.32746 +*/
 1.32747 +static int winMemSize(void *p){
 1.32748 +  HANDLE hHeap;
 1.32749 +  SIZE_T n;
 1.32750 +
 1.32751 +  winMemAssertMagic();
 1.32752 +  hHeap = winMemGetHeap();
 1.32753 +  assert( hHeap!=0 );
 1.32754 +  assert( hHeap!=INVALID_HANDLE_VALUE );
 1.32755 +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 1.32756 +  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
 1.32757 +#endif
 1.32758 +  if( !p ) return 0;
 1.32759 +  n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
 1.32760 +  if( n==(SIZE_T)-1 ){
 1.32761 +    sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
 1.32762 +                p, osGetLastError(), (void*)hHeap);
 1.32763 +    return 0;
 1.32764 +  }
 1.32765 +  return (int)n;
 1.32766 +}
 1.32767 +
 1.32768 +/*
 1.32769 +** Round up a request size to the next valid allocation size.
 1.32770 +*/
 1.32771 +static int winMemRoundup(int n){
 1.32772 +  return n;
 1.32773 +}
 1.32774 +
 1.32775 +/*
 1.32776 +** Initialize this module.
 1.32777 +*/
 1.32778 +static int winMemInit(void *pAppData){
 1.32779 +  winMemData *pWinMemData = (winMemData *)pAppData;
 1.32780 +
 1.32781 +  if( !pWinMemData ) return SQLITE_ERROR;
 1.32782 +  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
 1.32783 +  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
 1.32784 +
 1.32785 +#if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
 1.32786 +  if( !pWinMemData->hHeap ){
 1.32787 +    DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
 1.32788 +    DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
 1.32789 +    if( dwMaximumSize==0 ){
 1.32790 +      dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
 1.32791 +    }else if( dwInitialSize>dwMaximumSize ){
 1.32792 +      dwInitialSize = dwMaximumSize;
 1.32793 +    }
 1.32794 +    pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
 1.32795 +                                      dwInitialSize, dwMaximumSize);
 1.32796 +    if( !pWinMemData->hHeap ){
 1.32797 +      sqlite3_log(SQLITE_NOMEM,
 1.32798 +          "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
 1.32799 +          osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
 1.32800 +          dwMaximumSize);
 1.32801 +      return SQLITE_NOMEM;
 1.32802 +    }
 1.32803 +    pWinMemData->bOwned = TRUE;
 1.32804 +    assert( pWinMemData->bOwned );
 1.32805 +  }
 1.32806 +#else
 1.32807 +  pWinMemData->hHeap = osGetProcessHeap();
 1.32808 +  if( !pWinMemData->hHeap ){
 1.32809 +    sqlite3_log(SQLITE_NOMEM,
 1.32810 +        "failed to GetProcessHeap (%lu)", osGetLastError());
 1.32811 +    return SQLITE_NOMEM;
 1.32812 +  }
 1.32813 +  pWinMemData->bOwned = FALSE;
 1.32814 +  assert( !pWinMemData->bOwned );
 1.32815 +#endif
 1.32816 +  assert( pWinMemData->hHeap!=0 );
 1.32817 +  assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
 1.32818 +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 1.32819 +  assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
 1.32820 +#endif
 1.32821 +  return SQLITE_OK;
 1.32822 +}
 1.32823 +
 1.32824 +/*
 1.32825 +** Deinitialize this module.
 1.32826 +*/
 1.32827 +static void winMemShutdown(void *pAppData){
 1.32828 +  winMemData *pWinMemData = (winMemData *)pAppData;
 1.32829 +
 1.32830 +  if( !pWinMemData ) return;
 1.32831 +  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
 1.32832 +  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
 1.32833 +
 1.32834 +  if( pWinMemData->hHeap ){
 1.32835 +    assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
 1.32836 +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 1.32837 +    assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
 1.32838 +#endif
 1.32839 +    if( pWinMemData->bOwned ){
 1.32840 +      if( !osHeapDestroy(pWinMemData->hHeap) ){
 1.32841 +        sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
 1.32842 +                    osGetLastError(), (void*)pWinMemData->hHeap);
 1.32843 +      }
 1.32844 +      pWinMemData->bOwned = FALSE;
 1.32845 +    }
 1.32846 +    pWinMemData->hHeap = NULL;
 1.32847 +  }
 1.32848 +}
 1.32849 +
 1.32850 +/*
 1.32851 +** Populate the low-level memory allocation function pointers in
 1.32852 +** sqlite3GlobalConfig.m with pointers to the routines in this file. The
 1.32853 +** arguments specify the block of memory to manage.
 1.32854 +**
 1.32855 +** This routine is only called by sqlite3_config(), and therefore
 1.32856 +** is not required to be threadsafe (it is not).
 1.32857 +*/
 1.32858 +SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
 1.32859 +  static const sqlite3_mem_methods winMemMethods = {
 1.32860 +    winMemMalloc,
 1.32861 +    winMemFree,
 1.32862 +    winMemRealloc,
 1.32863 +    winMemSize,
 1.32864 +    winMemRoundup,
 1.32865 +    winMemInit,
 1.32866 +    winMemShutdown,
 1.32867 +    &win_mem_data
 1.32868 +  };
 1.32869 +  return &winMemMethods;
 1.32870 +}
 1.32871 +
 1.32872 +SQLITE_PRIVATE void sqlite3MemSetDefault(void){
 1.32873 +  sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
 1.32874 +}
 1.32875 +#endif /* SQLITE_WIN32_MALLOC */
 1.32876 +
 1.32877 +/*
 1.32878 +** Convert a UTF-8 string to Microsoft Unicode (UTF-16?). 
 1.32879 +**
 1.32880 +** Space to hold the returned string is obtained from malloc.
 1.32881 +*/
 1.32882 +static LPWSTR winUtf8ToUnicode(const char *zFilename){
 1.32883 +  int nChar;
 1.32884 +  LPWSTR zWideFilename;
 1.32885 +
 1.32886 +  nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
 1.32887 +  if( nChar==0 ){
 1.32888 +    return 0;
 1.32889 +  }
 1.32890 +  zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
 1.32891 +  if( zWideFilename==0 ){
 1.32892 +    return 0;
 1.32893 +  }
 1.32894 +  nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
 1.32895 +                                nChar);
 1.32896 +  if( nChar==0 ){
 1.32897 +    sqlite3_free(zWideFilename);
 1.32898 +    zWideFilename = 0;
 1.32899 +  }
 1.32900 +  return zWideFilename;
 1.32901 +}
 1.32902 +
 1.32903 +/*
 1.32904 +** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
 1.32905 +** obtained from sqlite3_malloc().
 1.32906 +*/
 1.32907 +static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
 1.32908 +  int nByte;
 1.32909 +  char *zFilename;
 1.32910 +
 1.32911 +  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
 1.32912 +  if( nByte == 0 ){
 1.32913 +    return 0;
 1.32914 +  }
 1.32915 +  zFilename = sqlite3MallocZero( nByte );
 1.32916 +  if( zFilename==0 ){
 1.32917 +    return 0;
 1.32918 +  }
 1.32919 +  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
 1.32920 +                                0, 0);
 1.32921 +  if( nByte == 0 ){
 1.32922 +    sqlite3_free(zFilename);
 1.32923 +    zFilename = 0;
 1.32924 +  }
 1.32925 +  return zFilename;
 1.32926 +}
 1.32927 +
 1.32928 +/*
 1.32929 +** Convert an ANSI string to Microsoft Unicode, based on the
 1.32930 +** current codepage settings for file apis.
 1.32931 +** 
 1.32932 +** Space to hold the returned string is obtained
 1.32933 +** from sqlite3_malloc.
 1.32934 +*/
 1.32935 +static LPWSTR winMbcsToUnicode(const char *zFilename){
 1.32936 +  int nByte;
 1.32937 +  LPWSTR zMbcsFilename;
 1.32938 +  int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
 1.32939 +
 1.32940 +  nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
 1.32941 +                                0)*sizeof(WCHAR);
 1.32942 +  if( nByte==0 ){
 1.32943 +    return 0;
 1.32944 +  }
 1.32945 +  zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
 1.32946 +  if( zMbcsFilename==0 ){
 1.32947 +    return 0;
 1.32948 +  }
 1.32949 +  nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
 1.32950 +                                nByte);
 1.32951 +  if( nByte==0 ){
 1.32952 +    sqlite3_free(zMbcsFilename);
 1.32953 +    zMbcsFilename = 0;
 1.32954 +  }
 1.32955 +  return zMbcsFilename;
 1.32956 +}
 1.32957 +
 1.32958 +/*
 1.32959 +** Convert Microsoft Unicode to multi-byte character string, based on the
 1.32960 +** user's ANSI codepage.
 1.32961 +**
 1.32962 +** Space to hold the returned string is obtained from
 1.32963 +** sqlite3_malloc().
 1.32964 +*/
 1.32965 +static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
 1.32966 +  int nByte;
 1.32967 +  char *zFilename;
 1.32968 +  int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
 1.32969 +
 1.32970 +  nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
 1.32971 +  if( nByte == 0 ){
 1.32972 +    return 0;
 1.32973 +  }
 1.32974 +  zFilename = sqlite3MallocZero( nByte );
 1.32975 +  if( zFilename==0 ){
 1.32976 +    return 0;
 1.32977 +  }
 1.32978 +  nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
 1.32979 +                                nByte, 0, 0);
 1.32980 +  if( nByte == 0 ){
 1.32981 +    sqlite3_free(zFilename);
 1.32982 +    zFilename = 0;
 1.32983 +  }
 1.32984 +  return zFilename;
 1.32985 +}
 1.32986 +
 1.32987 +/*
 1.32988 +** Convert multibyte character string to UTF-8.  Space to hold the
 1.32989 +** returned string is obtained from sqlite3_malloc().
 1.32990 +*/
 1.32991 +SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
 1.32992 +  char *zFilenameUtf8;
 1.32993 +  LPWSTR zTmpWide;
 1.32994 +
 1.32995 +  zTmpWide = winMbcsToUnicode(zFilename);
 1.32996 +  if( zTmpWide==0 ){
 1.32997 +    return 0;
 1.32998 +  }
 1.32999 +  zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
 1.33000 +  sqlite3_free(zTmpWide);
 1.33001 +  return zFilenameUtf8;
 1.33002 +}
 1.33003 +
 1.33004 +/*
 1.33005 +** Convert UTF-8 to multibyte character string.  Space to hold the 
 1.33006 +** returned string is obtained from sqlite3_malloc().
 1.33007 +*/
 1.33008 +SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
 1.33009 +  char *zFilenameMbcs;
 1.33010 +  LPWSTR zTmpWide;
 1.33011 +
 1.33012 +  zTmpWide = winUtf8ToUnicode(zFilename);
 1.33013 +  if( zTmpWide==0 ){
 1.33014 +    return 0;
 1.33015 +  }
 1.33016 +  zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
 1.33017 +  sqlite3_free(zTmpWide);
 1.33018 +  return zFilenameMbcs;
 1.33019 +}
 1.33020 +
 1.33021 +/*
 1.33022 +** This function sets the data directory or the temporary directory based on
 1.33023 +** the provided arguments.  The type argument must be 1 in order to set the
 1.33024 +** data directory or 2 in order to set the temporary directory.  The zValue
 1.33025 +** argument is the name of the directory to use.  The return value will be
 1.33026 +** SQLITE_OK if successful.
 1.33027 +*/
 1.33028 +SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
 1.33029 +  char **ppDirectory = 0;
 1.33030 +#ifndef SQLITE_OMIT_AUTOINIT
 1.33031 +  int rc = sqlite3_initialize();
 1.33032 +  if( rc ) return rc;
 1.33033 +#endif
 1.33034 +  if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
 1.33035 +    ppDirectory = &sqlite3_data_directory;
 1.33036 +  }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
 1.33037 +    ppDirectory = &sqlite3_temp_directory;
 1.33038 +  }
 1.33039 +  assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
 1.33040 +          || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
 1.33041 +  );
 1.33042 +  assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
 1.33043 +  if( ppDirectory ){
 1.33044 +    char *zValueUtf8 = 0;
 1.33045 +    if( zValue && zValue[0] ){
 1.33046 +      zValueUtf8 = winUnicodeToUtf8(zValue);
 1.33047 +      if ( zValueUtf8==0 ){
 1.33048 +        return SQLITE_NOMEM;
 1.33049 +      }
 1.33050 +    }
 1.33051 +    sqlite3_free(*ppDirectory);
 1.33052 +    *ppDirectory = zValueUtf8;
 1.33053 +    return SQLITE_OK;
 1.33054 +  }
 1.33055 +  return SQLITE_ERROR;
 1.33056 +}
 1.33057 +
 1.33058 +/*
 1.33059 +** The return value of winGetLastErrorMsg
 1.33060 +** is zero if the error message fits in the buffer, or non-zero
 1.33061 +** otherwise (if the message was truncated).
 1.33062 +*/
 1.33063 +static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
 1.33064 +  /* FormatMessage returns 0 on failure.  Otherwise it
 1.33065 +  ** returns the number of TCHARs written to the output
 1.33066 +  ** buffer, excluding the terminating null char.
 1.33067 +  */
 1.33068 +  DWORD dwLen = 0;
 1.33069 +  char *zOut = 0;
 1.33070 +
 1.33071 +  if( osIsNT() ){
 1.33072 +#if SQLITE_OS_WINRT
 1.33073 +    WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
 1.33074 +    dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
 1.33075 +                             FORMAT_MESSAGE_IGNORE_INSERTS,
 1.33076 +                             NULL,
 1.33077 +                             lastErrno,
 1.33078 +                             0,
 1.33079 +                             zTempWide,
 1.33080 +                             SQLITE_WIN32_MAX_ERRMSG_CHARS,
 1.33081 +                             0);
 1.33082 +#else
 1.33083 +    LPWSTR zTempWide = NULL;
 1.33084 +    dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
 1.33085 +                             FORMAT_MESSAGE_FROM_SYSTEM |
 1.33086 +                             FORMAT_MESSAGE_IGNORE_INSERTS,
 1.33087 +                             NULL,
 1.33088 +                             lastErrno,
 1.33089 +                             0,
 1.33090 +                             (LPWSTR) &zTempWide,
 1.33091 +                             0,
 1.33092 +                             0);
 1.33093 +#endif
 1.33094 +    if( dwLen > 0 ){
 1.33095 +      /* allocate a buffer and convert to UTF8 */
 1.33096 +      sqlite3BeginBenignMalloc();
 1.33097 +      zOut = winUnicodeToUtf8(zTempWide);
 1.33098 +      sqlite3EndBenignMalloc();
 1.33099 +#if !SQLITE_OS_WINRT
 1.33100 +      /* free the system buffer allocated by FormatMessage */
 1.33101 +      osLocalFree(zTempWide);
 1.33102 +#endif
 1.33103 +    }
 1.33104 +  }
 1.33105 +#ifdef SQLITE_WIN32_HAS_ANSI
 1.33106 +  else{
 1.33107 +    char *zTemp = NULL;
 1.33108 +    dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
 1.33109 +                             FORMAT_MESSAGE_FROM_SYSTEM |
 1.33110 +                             FORMAT_MESSAGE_IGNORE_INSERTS,
 1.33111 +                             NULL,
 1.33112 +                             lastErrno,
 1.33113 +                             0,
 1.33114 +                             (LPSTR) &zTemp,
 1.33115 +                             0,
 1.33116 +                             0);
 1.33117 +    if( dwLen > 0 ){
 1.33118 +      /* allocate a buffer and convert to UTF8 */
 1.33119 +      sqlite3BeginBenignMalloc();
 1.33120 +      zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
 1.33121 +      sqlite3EndBenignMalloc();
 1.33122 +      /* free the system buffer allocated by FormatMessage */
 1.33123 +      osLocalFree(zTemp);
 1.33124 +    }
 1.33125 +  }
 1.33126 +#endif
 1.33127 +  if( 0 == dwLen ){
 1.33128 +    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
 1.33129 +  }else{
 1.33130 +    /* copy a maximum of nBuf chars to output buffer */
 1.33131 +    sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
 1.33132 +    /* free the UTF8 buffer */
 1.33133 +    sqlite3_free(zOut);
 1.33134 +  }
 1.33135 +  return 0;
 1.33136 +}
 1.33137 +
 1.33138 +/*
 1.33139 +**
 1.33140 +** This function - winLogErrorAtLine() - is only ever called via the macro
 1.33141 +** winLogError().
 1.33142 +**
 1.33143 +** This routine is invoked after an error occurs in an OS function.
 1.33144 +** It logs a message using sqlite3_log() containing the current value of
 1.33145 +** error code and, if possible, the human-readable equivalent from 
 1.33146 +** FormatMessage.
 1.33147 +**
 1.33148 +** The first argument passed to the macro should be the error code that
 1.33149 +** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
 1.33150 +** The two subsequent arguments should be the name of the OS function that
 1.33151 +** failed and the associated file-system path, if any.
 1.33152 +*/
 1.33153 +#define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
 1.33154 +static int winLogErrorAtLine(
 1.33155 +  int errcode,                    /* SQLite error code */
 1.33156 +  DWORD lastErrno,                /* Win32 last error */
 1.33157 +  const char *zFunc,              /* Name of OS function that failed */
 1.33158 +  const char *zPath,              /* File path associated with error */
 1.33159 +  int iLine                       /* Source line number where error occurred */
 1.33160 +){
 1.33161 +  char zMsg[500];                 /* Human readable error text */
 1.33162 +  int i;                          /* Loop counter */
 1.33163 +
 1.33164 +  zMsg[0] = 0;
 1.33165 +  winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
 1.33166 +  assert( errcode!=SQLITE_OK );
 1.33167 +  if( zPath==0 ) zPath = "";
 1.33168 +  for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
 1.33169 +  zMsg[i] = 0;
 1.33170 +  sqlite3_log(errcode,
 1.33171 +      "os_win.c:%d: (%lu) %s(%s) - %s",
 1.33172 +      iLine, lastErrno, zFunc, zPath, zMsg
 1.33173 +  );
 1.33174 +
 1.33175 +  return errcode;
 1.33176 +}
 1.33177 +
 1.33178 +/*
 1.33179 +** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
 1.33180 +** will be retried following a locking error - probably caused by 
 1.33181 +** antivirus software.  Also the initial delay before the first retry.
 1.33182 +** The delay increases linearly with each retry.
 1.33183 +*/
 1.33184 +#ifndef SQLITE_WIN32_IOERR_RETRY
 1.33185 +# define SQLITE_WIN32_IOERR_RETRY 10
 1.33186 +#endif
 1.33187 +#ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
 1.33188 +# define SQLITE_WIN32_IOERR_RETRY_DELAY 25
 1.33189 +#endif
 1.33190 +static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
 1.33191 +static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
 1.33192 +
 1.33193 +/*
 1.33194 +** If a ReadFile() or WriteFile() error occurs, invoke this routine
 1.33195 +** to see if it should be retried.  Return TRUE to retry.  Return FALSE
 1.33196 +** to give up with an error.
 1.33197 +*/
 1.33198 +static int winRetryIoerr(int *pnRetry, DWORD *pError){
 1.33199 +  DWORD e = osGetLastError();
 1.33200 +  if( *pnRetry>=winIoerrRetry ){
 1.33201 +    if( pError ){
 1.33202 +      *pError = e;
 1.33203 +    }
 1.33204 +    return 0;
 1.33205 +  }
 1.33206 +  if( e==ERROR_ACCESS_DENIED ||
 1.33207 +      e==ERROR_LOCK_VIOLATION ||
 1.33208 +      e==ERROR_SHARING_VIOLATION ){
 1.33209 +    sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
 1.33210 +    ++*pnRetry;
 1.33211 +    return 1;
 1.33212 +  }
 1.33213 +  if( pError ){
 1.33214 +    *pError = e;
 1.33215 +  }
 1.33216 +  return 0;
 1.33217 +}
 1.33218 +
 1.33219 +/*
 1.33220 +** Log a I/O error retry episode.
 1.33221 +*/
 1.33222 +static void winLogIoerr(int nRetry){
 1.33223 +  if( nRetry ){
 1.33224 +    sqlite3_log(SQLITE_IOERR, 
 1.33225 +      "delayed %dms for lock/sharing conflict",
 1.33226 +      winIoerrRetryDelay*nRetry*(nRetry+1)/2
 1.33227 +    );
 1.33228 +  }
 1.33229 +}
 1.33230 +
 1.33231 +#if SQLITE_OS_WINCE
 1.33232 +/*************************************************************************
 1.33233 +** This section contains code for WinCE only.
 1.33234 +*/
 1.33235 +#if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
 1.33236 +/*
 1.33237 +** The MSVC CRT on Windows CE may not have a localtime() function.  So
 1.33238 +** create a substitute.
 1.33239 +*/
 1.33240 +/* #include <time.h> */
 1.33241 +struct tm *__cdecl localtime(const time_t *t)
 1.33242 +{
 1.33243 +  static struct tm y;
 1.33244 +  FILETIME uTm, lTm;
 1.33245 +  SYSTEMTIME pTm;
 1.33246 +  sqlite3_int64 t64;
 1.33247 +  t64 = *t;
 1.33248 +  t64 = (t64 + 11644473600)*10000000;
 1.33249 +  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
 1.33250 +  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
 1.33251 +  osFileTimeToLocalFileTime(&uTm,&lTm);
 1.33252 +  osFileTimeToSystemTime(&lTm,&pTm);
 1.33253 +  y.tm_year = pTm.wYear - 1900;
 1.33254 +  y.tm_mon = pTm.wMonth - 1;
 1.33255 +  y.tm_wday = pTm.wDayOfWeek;
 1.33256 +  y.tm_mday = pTm.wDay;
 1.33257 +  y.tm_hour = pTm.wHour;
 1.33258 +  y.tm_min = pTm.wMinute;
 1.33259 +  y.tm_sec = pTm.wSecond;
 1.33260 +  return &y;
 1.33261 +}
 1.33262 +#endif
 1.33263 +
 1.33264 +#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
 1.33265 +
 1.33266 +/*
 1.33267 +** Acquire a lock on the handle h
 1.33268 +*/
 1.33269 +static void winceMutexAcquire(HANDLE h){
 1.33270 +   DWORD dwErr;
 1.33271 +   do {
 1.33272 +     dwErr = osWaitForSingleObject(h, INFINITE);
 1.33273 +   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
 1.33274 +}
 1.33275 +/*
 1.33276 +** Release a lock acquired by winceMutexAcquire()
 1.33277 +*/
 1.33278 +#define winceMutexRelease(h) ReleaseMutex(h)
 1.33279 +
 1.33280 +/*
 1.33281 +** Create the mutex and shared memory used for locking in the file
 1.33282 +** descriptor pFile
 1.33283 +*/
 1.33284 +static int winceCreateLock(const char *zFilename, winFile *pFile){
 1.33285 +  LPWSTR zTok;
 1.33286 +  LPWSTR zName;
 1.33287 +  DWORD lastErrno;
 1.33288 +  BOOL bLogged = FALSE;
 1.33289 +  BOOL bInit = TRUE;
 1.33290 +
 1.33291 +  zName = winUtf8ToUnicode(zFilename);
 1.33292 +  if( zName==0 ){
 1.33293 +    /* out of memory */
 1.33294 +    return SQLITE_IOERR_NOMEM;
 1.33295 +  }
 1.33296 +
 1.33297 +  /* Initialize the local lockdata */
 1.33298 +  memset(&pFile->local, 0, sizeof(pFile->local));
 1.33299 +
 1.33300 +  /* Replace the backslashes from the filename and lowercase it
 1.33301 +  ** to derive a mutex name. */
 1.33302 +  zTok = osCharLowerW(zName);
 1.33303 +  for (;*zTok;zTok++){
 1.33304 +    if (*zTok == '\\') *zTok = '_';
 1.33305 +  }
 1.33306 +
 1.33307 +  /* Create/open the named mutex */
 1.33308 +  pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
 1.33309 +  if (!pFile->hMutex){
 1.33310 +    pFile->lastErrno = osGetLastError();
 1.33311 +    sqlite3_free(zName);
 1.33312 +    return winLogError(SQLITE_IOERR, pFile->lastErrno,
 1.33313 +                       "winceCreateLock1", zFilename);
 1.33314 +  }
 1.33315 +
 1.33316 +  /* Acquire the mutex before continuing */
 1.33317 +  winceMutexAcquire(pFile->hMutex);
 1.33318 +  
 1.33319 +  /* Since the names of named mutexes, semaphores, file mappings etc are 
 1.33320 +  ** case-sensitive, take advantage of that by uppercasing the mutex name
 1.33321 +  ** and using that as the shared filemapping name.
 1.33322 +  */
 1.33323 +  osCharUpperW(zName);
 1.33324 +  pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
 1.33325 +                                        PAGE_READWRITE, 0, sizeof(winceLock),
 1.33326 +                                        zName);  
 1.33327 +
 1.33328 +  /* Set a flag that indicates we're the first to create the memory so it 
 1.33329 +  ** must be zero-initialized */
 1.33330 +  lastErrno = osGetLastError();
 1.33331 +  if (lastErrno == ERROR_ALREADY_EXISTS){
 1.33332 +    bInit = FALSE;
 1.33333 +  }
 1.33334 +
 1.33335 +  sqlite3_free(zName);
 1.33336 +
 1.33337 +  /* If we succeeded in making the shared memory handle, map it. */
 1.33338 +  if( pFile->hShared ){
 1.33339 +    pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared, 
 1.33340 +             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
 1.33341 +    /* If mapping failed, close the shared memory handle and erase it */
 1.33342 +    if( !pFile->shared ){
 1.33343 +      pFile->lastErrno = osGetLastError();
 1.33344 +      winLogError(SQLITE_IOERR, pFile->lastErrno,
 1.33345 +                  "winceCreateLock2", zFilename);
 1.33346 +      bLogged = TRUE;
 1.33347 +      osCloseHandle(pFile->hShared);
 1.33348 +      pFile->hShared = NULL;
 1.33349 +    }
 1.33350 +  }
 1.33351 +
 1.33352 +  /* If shared memory could not be created, then close the mutex and fail */
 1.33353 +  if( pFile->hShared==NULL ){
 1.33354 +    if( !bLogged ){
 1.33355 +      pFile->lastErrno = lastErrno;
 1.33356 +      winLogError(SQLITE_IOERR, pFile->lastErrno,
 1.33357 +                  "winceCreateLock3", zFilename);
 1.33358 +      bLogged = TRUE;
 1.33359 +    }
 1.33360 +    winceMutexRelease(pFile->hMutex);
 1.33361 +    osCloseHandle(pFile->hMutex);
 1.33362 +    pFile->hMutex = NULL;
 1.33363 +    return SQLITE_IOERR;
 1.33364 +  }
 1.33365 +  
 1.33366 +  /* Initialize the shared memory if we're supposed to */
 1.33367 +  if( bInit ){
 1.33368 +    memset(pFile->shared, 0, sizeof(winceLock));
 1.33369 +  }
 1.33370 +
 1.33371 +  winceMutexRelease(pFile->hMutex);
 1.33372 +  return SQLITE_OK;
 1.33373 +}
 1.33374 +
 1.33375 +/*
 1.33376 +** Destroy the part of winFile that deals with wince locks
 1.33377 +*/
 1.33378 +static void winceDestroyLock(winFile *pFile){
 1.33379 +  if (pFile->hMutex){
 1.33380 +    /* Acquire the mutex */
 1.33381 +    winceMutexAcquire(pFile->hMutex);
 1.33382 +
 1.33383 +    /* The following blocks should probably assert in debug mode, but they
 1.33384 +       are to cleanup in case any locks remained open */
 1.33385 +    if (pFile->local.nReaders){
 1.33386 +      pFile->shared->nReaders --;
 1.33387 +    }
 1.33388 +    if (pFile->local.bReserved){
 1.33389 +      pFile->shared->bReserved = FALSE;
 1.33390 +    }
 1.33391 +    if (pFile->local.bPending){
 1.33392 +      pFile->shared->bPending = FALSE;
 1.33393 +    }
 1.33394 +    if (pFile->local.bExclusive){
 1.33395 +      pFile->shared->bExclusive = FALSE;
 1.33396 +    }
 1.33397 +
 1.33398 +    /* De-reference and close our copy of the shared memory handle */
 1.33399 +    osUnmapViewOfFile(pFile->shared);
 1.33400 +    osCloseHandle(pFile->hShared);
 1.33401 +
 1.33402 +    /* Done with the mutex */
 1.33403 +    winceMutexRelease(pFile->hMutex);    
 1.33404 +    osCloseHandle(pFile->hMutex);
 1.33405 +    pFile->hMutex = NULL;
 1.33406 +  }
 1.33407 +}
 1.33408 +
 1.33409 +/* 
 1.33410 +** An implementation of the LockFile() API of Windows for CE
 1.33411 +*/
 1.33412 +static BOOL winceLockFile(
 1.33413 +  LPHANDLE phFile,
 1.33414 +  DWORD dwFileOffsetLow,
 1.33415 +  DWORD dwFileOffsetHigh,
 1.33416 +  DWORD nNumberOfBytesToLockLow,
 1.33417 +  DWORD nNumberOfBytesToLockHigh
 1.33418 +){
 1.33419 +  winFile *pFile = HANDLE_TO_WINFILE(phFile);
 1.33420 +  BOOL bReturn = FALSE;
 1.33421 +
 1.33422 +  UNUSED_PARAMETER(dwFileOffsetHigh);
 1.33423 +  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
 1.33424 +
 1.33425 +  if (!pFile->hMutex) return TRUE;
 1.33426 +  winceMutexAcquire(pFile->hMutex);
 1.33427 +
 1.33428 +  /* Wanting an exclusive lock? */
 1.33429 +  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
 1.33430 +       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
 1.33431 +    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
 1.33432 +       pFile->shared->bExclusive = TRUE;
 1.33433 +       pFile->local.bExclusive = TRUE;
 1.33434 +       bReturn = TRUE;
 1.33435 +    }
 1.33436 +  }
 1.33437 +
 1.33438 +  /* Want a read-only lock? */
 1.33439 +  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
 1.33440 +           nNumberOfBytesToLockLow == 1){
 1.33441 +    if (pFile->shared->bExclusive == 0){
 1.33442 +      pFile->local.nReaders ++;
 1.33443 +      if (pFile->local.nReaders == 1){
 1.33444 +        pFile->shared->nReaders ++;
 1.33445 +      }
 1.33446 +      bReturn = TRUE;
 1.33447 +    }
 1.33448 +  }
 1.33449 +
 1.33450 +  /* Want a pending lock? */
 1.33451 +  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
 1.33452 +           && nNumberOfBytesToLockLow == 1){
 1.33453 +    /* If no pending lock has been acquired, then acquire it */
 1.33454 +    if (pFile->shared->bPending == 0) {
 1.33455 +      pFile->shared->bPending = TRUE;
 1.33456 +      pFile->local.bPending = TRUE;
 1.33457 +      bReturn = TRUE;
 1.33458 +    }
 1.33459 +  }
 1.33460 +
 1.33461 +  /* Want a reserved lock? */
 1.33462 +  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
 1.33463 +           && nNumberOfBytesToLockLow == 1){
 1.33464 +    if (pFile->shared->bReserved == 0) {
 1.33465 +      pFile->shared->bReserved = TRUE;
 1.33466 +      pFile->local.bReserved = TRUE;
 1.33467 +      bReturn = TRUE;
 1.33468 +    }
 1.33469 +  }
 1.33470 +
 1.33471 +  winceMutexRelease(pFile->hMutex);
 1.33472 +  return bReturn;
 1.33473 +}
 1.33474 +
 1.33475 +/*
 1.33476 +** An implementation of the UnlockFile API of Windows for CE
 1.33477 +*/
 1.33478 +static BOOL winceUnlockFile(
 1.33479 +  LPHANDLE phFile,
 1.33480 +  DWORD dwFileOffsetLow,
 1.33481 +  DWORD dwFileOffsetHigh,
 1.33482 +  DWORD nNumberOfBytesToUnlockLow,
 1.33483 +  DWORD nNumberOfBytesToUnlockHigh
 1.33484 +){
 1.33485 +  winFile *pFile = HANDLE_TO_WINFILE(phFile);
 1.33486 +  BOOL bReturn = FALSE;
 1.33487 +
 1.33488 +  UNUSED_PARAMETER(dwFileOffsetHigh);
 1.33489 +  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
 1.33490 +
 1.33491 +  if (!pFile->hMutex) return TRUE;
 1.33492 +  winceMutexAcquire(pFile->hMutex);
 1.33493 +
 1.33494 +  /* Releasing a reader lock or an exclusive lock */
 1.33495 +  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
 1.33496 +    /* Did we have an exclusive lock? */
 1.33497 +    if (pFile->local.bExclusive){
 1.33498 +      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
 1.33499 +      pFile->local.bExclusive = FALSE;
 1.33500 +      pFile->shared->bExclusive = FALSE;
 1.33501 +      bReturn = TRUE;
 1.33502 +    }
 1.33503 +
 1.33504 +    /* Did we just have a reader lock? */
 1.33505 +    else if (pFile->local.nReaders){
 1.33506 +      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
 1.33507 +             || nNumberOfBytesToUnlockLow == 1);
 1.33508 +      pFile->local.nReaders --;
 1.33509 +      if (pFile->local.nReaders == 0)
 1.33510 +      {
 1.33511 +        pFile->shared->nReaders --;
 1.33512 +      }
 1.33513 +      bReturn = TRUE;
 1.33514 +    }
 1.33515 +  }
 1.33516 +
 1.33517 +  /* Releasing a pending lock */
 1.33518 +  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
 1.33519 +           && nNumberOfBytesToUnlockLow == 1){
 1.33520 +    if (pFile->local.bPending){
 1.33521 +      pFile->local.bPending = FALSE;
 1.33522 +      pFile->shared->bPending = FALSE;
 1.33523 +      bReturn = TRUE;
 1.33524 +    }
 1.33525 +  }
 1.33526 +  /* Releasing a reserved lock */
 1.33527 +  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
 1.33528 +           && nNumberOfBytesToUnlockLow == 1){
 1.33529 +    if (pFile->local.bReserved) {
 1.33530 +      pFile->local.bReserved = FALSE;
 1.33531 +      pFile->shared->bReserved = FALSE;
 1.33532 +      bReturn = TRUE;
 1.33533 +    }
 1.33534 +  }
 1.33535 +
 1.33536 +  winceMutexRelease(pFile->hMutex);
 1.33537 +  return bReturn;
 1.33538 +}
 1.33539 +/*
 1.33540 +** End of the special code for wince
 1.33541 +*****************************************************************************/
 1.33542 +#endif /* SQLITE_OS_WINCE */
 1.33543 +
 1.33544 +/*
 1.33545 +** Lock a file region.
 1.33546 +*/
 1.33547 +static BOOL winLockFile(
 1.33548 +  LPHANDLE phFile,
 1.33549 +  DWORD flags,
 1.33550 +  DWORD offsetLow,
 1.33551 +  DWORD offsetHigh,
 1.33552 +  DWORD numBytesLow,
 1.33553 +  DWORD numBytesHigh
 1.33554 +){
 1.33555 +#if SQLITE_OS_WINCE
 1.33556 +  /*
 1.33557 +  ** NOTE: Windows CE is handled differently here due its lack of the Win32
 1.33558 +  **       API LockFile.
 1.33559 +  */
 1.33560 +  return winceLockFile(phFile, offsetLow, offsetHigh,
 1.33561 +                       numBytesLow, numBytesHigh);
 1.33562 +#else
 1.33563 +  if( osIsNT() ){
 1.33564 +    OVERLAPPED ovlp;
 1.33565 +    memset(&ovlp, 0, sizeof(OVERLAPPED));
 1.33566 +    ovlp.Offset = offsetLow;
 1.33567 +    ovlp.OffsetHigh = offsetHigh;
 1.33568 +    return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
 1.33569 +  }else{
 1.33570 +    return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
 1.33571 +                      numBytesHigh);
 1.33572 +  }
 1.33573 +#endif
 1.33574 +}
 1.33575 +
 1.33576 +/*
 1.33577 +** Unlock a file region.
 1.33578 + */
 1.33579 +static BOOL winUnlockFile(
 1.33580 +  LPHANDLE phFile,
 1.33581 +  DWORD offsetLow,
 1.33582 +  DWORD offsetHigh,
 1.33583 +  DWORD numBytesLow,
 1.33584 +  DWORD numBytesHigh
 1.33585 +){
 1.33586 +#if SQLITE_OS_WINCE
 1.33587 +  /*
 1.33588 +  ** NOTE: Windows CE is handled differently here due its lack of the Win32
 1.33589 +  **       API UnlockFile.
 1.33590 +  */
 1.33591 +  return winceUnlockFile(phFile, offsetLow, offsetHigh,
 1.33592 +                         numBytesLow, numBytesHigh);
 1.33593 +#else
 1.33594 +  if( osIsNT() ){
 1.33595 +    OVERLAPPED ovlp;
 1.33596 +    memset(&ovlp, 0, sizeof(OVERLAPPED));
 1.33597 +    ovlp.Offset = offsetLow;
 1.33598 +    ovlp.OffsetHigh = offsetHigh;
 1.33599 +    return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
 1.33600 +  }else{
 1.33601 +    return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
 1.33602 +                        numBytesHigh);
 1.33603 +  }
 1.33604 +#endif
 1.33605 +}
 1.33606 +
 1.33607 +/*****************************************************************************
 1.33608 +** The next group of routines implement the I/O methods specified
 1.33609 +** by the sqlite3_io_methods object.
 1.33610 +******************************************************************************/
 1.33611 +
 1.33612 +/*
 1.33613 +** Some Microsoft compilers lack this definition.
 1.33614 +*/
 1.33615 +#ifndef INVALID_SET_FILE_POINTER
 1.33616 +# define INVALID_SET_FILE_POINTER ((DWORD)-1)
 1.33617 +#endif
 1.33618 +
 1.33619 +/*
 1.33620 +** Move the current position of the file handle passed as the first 
 1.33621 +** argument to offset iOffset within the file. If successful, return 0. 
 1.33622 +** Otherwise, set pFile->lastErrno and return non-zero.
 1.33623 +*/
 1.33624 +static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
 1.33625 +#if !SQLITE_OS_WINRT
 1.33626 +  LONG upperBits;                 /* Most sig. 32 bits of new offset */
 1.33627 +  LONG lowerBits;                 /* Least sig. 32 bits of new offset */
 1.33628 +  DWORD dwRet;                    /* Value returned by SetFilePointer() */
 1.33629 +  DWORD lastErrno;                /* Value returned by GetLastError() */
 1.33630 +
 1.33631 +  OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
 1.33632 +
 1.33633 +  upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
 1.33634 +  lowerBits = (LONG)(iOffset & 0xffffffff);
 1.33635 +
 1.33636 +  /* API oddity: If successful, SetFilePointer() returns a dword 
 1.33637 +  ** containing the lower 32-bits of the new file-offset. Or, if it fails,
 1.33638 +  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, 
 1.33639 +  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine 
 1.33640 +  ** whether an error has actually occurred, it is also necessary to call 
 1.33641 +  ** GetLastError().
 1.33642 +  */
 1.33643 +  dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
 1.33644 +
 1.33645 +  if( (dwRet==INVALID_SET_FILE_POINTER
 1.33646 +      && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
 1.33647 +    pFile->lastErrno = lastErrno;
 1.33648 +    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
 1.33649 +                "winSeekFile", pFile->zPath);
 1.33650 +    OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
 1.33651 +    return 1;
 1.33652 +  }
 1.33653 +
 1.33654 +  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
 1.33655 +  return 0;
 1.33656 +#else
 1.33657 +  /*
 1.33658 +  ** Same as above, except that this implementation works for WinRT.
 1.33659 +  */
 1.33660 +
 1.33661 +  LARGE_INTEGER x;                /* The new offset */
 1.33662 +  BOOL bRet;                      /* Value returned by SetFilePointerEx() */
 1.33663 +
 1.33664 +  x.QuadPart = iOffset;
 1.33665 +  bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
 1.33666 +
 1.33667 +  if(!bRet){
 1.33668 +    pFile->lastErrno = osGetLastError();
 1.33669 +    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
 1.33670 +                "winSeekFile", pFile->zPath);
 1.33671 +    OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
 1.33672 +    return 1;
 1.33673 +  }
 1.33674 +
 1.33675 +  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
 1.33676 +  return 0;
 1.33677 +#endif
 1.33678 +}
 1.33679 +
 1.33680 +#if SQLITE_MAX_MMAP_SIZE>0
 1.33681 +/* Forward references to VFS helper methods used for memory mapped files */
 1.33682 +static int winMapfile(winFile*, sqlite3_int64);
 1.33683 +static int winUnmapfile(winFile*);
 1.33684 +#endif
 1.33685 +
 1.33686 +/*
 1.33687 +** Close a file.
 1.33688 +**
 1.33689 +** It is reported that an attempt to close a handle might sometimes
 1.33690 +** fail.  This is a very unreasonable result, but Windows is notorious
 1.33691 +** for being unreasonable so I do not doubt that it might happen.  If
 1.33692 +** the close fails, we pause for 100 milliseconds and try again.  As
 1.33693 +** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
 1.33694 +** giving up and returning an error.
 1.33695 +*/
 1.33696 +#define MX_CLOSE_ATTEMPT 3
 1.33697 +static int winClose(sqlite3_file *id){
 1.33698 +  int rc, cnt = 0;
 1.33699 +  winFile *pFile = (winFile*)id;
 1.33700 +
 1.33701 +  assert( id!=0 );
 1.33702 +#ifndef SQLITE_OMIT_WAL
 1.33703 +  assert( pFile->pShm==0 );
 1.33704 +#endif
 1.33705 +  assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
 1.33706 +  OSTRACE(("CLOSE file=%p\n", pFile->h));
 1.33707 +
 1.33708 +#if SQLITE_MAX_MMAP_SIZE>0
 1.33709 +  winUnmapfile(pFile);
 1.33710 +#endif
 1.33711 +
 1.33712 +  do{
 1.33713 +    rc = osCloseHandle(pFile->h);
 1.33714 +    /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
 1.33715 +  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
 1.33716 +#if SQLITE_OS_WINCE
 1.33717 +#define WINCE_DELETION_ATTEMPTS 3
 1.33718 +  winceDestroyLock(pFile);
 1.33719 +  if( pFile->zDeleteOnClose ){
 1.33720 +    int cnt = 0;
 1.33721 +    while(
 1.33722 +           osDeleteFileW(pFile->zDeleteOnClose)==0
 1.33723 +        && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
 1.33724 +        && cnt++ < WINCE_DELETION_ATTEMPTS
 1.33725 +    ){
 1.33726 +       sqlite3_win32_sleep(100);  /* Wait a little before trying again */
 1.33727 +    }
 1.33728 +    sqlite3_free(pFile->zDeleteOnClose);
 1.33729 +  }
 1.33730 +#endif
 1.33731 +  if( rc ){
 1.33732 +    pFile->h = NULL;
 1.33733 +  }
 1.33734 +  OpenCounter(-1);
 1.33735 +  OSTRACE(("CLOSE file=%p, rc=%s\n", pFile->h, rc ? "ok" : "failed"));
 1.33736 +  return rc ? SQLITE_OK
 1.33737 +            : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
 1.33738 +                          "winClose", pFile->zPath);
 1.33739 +}
 1.33740 +
 1.33741 +/*
 1.33742 +** Read data from a file into a buffer.  Return SQLITE_OK if all
 1.33743 +** bytes were read successfully and SQLITE_IOERR if anything goes
 1.33744 +** wrong.
 1.33745 +*/
 1.33746 +static int winRead(
 1.33747 +  sqlite3_file *id,          /* File to read from */
 1.33748 +  void *pBuf,                /* Write content into this buffer */
 1.33749 +  int amt,                   /* Number of bytes to read */
 1.33750 +  sqlite3_int64 offset       /* Begin reading at this offset */
 1.33751 +){
 1.33752 +#if !SQLITE_OS_WINCE
 1.33753 +  OVERLAPPED overlapped;          /* The offset for ReadFile. */
 1.33754 +#endif
 1.33755 +  winFile *pFile = (winFile*)id;  /* file handle */
 1.33756 +  DWORD nRead;                    /* Number of bytes actually read from file */
 1.33757 +  int nRetry = 0;                 /* Number of retrys */
 1.33758 +
 1.33759 +  assert( id!=0 );
 1.33760 +  assert( amt>0 );
 1.33761 +  assert( offset>=0 );
 1.33762 +  SimulateIOError(return SQLITE_IOERR_READ);
 1.33763 +  OSTRACE(("READ file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
 1.33764 +           pFile->h, pBuf, amt, offset, pFile->locktype));
 1.33765 +
 1.33766 +#if SQLITE_MAX_MMAP_SIZE>0
 1.33767 +  /* Deal with as much of this read request as possible by transfering
 1.33768 +  ** data from the memory mapping using memcpy().  */
 1.33769 +  if( offset<pFile->mmapSize ){
 1.33770 +    if( offset+amt <= pFile->mmapSize ){
 1.33771 +      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
 1.33772 +      OSTRACE(("READ-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
 1.33773 +      return SQLITE_OK;
 1.33774 +    }else{
 1.33775 +      int nCopy = (int)(pFile->mmapSize - offset);
 1.33776 +      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
 1.33777 +      pBuf = &((u8 *)pBuf)[nCopy];
 1.33778 +      amt -= nCopy;
 1.33779 +      offset += nCopy;
 1.33780 +    }
 1.33781 +  }
 1.33782 +#endif
 1.33783 +
 1.33784 +#if SQLITE_OS_WINCE
 1.33785 +  if( winSeekFile(pFile, offset) ){
 1.33786 +    OSTRACE(("READ file=%p, rc=SQLITE_FULL\n", pFile->h));
 1.33787 +    return SQLITE_FULL;
 1.33788 +  }
 1.33789 +  while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
 1.33790 +#else
 1.33791 +  memset(&overlapped, 0, sizeof(OVERLAPPED));
 1.33792 +  overlapped.Offset = (LONG)(offset & 0xffffffff);
 1.33793 +  overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
 1.33794 +  while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
 1.33795 +         osGetLastError()!=ERROR_HANDLE_EOF ){
 1.33796 +#endif
 1.33797 +    DWORD lastErrno;
 1.33798 +    if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
 1.33799 +    pFile->lastErrno = lastErrno;
 1.33800 +    OSTRACE(("READ file=%p, rc=SQLITE_IOERR_READ\n", pFile->h));
 1.33801 +    return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
 1.33802 +                       "winRead", pFile->zPath);
 1.33803 +  }
 1.33804 +  winLogIoerr(nRetry);
 1.33805 +  if( nRead<(DWORD)amt ){
 1.33806 +    /* Unread parts of the buffer must be zero-filled */
 1.33807 +    memset(&((char*)pBuf)[nRead], 0, amt-nRead);
 1.33808 +    OSTRACE(("READ file=%p, rc=SQLITE_IOERR_SHORT_READ\n", pFile->h));
 1.33809 +    return SQLITE_IOERR_SHORT_READ;
 1.33810 +  }
 1.33811 +
 1.33812 +  OSTRACE(("READ file=%p, rc=SQLITE_OK\n", pFile->h));
 1.33813 +  return SQLITE_OK;
 1.33814 +}
 1.33815 +
 1.33816 +/*
 1.33817 +** Write data from a buffer into a file.  Return SQLITE_OK on success
 1.33818 +** or some other error code on failure.
 1.33819 +*/
 1.33820 +static int winWrite(
 1.33821 +  sqlite3_file *id,               /* File to write into */
 1.33822 +  const void *pBuf,               /* The bytes to be written */
 1.33823 +  int amt,                        /* Number of bytes to write */
 1.33824 +  sqlite3_int64 offset            /* Offset into the file to begin writing at */
 1.33825 +){
 1.33826 +  int rc = 0;                     /* True if error has occurred, else false */
 1.33827 +  winFile *pFile = (winFile*)id;  /* File handle */
 1.33828 +  int nRetry = 0;                 /* Number of retries */
 1.33829 +
 1.33830 +  assert( amt>0 );
 1.33831 +  assert( pFile );
 1.33832 +  SimulateIOError(return SQLITE_IOERR_WRITE);
 1.33833 +  SimulateDiskfullError(return SQLITE_FULL);
 1.33834 +
 1.33835 +  OSTRACE(("WRITE file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
 1.33836 +           pFile->h, pBuf, amt, offset, pFile->locktype));
 1.33837 +
 1.33838 +#if SQLITE_MAX_MMAP_SIZE>0
 1.33839 +  /* Deal with as much of this write request as possible by transfering
 1.33840 +  ** data from the memory mapping using memcpy().  */
 1.33841 +  if( offset<pFile->mmapSize ){
 1.33842 +    if( offset+amt <= pFile->mmapSize ){
 1.33843 +      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
 1.33844 +      OSTRACE(("WRITE-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
 1.33845 +      return SQLITE_OK;
 1.33846 +    }else{
 1.33847 +      int nCopy = (int)(pFile->mmapSize - offset);
 1.33848 +      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
 1.33849 +      pBuf = &((u8 *)pBuf)[nCopy];
 1.33850 +      amt -= nCopy;
 1.33851 +      offset += nCopy;
 1.33852 +    }
 1.33853 +  }
 1.33854 +#endif
 1.33855 +
 1.33856 +#if SQLITE_OS_WINCE
 1.33857 +  rc = winSeekFile(pFile, offset);
 1.33858 +  if( rc==0 ){
 1.33859 +#else
 1.33860 +  {
 1.33861 +#endif
 1.33862 +#if !SQLITE_OS_WINCE
 1.33863 +    OVERLAPPED overlapped;        /* The offset for WriteFile. */
 1.33864 +#endif
 1.33865 +    u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
 1.33866 +    int nRem = amt;               /* Number of bytes yet to be written */
 1.33867 +    DWORD nWrite;                 /* Bytes written by each WriteFile() call */
 1.33868 +    DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
 1.33869 +
 1.33870 +#if !SQLITE_OS_WINCE
 1.33871 +    memset(&overlapped, 0, sizeof(OVERLAPPED));
 1.33872 +    overlapped.Offset = (LONG)(offset & 0xffffffff);
 1.33873 +    overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
 1.33874 +#endif
 1.33875 +
 1.33876 +    while( nRem>0 ){
 1.33877 +#if SQLITE_OS_WINCE
 1.33878 +      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
 1.33879 +#else
 1.33880 +      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
 1.33881 +#endif
 1.33882 +        if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
 1.33883 +        break;
 1.33884 +      }
 1.33885 +      assert( nWrite==0 || nWrite<=(DWORD)nRem );
 1.33886 +      if( nWrite==0 || nWrite>(DWORD)nRem ){
 1.33887 +        lastErrno = osGetLastError();
 1.33888 +        break;
 1.33889 +      }
 1.33890 +#if !SQLITE_OS_WINCE
 1.33891 +      offset += nWrite;
 1.33892 +      overlapped.Offset = (LONG)(offset & 0xffffffff);
 1.33893 +      overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
 1.33894 +#endif
 1.33895 +      aRem += nWrite;
 1.33896 +      nRem -= nWrite;
 1.33897 +    }
 1.33898 +    if( nRem>0 ){
 1.33899 +      pFile->lastErrno = lastErrno;
 1.33900 +      rc = 1;
 1.33901 +    }
 1.33902 +  }
 1.33903 +
 1.33904 +  if( rc ){
 1.33905 +    if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
 1.33906 +       || ( pFile->lastErrno==ERROR_DISK_FULL )){
 1.33907 +      OSTRACE(("WRITE file=%p, rc=SQLITE_FULL\n", pFile->h));
 1.33908 +      return winLogError(SQLITE_FULL, pFile->lastErrno,
 1.33909 +                         "winWrite1", pFile->zPath);
 1.33910 +    }
 1.33911 +    OSTRACE(("WRITE file=%p, rc=SQLITE_IOERR_WRITE\n", pFile->h));
 1.33912 +    return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
 1.33913 +                       "winWrite2", pFile->zPath);
 1.33914 +  }else{
 1.33915 +    winLogIoerr(nRetry);
 1.33916 +  }
 1.33917 +  OSTRACE(("WRITE file=%p, rc=SQLITE_OK\n", pFile->h));
 1.33918 +  return SQLITE_OK;
 1.33919 +}
 1.33920 +
 1.33921 +/*
 1.33922 +** Truncate an open file to a specified size
 1.33923 +*/
 1.33924 +static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
 1.33925 +  winFile *pFile = (winFile*)id;  /* File handle object */
 1.33926 +  int rc = SQLITE_OK;             /* Return code for this function */
 1.33927 +  DWORD lastErrno;
 1.33928 +
 1.33929 +  assert( pFile );
 1.33930 +  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
 1.33931 +  OSTRACE(("TRUNCATE file=%p, size=%lld, lock=%d\n",
 1.33932 +           pFile->h, nByte, pFile->locktype));
 1.33933 +
 1.33934 +  /* If the user has configured a chunk-size for this file, truncate the
 1.33935 +  ** file so that it consists of an integer number of chunks (i.e. the
 1.33936 +  ** actual file size after the operation may be larger than the requested
 1.33937 +  ** size).
 1.33938 +  */
 1.33939 +  if( pFile->szChunk>0 ){
 1.33940 +    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
 1.33941 +  }
 1.33942 +
 1.33943 +  /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
 1.33944 +  if( winSeekFile(pFile, nByte) ){
 1.33945 +    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
 1.33946 +                     "winTruncate1", pFile->zPath);
 1.33947 +  }else if( 0==osSetEndOfFile(pFile->h) &&
 1.33948 +            ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
 1.33949 +    pFile->lastErrno = lastErrno;
 1.33950 +    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
 1.33951 +                     "winTruncate2", pFile->zPath);
 1.33952 +  }
 1.33953 +
 1.33954 +#if SQLITE_MAX_MMAP_SIZE>0
 1.33955 +  /* If the file was truncated to a size smaller than the currently
 1.33956 +  ** mapped region, reduce the effective mapping size as well. SQLite will
 1.33957 +  ** use read() and write() to access data beyond this point from now on.
 1.33958 +  */
 1.33959 +  if( pFile->pMapRegion && nByte<pFile->mmapSize ){
 1.33960 +    pFile->mmapSize = nByte;
 1.33961 +  }
 1.33962 +#endif
 1.33963 +
 1.33964 +  OSTRACE(("TRUNCATE file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
 1.33965 +  return rc;
 1.33966 +}
 1.33967 +
 1.33968 +#ifdef SQLITE_TEST
 1.33969 +/*
 1.33970 +** Count the number of fullsyncs and normal syncs.  This is used to test
 1.33971 +** that syncs and fullsyncs are occuring at the right times.
 1.33972 +*/
 1.33973 +SQLITE_API int sqlite3_sync_count = 0;
 1.33974 +SQLITE_API int sqlite3_fullsync_count = 0;
 1.33975 +#endif
 1.33976 +
 1.33977 +/*
 1.33978 +** Make sure all writes to a particular file are committed to disk.
 1.33979 +*/
 1.33980 +static int winSync(sqlite3_file *id, int flags){
 1.33981 +#ifndef SQLITE_NO_SYNC
 1.33982 +  /*
 1.33983 +  ** Used only when SQLITE_NO_SYNC is not defined.
 1.33984 +   */
 1.33985 +  BOOL rc;
 1.33986 +#endif
 1.33987 +#if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
 1.33988 +    (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
 1.33989 +  /*
 1.33990 +  ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
 1.33991 +  ** OSTRACE() macros.
 1.33992 +   */
 1.33993 +  winFile *pFile = (winFile*)id;
 1.33994 +#else
 1.33995 +  UNUSED_PARAMETER(id);
 1.33996 +#endif
 1.33997 +
 1.33998 +  assert( pFile );
 1.33999 +  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
 1.34000 +  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
 1.34001 +      || (flags&0x0F)==SQLITE_SYNC_FULL
 1.34002 +  );
 1.34003 +
 1.34004 +  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
 1.34005 +  ** line is to test that doing so does not cause any problems.
 1.34006 +  */
 1.34007 +  SimulateDiskfullError( return SQLITE_FULL );
 1.34008 +
 1.34009 +  OSTRACE(("SYNC file=%p, flags=%x, lock=%d\n",
 1.34010 +           pFile->h, flags, pFile->locktype));
 1.34011 +
 1.34012 +#ifndef SQLITE_TEST
 1.34013 +  UNUSED_PARAMETER(flags);
 1.34014 +#else
 1.34015 +  if( (flags&0x0F)==SQLITE_SYNC_FULL ){
 1.34016 +    sqlite3_fullsync_count++;
 1.34017 +  }
 1.34018 +  sqlite3_sync_count++;
 1.34019 +#endif
 1.34020 +
 1.34021 +  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
 1.34022 +  ** no-op
 1.34023 +  */
 1.34024 +#ifdef SQLITE_NO_SYNC
 1.34025 +  OSTRACE(("SYNC-NOP file=%p, rc=SQLITE_OK\n", pFile->h));
 1.34026 +  return SQLITE_OK;
 1.34027 +#else
 1.34028 +  rc = osFlushFileBuffers(pFile->h);
 1.34029 +  SimulateIOError( rc=FALSE );
 1.34030 +  if( rc ){
 1.34031 +    OSTRACE(("SYNC file=%p, rc=SQLITE_OK\n", pFile->h));
 1.34032 +    return SQLITE_OK;
 1.34033 +  }else{
 1.34034 +    pFile->lastErrno = osGetLastError();
 1.34035 +    OSTRACE(("SYNC file=%p, rc=SQLITE_IOERR_FSYNC\n", pFile->h));
 1.34036 +    return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
 1.34037 +                       "winSync", pFile->zPath);
 1.34038 +  }
 1.34039 +#endif
 1.34040 +}
 1.34041 +
 1.34042 +/*
 1.34043 +** Determine the current size of a file in bytes
 1.34044 +*/
 1.34045 +static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
 1.34046 +  winFile *pFile = (winFile*)id;
 1.34047 +  int rc = SQLITE_OK;
 1.34048 +
 1.34049 +  assert( id!=0 );
 1.34050 +  assert( pSize!=0 );
 1.34051 +  SimulateIOError(return SQLITE_IOERR_FSTAT);
 1.34052 +  OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
 1.34053 +
 1.34054 +#if SQLITE_OS_WINRT
 1.34055 +  {
 1.34056 +    FILE_STANDARD_INFO info;
 1.34057 +    if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
 1.34058 +                                     &info, sizeof(info)) ){
 1.34059 +      *pSize = info.EndOfFile.QuadPart;
 1.34060 +    }else{
 1.34061 +      pFile->lastErrno = osGetLastError();
 1.34062 +      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
 1.34063 +                       "winFileSize", pFile->zPath);
 1.34064 +    }
 1.34065 +  }
 1.34066 +#else
 1.34067 +  {
 1.34068 +    DWORD upperBits;
 1.34069 +    DWORD lowerBits;
 1.34070 +    DWORD lastErrno;
 1.34071 +
 1.34072 +    lowerBits = osGetFileSize(pFile->h, &upperBits);
 1.34073 +    *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
 1.34074 +    if(   (lowerBits == INVALID_FILE_SIZE)
 1.34075 +       && ((lastErrno = osGetLastError())!=NO_ERROR) ){
 1.34076 +      pFile->lastErrno = lastErrno;
 1.34077 +      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
 1.34078 +                       "winFileSize", pFile->zPath);
 1.34079 +    }
 1.34080 +  }
 1.34081 +#endif
 1.34082 +  OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
 1.34083 +           pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
 1.34084 +  return rc;
 1.34085 +}
 1.34086 +
 1.34087 +/*
 1.34088 +** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
 1.34089 +*/
 1.34090 +#ifndef LOCKFILE_FAIL_IMMEDIATELY
 1.34091 +# define LOCKFILE_FAIL_IMMEDIATELY 1
 1.34092 +#endif
 1.34093 +
 1.34094 +#ifndef LOCKFILE_EXCLUSIVE_LOCK
 1.34095 +# define LOCKFILE_EXCLUSIVE_LOCK 2
 1.34096 +#endif
 1.34097 +
 1.34098 +/*
 1.34099 +** Historically, SQLite has used both the LockFile and LockFileEx functions.
 1.34100 +** When the LockFile function was used, it was always expected to fail
 1.34101 +** immediately if the lock could not be obtained.  Also, it always expected to
 1.34102 +** obtain an exclusive lock.  These flags are used with the LockFileEx function
 1.34103 +** and reflect those expectations; therefore, they should not be changed.
 1.34104 +*/
 1.34105 +#ifndef SQLITE_LOCKFILE_FLAGS
 1.34106 +# define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
 1.34107 +                                  LOCKFILE_EXCLUSIVE_LOCK)
 1.34108 +#endif
 1.34109 +
 1.34110 +/*
 1.34111 +** Currently, SQLite never calls the LockFileEx function without wanting the
 1.34112 +** call to fail immediately if the lock cannot be obtained.
 1.34113 +*/
 1.34114 +#ifndef SQLITE_LOCKFILEEX_FLAGS
 1.34115 +# define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
 1.34116 +#endif
 1.34117 +
 1.34118 +/*
 1.34119 +** Acquire a reader lock.
 1.34120 +** Different API routines are called depending on whether or not this
 1.34121 +** is Win9x or WinNT.
 1.34122 +*/
 1.34123 +static int winGetReadLock(winFile *pFile){
 1.34124 +  int res;
 1.34125 +  OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
 1.34126 +  if( osIsNT() ){
 1.34127 +#if SQLITE_OS_WINCE
 1.34128 +    /*
 1.34129 +    ** NOTE: Windows CE is handled differently here due its lack of the Win32
 1.34130 +    **       API LockFileEx.
 1.34131 +    */
 1.34132 +    res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
 1.34133 +#else
 1.34134 +    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
 1.34135 +                      SHARED_SIZE, 0);
 1.34136 +#endif
 1.34137 +  }
 1.34138 +#ifdef SQLITE_WIN32_HAS_ANSI
 1.34139 +  else{
 1.34140 +    int lk;
 1.34141 +    sqlite3_randomness(sizeof(lk), &lk);
 1.34142 +    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
 1.34143 +    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
 1.34144 +                      SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
 1.34145 +  }
 1.34146 +#endif
 1.34147 +  if( res == 0 ){
 1.34148 +    pFile->lastErrno = osGetLastError();
 1.34149 +    /* No need to log a failure to lock */
 1.34150 +  }
 1.34151 +  OSTRACE(("READ-LOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
 1.34152 +  return res;
 1.34153 +}
 1.34154 +
 1.34155 +/*
 1.34156 +** Undo a readlock
 1.34157 +*/
 1.34158 +static int winUnlockReadLock(winFile *pFile){
 1.34159 +  int res;
 1.34160 +  DWORD lastErrno;
 1.34161 +  OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
 1.34162 +  if( osIsNT() ){
 1.34163 +    res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
 1.34164 +  }
 1.34165 +#ifdef SQLITE_WIN32_HAS_ANSI
 1.34166 +  else{
 1.34167 +    res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
 1.34168 +  }
 1.34169 +#endif
 1.34170 +  if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
 1.34171 +    pFile->lastErrno = lastErrno;
 1.34172 +    winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
 1.34173 +                "winUnlockReadLock", pFile->zPath);
 1.34174 +  }
 1.34175 +  OSTRACE(("READ-UNLOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
 1.34176 +  return res;
 1.34177 +}
 1.34178 +
 1.34179 +/*
 1.34180 +** Lock the file with the lock specified by parameter locktype - one
 1.34181 +** of the following:
 1.34182 +**
 1.34183 +**     (1) SHARED_LOCK
 1.34184 +**     (2) RESERVED_LOCK
 1.34185 +**     (3) PENDING_LOCK
 1.34186 +**     (4) EXCLUSIVE_LOCK
 1.34187 +**
 1.34188 +** Sometimes when requesting one lock state, additional lock states
 1.34189 +** are inserted in between.  The locking might fail on one of the later
 1.34190 +** transitions leaving the lock state different from what it started but
 1.34191 +** still short of its goal.  The following chart shows the allowed
 1.34192 +** transitions and the inserted intermediate states:
 1.34193 +**
 1.34194 +**    UNLOCKED -> SHARED
 1.34195 +**    SHARED -> RESERVED
 1.34196 +**    SHARED -> (PENDING) -> EXCLUSIVE
 1.34197 +**    RESERVED -> (PENDING) -> EXCLUSIVE
 1.34198 +**    PENDING -> EXCLUSIVE
 1.34199 +**
 1.34200 +** This routine will only increase a lock.  The winUnlock() routine
 1.34201 +** erases all locks at once and returns us immediately to locking level 0.
 1.34202 +** It is not possible to lower the locking level one step at a time.  You
 1.34203 +** must go straight to locking level 0.
 1.34204 +*/
 1.34205 +static int winLock(sqlite3_file *id, int locktype){
 1.34206 +  int rc = SQLITE_OK;    /* Return code from subroutines */
 1.34207 +  int res = 1;           /* Result of a Windows lock call */
 1.34208 +  int newLocktype;       /* Set pFile->locktype to this value before exiting */
 1.34209 +  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
 1.34210 +  winFile *pFile = (winFile*)id;
 1.34211 +  DWORD lastErrno = NO_ERROR;
 1.34212 +
 1.34213 +  assert( id!=0 );
 1.34214 +  OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
 1.34215 +           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
 1.34216 +
 1.34217 +  /* If there is already a lock of this type or more restrictive on the
 1.34218 +  ** OsFile, do nothing. Don't use the end_lock: exit path, as
 1.34219 +  ** sqlite3OsEnterMutex() hasn't been called yet.
 1.34220 +  */
 1.34221 +  if( pFile->locktype>=locktype ){
 1.34222 +    OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
 1.34223 +    return SQLITE_OK;
 1.34224 +  }
 1.34225 +
 1.34226 +  /* Make sure the locking sequence is correct
 1.34227 +  */
 1.34228 +  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
 1.34229 +  assert( locktype!=PENDING_LOCK );
 1.34230 +  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
 1.34231 +
 1.34232 +  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
 1.34233 +  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
 1.34234 +  ** the PENDING_LOCK byte is temporary.
 1.34235 +  */
 1.34236 +  newLocktype = pFile->locktype;
 1.34237 +  if(   (pFile->locktype==NO_LOCK)
 1.34238 +     || (   (locktype==EXCLUSIVE_LOCK)
 1.34239 +         && (pFile->locktype==RESERVED_LOCK))
 1.34240 +  ){
 1.34241 +    int cnt = 3;
 1.34242 +    while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
 1.34243 +                                         PENDING_BYTE, 0, 1, 0))==0 ){
 1.34244 +      /* Try 3 times to get the pending lock.  This is needed to work
 1.34245 +      ** around problems caused by indexing and/or anti-virus software on
 1.34246 +      ** Windows systems.
 1.34247 +      ** If you are using this code as a model for alternative VFSes, do not
 1.34248 +      ** copy this retry logic.  It is a hack intended for Windows only.
 1.34249 +      */
 1.34250 +      OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, rc=%s\n",
 1.34251 +               pFile->h, cnt, sqlite3ErrName(res)));
 1.34252 +      if( cnt ) sqlite3_win32_sleep(1);
 1.34253 +    }
 1.34254 +    gotPendingLock = res;
 1.34255 +    if( !res ){
 1.34256 +      lastErrno = osGetLastError();
 1.34257 +    }
 1.34258 +  }
 1.34259 +
 1.34260 +  /* Acquire a shared lock
 1.34261 +  */
 1.34262 +  if( locktype==SHARED_LOCK && res ){
 1.34263 +    assert( pFile->locktype==NO_LOCK );
 1.34264 +    res = winGetReadLock(pFile);
 1.34265 +    if( res ){
 1.34266 +      newLocktype = SHARED_LOCK;
 1.34267 +    }else{
 1.34268 +      lastErrno = osGetLastError();
 1.34269 +    }
 1.34270 +  }
 1.34271 +
 1.34272 +  /* Acquire a RESERVED lock
 1.34273 +  */
 1.34274 +  if( locktype==RESERVED_LOCK && res ){
 1.34275 +    assert( pFile->locktype==SHARED_LOCK );
 1.34276 +    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
 1.34277 +    if( res ){
 1.34278 +      newLocktype = RESERVED_LOCK;
 1.34279 +    }else{
 1.34280 +      lastErrno = osGetLastError();
 1.34281 +    }
 1.34282 +  }
 1.34283 +
 1.34284 +  /* Acquire a PENDING lock
 1.34285 +  */
 1.34286 +  if( locktype==EXCLUSIVE_LOCK && res ){
 1.34287 +    newLocktype = PENDING_LOCK;
 1.34288 +    gotPendingLock = 0;
 1.34289 +  }
 1.34290 +
 1.34291 +  /* Acquire an EXCLUSIVE lock
 1.34292 +  */
 1.34293 +  if( locktype==EXCLUSIVE_LOCK && res ){
 1.34294 +    assert( pFile->locktype>=SHARED_LOCK );
 1.34295 +    res = winUnlockReadLock(pFile);
 1.34296 +    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
 1.34297 +                      SHARED_SIZE, 0);
 1.34298 +    if( res ){
 1.34299 +      newLocktype = EXCLUSIVE_LOCK;
 1.34300 +    }else{
 1.34301 +      lastErrno = osGetLastError();
 1.34302 +      winGetReadLock(pFile);
 1.34303 +    }
 1.34304 +  }
 1.34305 +
 1.34306 +  /* If we are holding a PENDING lock that ought to be released, then
 1.34307 +  ** release it now.
 1.34308 +  */
 1.34309 +  if( gotPendingLock && locktype==SHARED_LOCK ){
 1.34310 +    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
 1.34311 +  }
 1.34312 +
 1.34313 +  /* Update the state of the lock has held in the file descriptor then
 1.34314 +  ** return the appropriate result code.
 1.34315 +  */
 1.34316 +  if( res ){
 1.34317 +    rc = SQLITE_OK;
 1.34318 +  }else{
 1.34319 +    pFile->lastErrno = lastErrno;
 1.34320 +    rc = SQLITE_BUSY;
 1.34321 +    OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
 1.34322 +             pFile->h, locktype, newLocktype));
 1.34323 +  }
 1.34324 +  pFile->locktype = (u8)newLocktype;
 1.34325 +  OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
 1.34326 +           pFile->h, pFile->locktype, sqlite3ErrName(rc)));
 1.34327 +  return rc;
 1.34328 +}
 1.34329 +
 1.34330 +/*
 1.34331 +** This routine checks if there is a RESERVED lock held on the specified
 1.34332 +** file by this or any other process. If such a lock is held, return
 1.34333 +** non-zero, otherwise zero.
 1.34334 +*/
 1.34335 +static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
 1.34336 +  int rc;
 1.34337 +  winFile *pFile = (winFile*)id;
 1.34338 +
 1.34339 +  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
 1.34340 +  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
 1.34341 +
 1.34342 +  assert( id!=0 );
 1.34343 +  if( pFile->locktype>=RESERVED_LOCK ){
 1.34344 +    rc = 1;
 1.34345 +    OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (local)\n", pFile->h, rc));
 1.34346 +  }else{
 1.34347 +    rc = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
 1.34348 +    if( rc ){
 1.34349 +      winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
 1.34350 +    }
 1.34351 +    rc = !rc;
 1.34352 +    OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (remote)\n", pFile->h, rc));
 1.34353 +  }
 1.34354 +  *pResOut = rc;
 1.34355 +  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
 1.34356 +           pFile->h, pResOut, *pResOut));
 1.34357 +  return SQLITE_OK;
 1.34358 +}
 1.34359 +
 1.34360 +/*
 1.34361 +** Lower the locking level on file descriptor id to locktype.  locktype
 1.34362 +** must be either NO_LOCK or SHARED_LOCK.
 1.34363 +**
 1.34364 +** If the locking level of the file descriptor is already at or below
 1.34365 +** the requested locking level, this routine is a no-op.
 1.34366 +**
 1.34367 +** It is not possible for this routine to fail if the second argument
 1.34368 +** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
 1.34369 +** might return SQLITE_IOERR;
 1.34370 +*/
 1.34371 +static int winUnlock(sqlite3_file *id, int locktype){
 1.34372 +  int type;
 1.34373 +  winFile *pFile = (winFile*)id;
 1.34374 +  int rc = SQLITE_OK;
 1.34375 +  assert( pFile!=0 );
 1.34376 +  assert( locktype<=SHARED_LOCK );
 1.34377 +  OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
 1.34378 +           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
 1.34379 +  type = pFile->locktype;
 1.34380 +  if( type>=EXCLUSIVE_LOCK ){
 1.34381 +    winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
 1.34382 +    if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
 1.34383 +      /* This should never happen.  We should always be able to
 1.34384 +      ** reacquire the read lock */
 1.34385 +      rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
 1.34386 +                       "winUnlock", pFile->zPath);
 1.34387 +    }
 1.34388 +  }
 1.34389 +  if( type>=RESERVED_LOCK ){
 1.34390 +    winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
 1.34391 +  }
 1.34392 +  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
 1.34393 +    winUnlockReadLock(pFile);
 1.34394 +  }
 1.34395 +  if( type>=PENDING_LOCK ){
 1.34396 +    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
 1.34397 +  }
 1.34398 +  pFile->locktype = (u8)locktype;
 1.34399 +  OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
 1.34400 +           pFile->h, pFile->locktype, sqlite3ErrName(rc)));
 1.34401 +  return rc;
 1.34402 +}
 1.34403 +
 1.34404 +/*
 1.34405 +** If *pArg is inititially negative then this is a query.  Set *pArg to
 1.34406 +** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
 1.34407 +**
 1.34408 +** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
 1.34409 +*/
 1.34410 +static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
 1.34411 +  if( *pArg<0 ){
 1.34412 +    *pArg = (pFile->ctrlFlags & mask)!=0;
 1.34413 +  }else if( (*pArg)==0 ){
 1.34414 +    pFile->ctrlFlags &= ~mask;
 1.34415 +  }else{
 1.34416 +    pFile->ctrlFlags |= mask;
 1.34417 +  }
 1.34418 +}
 1.34419 +
 1.34420 +/* Forward references to VFS helper methods used for temporary files */
 1.34421 +static int winGetTempname(sqlite3_vfs *, char **);
 1.34422 +static int winIsDir(const void *);
 1.34423 +static BOOL winIsDriveLetterAndColon(const char *);
 1.34424 +
 1.34425 +/*
 1.34426 +** Control and query of the open file handle.
 1.34427 +*/
 1.34428 +static int winFileControl(sqlite3_file *id, int op, void *pArg){
 1.34429 +  winFile *pFile = (winFile*)id;
 1.34430 +  OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
 1.34431 +  switch( op ){
 1.34432 +    case SQLITE_FCNTL_LOCKSTATE: {
 1.34433 +      *(int*)pArg = pFile->locktype;
 1.34434 +      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 1.34435 +      return SQLITE_OK;
 1.34436 +    }
 1.34437 +    case SQLITE_LAST_ERRNO: {
 1.34438 +      *(int*)pArg = (int)pFile->lastErrno;
 1.34439 +      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 1.34440 +      return SQLITE_OK;
 1.34441 +    }
 1.34442 +    case SQLITE_FCNTL_CHUNK_SIZE: {
 1.34443 +      pFile->szChunk = *(int *)pArg;
 1.34444 +      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 1.34445 +      return SQLITE_OK;
 1.34446 +    }
 1.34447 +    case SQLITE_FCNTL_SIZE_HINT: {
 1.34448 +      if( pFile->szChunk>0 ){
 1.34449 +        sqlite3_int64 oldSz;
 1.34450 +        int rc = winFileSize(id, &oldSz);
 1.34451 +        if( rc==SQLITE_OK ){
 1.34452 +          sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
 1.34453 +          if( newSz>oldSz ){
 1.34454 +            SimulateIOErrorBenign(1);
 1.34455 +            rc = winTruncate(id, newSz);
 1.34456 +            SimulateIOErrorBenign(0);
 1.34457 +          }
 1.34458 +        }
 1.34459 +        OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
 1.34460 +        return rc;
 1.34461 +      }
 1.34462 +      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 1.34463 +      return SQLITE_OK;
 1.34464 +    }
 1.34465 +    case SQLITE_FCNTL_PERSIST_WAL: {
 1.34466 +      winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
 1.34467 +      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 1.34468 +      return SQLITE_OK;
 1.34469 +    }
 1.34470 +    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
 1.34471 +      winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
 1.34472 +      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 1.34473 +      return SQLITE_OK;
 1.34474 +    }
 1.34475 +    case SQLITE_FCNTL_VFSNAME: {
 1.34476 +      *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
 1.34477 +      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 1.34478 +      return SQLITE_OK;
 1.34479 +    }
 1.34480 +    case SQLITE_FCNTL_WIN32_AV_RETRY: {
 1.34481 +      int *a = (int*)pArg;
 1.34482 +      if( a[0]>0 ){
 1.34483 +        winIoerrRetry = a[0];
 1.34484 +      }else{
 1.34485 +        a[0] = winIoerrRetry;
 1.34486 +      }
 1.34487 +      if( a[1]>0 ){
 1.34488 +        winIoerrRetryDelay = a[1];
 1.34489 +      }else{
 1.34490 +        a[1] = winIoerrRetryDelay;
 1.34491 +      }
 1.34492 +      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 1.34493 +      return SQLITE_OK;
 1.34494 +    }
 1.34495 +    case SQLITE_FCNTL_TEMPFILENAME: {
 1.34496 +      char *zTFile = 0;
 1.34497 +      int rc = winGetTempname(pFile->pVfs, &zTFile);
 1.34498 +      if( rc==SQLITE_OK ){
 1.34499 +        *(char**)pArg = zTFile;
 1.34500 +      }
 1.34501 +      OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
 1.34502 +      return rc;
 1.34503 +    }
 1.34504 +#if SQLITE_MAX_MMAP_SIZE>0
 1.34505 +    case SQLITE_FCNTL_MMAP_SIZE: {
 1.34506 +      i64 newLimit = *(i64*)pArg;
 1.34507 +      int rc = SQLITE_OK;
 1.34508 +      if( newLimit>sqlite3GlobalConfig.mxMmap ){
 1.34509 +        newLimit = sqlite3GlobalConfig.mxMmap;
 1.34510 +      }
 1.34511 +      *(i64*)pArg = pFile->mmapSizeMax;
 1.34512 +      if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
 1.34513 +        pFile->mmapSizeMax = newLimit;
 1.34514 +        if( pFile->mmapSize>0 ){
 1.34515 +          winUnmapfile(pFile);
 1.34516 +          rc = winMapfile(pFile, -1);
 1.34517 +        }
 1.34518 +      }
 1.34519 +      OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
 1.34520 +      return rc;
 1.34521 +    }
 1.34522 +#endif
 1.34523 +  }
 1.34524 +  OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
 1.34525 +  return SQLITE_NOTFOUND;
 1.34526 +}
 1.34527 +
 1.34528 +/*
 1.34529 +** Return the sector size in bytes of the underlying block device for
 1.34530 +** the specified file. This is almost always 512 bytes, but may be
 1.34531 +** larger for some devices.
 1.34532 +**
 1.34533 +** SQLite code assumes this function cannot fail. It also assumes that
 1.34534 +** if two files are created in the same file-system directory (i.e.
 1.34535 +** a database and its journal file) that the sector size will be the
 1.34536 +** same for both.
 1.34537 +*/
 1.34538 +static int winSectorSize(sqlite3_file *id){
 1.34539 +  (void)id;
 1.34540 +  return SQLITE_DEFAULT_SECTOR_SIZE;
 1.34541 +}
 1.34542 +
 1.34543 +/*
 1.34544 +** Return a vector of device characteristics.
 1.34545 +*/
 1.34546 +static int winDeviceCharacteristics(sqlite3_file *id){
 1.34547 +  winFile *p = (winFile*)id;
 1.34548 +  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
 1.34549 +         ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
 1.34550 +}
 1.34551 +
 1.34552 +/* 
 1.34553 +** Windows will only let you create file view mappings
 1.34554 +** on allocation size granularity boundaries.
 1.34555 +** During sqlite3_os_init() we do a GetSystemInfo()
 1.34556 +** to get the granularity size.
 1.34557 +*/
 1.34558 +static SYSTEM_INFO winSysInfo;
 1.34559 +
 1.34560 +#ifndef SQLITE_OMIT_WAL
 1.34561 +
 1.34562 +/*
 1.34563 +** Helper functions to obtain and relinquish the global mutex. The
 1.34564 +** global mutex is used to protect the winLockInfo objects used by 
 1.34565 +** this file, all of which may be shared by multiple threads.
 1.34566 +**
 1.34567 +** Function winShmMutexHeld() is used to assert() that the global mutex 
 1.34568 +** is held when required. This function is only used as part of assert() 
 1.34569 +** statements. e.g.
 1.34570 +**
 1.34571 +**   winShmEnterMutex()
 1.34572 +**     assert( winShmMutexHeld() );
 1.34573 +**   winShmLeaveMutex()
 1.34574 +*/
 1.34575 +static void winShmEnterMutex(void){
 1.34576 +  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
 1.34577 +}
 1.34578 +static void winShmLeaveMutex(void){
 1.34579 +  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
 1.34580 +}
 1.34581 +#ifndef NDEBUG
 1.34582 +static int winShmMutexHeld(void) {
 1.34583 +  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
 1.34584 +}
 1.34585 +#endif
 1.34586 +
 1.34587 +/*
 1.34588 +** Object used to represent a single file opened and mmapped to provide
 1.34589 +** shared memory.  When multiple threads all reference the same
 1.34590 +** log-summary, each thread has its own winFile object, but they all
 1.34591 +** point to a single instance of this object.  In other words, each
 1.34592 +** log-summary is opened only once per process.
 1.34593 +**
 1.34594 +** winShmMutexHeld() must be true when creating or destroying
 1.34595 +** this object or while reading or writing the following fields:
 1.34596 +**
 1.34597 +**      nRef
 1.34598 +**      pNext 
 1.34599 +**
 1.34600 +** The following fields are read-only after the object is created:
 1.34601 +** 
 1.34602 +**      fid
 1.34603 +**      zFilename
 1.34604 +**
 1.34605 +** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
 1.34606 +** winShmMutexHeld() is true when reading or writing any other field
 1.34607 +** in this structure.
 1.34608 +**
 1.34609 +*/
 1.34610 +struct winShmNode {
 1.34611 +  sqlite3_mutex *mutex;      /* Mutex to access this object */
 1.34612 +  char *zFilename;           /* Name of the file */
 1.34613 +  winFile hFile;             /* File handle from winOpen */
 1.34614 +
 1.34615 +  int szRegion;              /* Size of shared-memory regions */
 1.34616 +  int nRegion;               /* Size of array apRegion */
 1.34617 +  struct ShmRegion {
 1.34618 +    HANDLE hMap;             /* File handle from CreateFileMapping */
 1.34619 +    void *pMap;
 1.34620 +  } *aRegion;
 1.34621 +  DWORD lastErrno;           /* The Windows errno from the last I/O error */
 1.34622 +
 1.34623 +  int nRef;                  /* Number of winShm objects pointing to this */
 1.34624 +  winShm *pFirst;            /* All winShm objects pointing to this */
 1.34625 +  winShmNode *pNext;         /* Next in list of all winShmNode objects */
 1.34626 +#ifdef SQLITE_DEBUG
 1.34627 +  u8 nextShmId;              /* Next available winShm.id value */
 1.34628 +#endif
 1.34629 +};
 1.34630 +
 1.34631 +/*
 1.34632 +** A global array of all winShmNode objects.
 1.34633 +**
 1.34634 +** The winShmMutexHeld() must be true while reading or writing this list.
 1.34635 +*/
 1.34636 +static winShmNode *winShmNodeList = 0;
 1.34637 +
 1.34638 +/*
 1.34639 +** Structure used internally by this VFS to record the state of an
 1.34640 +** open shared memory connection.
 1.34641 +**
 1.34642 +** The following fields are initialized when this object is created and
 1.34643 +** are read-only thereafter:
 1.34644 +**
 1.34645 +**    winShm.pShmNode
 1.34646 +**    winShm.id
 1.34647 +**
 1.34648 +** All other fields are read/write.  The winShm.pShmNode->mutex must be held
 1.34649 +** while accessing any read/write fields.
 1.34650 +*/
 1.34651 +struct winShm {
 1.34652 +  winShmNode *pShmNode;      /* The underlying winShmNode object */
 1.34653 +  winShm *pNext;             /* Next winShm with the same winShmNode */
 1.34654 +  u8 hasMutex;               /* True if holding the winShmNode mutex */
 1.34655 +  u16 sharedMask;            /* Mask of shared locks held */
 1.34656 +  u16 exclMask;              /* Mask of exclusive locks held */
 1.34657 +#ifdef SQLITE_DEBUG
 1.34658 +  u8 id;                     /* Id of this connection with its winShmNode */
 1.34659 +#endif
 1.34660 +};
 1.34661 +
 1.34662 +/*
 1.34663 +** Constants used for locking
 1.34664 +*/
 1.34665 +#define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
 1.34666 +#define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
 1.34667 +
 1.34668 +/*
 1.34669 +** Apply advisory locks for all n bytes beginning at ofst.
 1.34670 +*/
 1.34671 +#define _SHM_UNLCK  1
 1.34672 +#define _SHM_RDLCK  2
 1.34673 +#define _SHM_WRLCK  3
 1.34674 +static int winShmSystemLock(
 1.34675 +  winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
 1.34676 +  int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
 1.34677 +  int ofst,             /* Offset to first byte to be locked/unlocked */
 1.34678 +  int nByte             /* Number of bytes to lock or unlock */
 1.34679 +){
 1.34680 +  int rc = 0;           /* Result code form Lock/UnlockFileEx() */
 1.34681 +
 1.34682 +  /* Access to the winShmNode object is serialized by the caller */
 1.34683 +  assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
 1.34684 +
 1.34685 +  OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
 1.34686 +           pFile->hFile.h, lockType, ofst, nByte));
 1.34687 +
 1.34688 +  /* Release/Acquire the system-level lock */
 1.34689 +  if( lockType==_SHM_UNLCK ){
 1.34690 +    rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
 1.34691 +  }else{
 1.34692 +    /* Initialize the locking parameters */
 1.34693 +    DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
 1.34694 +    if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
 1.34695 +    rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
 1.34696 +  }
 1.34697 +  
 1.34698 +  if( rc!= 0 ){
 1.34699 +    rc = SQLITE_OK;
 1.34700 +  }else{
 1.34701 +    pFile->lastErrno =  osGetLastError();
 1.34702 +    rc = SQLITE_BUSY;
 1.34703 +  }
 1.34704 +
 1.34705 +  OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
 1.34706 +           pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
 1.34707 +           "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
 1.34708 +
 1.34709 +  return rc;
 1.34710 +}
 1.34711 +
 1.34712 +/* Forward references to VFS methods */
 1.34713 +static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
 1.34714 +static int winDelete(sqlite3_vfs *,const char*,int);
 1.34715 +
 1.34716 +/*
 1.34717 +** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
 1.34718 +**
 1.34719 +** This is not a VFS shared-memory method; it is a utility function called
 1.34720 +** by VFS shared-memory methods.
 1.34721 +*/
 1.34722 +static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
 1.34723 +  winShmNode **pp;
 1.34724 +  winShmNode *p;
 1.34725 +  assert( winShmMutexHeld() );
 1.34726 +  OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
 1.34727 +           osGetCurrentProcessId(), deleteFlag));
 1.34728 +  pp = &winShmNodeList;
 1.34729 +  while( (p = *pp)!=0 ){
 1.34730 +    if( p->nRef==0 ){
 1.34731 +      int i;
 1.34732 +      if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
 1.34733 +      for(i=0; i<p->nRegion; i++){
 1.34734 +        BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
 1.34735 +        OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
 1.34736 +                 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
 1.34737 +        UNUSED_VARIABLE_VALUE(bRc);
 1.34738 +        bRc = osCloseHandle(p->aRegion[i].hMap);
 1.34739 +        OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
 1.34740 +                 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
 1.34741 +        UNUSED_VARIABLE_VALUE(bRc);
 1.34742 +      }
 1.34743 +      if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
 1.34744 +        SimulateIOErrorBenign(1);
 1.34745 +        winClose((sqlite3_file *)&p->hFile);
 1.34746 +        SimulateIOErrorBenign(0);
 1.34747 +      }
 1.34748 +      if( deleteFlag ){
 1.34749 +        SimulateIOErrorBenign(1);
 1.34750 +        sqlite3BeginBenignMalloc();
 1.34751 +        winDelete(pVfs, p->zFilename, 0);
 1.34752 +        sqlite3EndBenignMalloc();
 1.34753 +        SimulateIOErrorBenign(0);
 1.34754 +      }
 1.34755 +      *pp = p->pNext;
 1.34756 +      sqlite3_free(p->aRegion);
 1.34757 +      sqlite3_free(p);
 1.34758 +    }else{
 1.34759 +      pp = &p->pNext;
 1.34760 +    }
 1.34761 +  }
 1.34762 +}
 1.34763 +
 1.34764 +/*
 1.34765 +** Open the shared-memory area associated with database file pDbFd.
 1.34766 +**
 1.34767 +** When opening a new shared-memory file, if no other instances of that
 1.34768 +** file are currently open, in this process or in other processes, then
 1.34769 +** the file must be truncated to zero length or have its header cleared.
 1.34770 +*/
 1.34771 +static int winOpenSharedMemory(winFile *pDbFd){
 1.34772 +  struct winShm *p;                  /* The connection to be opened */
 1.34773 +  struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
 1.34774 +  int rc;                            /* Result code */
 1.34775 +  struct winShmNode *pNew;           /* Newly allocated winShmNode */
 1.34776 +  int nName;                         /* Size of zName in bytes */
 1.34777 +
 1.34778 +  assert( pDbFd->pShm==0 );    /* Not previously opened */
 1.34779 +
 1.34780 +  /* Allocate space for the new sqlite3_shm object.  Also speculatively
 1.34781 +  ** allocate space for a new winShmNode and filename.
 1.34782 +  */
 1.34783 +  p = sqlite3MallocZero( sizeof(*p) );
 1.34784 +  if( p==0 ) return SQLITE_IOERR_NOMEM;
 1.34785 +  nName = sqlite3Strlen30(pDbFd->zPath);
 1.34786 +  pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
 1.34787 +  if( pNew==0 ){
 1.34788 +    sqlite3_free(p);
 1.34789 +    return SQLITE_IOERR_NOMEM;
 1.34790 +  }
 1.34791 +  pNew->zFilename = (char*)&pNew[1];
 1.34792 +  sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
 1.34793 +  sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename); 
 1.34794 +
 1.34795 +  /* Look to see if there is an existing winShmNode that can be used.
 1.34796 +  ** If no matching winShmNode currently exists, create a new one.
 1.34797 +  */
 1.34798 +  winShmEnterMutex();
 1.34799 +  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
 1.34800 +    /* TBD need to come up with better match here.  Perhaps
 1.34801 +    ** use FILE_ID_BOTH_DIR_INFO Structure.
 1.34802 +    */
 1.34803 +    if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
 1.34804 +  }
 1.34805 +  if( pShmNode ){
 1.34806 +    sqlite3_free(pNew);
 1.34807 +  }else{
 1.34808 +    pShmNode = pNew;
 1.34809 +    pNew = 0;
 1.34810 +    ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
 1.34811 +    pShmNode->pNext = winShmNodeList;
 1.34812 +    winShmNodeList = pShmNode;
 1.34813 +
 1.34814 +    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
 1.34815 +    if( pShmNode->mutex==0 ){
 1.34816 +      rc = SQLITE_IOERR_NOMEM;
 1.34817 +      goto shm_open_err;
 1.34818 +    }
 1.34819 +
 1.34820 +    rc = winOpen(pDbFd->pVfs,
 1.34821 +                 pShmNode->zFilename,             /* Name of the file (UTF-8) */
 1.34822 +                 (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
 1.34823 +                 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
 1.34824 +                 0);
 1.34825 +    if( SQLITE_OK!=rc ){
 1.34826 +      goto shm_open_err;
 1.34827 +    }
 1.34828 +
 1.34829 +    /* Check to see if another process is holding the dead-man switch.
 1.34830 +    ** If not, truncate the file to zero length. 
 1.34831 +    */
 1.34832 +    if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
 1.34833 +      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
 1.34834 +      if( rc!=SQLITE_OK ){
 1.34835 +        rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
 1.34836 +                         "winOpenShm", pDbFd->zPath);
 1.34837 +      }
 1.34838 +    }
 1.34839 +    if( rc==SQLITE_OK ){
 1.34840 +      winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
 1.34841 +      rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
 1.34842 +    }
 1.34843 +    if( rc ) goto shm_open_err;
 1.34844 +  }
 1.34845 +
 1.34846 +  /* Make the new connection a child of the winShmNode */
 1.34847 +  p->pShmNode = pShmNode;
 1.34848 +#ifdef SQLITE_DEBUG
 1.34849 +  p->id = pShmNode->nextShmId++;
 1.34850 +#endif
 1.34851 +  pShmNode->nRef++;
 1.34852 +  pDbFd->pShm = p;
 1.34853 +  winShmLeaveMutex();
 1.34854 +
 1.34855 +  /* The reference count on pShmNode has already been incremented under
 1.34856 +  ** the cover of the winShmEnterMutex() mutex and the pointer from the
 1.34857 +  ** new (struct winShm) object to the pShmNode has been set. All that is
 1.34858 +  ** left to do is to link the new object into the linked list starting
 1.34859 +  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
 1.34860 +  ** mutex.
 1.34861 +  */
 1.34862 +  sqlite3_mutex_enter(pShmNode->mutex);
 1.34863 +  p->pNext = pShmNode->pFirst;
 1.34864 +  pShmNode->pFirst = p;
 1.34865 +  sqlite3_mutex_leave(pShmNode->mutex);
 1.34866 +  return SQLITE_OK;
 1.34867 +
 1.34868 +  /* Jump here on any error */
 1.34869 +shm_open_err:
 1.34870 +  winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
 1.34871 +  winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
 1.34872 +  sqlite3_free(p);
 1.34873 +  sqlite3_free(pNew);
 1.34874 +  winShmLeaveMutex();
 1.34875 +  return rc;
 1.34876 +}
 1.34877 +
 1.34878 +/*
 1.34879 +** Close a connection to shared-memory.  Delete the underlying 
 1.34880 +** storage if deleteFlag is true.
 1.34881 +*/
 1.34882 +static int winShmUnmap(
 1.34883 +  sqlite3_file *fd,          /* Database holding shared memory */
 1.34884 +  int deleteFlag             /* Delete after closing if true */
 1.34885 +){
 1.34886 +  winFile *pDbFd;       /* Database holding shared-memory */
 1.34887 +  winShm *p;            /* The connection to be closed */
 1.34888 +  winShmNode *pShmNode; /* The underlying shared-memory file */
 1.34889 +  winShm **pp;          /* For looping over sibling connections */
 1.34890 +
 1.34891 +  pDbFd = (winFile*)fd;
 1.34892 +  p = pDbFd->pShm;
 1.34893 +  if( p==0 ) return SQLITE_OK;
 1.34894 +  pShmNode = p->pShmNode;
 1.34895 +
 1.34896 +  /* Remove connection p from the set of connections associated
 1.34897 +  ** with pShmNode */
 1.34898 +  sqlite3_mutex_enter(pShmNode->mutex);
 1.34899 +  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
 1.34900 +  *pp = p->pNext;
 1.34901 +
 1.34902 +  /* Free the connection p */
 1.34903 +  sqlite3_free(p);
 1.34904 +  pDbFd->pShm = 0;
 1.34905 +  sqlite3_mutex_leave(pShmNode->mutex);
 1.34906 +
 1.34907 +  /* If pShmNode->nRef has reached 0, then close the underlying
 1.34908 +  ** shared-memory file, too */
 1.34909 +  winShmEnterMutex();
 1.34910 +  assert( pShmNode->nRef>0 );
 1.34911 +  pShmNode->nRef--;
 1.34912 +  if( pShmNode->nRef==0 ){
 1.34913 +    winShmPurge(pDbFd->pVfs, deleteFlag);
 1.34914 +  }
 1.34915 +  winShmLeaveMutex();
 1.34916 +
 1.34917 +  return SQLITE_OK;
 1.34918 +}
 1.34919 +
 1.34920 +/*
 1.34921 +** Change the lock state for a shared-memory segment.
 1.34922 +*/
 1.34923 +static int winShmLock(
 1.34924 +  sqlite3_file *fd,          /* Database file holding the shared memory */
 1.34925 +  int ofst,                  /* First lock to acquire or release */
 1.34926 +  int n,                     /* Number of locks to acquire or release */
 1.34927 +  int flags                  /* What to do with the lock */
 1.34928 +){
 1.34929 +  winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
 1.34930 +  winShm *p = pDbFd->pShm;              /* The shared memory being locked */
 1.34931 +  winShm *pX;                           /* For looping over all siblings */
 1.34932 +  winShmNode *pShmNode = p->pShmNode;
 1.34933 +  int rc = SQLITE_OK;                   /* Result code */
 1.34934 +  u16 mask;                             /* Mask of locks to take or release */
 1.34935 +
 1.34936 +  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
 1.34937 +  assert( n>=1 );
 1.34938 +  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
 1.34939 +       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
 1.34940 +       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
 1.34941 +       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
 1.34942 +  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
 1.34943 +
 1.34944 +  mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
 1.34945 +  assert( n>1 || mask==(1<<ofst) );
 1.34946 +  sqlite3_mutex_enter(pShmNode->mutex);
 1.34947 +  if( flags & SQLITE_SHM_UNLOCK ){
 1.34948 +    u16 allMask = 0; /* Mask of locks held by siblings */
 1.34949 +
 1.34950 +    /* See if any siblings hold this same lock */
 1.34951 +    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
 1.34952 +      if( pX==p ) continue;
 1.34953 +      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
 1.34954 +      allMask |= pX->sharedMask;
 1.34955 +    }
 1.34956 +
 1.34957 +    /* Unlock the system-level locks */
 1.34958 +    if( (mask & allMask)==0 ){
 1.34959 +      rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
 1.34960 +    }else{
 1.34961 +      rc = SQLITE_OK;
 1.34962 +    }
 1.34963 +
 1.34964 +    /* Undo the local locks */
 1.34965 +    if( rc==SQLITE_OK ){
 1.34966 +      p->exclMask &= ~mask;
 1.34967 +      p->sharedMask &= ~mask;
 1.34968 +    } 
 1.34969 +  }else if( flags & SQLITE_SHM_SHARED ){
 1.34970 +    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
 1.34971 +
 1.34972 +    /* Find out which shared locks are already held by sibling connections.
 1.34973 +    ** If any sibling already holds an exclusive lock, go ahead and return
 1.34974 +    ** SQLITE_BUSY.
 1.34975 +    */
 1.34976 +    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
 1.34977 +      if( (pX->exclMask & mask)!=0 ){
 1.34978 +        rc = SQLITE_BUSY;
 1.34979 +        break;
 1.34980 +      }
 1.34981 +      allShared |= pX->sharedMask;
 1.34982 +    }
 1.34983 +
 1.34984 +    /* Get shared locks at the system level, if necessary */
 1.34985 +    if( rc==SQLITE_OK ){
 1.34986 +      if( (allShared & mask)==0 ){
 1.34987 +        rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
 1.34988 +      }else{
 1.34989 +        rc = SQLITE_OK;
 1.34990 +      }
 1.34991 +    }
 1.34992 +
 1.34993 +    /* Get the local shared locks */
 1.34994 +    if( rc==SQLITE_OK ){
 1.34995 +      p->sharedMask |= mask;
 1.34996 +    }
 1.34997 +  }else{
 1.34998 +    /* Make sure no sibling connections hold locks that will block this
 1.34999 +    ** lock.  If any do, return SQLITE_BUSY right away.
 1.35000 +    */
 1.35001 +    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
 1.35002 +      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
 1.35003 +        rc = SQLITE_BUSY;
 1.35004 +        break;
 1.35005 +      }
 1.35006 +    }
 1.35007 +  
 1.35008 +    /* Get the exclusive locks at the system level.  Then if successful
 1.35009 +    ** also mark the local connection as being locked.
 1.35010 +    */
 1.35011 +    if( rc==SQLITE_OK ){
 1.35012 +      rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
 1.35013 +      if( rc==SQLITE_OK ){
 1.35014 +        assert( (p->sharedMask & mask)==0 );
 1.35015 +        p->exclMask |= mask;
 1.35016 +      }
 1.35017 +    }
 1.35018 +  }
 1.35019 +  sqlite3_mutex_leave(pShmNode->mutex);
 1.35020 +  OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
 1.35021 +           osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
 1.35022 +           sqlite3ErrName(rc)));
 1.35023 +  return rc;
 1.35024 +}
 1.35025 +
 1.35026 +/*
 1.35027 +** Implement a memory barrier or memory fence on shared memory.  
 1.35028 +**
 1.35029 +** All loads and stores begun before the barrier must complete before
 1.35030 +** any load or store begun after the barrier.
 1.35031 +*/
 1.35032 +static void winShmBarrier(
 1.35033 +  sqlite3_file *fd          /* Database holding the shared memory */
 1.35034 +){
 1.35035 +  UNUSED_PARAMETER(fd);
 1.35036 +  /* MemoryBarrier(); // does not work -- do not know why not */
 1.35037 +  winShmEnterMutex();
 1.35038 +  winShmLeaveMutex();
 1.35039 +}
 1.35040 +
 1.35041 +/*
 1.35042 +** This function is called to obtain a pointer to region iRegion of the 
 1.35043 +** shared-memory associated with the database file fd. Shared-memory regions 
 1.35044 +** are numbered starting from zero. Each shared-memory region is szRegion 
 1.35045 +** bytes in size.
 1.35046 +**
 1.35047 +** If an error occurs, an error code is returned and *pp is set to NULL.
 1.35048 +**
 1.35049 +** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
 1.35050 +** region has not been allocated (by any client, including one running in a
 1.35051 +** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
 1.35052 +** isWrite is non-zero and the requested shared-memory region has not yet 
 1.35053 +** been allocated, it is allocated by this function.
 1.35054 +**
 1.35055 +** If the shared-memory region has already been allocated or is allocated by
 1.35056 +** this call as described above, then it is mapped into this processes 
 1.35057 +** address space (if it is not already), *pp is set to point to the mapped 
 1.35058 +** memory and SQLITE_OK returned.
 1.35059 +*/
 1.35060 +static int winShmMap(
 1.35061 +  sqlite3_file *fd,               /* Handle open on database file */
 1.35062 +  int iRegion,                    /* Region to retrieve */
 1.35063 +  int szRegion,                   /* Size of regions */
 1.35064 +  int isWrite,                    /* True to extend file if necessary */
 1.35065 +  void volatile **pp              /* OUT: Mapped memory */
 1.35066 +){
 1.35067 +  winFile *pDbFd = (winFile*)fd;
 1.35068 +  winShm *p = pDbFd->pShm;
 1.35069 +  winShmNode *pShmNode;
 1.35070 +  int rc = SQLITE_OK;
 1.35071 +
 1.35072 +  if( !p ){
 1.35073 +    rc = winOpenSharedMemory(pDbFd);
 1.35074 +    if( rc!=SQLITE_OK ) return rc;
 1.35075 +    p = pDbFd->pShm;
 1.35076 +  }
 1.35077 +  pShmNode = p->pShmNode;
 1.35078 +
 1.35079 +  sqlite3_mutex_enter(pShmNode->mutex);
 1.35080 +  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
 1.35081 +
 1.35082 +  if( pShmNode->nRegion<=iRegion ){
 1.35083 +    struct ShmRegion *apNew;           /* New aRegion[] array */
 1.35084 +    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
 1.35085 +    sqlite3_int64 sz;                  /* Current size of wal-index file */
 1.35086 +
 1.35087 +    pShmNode->szRegion = szRegion;
 1.35088 +
 1.35089 +    /* The requested region is not mapped into this processes address space.
 1.35090 +    ** Check to see if it has been allocated (i.e. if the wal-index file is
 1.35091 +    ** large enough to contain the requested region).
 1.35092 +    */
 1.35093 +    rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
 1.35094 +    if( rc!=SQLITE_OK ){
 1.35095 +      rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
 1.35096 +                       "winShmMap1", pDbFd->zPath);
 1.35097 +      goto shmpage_out;
 1.35098 +    }
 1.35099 +
 1.35100 +    if( sz<nByte ){
 1.35101 +      /* The requested memory region does not exist. If isWrite is set to
 1.35102 +      ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
 1.35103 +      **
 1.35104 +      ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
 1.35105 +      ** the requested memory region.
 1.35106 +      */
 1.35107 +      if( !isWrite ) goto shmpage_out;
 1.35108 +      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
 1.35109 +      if( rc!=SQLITE_OK ){
 1.35110 +        rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
 1.35111 +                         "winShmMap2", pDbFd->zPath);
 1.35112 +        goto shmpage_out;
 1.35113 +      }
 1.35114 +    }
 1.35115 +
 1.35116 +    /* Map the requested memory region into this processes address space. */
 1.35117 +    apNew = (struct ShmRegion *)sqlite3_realloc(
 1.35118 +        pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
 1.35119 +    );
 1.35120 +    if( !apNew ){
 1.35121 +      rc = SQLITE_IOERR_NOMEM;
 1.35122 +      goto shmpage_out;
 1.35123 +    }
 1.35124 +    pShmNode->aRegion = apNew;
 1.35125 +
 1.35126 +    while( pShmNode->nRegion<=iRegion ){
 1.35127 +      HANDLE hMap = NULL;         /* file-mapping handle */
 1.35128 +      void *pMap = 0;             /* Mapped memory region */
 1.35129 +     
 1.35130 +#if SQLITE_OS_WINRT
 1.35131 +      hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
 1.35132 +          NULL, PAGE_READWRITE, nByte, NULL
 1.35133 +      );
 1.35134 +#elif defined(SQLITE_WIN32_HAS_WIDE)
 1.35135 +      hMap = osCreateFileMappingW(pShmNode->hFile.h, 
 1.35136 +          NULL, PAGE_READWRITE, 0, nByte, NULL
 1.35137 +      );
 1.35138 +#elif defined(SQLITE_WIN32_HAS_ANSI)
 1.35139 +      hMap = osCreateFileMappingA(pShmNode->hFile.h, 
 1.35140 +          NULL, PAGE_READWRITE, 0, nByte, NULL
 1.35141 +      );
 1.35142 +#endif
 1.35143 +      OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
 1.35144 +               osGetCurrentProcessId(), pShmNode->nRegion, nByte,
 1.35145 +               hMap ? "ok" : "failed"));
 1.35146 +      if( hMap ){
 1.35147 +        int iOffset = pShmNode->nRegion*szRegion;
 1.35148 +        int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
 1.35149 +#if SQLITE_OS_WINRT
 1.35150 +        pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
 1.35151 +            iOffset - iOffsetShift, szRegion + iOffsetShift
 1.35152 +        );
 1.35153 +#else
 1.35154 +        pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
 1.35155 +            0, iOffset - iOffsetShift, szRegion + iOffsetShift
 1.35156 +        );
 1.35157 +#endif
 1.35158 +        OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
 1.35159 +                 osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
 1.35160 +                 szRegion, pMap ? "ok" : "failed"));
 1.35161 +      }
 1.35162 +      if( !pMap ){
 1.35163 +        pShmNode->lastErrno = osGetLastError();
 1.35164 +        rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
 1.35165 +                         "winShmMap3", pDbFd->zPath);
 1.35166 +        if( hMap ) osCloseHandle(hMap);
 1.35167 +        goto shmpage_out;
 1.35168 +      }
 1.35169 +
 1.35170 +      pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
 1.35171 +      pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
 1.35172 +      pShmNode->nRegion++;
 1.35173 +    }
 1.35174 +  }
 1.35175 +
 1.35176 +shmpage_out:
 1.35177 +  if( pShmNode->nRegion>iRegion ){
 1.35178 +    int iOffset = iRegion*szRegion;
 1.35179 +    int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
 1.35180 +    char *p = (char *)pShmNode->aRegion[iRegion].pMap;
 1.35181 +    *pp = (void *)&p[iOffsetShift];
 1.35182 +  }else{
 1.35183 +    *pp = 0;
 1.35184 +  }
 1.35185 +  sqlite3_mutex_leave(pShmNode->mutex);
 1.35186 +  return rc;
 1.35187 +}
 1.35188 +
 1.35189 +#else
 1.35190 +# define winShmMap     0
 1.35191 +# define winShmLock    0
 1.35192 +# define winShmBarrier 0
 1.35193 +# define winShmUnmap   0
 1.35194 +#endif /* #ifndef SQLITE_OMIT_WAL */
 1.35195 +
 1.35196 +/*
 1.35197 +** Cleans up the mapped region of the specified file, if any.
 1.35198 +*/
 1.35199 +#if SQLITE_MAX_MMAP_SIZE>0
 1.35200 +static int winUnmapfile(winFile *pFile){
 1.35201 +  assert( pFile!=0 );
 1.35202 +  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
 1.35203 +           "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
 1.35204 +           osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
 1.35205 +           pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
 1.35206 +  if( pFile->pMapRegion ){
 1.35207 +    if( !osUnmapViewOfFile(pFile->pMapRegion) ){
 1.35208 +      pFile->lastErrno = osGetLastError();
 1.35209 +      OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
 1.35210 +               "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
 1.35211 +               pFile->pMapRegion));
 1.35212 +      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
 1.35213 +                         "winUnmapfile1", pFile->zPath);
 1.35214 +    }
 1.35215 +    pFile->pMapRegion = 0;
 1.35216 +    pFile->mmapSize = 0;
 1.35217 +    pFile->mmapSizeActual = 0;
 1.35218 +  }
 1.35219 +  if( pFile->hMap!=NULL ){
 1.35220 +    if( !osCloseHandle(pFile->hMap) ){
 1.35221 +      pFile->lastErrno = osGetLastError();
 1.35222 +      OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
 1.35223 +               osGetCurrentProcessId(), pFile, pFile->hMap));
 1.35224 +      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
 1.35225 +                         "winUnmapfile2", pFile->zPath);
 1.35226 +    }
 1.35227 +    pFile->hMap = NULL;
 1.35228 +  }
 1.35229 +  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
 1.35230 +           osGetCurrentProcessId(), pFile));
 1.35231 +  return SQLITE_OK;
 1.35232 +}
 1.35233 +
 1.35234 +/*
 1.35235 +** Memory map or remap the file opened by file-descriptor pFd (if the file
 1.35236 +** is already mapped, the existing mapping is replaced by the new). Or, if 
 1.35237 +** there already exists a mapping for this file, and there are still 
 1.35238 +** outstanding xFetch() references to it, this function is a no-op.
 1.35239 +**
 1.35240 +** If parameter nByte is non-negative, then it is the requested size of 
 1.35241 +** the mapping to create. Otherwise, if nByte is less than zero, then the 
 1.35242 +** requested size is the size of the file on disk. The actual size of the
 1.35243 +** created mapping is either the requested size or the value configured 
 1.35244 +** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
 1.35245 +**
 1.35246 +** SQLITE_OK is returned if no error occurs (even if the mapping is not
 1.35247 +** recreated as a result of outstanding references) or an SQLite error
 1.35248 +** code otherwise.
 1.35249 +*/
 1.35250 +static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
 1.35251 +  sqlite3_int64 nMap = nByte;
 1.35252 +  int rc;
 1.35253 +
 1.35254 +  assert( nMap>=0 || pFd->nFetchOut==0 );
 1.35255 +  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
 1.35256 +           osGetCurrentProcessId(), pFd, nByte));
 1.35257 +
 1.35258 +  if( pFd->nFetchOut>0 ) return SQLITE_OK;
 1.35259 +
 1.35260 +  if( nMap<0 ){
 1.35261 +    rc = winFileSize((sqlite3_file*)pFd, &nMap);
 1.35262 +    if( rc ){
 1.35263 +      OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
 1.35264 +               osGetCurrentProcessId(), pFd));
 1.35265 +      return SQLITE_IOERR_FSTAT;
 1.35266 +    }
 1.35267 +  }
 1.35268 +  if( nMap>pFd->mmapSizeMax ){
 1.35269 +    nMap = pFd->mmapSizeMax;
 1.35270 +  }
 1.35271 +  nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
 1.35272 + 
 1.35273 +  if( nMap==0 && pFd->mmapSize>0 ){
 1.35274 +    winUnmapfile(pFd);
 1.35275 +  }
 1.35276 +  if( nMap!=pFd->mmapSize ){
 1.35277 +    void *pNew = 0;
 1.35278 +    DWORD protect = PAGE_READONLY;
 1.35279 +    DWORD flags = FILE_MAP_READ;
 1.35280 +
 1.35281 +    winUnmapfile(pFd);
 1.35282 +    if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
 1.35283 +      protect = PAGE_READWRITE;
 1.35284 +      flags |= FILE_MAP_WRITE;
 1.35285 +    }
 1.35286 +#if SQLITE_OS_WINRT
 1.35287 +    pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
 1.35288 +#elif defined(SQLITE_WIN32_HAS_WIDE)
 1.35289 +    pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
 1.35290 +                                (DWORD)((nMap>>32) & 0xffffffff),
 1.35291 +                                (DWORD)(nMap & 0xffffffff), NULL);
 1.35292 +#elif defined(SQLITE_WIN32_HAS_ANSI)
 1.35293 +    pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
 1.35294 +                                (DWORD)((nMap>>32) & 0xffffffff),
 1.35295 +                                (DWORD)(nMap & 0xffffffff), NULL);
 1.35296 +#endif
 1.35297 +    if( pFd->hMap==NULL ){
 1.35298 +      pFd->lastErrno = osGetLastError();
 1.35299 +      rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
 1.35300 +                       "winMapfile1", pFd->zPath);
 1.35301 +      /* Log the error, but continue normal operation using xRead/xWrite */
 1.35302 +      OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
 1.35303 +               osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
 1.35304 +      return SQLITE_OK;
 1.35305 +    }
 1.35306 +    assert( (nMap % winSysInfo.dwPageSize)==0 );
 1.35307 +    assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
 1.35308 +#if SQLITE_OS_WINRT
 1.35309 +    pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
 1.35310 +#else
 1.35311 +    pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
 1.35312 +#endif
 1.35313 +    if( pNew==NULL ){
 1.35314 +      osCloseHandle(pFd->hMap);
 1.35315 +      pFd->hMap = NULL;
 1.35316 +      pFd->lastErrno = osGetLastError();
 1.35317 +      rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
 1.35318 +                       "winMapfile2", pFd->zPath);
 1.35319 +      /* Log the error, but continue normal operation using xRead/xWrite */
 1.35320 +      OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
 1.35321 +               osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
 1.35322 +      return SQLITE_OK;
 1.35323 +    }
 1.35324 +    pFd->pMapRegion = pNew;
 1.35325 +    pFd->mmapSize = nMap;
 1.35326 +    pFd->mmapSizeActual = nMap;
 1.35327 +  }
 1.35328 +
 1.35329 +  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
 1.35330 +           osGetCurrentProcessId(), pFd));
 1.35331 +  return SQLITE_OK;
 1.35332 +}
 1.35333 +#endif /* SQLITE_MAX_MMAP_SIZE>0 */
 1.35334 +
 1.35335 +/*
 1.35336 +** If possible, return a pointer to a mapping of file fd starting at offset
 1.35337 +** iOff. The mapping must be valid for at least nAmt bytes.
 1.35338 +**
 1.35339 +** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
 1.35340 +** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
 1.35341 +** Finally, if an error does occur, return an SQLite error code. The final
 1.35342 +** value of *pp is undefined in this case.
 1.35343 +**
 1.35344 +** If this function does return a pointer, the caller must eventually 
 1.35345 +** release the reference by calling winUnfetch().
 1.35346 +*/
 1.35347 +static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
 1.35348 +#if SQLITE_MAX_MMAP_SIZE>0
 1.35349 +  winFile *pFd = (winFile*)fd;   /* The underlying database file */
 1.35350 +#endif
 1.35351 +  *pp = 0;
 1.35352 +
 1.35353 +  OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
 1.35354 +           osGetCurrentProcessId(), fd, iOff, nAmt, pp));
 1.35355 +
 1.35356 +#if SQLITE_MAX_MMAP_SIZE>0
 1.35357 +  if( pFd->mmapSizeMax>0 ){
 1.35358 +    if( pFd->pMapRegion==0 ){
 1.35359 +      int rc = winMapfile(pFd, -1);
 1.35360 +      if( rc!=SQLITE_OK ){
 1.35361 +        OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
 1.35362 +                 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
 1.35363 +        return rc;
 1.35364 +      }
 1.35365 +    }
 1.35366 +    if( pFd->mmapSize >= iOff+nAmt ){
 1.35367 +      *pp = &((u8 *)pFd->pMapRegion)[iOff];
 1.35368 +      pFd->nFetchOut++;
 1.35369 +    }
 1.35370 +  }
 1.35371 +#endif
 1.35372 +
 1.35373 +  OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
 1.35374 +           osGetCurrentProcessId(), fd, pp, *pp));
 1.35375 +  return SQLITE_OK;
 1.35376 +}
 1.35377 +
 1.35378 +/*
 1.35379 +** If the third argument is non-NULL, then this function releases a 
 1.35380 +** reference obtained by an earlier call to winFetch(). The second
 1.35381 +** argument passed to this function must be the same as the corresponding
 1.35382 +** argument that was passed to the winFetch() invocation. 
 1.35383 +**
 1.35384 +** Or, if the third argument is NULL, then this function is being called 
 1.35385 +** to inform the VFS layer that, according to POSIX, any existing mapping 
 1.35386 +** may now be invalid and should be unmapped.
 1.35387 +*/
 1.35388 +static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
 1.35389 +#if SQLITE_MAX_MMAP_SIZE>0
 1.35390 +  winFile *pFd = (winFile*)fd;   /* The underlying database file */
 1.35391 +
 1.35392 +  /* If p==0 (unmap the entire file) then there must be no outstanding 
 1.35393 +  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
 1.35394 +  ** then there must be at least one outstanding.  */
 1.35395 +  assert( (p==0)==(pFd->nFetchOut==0) );
 1.35396 +
 1.35397 +  /* If p!=0, it must match the iOff value. */
 1.35398 +  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
 1.35399 +
 1.35400 +  OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
 1.35401 +           osGetCurrentProcessId(), pFd, iOff, p));
 1.35402 +
 1.35403 +  if( p ){
 1.35404 +    pFd->nFetchOut--;
 1.35405 +  }else{
 1.35406 +    /* FIXME:  If Windows truly always prevents truncating or deleting a
 1.35407 +    ** file while a mapping is held, then the following winUnmapfile() call
 1.35408 +    ** is unnecessary can can be omitted - potentially improving
 1.35409 +    ** performance.  */
 1.35410 +    winUnmapfile(pFd);
 1.35411 +  }
 1.35412 +
 1.35413 +  assert( pFd->nFetchOut>=0 );
 1.35414 +#endif
 1.35415 +
 1.35416 +  OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
 1.35417 +           osGetCurrentProcessId(), fd));
 1.35418 +  return SQLITE_OK;
 1.35419 +}
 1.35420 +
 1.35421 +/*
 1.35422 +** Here ends the implementation of all sqlite3_file methods.
 1.35423 +**
 1.35424 +********************** End sqlite3_file Methods *******************************
 1.35425 +******************************************************************************/
 1.35426 +
 1.35427 +/*
 1.35428 +** This vector defines all the methods that can operate on an
 1.35429 +** sqlite3_file for win32.
 1.35430 +*/
 1.35431 +static const sqlite3_io_methods winIoMethod = {
 1.35432 +  3,                              /* iVersion */
 1.35433 +  winClose,                       /* xClose */
 1.35434 +  winRead,                        /* xRead */
 1.35435 +  winWrite,                       /* xWrite */
 1.35436 +  winTruncate,                    /* xTruncate */
 1.35437 +  winSync,                        /* xSync */
 1.35438 +  winFileSize,                    /* xFileSize */
 1.35439 +  winLock,                        /* xLock */
 1.35440 +  winUnlock,                      /* xUnlock */
 1.35441 +  winCheckReservedLock,           /* xCheckReservedLock */
 1.35442 +  winFileControl,                 /* xFileControl */
 1.35443 +  winSectorSize,                  /* xSectorSize */
 1.35444 +  winDeviceCharacteristics,       /* xDeviceCharacteristics */
 1.35445 +  winShmMap,                      /* xShmMap */
 1.35446 +  winShmLock,                     /* xShmLock */
 1.35447 +  winShmBarrier,                  /* xShmBarrier */
 1.35448 +  winShmUnmap,                    /* xShmUnmap */
 1.35449 +  winFetch,                       /* xFetch */
 1.35450 +  winUnfetch                      /* xUnfetch */
 1.35451 +};
 1.35452 +
 1.35453 +/****************************************************************************
 1.35454 +**************************** sqlite3_vfs methods ****************************
 1.35455 +**
 1.35456 +** This division contains the implementation of methods on the
 1.35457 +** sqlite3_vfs object.
 1.35458 +*/
 1.35459 +
 1.35460 +#if defined(__CYGWIN__)
 1.35461 +/*
 1.35462 +** Convert a filename from whatever the underlying operating system
 1.35463 +** supports for filenames into UTF-8.  Space to hold the result is
 1.35464 +** obtained from malloc and must be freed by the calling function.
 1.35465 +*/
 1.35466 +static char *winConvertToUtf8Filename(const void *zFilename){
 1.35467 +  char *zConverted = 0;
 1.35468 +  if( osIsNT() ){
 1.35469 +    zConverted = winUnicodeToUtf8(zFilename);
 1.35470 +  }
 1.35471 +#ifdef SQLITE_WIN32_HAS_ANSI
 1.35472 +  else{
 1.35473 +    zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
 1.35474 +  }
 1.35475 +#endif
 1.35476 +  /* caller will handle out of memory */
 1.35477 +  return zConverted;
 1.35478 +}
 1.35479 +#endif
 1.35480 +
 1.35481 +/*
 1.35482 +** Convert a UTF-8 filename into whatever form the underlying
 1.35483 +** operating system wants filenames in.  Space to hold the result
 1.35484 +** is obtained from malloc and must be freed by the calling
 1.35485 +** function.
 1.35486 +*/
 1.35487 +static void *winConvertFromUtf8Filename(const char *zFilename){
 1.35488 +  void *zConverted = 0;
 1.35489 +  if( osIsNT() ){
 1.35490 +    zConverted = winUtf8ToUnicode(zFilename);
 1.35491 +  }
 1.35492 +#ifdef SQLITE_WIN32_HAS_ANSI
 1.35493 +  else{
 1.35494 +    zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
 1.35495 +  }
 1.35496 +#endif
 1.35497 +  /* caller will handle out of memory */
 1.35498 +  return zConverted;
 1.35499 +}
 1.35500 +
 1.35501 +/*
 1.35502 +** This function returns non-zero if the specified UTF-8 string buffer
 1.35503 +** ends with a directory separator character or one was successfully
 1.35504 +** added to it.
 1.35505 +*/
 1.35506 +static int winMakeEndInDirSep(int nBuf, char *zBuf){
 1.35507 +  if( zBuf ){
 1.35508 +    int nLen = sqlite3Strlen30(zBuf);
 1.35509 +    if( nLen>0 ){
 1.35510 +      if( winIsDirSep(zBuf[nLen-1]) ){
 1.35511 +        return 1;
 1.35512 +      }else if( nLen+1<nBuf ){
 1.35513 +        zBuf[nLen] = winGetDirSep();
 1.35514 +        zBuf[nLen+1] = '\0';
 1.35515 +        return 1;
 1.35516 +      }
 1.35517 +    }
 1.35518 +  }
 1.35519 +  return 0;
 1.35520 +}
 1.35521 +
 1.35522 +/*
 1.35523 +** Create a temporary file name and store the resulting pointer into pzBuf.
 1.35524 +** The pointer returned in pzBuf must be freed via sqlite3_free().
 1.35525 +*/
 1.35526 +static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
 1.35527 +  static char zChars[] =
 1.35528 +    "abcdefghijklmnopqrstuvwxyz"
 1.35529 +    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 1.35530 +    "0123456789";
 1.35531 +  size_t i, j;
 1.35532 +  int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
 1.35533 +  int nMax, nBuf, nDir, nLen;
 1.35534 +  char *zBuf;
 1.35535 +
 1.35536 +  /* It's odd to simulate an io-error here, but really this is just
 1.35537 +  ** using the io-error infrastructure to test that SQLite handles this
 1.35538 +  ** function failing. 
 1.35539 +  */
 1.35540 +  SimulateIOError( return SQLITE_IOERR );
 1.35541 +
 1.35542 +  /* Allocate a temporary buffer to store the fully qualified file
 1.35543 +  ** name for the temporary file.  If this fails, we cannot continue.
 1.35544 +  */
 1.35545 +  nMax = pVfs->mxPathname; nBuf = nMax + 2;
 1.35546 +  zBuf = sqlite3MallocZero( nBuf );
 1.35547 +  if( !zBuf ){
 1.35548 +    OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 1.35549 +    return SQLITE_IOERR_NOMEM;
 1.35550 +  }
 1.35551 +
 1.35552 +  /* Figure out the effective temporary directory.  First, check if one
 1.35553 +  ** has been explicitly set by the application; otherwise, use the one
 1.35554 +  ** configured by the operating system.
 1.35555 +  */
 1.35556 +  nDir = nMax - (nPre + 15);
 1.35557 +  assert( nDir>0 );
 1.35558 +  if( sqlite3_temp_directory ){
 1.35559 +    int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
 1.35560 +    if( nDirLen>0 ){
 1.35561 +      if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
 1.35562 +        nDirLen++;
 1.35563 +      }
 1.35564 +      if( nDirLen>nDir ){
 1.35565 +        sqlite3_free(zBuf);
 1.35566 +        OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
 1.35567 +        return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
 1.35568 +      }
 1.35569 +      sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
 1.35570 +    }
 1.35571 +  }
 1.35572 +#if defined(__CYGWIN__)
 1.35573 +  else{
 1.35574 +    static const char *azDirs[] = {
 1.35575 +       0, /* getenv("SQLITE_TMPDIR") */
 1.35576 +       0, /* getenv("TMPDIR") */
 1.35577 +       0, /* getenv("TMP") */
 1.35578 +       0, /* getenv("TEMP") */
 1.35579 +       0, /* getenv("USERPROFILE") */
 1.35580 +       "/var/tmp",
 1.35581 +       "/usr/tmp",
 1.35582 +       "/tmp",
 1.35583 +       ".",
 1.35584 +       0        /* List terminator */
 1.35585 +    };
 1.35586 +    unsigned int i;
 1.35587 +    const char *zDir = 0;
 1.35588 +
 1.35589 +    if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
 1.35590 +    if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
 1.35591 +    if( !azDirs[2] ) azDirs[2] = getenv("TMP");
 1.35592 +    if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
 1.35593 +    if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
 1.35594 +    for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
 1.35595 +      void *zConverted;
 1.35596 +      if( zDir==0 ) continue;
 1.35597 +      /* If the path starts with a drive letter followed by the colon
 1.35598 +      ** character, assume it is already a native Win32 path; otherwise,
 1.35599 +      ** it must be converted to a native Win32 path via the Cygwin API
 1.35600 +      ** prior to using it.
 1.35601 +      */
 1.35602 +      if( winIsDriveLetterAndColon(zDir) ){
 1.35603 +        zConverted = winConvertFromUtf8Filename(zDir);
 1.35604 +        if( !zConverted ){
 1.35605 +          sqlite3_free(zBuf);
 1.35606 +          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 1.35607 +          return SQLITE_IOERR_NOMEM;
 1.35608 +        }
 1.35609 +        if( winIsDir(zConverted) ){
 1.35610 +          sqlite3_snprintf(nMax, zBuf, "%s", zDir);
 1.35611 +          sqlite3_free(zConverted);
 1.35612 +          break;
 1.35613 +        }
 1.35614 +        sqlite3_free(zConverted);
 1.35615 +      }else{
 1.35616 +        zConverted = sqlite3MallocZero( nMax+1 );
 1.35617 +        if( !zConverted ){
 1.35618 +          sqlite3_free(zBuf);
 1.35619 +          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 1.35620 +          return SQLITE_IOERR_NOMEM;
 1.35621 +        }
 1.35622 +        if( cygwin_conv_path(
 1.35623 +                osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
 1.35624 +                zConverted, nMax+1)<0 ){
 1.35625 +          sqlite3_free(zConverted);
 1.35626 +          sqlite3_free(zBuf);
 1.35627 +          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
 1.35628 +          return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
 1.35629 +                             "winGetTempname2", zDir);
 1.35630 +        }
 1.35631 +        if( winIsDir(zConverted) ){
 1.35632 +          /* At this point, we know the candidate directory exists and should
 1.35633 +          ** be used.  However, we may need to convert the string containing
 1.35634 +          ** its name into UTF-8 (i.e. if it is UTF-16 right now).
 1.35635 +          */
 1.35636 +          char *zUtf8 = winConvertToUtf8Filename(zConverted);
 1.35637 +          if( !zUtf8 ){
 1.35638 +            sqlite3_free(zConverted);
 1.35639 +            sqlite3_free(zBuf);
 1.35640 +            OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 1.35641 +            return SQLITE_IOERR_NOMEM;
 1.35642 +          }
 1.35643 +          sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
 1.35644 +          sqlite3_free(zUtf8);
 1.35645 +          sqlite3_free(zConverted);
 1.35646 +          break;
 1.35647 +        }
 1.35648 +        sqlite3_free(zConverted);
 1.35649 +      }
 1.35650 +    }
 1.35651 +  }
 1.35652 +#elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
 1.35653 +  else if( osIsNT() ){
 1.35654 +    char *zMulti;
 1.35655 +    LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
 1.35656 +    if( !zWidePath ){
 1.35657 +      sqlite3_free(zBuf);
 1.35658 +      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 1.35659 +      return SQLITE_IOERR_NOMEM;
 1.35660 +    }
 1.35661 +    if( osGetTempPathW(nMax, zWidePath)==0 ){
 1.35662 +      sqlite3_free(zWidePath);
 1.35663 +      sqlite3_free(zBuf);
 1.35664 +      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
 1.35665 +      return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
 1.35666 +                         "winGetTempname2", 0);
 1.35667 +    }
 1.35668 +    zMulti = winUnicodeToUtf8(zWidePath);
 1.35669 +    if( zMulti ){
 1.35670 +      sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
 1.35671 +      sqlite3_free(zMulti);
 1.35672 +      sqlite3_free(zWidePath);
 1.35673 +    }else{
 1.35674 +      sqlite3_free(zWidePath);
 1.35675 +      sqlite3_free(zBuf);
 1.35676 +      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 1.35677 +      return SQLITE_IOERR_NOMEM;
 1.35678 +    }
 1.35679 +  }
 1.35680 +#ifdef SQLITE_WIN32_HAS_ANSI
 1.35681 +  else{
 1.35682 +    char *zUtf8;
 1.35683 +    char *zMbcsPath = sqlite3MallocZero( nMax );
 1.35684 +    if( !zMbcsPath ){
 1.35685 +      sqlite3_free(zBuf);
 1.35686 +      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 1.35687 +      return SQLITE_IOERR_NOMEM;
 1.35688 +    }
 1.35689 +    if( osGetTempPathA(nMax, zMbcsPath)==0 ){
 1.35690 +      sqlite3_free(zBuf);
 1.35691 +      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
 1.35692 +      return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
 1.35693 +                         "winGetTempname3", 0);
 1.35694 +    }
 1.35695 +    zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
 1.35696 +    if( zUtf8 ){
 1.35697 +      sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
 1.35698 +      sqlite3_free(zUtf8);
 1.35699 +    }else{
 1.35700 +      sqlite3_free(zBuf);
 1.35701 +      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 1.35702 +      return SQLITE_IOERR_NOMEM;
 1.35703 +    }
 1.35704 +  }
 1.35705 +#endif /* SQLITE_WIN32_HAS_ANSI */
 1.35706 +#endif /* !SQLITE_OS_WINRT */
 1.35707 +
 1.35708 +  /*
 1.35709 +  ** Check to make sure the temporary directory ends with an appropriate
 1.35710 +  ** separator.  If it does not and there is not enough space left to add
 1.35711 +  ** one, fail.
 1.35712 +  */
 1.35713 +  if( !winMakeEndInDirSep(nDir+1, zBuf) ){
 1.35714 +    sqlite3_free(zBuf);
 1.35715 +    OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
 1.35716 +    return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
 1.35717 +  }
 1.35718 +
 1.35719 +  /*
 1.35720 +  ** Check that the output buffer is large enough for the temporary file 
 1.35721 +  ** name in the following format:
 1.35722 +  **
 1.35723 +  **   "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
 1.35724 +  **
 1.35725 +  ** If not, return SQLITE_ERROR.  The number 17 is used here in order to
 1.35726 +  ** account for the space used by the 15 character random suffix and the
 1.35727 +  ** two trailing NUL characters.  The final directory separator character
 1.35728 +  ** has already added if it was not already present.
 1.35729 +  */
 1.35730 +  nLen = sqlite3Strlen30(zBuf);
 1.35731 +  if( (nLen + nPre + 17) > nBuf ){
 1.35732 +    sqlite3_free(zBuf);
 1.35733 +    OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
 1.35734 +    return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
 1.35735 +  }
 1.35736 +
 1.35737 +  sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
 1.35738 +
 1.35739 +  j = sqlite3Strlen30(zBuf);
 1.35740 +  sqlite3_randomness(15, &zBuf[j]);
 1.35741 +  for(i=0; i<15; i++, j++){
 1.35742 +    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
 1.35743 +  }
 1.35744 +  zBuf[j] = 0;
 1.35745 +  zBuf[j+1] = 0;
 1.35746 +  *pzBuf = zBuf;
 1.35747 +
 1.35748 +  OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
 1.35749 +  return SQLITE_OK;
 1.35750 +}
 1.35751 +
 1.35752 +/*
 1.35753 +** Return TRUE if the named file is really a directory.  Return false if
 1.35754 +** it is something other than a directory, or if there is any kind of memory
 1.35755 +** allocation failure.
 1.35756 +*/
 1.35757 +static int winIsDir(const void *zConverted){
 1.35758 +  DWORD attr;
 1.35759 +  int rc = 0;
 1.35760 +  DWORD lastErrno;
 1.35761 +
 1.35762 +  if( osIsNT() ){
 1.35763 +    int cnt = 0;
 1.35764 +    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
 1.35765 +    memset(&sAttrData, 0, sizeof(sAttrData));
 1.35766 +    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
 1.35767 +                             GetFileExInfoStandard,
 1.35768 +                             &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
 1.35769 +    if( !rc ){
 1.35770 +      return 0; /* Invalid name? */
 1.35771 +    }
 1.35772 +    attr = sAttrData.dwFileAttributes;
 1.35773 +#if SQLITE_OS_WINCE==0
 1.35774 +  }else{
 1.35775 +    attr = osGetFileAttributesA((char*)zConverted);
 1.35776 +#endif
 1.35777 +  }
 1.35778 +  return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
 1.35779 +}
 1.35780 +
 1.35781 +/*
 1.35782 +** Open a file.
 1.35783 +*/
 1.35784 +static int winOpen(
 1.35785 +  sqlite3_vfs *pVfs,        /* Used to get maximum path name length */
 1.35786 +  const char *zName,        /* Name of the file (UTF-8) */
 1.35787 +  sqlite3_file *id,         /* Write the SQLite file handle here */
 1.35788 +  int flags,                /* Open mode flags */
 1.35789 +  int *pOutFlags            /* Status return flags */
 1.35790 +){
 1.35791 +  HANDLE h;
 1.35792 +  DWORD lastErrno = 0;
 1.35793 +  DWORD dwDesiredAccess;
 1.35794 +  DWORD dwShareMode;
 1.35795 +  DWORD dwCreationDisposition;
 1.35796 +  DWORD dwFlagsAndAttributes = 0;
 1.35797 +#if SQLITE_OS_WINCE
 1.35798 +  int isTemp = 0;
 1.35799 +#endif
 1.35800 +  winFile *pFile = (winFile*)id;
 1.35801 +  void *zConverted;              /* Filename in OS encoding */
 1.35802 +  const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
 1.35803 +  int cnt = 0;
 1.35804 +
 1.35805 +  /* If argument zPath is a NULL pointer, this function is required to open
 1.35806 +  ** a temporary file. Use this buffer to store the file name in.
 1.35807 +  */
 1.35808 +  char *zTmpname = 0; /* For temporary filename, if necessary. */
 1.35809 +
 1.35810 +  int rc = SQLITE_OK;            /* Function Return Code */
 1.35811 +#if !defined(NDEBUG) || SQLITE_OS_WINCE
 1.35812 +  int eType = flags&0xFFFFFF00;  /* Type of file to open */
 1.35813 +#endif
 1.35814 +
 1.35815 +  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
 1.35816 +  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
 1.35817 +  int isCreate     = (flags & SQLITE_OPEN_CREATE);
 1.35818 +  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
 1.35819 +  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
 1.35820 +
 1.35821 +#ifndef NDEBUG
 1.35822 +  int isOpenJournal = (isCreate && (
 1.35823 +        eType==SQLITE_OPEN_MASTER_JOURNAL 
 1.35824 +     || eType==SQLITE_OPEN_MAIN_JOURNAL 
 1.35825 +     || eType==SQLITE_OPEN_WAL
 1.35826 +  ));
 1.35827 +#endif
 1.35828 +
 1.35829 +  OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
 1.35830 +           zUtf8Name, id, flags, pOutFlags));
 1.35831 +
 1.35832 +  /* Check the following statements are true: 
 1.35833 +  **
 1.35834 +  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
 1.35835 +  **   (b) if CREATE is set, then READWRITE must also be set, and
 1.35836 +  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
 1.35837 +  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
 1.35838 +  */
 1.35839 +  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
 1.35840 +  assert(isCreate==0 || isReadWrite);
 1.35841 +  assert(isExclusive==0 || isCreate);
 1.35842 +  assert(isDelete==0 || isCreate);
 1.35843 +
 1.35844 +  /* The main DB, main journal, WAL file and master journal are never 
 1.35845 +  ** automatically deleted. Nor are they ever temporary files.  */
 1.35846 +  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
 1.35847 +  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
 1.35848 +  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
 1.35849 +  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
 1.35850 +
 1.35851 +  /* Assert that the upper layer has set one of the "file-type" flags. */
 1.35852 +  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
 1.35853 +       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
 1.35854 +       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
 1.35855 +       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
 1.35856 +  );
 1.35857 +
 1.35858 +  assert( pFile!=0 );
 1.35859 +  memset(pFile, 0, sizeof(winFile));
 1.35860 +  pFile->h = INVALID_HANDLE_VALUE;
 1.35861 +
 1.35862 +#if SQLITE_OS_WINRT
 1.35863 +  if( !zUtf8Name && !sqlite3_temp_directory ){
 1.35864 +    sqlite3_log(SQLITE_ERROR,
 1.35865 +        "sqlite3_temp_directory variable should be set for WinRT");
 1.35866 +  }
 1.35867 +#endif
 1.35868 +
 1.35869 +  /* If the second argument to this function is NULL, generate a 
 1.35870 +  ** temporary file name to use 
 1.35871 +  */
 1.35872 +  if( !zUtf8Name ){
 1.35873 +    assert( isDelete && !isOpenJournal );
 1.35874 +    rc = winGetTempname(pVfs, &zTmpname);
 1.35875 +    if( rc!=SQLITE_OK ){
 1.35876 +      OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
 1.35877 +      return rc;
 1.35878 +    }
 1.35879 +    zUtf8Name = zTmpname;
 1.35880 +  }
 1.35881 +
 1.35882 +  /* Database filenames are double-zero terminated if they are not
 1.35883 +  ** URIs with parameters.  Hence, they can always be passed into
 1.35884 +  ** sqlite3_uri_parameter().
 1.35885 +  */
 1.35886 +  assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
 1.35887 +       zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
 1.35888 +
 1.35889 +  /* Convert the filename to the system encoding. */
 1.35890 +  zConverted = winConvertFromUtf8Filename(zUtf8Name);
 1.35891 +  if( zConverted==0 ){
 1.35892 +    sqlite3_free(zTmpname);
 1.35893 +    OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
 1.35894 +    return SQLITE_IOERR_NOMEM;
 1.35895 +  }
 1.35896 +
 1.35897 +  if( winIsDir(zConverted) ){
 1.35898 +    sqlite3_free(zConverted);
 1.35899 +    sqlite3_free(zTmpname);
 1.35900 +    OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
 1.35901 +    return SQLITE_CANTOPEN_ISDIR;
 1.35902 +  }
 1.35903 +
 1.35904 +  if( isReadWrite ){
 1.35905 +    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
 1.35906 +  }else{
 1.35907 +    dwDesiredAccess = GENERIC_READ;
 1.35908 +  }
 1.35909 +
 1.35910 +  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
 1.35911 +  ** created. SQLite doesn't use it to indicate "exclusive access" 
 1.35912 +  ** as it is usually understood.
 1.35913 +  */
 1.35914 +  if( isExclusive ){
 1.35915 +    /* Creates a new file, only if it does not already exist. */
 1.35916 +    /* If the file exists, it fails. */
 1.35917 +    dwCreationDisposition = CREATE_NEW;
 1.35918 +  }else if( isCreate ){
 1.35919 +    /* Open existing file, or create if it doesn't exist */
 1.35920 +    dwCreationDisposition = OPEN_ALWAYS;
 1.35921 +  }else{
 1.35922 +    /* Opens a file, only if it exists. */
 1.35923 +    dwCreationDisposition = OPEN_EXISTING;
 1.35924 +  }
 1.35925 +
 1.35926 +  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
 1.35927 +
 1.35928 +  if( isDelete ){
 1.35929 +#if SQLITE_OS_WINCE
 1.35930 +    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
 1.35931 +    isTemp = 1;
 1.35932 +#else
 1.35933 +    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
 1.35934 +                               | FILE_ATTRIBUTE_HIDDEN
 1.35935 +                               | FILE_FLAG_DELETE_ON_CLOSE;
 1.35936 +#endif
 1.35937 +  }else{
 1.35938 +    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
 1.35939 +  }
 1.35940 +  /* Reports from the internet are that performance is always
 1.35941 +  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
 1.35942 +#if SQLITE_OS_WINCE
 1.35943 +  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
 1.35944 +#endif
 1.35945 +
 1.35946 +  if( osIsNT() ){
 1.35947 +#if SQLITE_OS_WINRT
 1.35948 +    CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
 1.35949 +    extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
 1.35950 +    extendedParameters.dwFileAttributes =
 1.35951 +            dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
 1.35952 +    extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
 1.35953 +    extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
 1.35954 +    extendedParameters.lpSecurityAttributes = NULL;
 1.35955 +    extendedParameters.hTemplateFile = NULL;
 1.35956 +    while( (h = osCreateFile2((LPCWSTR)zConverted,
 1.35957 +                              dwDesiredAccess,
 1.35958 +                              dwShareMode,
 1.35959 +                              dwCreationDisposition,
 1.35960 +                              &extendedParameters))==INVALID_HANDLE_VALUE &&
 1.35961 +                              winRetryIoerr(&cnt, &lastErrno) ){
 1.35962 +               /* Noop */
 1.35963 +    }
 1.35964 +#else
 1.35965 +    while( (h = osCreateFileW((LPCWSTR)zConverted,
 1.35966 +                              dwDesiredAccess,
 1.35967 +                              dwShareMode, NULL,
 1.35968 +                              dwCreationDisposition,
 1.35969 +                              dwFlagsAndAttributes,
 1.35970 +                              NULL))==INVALID_HANDLE_VALUE &&
 1.35971 +                              winRetryIoerr(&cnt, &lastErrno) ){
 1.35972 +               /* Noop */
 1.35973 +    }
 1.35974 +#endif
 1.35975 +  }
 1.35976 +#ifdef SQLITE_WIN32_HAS_ANSI
 1.35977 +  else{
 1.35978 +    while( (h = osCreateFileA((LPCSTR)zConverted,
 1.35979 +                              dwDesiredAccess,
 1.35980 +                              dwShareMode, NULL,
 1.35981 +                              dwCreationDisposition,
 1.35982 +                              dwFlagsAndAttributes,
 1.35983 +                              NULL))==INVALID_HANDLE_VALUE &&
 1.35984 +                              winRetryIoerr(&cnt, &lastErrno) ){
 1.35985 +               /* Noop */
 1.35986 +    }
 1.35987 +  }
 1.35988 +#endif
 1.35989 +  winLogIoerr(cnt);
 1.35990 +
 1.35991 +  OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
 1.35992 +           dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
 1.35993 +
 1.35994 +  if( h==INVALID_HANDLE_VALUE ){
 1.35995 +    pFile->lastErrno = lastErrno;
 1.35996 +    winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
 1.35997 +    sqlite3_free(zConverted);
 1.35998 +    sqlite3_free(zTmpname);
 1.35999 +    if( isReadWrite && !isExclusive ){
 1.36000 +      return winOpen(pVfs, zName, id, 
 1.36001 +         ((flags|SQLITE_OPEN_READONLY) &
 1.36002 +                     ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
 1.36003 +         pOutFlags);
 1.36004 +    }else{
 1.36005 +      return SQLITE_CANTOPEN_BKPT;
 1.36006 +    }
 1.36007 +  }
 1.36008 +
 1.36009 +  if( pOutFlags ){
 1.36010 +    if( isReadWrite ){
 1.36011 +      *pOutFlags = SQLITE_OPEN_READWRITE;
 1.36012 +    }else{
 1.36013 +      *pOutFlags = SQLITE_OPEN_READONLY;
 1.36014 +    }
 1.36015 +  }
 1.36016 +
 1.36017 +  OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
 1.36018 +           "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
 1.36019 +           *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
 1.36020 +
 1.36021 +#if SQLITE_OS_WINCE
 1.36022 +  if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
 1.36023 +       && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
 1.36024 +  ){
 1.36025 +    osCloseHandle(h);
 1.36026 +    sqlite3_free(zConverted);
 1.36027 +    sqlite3_free(zTmpname);
 1.36028 +    OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
 1.36029 +    return rc;
 1.36030 +  }
 1.36031 +  if( isTemp ){
 1.36032 +    pFile->zDeleteOnClose = zConverted;
 1.36033 +  }else
 1.36034 +#endif
 1.36035 +  {
 1.36036 +    sqlite3_free(zConverted);
 1.36037 +  }
 1.36038 +
 1.36039 +  sqlite3_free(zTmpname);
 1.36040 +  pFile->pMethod = &winIoMethod;
 1.36041 +  pFile->pVfs = pVfs;
 1.36042 +  pFile->h = h;
 1.36043 +  if( isReadonly ){
 1.36044 +    pFile->ctrlFlags |= WINFILE_RDONLY;
 1.36045 +  }
 1.36046 +  if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
 1.36047 +    pFile->ctrlFlags |= WINFILE_PSOW;
 1.36048 +  }
 1.36049 +  pFile->lastErrno = NO_ERROR;
 1.36050 +  pFile->zPath = zName;
 1.36051 +#if SQLITE_MAX_MMAP_SIZE>0
 1.36052 +  pFile->hMap = NULL;
 1.36053 +  pFile->pMapRegion = 0;
 1.36054 +  pFile->mmapSize = 0;
 1.36055 +  pFile->mmapSizeActual = 0;
 1.36056 +  pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
 1.36057 +#endif
 1.36058 +
 1.36059 +  OpenCounter(+1);
 1.36060 +  return rc;
 1.36061 +}
 1.36062 +
 1.36063 +/*
 1.36064 +** Delete the named file.
 1.36065 +**
 1.36066 +** Note that Windows does not allow a file to be deleted if some other
 1.36067 +** process has it open.  Sometimes a virus scanner or indexing program
 1.36068 +** will open a journal file shortly after it is created in order to do
 1.36069 +** whatever it does.  While this other process is holding the
 1.36070 +** file open, we will be unable to delete it.  To work around this
 1.36071 +** problem, we delay 100 milliseconds and try to delete again.  Up
 1.36072 +** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
 1.36073 +** up and returning an error.
 1.36074 +*/
 1.36075 +static int winDelete(
 1.36076 +  sqlite3_vfs *pVfs,          /* Not used on win32 */
 1.36077 +  const char *zFilename,      /* Name of file to delete */
 1.36078 +  int syncDir                 /* Not used on win32 */
 1.36079 +){
 1.36080 +  int cnt = 0;
 1.36081 +  int rc;
 1.36082 +  DWORD attr;
 1.36083 +  DWORD lastErrno = 0;
 1.36084 +  void *zConverted;
 1.36085 +  UNUSED_PARAMETER(pVfs);
 1.36086 +  UNUSED_PARAMETER(syncDir);
 1.36087 +
 1.36088 +  SimulateIOError(return SQLITE_IOERR_DELETE);
 1.36089 +  OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
 1.36090 +
 1.36091 +  zConverted = winConvertFromUtf8Filename(zFilename);
 1.36092 +  if( zConverted==0 ){
 1.36093 +    OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
 1.36094 +    return SQLITE_IOERR_NOMEM;
 1.36095 +  }
 1.36096 +  if( osIsNT() ){
 1.36097 +    do {
 1.36098 +#if SQLITE_OS_WINRT
 1.36099 +      WIN32_FILE_ATTRIBUTE_DATA sAttrData;
 1.36100 +      memset(&sAttrData, 0, sizeof(sAttrData));
 1.36101 +      if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
 1.36102 +                                  &sAttrData) ){
 1.36103 +        attr = sAttrData.dwFileAttributes;
 1.36104 +      }else{
 1.36105 +        lastErrno = osGetLastError();
 1.36106 +        if( lastErrno==ERROR_FILE_NOT_FOUND
 1.36107 +         || lastErrno==ERROR_PATH_NOT_FOUND ){
 1.36108 +          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
 1.36109 +        }else{
 1.36110 +          rc = SQLITE_ERROR;
 1.36111 +        }
 1.36112 +        break;
 1.36113 +      }
 1.36114 +#else
 1.36115 +      attr = osGetFileAttributesW(zConverted);
 1.36116 +#endif
 1.36117 +      if ( attr==INVALID_FILE_ATTRIBUTES ){
 1.36118 +        lastErrno = osGetLastError();
 1.36119 +        if( lastErrno==ERROR_FILE_NOT_FOUND
 1.36120 +         || lastErrno==ERROR_PATH_NOT_FOUND ){
 1.36121 +          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
 1.36122 +        }else{
 1.36123 +          rc = SQLITE_ERROR;
 1.36124 +        }
 1.36125 +        break;
 1.36126 +      }
 1.36127 +      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
 1.36128 +        rc = SQLITE_ERROR; /* Files only. */
 1.36129 +        break;
 1.36130 +      }
 1.36131 +      if ( osDeleteFileW(zConverted) ){
 1.36132 +        rc = SQLITE_OK; /* Deleted OK. */
 1.36133 +        break;
 1.36134 +      }
 1.36135 +      if ( !winRetryIoerr(&cnt, &lastErrno) ){
 1.36136 +        rc = SQLITE_ERROR; /* No more retries. */
 1.36137 +        break;
 1.36138 +      }
 1.36139 +    } while(1);
 1.36140 +  }
 1.36141 +#ifdef SQLITE_WIN32_HAS_ANSI
 1.36142 +  else{
 1.36143 +    do {
 1.36144 +      attr = osGetFileAttributesA(zConverted);
 1.36145 +      if ( attr==INVALID_FILE_ATTRIBUTES ){
 1.36146 +        lastErrno = osGetLastError();
 1.36147 +        if( lastErrno==ERROR_FILE_NOT_FOUND
 1.36148 +         || lastErrno==ERROR_PATH_NOT_FOUND ){
 1.36149 +          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
 1.36150 +        }else{
 1.36151 +          rc = SQLITE_ERROR;
 1.36152 +        }
 1.36153 +        break;
 1.36154 +      }
 1.36155 +      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
 1.36156 +        rc = SQLITE_ERROR; /* Files only. */
 1.36157 +        break;
 1.36158 +      }
 1.36159 +      if ( osDeleteFileA(zConverted) ){
 1.36160 +        rc = SQLITE_OK; /* Deleted OK. */
 1.36161 +        break;
 1.36162 +      }
 1.36163 +      if ( !winRetryIoerr(&cnt, &lastErrno) ){
 1.36164 +        rc = SQLITE_ERROR; /* No more retries. */
 1.36165 +        break;
 1.36166 +      }
 1.36167 +    } while(1);
 1.36168 +  }
 1.36169 +#endif
 1.36170 +  if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
 1.36171 +    rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
 1.36172 +  }else{
 1.36173 +    winLogIoerr(cnt);
 1.36174 +  }
 1.36175 +  sqlite3_free(zConverted);
 1.36176 +  OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
 1.36177 +  return rc;
 1.36178 +}
 1.36179 +
 1.36180 +/*
 1.36181 +** Check the existence and status of a file.
 1.36182 +*/
 1.36183 +static int winAccess(
 1.36184 +  sqlite3_vfs *pVfs,         /* Not used on win32 */
 1.36185 +  const char *zFilename,     /* Name of file to check */
 1.36186 +  int flags,                 /* Type of test to make on this file */
 1.36187 +  int *pResOut               /* OUT: Result */
 1.36188 +){
 1.36189 +  DWORD attr;
 1.36190 +  int rc = 0;
 1.36191 +  DWORD lastErrno = 0;
 1.36192 +  void *zConverted;
 1.36193 +  UNUSED_PARAMETER(pVfs);
 1.36194 +
 1.36195 +  SimulateIOError( return SQLITE_IOERR_ACCESS; );
 1.36196 +  OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
 1.36197 +           zFilename, flags, pResOut));
 1.36198 +
 1.36199 +  zConverted = winConvertFromUtf8Filename(zFilename);
 1.36200 +  if( zConverted==0 ){
 1.36201 +    OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
 1.36202 +    return SQLITE_IOERR_NOMEM;
 1.36203 +  }
 1.36204 +  if( osIsNT() ){
 1.36205 +    int cnt = 0;
 1.36206 +    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
 1.36207 +    memset(&sAttrData, 0, sizeof(sAttrData));
 1.36208 +    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
 1.36209 +                             GetFileExInfoStandard, 
 1.36210 +                             &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
 1.36211 +    if( rc ){
 1.36212 +      /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
 1.36213 +      ** as if it does not exist.
 1.36214 +      */
 1.36215 +      if(    flags==SQLITE_ACCESS_EXISTS
 1.36216 +          && sAttrData.nFileSizeHigh==0 
 1.36217 +          && sAttrData.nFileSizeLow==0 ){
 1.36218 +        attr = INVALID_FILE_ATTRIBUTES;
 1.36219 +      }else{
 1.36220 +        attr = sAttrData.dwFileAttributes;
 1.36221 +      }
 1.36222 +    }else{
 1.36223 +      winLogIoerr(cnt);
 1.36224 +      if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
 1.36225 +        sqlite3_free(zConverted);
 1.36226 +        return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
 1.36227 +                           zFilename);
 1.36228 +      }else{
 1.36229 +        attr = INVALID_FILE_ATTRIBUTES;
 1.36230 +      }
 1.36231 +    }
 1.36232 +  }
 1.36233 +#ifdef SQLITE_WIN32_HAS_ANSI
 1.36234 +  else{
 1.36235 +    attr = osGetFileAttributesA((char*)zConverted);
 1.36236 +  }
 1.36237 +#endif
 1.36238 +  sqlite3_free(zConverted);
 1.36239 +  switch( flags ){
 1.36240 +    case SQLITE_ACCESS_READ:
 1.36241 +    case SQLITE_ACCESS_EXISTS:
 1.36242 +      rc = attr!=INVALID_FILE_ATTRIBUTES;
 1.36243 +      break;
 1.36244 +    case SQLITE_ACCESS_READWRITE:
 1.36245 +      rc = attr!=INVALID_FILE_ATTRIBUTES &&
 1.36246 +             (attr & FILE_ATTRIBUTE_READONLY)==0;
 1.36247 +      break;
 1.36248 +    default:
 1.36249 +      assert(!"Invalid flags argument");
 1.36250 +  }
 1.36251 +  *pResOut = rc;
 1.36252 +  OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
 1.36253 +           zFilename, pResOut, *pResOut));
 1.36254 +  return SQLITE_OK;
 1.36255 +}
 1.36256 +
 1.36257 +/*
 1.36258 +** Returns non-zero if the specified path name starts with a drive letter
 1.36259 +** followed by a colon character.
 1.36260 +*/
 1.36261 +static BOOL winIsDriveLetterAndColon(
 1.36262 +  const char *zPathname
 1.36263 +){
 1.36264 +  return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
 1.36265 +}
 1.36266 +
 1.36267 +/*
 1.36268 +** Returns non-zero if the specified path name should be used verbatim.  If
 1.36269 +** non-zero is returned from this function, the calling function must simply
 1.36270 +** use the provided path name verbatim -OR- resolve it into a full path name
 1.36271 +** using the GetFullPathName Win32 API function (if available).
 1.36272 +*/
 1.36273 +static BOOL winIsVerbatimPathname(
 1.36274 +  const char *zPathname
 1.36275 +){
 1.36276 +  /*
 1.36277 +  ** If the path name starts with a forward slash or a backslash, it is either
 1.36278 +  ** a legal UNC name, a volume relative path, or an absolute path name in the
 1.36279 +  ** "Unix" format on Windows.  There is no easy way to differentiate between
 1.36280 +  ** the final two cases; therefore, we return the safer return value of TRUE
 1.36281 +  ** so that callers of this function will simply use it verbatim.
 1.36282 +  */
 1.36283 +  if ( winIsDirSep(zPathname[0]) ){
 1.36284 +    return TRUE;
 1.36285 +  }
 1.36286 +
 1.36287 +  /*
 1.36288 +  ** If the path name starts with a letter and a colon it is either a volume
 1.36289 +  ** relative path or an absolute path.  Callers of this function must not
 1.36290 +  ** attempt to treat it as a relative path name (i.e. they should simply use
 1.36291 +  ** it verbatim).
 1.36292 +  */
 1.36293 +  if ( winIsDriveLetterAndColon(zPathname) ){
 1.36294 +    return TRUE;
 1.36295 +  }
 1.36296 +
 1.36297 +  /*
 1.36298 +  ** If we get to this point, the path name should almost certainly be a purely
 1.36299 +  ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
 1.36300 +  */
 1.36301 +  return FALSE;
 1.36302 +}
 1.36303 +
 1.36304 +/*
 1.36305 +** Turn a relative pathname into a full pathname.  Write the full
 1.36306 +** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
 1.36307 +** bytes in size.
 1.36308 +*/
 1.36309 +static int winFullPathname(
 1.36310 +  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
 1.36311 +  const char *zRelative,        /* Possibly relative input path */
 1.36312 +  int nFull,                    /* Size of output buffer in bytes */
 1.36313 +  char *zFull                   /* Output buffer */
 1.36314 +){
 1.36315 +  
 1.36316 +#if defined(__CYGWIN__)
 1.36317 +  SimulateIOError( return SQLITE_ERROR );
 1.36318 +  UNUSED_PARAMETER(nFull);
 1.36319 +  assert( nFull>=pVfs->mxPathname );
 1.36320 +  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
 1.36321 +    /*
 1.36322 +    ** NOTE: We are dealing with a relative path name and the data
 1.36323 +    **       directory has been set.  Therefore, use it as the basis
 1.36324 +    **       for converting the relative path name to an absolute
 1.36325 +    **       one by prepending the data directory and a slash.
 1.36326 +    */
 1.36327 +    char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
 1.36328 +    if( !zOut ){
 1.36329 +      return SQLITE_IOERR_NOMEM;
 1.36330 +    }
 1.36331 +    if( cygwin_conv_path(
 1.36332 +            (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
 1.36333 +            CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
 1.36334 +      sqlite3_free(zOut);
 1.36335 +      return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
 1.36336 +                         "winFullPathname1", zRelative);
 1.36337 +    }else{
 1.36338 +      char *zUtf8 = winConvertToUtf8Filename(zOut);
 1.36339 +      if( !zUtf8 ){
 1.36340 +        sqlite3_free(zOut);
 1.36341 +        return SQLITE_IOERR_NOMEM;
 1.36342 +      }
 1.36343 +      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
 1.36344 +                       sqlite3_data_directory, winGetDirSep(), zUtf8);
 1.36345 +      sqlite3_free(zUtf8);
 1.36346 +      sqlite3_free(zOut);
 1.36347 +    }
 1.36348 +  }else{
 1.36349 +    char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
 1.36350 +    if( !zOut ){
 1.36351 +      return SQLITE_IOERR_NOMEM;
 1.36352 +    }
 1.36353 +    if( cygwin_conv_path(
 1.36354 +            (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
 1.36355 +            zRelative, zOut, pVfs->mxPathname+1)<0 ){
 1.36356 +      sqlite3_free(zOut);
 1.36357 +      return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
 1.36358 +                         "winFullPathname2", zRelative);
 1.36359 +    }else{
 1.36360 +      char *zUtf8 = winConvertToUtf8Filename(zOut);
 1.36361 +      if( !zUtf8 ){
 1.36362 +        sqlite3_free(zOut);
 1.36363 +        return SQLITE_IOERR_NOMEM;
 1.36364 +      }
 1.36365 +      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
 1.36366 +      sqlite3_free(zUtf8);
 1.36367 +      sqlite3_free(zOut);
 1.36368 +    }
 1.36369 +  }
 1.36370 +  return SQLITE_OK;
 1.36371 +#endif
 1.36372 +
 1.36373 +#if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
 1.36374 +  SimulateIOError( return SQLITE_ERROR );
 1.36375 +  /* WinCE has no concept of a relative pathname, or so I am told. */
 1.36376 +  /* WinRT has no way to convert a relative path to an absolute one. */
 1.36377 +  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
 1.36378 +    /*
 1.36379 +    ** NOTE: We are dealing with a relative path name and the data
 1.36380 +    **       directory has been set.  Therefore, use it as the basis
 1.36381 +    **       for converting the relative path name to an absolute
 1.36382 +    **       one by prepending the data directory and a backslash.
 1.36383 +    */
 1.36384 +    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
 1.36385 +                     sqlite3_data_directory, winGetDirSep(), zRelative);
 1.36386 +  }else{
 1.36387 +    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
 1.36388 +  }
 1.36389 +  return SQLITE_OK;
 1.36390 +#endif
 1.36391 +
 1.36392 +#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
 1.36393 +  DWORD nByte;
 1.36394 +  void *zConverted;
 1.36395 +  char *zOut;
 1.36396 +
 1.36397 +  /* If this path name begins with "/X:", where "X" is any alphabetic
 1.36398 +  ** character, discard the initial "/" from the pathname.
 1.36399 +  */
 1.36400 +  if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
 1.36401 +    zRelative++;
 1.36402 +  }
 1.36403 +
 1.36404 +  /* It's odd to simulate an io-error here, but really this is just
 1.36405 +  ** using the io-error infrastructure to test that SQLite handles this
 1.36406 +  ** function failing. This function could fail if, for example, the
 1.36407 +  ** current working directory has been unlinked.
 1.36408 +  */
 1.36409 +  SimulateIOError( return SQLITE_ERROR );
 1.36410 +  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
 1.36411 +    /*
 1.36412 +    ** NOTE: We are dealing with a relative path name and the data
 1.36413 +    **       directory has been set.  Therefore, use it as the basis
 1.36414 +    **       for converting the relative path name to an absolute
 1.36415 +    **       one by prepending the data directory and a backslash.
 1.36416 +    */
 1.36417 +    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
 1.36418 +                     sqlite3_data_directory, winGetDirSep(), zRelative);
 1.36419 +    return SQLITE_OK;
 1.36420 +  }
 1.36421 +  zConverted = winConvertFromUtf8Filename(zRelative);
 1.36422 +  if( zConverted==0 ){
 1.36423 +    return SQLITE_IOERR_NOMEM;
 1.36424 +  }
 1.36425 +  if( osIsNT() ){
 1.36426 +    LPWSTR zTemp;
 1.36427 +    nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
 1.36428 +    if( nByte==0 ){
 1.36429 +      sqlite3_free(zConverted);
 1.36430 +      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
 1.36431 +                         "winFullPathname1", zRelative);
 1.36432 +    }
 1.36433 +    nByte += 3;
 1.36434 +    zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
 1.36435 +    if( zTemp==0 ){
 1.36436 +      sqlite3_free(zConverted);
 1.36437 +      return SQLITE_IOERR_NOMEM;
 1.36438 +    }
 1.36439 +    nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
 1.36440 +    if( nByte==0 ){
 1.36441 +      sqlite3_free(zConverted);
 1.36442 +      sqlite3_free(zTemp);
 1.36443 +      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
 1.36444 +                         "winFullPathname2", zRelative);
 1.36445 +    }
 1.36446 +    sqlite3_free(zConverted);
 1.36447 +    zOut = winUnicodeToUtf8(zTemp);
 1.36448 +    sqlite3_free(zTemp);
 1.36449 +  }
 1.36450 +#ifdef SQLITE_WIN32_HAS_ANSI
 1.36451 +  else{
 1.36452 +    char *zTemp;
 1.36453 +    nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
 1.36454 +    if( nByte==0 ){
 1.36455 +      sqlite3_free(zConverted);
 1.36456 +      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
 1.36457 +                         "winFullPathname3", zRelative);
 1.36458 +    }
 1.36459 +    nByte += 3;
 1.36460 +    zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
 1.36461 +    if( zTemp==0 ){
 1.36462 +      sqlite3_free(zConverted);
 1.36463 +      return SQLITE_IOERR_NOMEM;
 1.36464 +    }
 1.36465 +    nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
 1.36466 +    if( nByte==0 ){
 1.36467 +      sqlite3_free(zConverted);
 1.36468 +      sqlite3_free(zTemp);
 1.36469 +      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
 1.36470 +                         "winFullPathname4", zRelative);
 1.36471 +    }
 1.36472 +    sqlite3_free(zConverted);
 1.36473 +    zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
 1.36474 +    sqlite3_free(zTemp);
 1.36475 +  }
 1.36476 +#endif
 1.36477 +  if( zOut ){
 1.36478 +    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
 1.36479 +    sqlite3_free(zOut);
 1.36480 +    return SQLITE_OK;
 1.36481 +  }else{
 1.36482 +    return SQLITE_IOERR_NOMEM;
 1.36483 +  }
 1.36484 +#endif
 1.36485 +}
 1.36486 +
 1.36487 +#ifndef SQLITE_OMIT_LOAD_EXTENSION
 1.36488 +/*
 1.36489 +** Interfaces for opening a shared library, finding entry points
 1.36490 +** within the shared library, and closing the shared library.
 1.36491 +*/
 1.36492 +static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
 1.36493 +  HANDLE h;
 1.36494 +#if defined(__CYGWIN__)
 1.36495 +  int nFull = pVfs->mxPathname+1;
 1.36496 +  char *zFull = sqlite3MallocZero( nFull );
 1.36497 +  void *zConverted = 0;
 1.36498 +  if( zFull==0 ){
 1.36499 +    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
 1.36500 +    return 0;
 1.36501 +  }
 1.36502 +  if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
 1.36503 +    sqlite3_free(zFull);
 1.36504 +    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
 1.36505 +    return 0;
 1.36506 +  }
 1.36507 +  zConverted = winConvertFromUtf8Filename(zFull);
 1.36508 +  sqlite3_free(zFull);
 1.36509 +#else
 1.36510 +  void *zConverted = winConvertFromUtf8Filename(zFilename);
 1.36511 +  UNUSED_PARAMETER(pVfs);
 1.36512 +#endif
 1.36513 +  if( zConverted==0 ){
 1.36514 +    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
 1.36515 +    return 0;
 1.36516 +  }
 1.36517 +  if( osIsNT() ){
 1.36518 +#if SQLITE_OS_WINRT
 1.36519 +    h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
 1.36520 +#else
 1.36521 +    h = osLoadLibraryW((LPCWSTR)zConverted);
 1.36522 +#endif
 1.36523 +  }
 1.36524 +#ifdef SQLITE_WIN32_HAS_ANSI
 1.36525 +  else{
 1.36526 +    h = osLoadLibraryA((char*)zConverted);
 1.36527 +  }
 1.36528 +#endif
 1.36529 +  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
 1.36530 +  sqlite3_free(zConverted);
 1.36531 +  return (void*)h;
 1.36532 +}
 1.36533 +static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
 1.36534 +  UNUSED_PARAMETER(pVfs);
 1.36535 +  winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
 1.36536 +}
 1.36537 +static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
 1.36538 +  FARPROC proc;
 1.36539 +  UNUSED_PARAMETER(pVfs);
 1.36540 +  proc = osGetProcAddressA((HANDLE)pH, zSym);
 1.36541 +  OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
 1.36542 +           (void*)pH, zSym, (void*)proc));
 1.36543 +  return (void(*)(void))proc;
 1.36544 +}
 1.36545 +static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
 1.36546 +  UNUSED_PARAMETER(pVfs);
 1.36547 +  osFreeLibrary((HANDLE)pHandle);
 1.36548 +  OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
 1.36549 +}
 1.36550 +#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
 1.36551 +  #define winDlOpen  0
 1.36552 +  #define winDlError 0
 1.36553 +  #define winDlSym   0
 1.36554 +  #define winDlClose 0
 1.36555 +#endif
 1.36556 +
 1.36557 +
 1.36558 +/*
 1.36559 +** Write up to nBuf bytes of randomness into zBuf.
 1.36560 +*/
 1.36561 +static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
 1.36562 +  int n = 0;
 1.36563 +  UNUSED_PARAMETER(pVfs);
 1.36564 +#if defined(SQLITE_TEST)
 1.36565 +  n = nBuf;
 1.36566 +  memset(zBuf, 0, nBuf);
 1.36567 +#else
 1.36568 +  if( sizeof(SYSTEMTIME)<=nBuf-n ){
 1.36569 +    SYSTEMTIME x;
 1.36570 +    osGetSystemTime(&x);
 1.36571 +    memcpy(&zBuf[n], &x, sizeof(x));
 1.36572 +    n += sizeof(x);
 1.36573 +  }
 1.36574 +  if( sizeof(DWORD)<=nBuf-n ){
 1.36575 +    DWORD pid = osGetCurrentProcessId();
 1.36576 +    memcpy(&zBuf[n], &pid, sizeof(pid));
 1.36577 +    n += sizeof(pid);
 1.36578 +  }
 1.36579 +#if SQLITE_OS_WINRT
 1.36580 +  if( sizeof(ULONGLONG)<=nBuf-n ){
 1.36581 +    ULONGLONG cnt = osGetTickCount64();
 1.36582 +    memcpy(&zBuf[n], &cnt, sizeof(cnt));
 1.36583 +    n += sizeof(cnt);
 1.36584 +  }
 1.36585 +#else
 1.36586 +  if( sizeof(DWORD)<=nBuf-n ){
 1.36587 +    DWORD cnt = osGetTickCount();
 1.36588 +    memcpy(&zBuf[n], &cnt, sizeof(cnt));
 1.36589 +    n += sizeof(cnt);
 1.36590 +  }
 1.36591 +#endif
 1.36592 +  if( sizeof(LARGE_INTEGER)<=nBuf-n ){
 1.36593 +    LARGE_INTEGER i;
 1.36594 +    osQueryPerformanceCounter(&i);
 1.36595 +    memcpy(&zBuf[n], &i, sizeof(i));
 1.36596 +    n += sizeof(i);
 1.36597 +  }
 1.36598 +#endif
 1.36599 +  return n;
 1.36600 +}
 1.36601 +
 1.36602 +
 1.36603 +/*
 1.36604 +** Sleep for a little while.  Return the amount of time slept.
 1.36605 +*/
 1.36606 +static int winSleep(sqlite3_vfs *pVfs, int microsec){
 1.36607 +  sqlite3_win32_sleep((microsec+999)/1000);
 1.36608 +  UNUSED_PARAMETER(pVfs);
 1.36609 +  return ((microsec+999)/1000)*1000;
 1.36610 +}
 1.36611 +
 1.36612 +/*
 1.36613 +** The following variable, if set to a non-zero value, is interpreted as
 1.36614 +** the number of seconds since 1970 and is used to set the result of
 1.36615 +** sqlite3OsCurrentTime() during testing.
 1.36616 +*/
 1.36617 +#ifdef SQLITE_TEST
 1.36618 +SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
 1.36619 +#endif
 1.36620 +
 1.36621 +/*
 1.36622 +** Find the current time (in Universal Coordinated Time).  Write into *piNow
 1.36623 +** the current time and date as a Julian Day number times 86_400_000.  In
 1.36624 +** other words, write into *piNow the number of milliseconds since the Julian
 1.36625 +** epoch of noon in Greenwich on November 24, 4714 B.C according to the
 1.36626 +** proleptic Gregorian calendar.
 1.36627 +**
 1.36628 +** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date 
 1.36629 +** cannot be found.
 1.36630 +*/
 1.36631 +static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
 1.36632 +  /* FILETIME structure is a 64-bit value representing the number of 
 1.36633 +     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
 1.36634 +  */
 1.36635 +  FILETIME ft;
 1.36636 +  static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
 1.36637 +#ifdef SQLITE_TEST
 1.36638 +  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
 1.36639 +#endif
 1.36640 +  /* 2^32 - to avoid use of LL and warnings in gcc */
 1.36641 +  static const sqlite3_int64 max32BitValue = 
 1.36642 +      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
 1.36643 +      (sqlite3_int64)294967296;
 1.36644 +
 1.36645 +#if SQLITE_OS_WINCE
 1.36646 +  SYSTEMTIME time;
 1.36647 +  osGetSystemTime(&time);
 1.36648 +  /* if SystemTimeToFileTime() fails, it returns zero. */
 1.36649 +  if (!osSystemTimeToFileTime(&time,&ft)){
 1.36650 +    return SQLITE_ERROR;
 1.36651 +  }
 1.36652 +#else
 1.36653 +  osGetSystemTimeAsFileTime( &ft );
 1.36654 +#endif
 1.36655 +
 1.36656 +  *piNow = winFiletimeEpoch +
 1.36657 +            ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + 
 1.36658 +               (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
 1.36659 +
 1.36660 +#ifdef SQLITE_TEST
 1.36661 +  if( sqlite3_current_time ){
 1.36662 +    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
 1.36663 +  }
 1.36664 +#endif
 1.36665 +  UNUSED_PARAMETER(pVfs);
 1.36666 +  return SQLITE_OK;
 1.36667 +}
 1.36668 +
 1.36669 +/*
 1.36670 +** Find the current time (in Universal Coordinated Time).  Write the
 1.36671 +** current time and date as a Julian Day number into *prNow and
 1.36672 +** return 0.  Return 1 if the time and date cannot be found.
 1.36673 +*/
 1.36674 +static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
 1.36675 +  int rc;
 1.36676 +  sqlite3_int64 i;
 1.36677 +  rc = winCurrentTimeInt64(pVfs, &i);
 1.36678 +  if( !rc ){
 1.36679 +    *prNow = i/86400000.0;
 1.36680 +  }
 1.36681 +  return rc;
 1.36682 +}
 1.36683 +
 1.36684 +/*
 1.36685 +** The idea is that this function works like a combination of
 1.36686 +** GetLastError() and FormatMessage() on Windows (or errno and
 1.36687 +** strerror_r() on Unix). After an error is returned by an OS
 1.36688 +** function, SQLite calls this function with zBuf pointing to
 1.36689 +** a buffer of nBuf bytes. The OS layer should populate the
 1.36690 +** buffer with a nul-terminated UTF-8 encoded error message
 1.36691 +** describing the last IO error to have occurred within the calling
 1.36692 +** thread.
 1.36693 +**
 1.36694 +** If the error message is too large for the supplied buffer,
 1.36695 +** it should be truncated. The return value of xGetLastError
 1.36696 +** is zero if the error message fits in the buffer, or non-zero
 1.36697 +** otherwise (if the message was truncated). If non-zero is returned,
 1.36698 +** then it is not necessary to include the nul-terminator character
 1.36699 +** in the output buffer.
 1.36700 +**
 1.36701 +** Not supplying an error message will have no adverse effect
 1.36702 +** on SQLite. It is fine to have an implementation that never
 1.36703 +** returns an error message:
 1.36704 +**
 1.36705 +**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
 1.36706 +**     assert(zBuf[0]=='\0');
 1.36707 +**     return 0;
 1.36708 +**   }
 1.36709 +**
 1.36710 +** However if an error message is supplied, it will be incorporated
 1.36711 +** by sqlite into the error message available to the user using
 1.36712 +** sqlite3_errmsg(), possibly making IO errors easier to debug.
 1.36713 +*/
 1.36714 +static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
 1.36715 +  UNUSED_PARAMETER(pVfs);
 1.36716 +  return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
 1.36717 +}
 1.36718 +
 1.36719 +/*
 1.36720 +** Initialize and deinitialize the operating system interface.
 1.36721 +*/
 1.36722 +SQLITE_API int sqlite3_os_init(void){
 1.36723 +  static sqlite3_vfs winVfs = {
 1.36724 +    3,                   /* iVersion */
 1.36725 +    sizeof(winFile),     /* szOsFile */
 1.36726 +    SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
 1.36727 +    0,                   /* pNext */
 1.36728 +    "win32",             /* zName */
 1.36729 +    0,                   /* pAppData */
 1.36730 +    winOpen,             /* xOpen */
 1.36731 +    winDelete,           /* xDelete */
 1.36732 +    winAccess,           /* xAccess */
 1.36733 +    winFullPathname,     /* xFullPathname */
 1.36734 +    winDlOpen,           /* xDlOpen */
 1.36735 +    winDlError,          /* xDlError */
 1.36736 +    winDlSym,            /* xDlSym */
 1.36737 +    winDlClose,          /* xDlClose */
 1.36738 +    winRandomness,       /* xRandomness */
 1.36739 +    winSleep,            /* xSleep */
 1.36740 +    winCurrentTime,      /* xCurrentTime */
 1.36741 +    winGetLastError,     /* xGetLastError */
 1.36742 +    winCurrentTimeInt64, /* xCurrentTimeInt64 */
 1.36743 +    winSetSystemCall,    /* xSetSystemCall */
 1.36744 +    winGetSystemCall,    /* xGetSystemCall */
 1.36745 +    winNextSystemCall,   /* xNextSystemCall */
 1.36746 +  };
 1.36747 +#if defined(SQLITE_WIN32_HAS_WIDE)
 1.36748 +  static sqlite3_vfs winLongPathVfs = {
 1.36749 +    3,                   /* iVersion */
 1.36750 +    sizeof(winFile),     /* szOsFile */
 1.36751 +    SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
 1.36752 +    0,                   /* pNext */
 1.36753 +    "win32-longpath",    /* zName */
 1.36754 +    0,                   /* pAppData */
 1.36755 +    winOpen,             /* xOpen */
 1.36756 +    winDelete,           /* xDelete */
 1.36757 +    winAccess,           /* xAccess */
 1.36758 +    winFullPathname,     /* xFullPathname */
 1.36759 +    winDlOpen,           /* xDlOpen */
 1.36760 +    winDlError,          /* xDlError */
 1.36761 +    winDlSym,            /* xDlSym */
 1.36762 +    winDlClose,          /* xDlClose */
 1.36763 +    winRandomness,       /* xRandomness */
 1.36764 +    winSleep,            /* xSleep */
 1.36765 +    winCurrentTime,      /* xCurrentTime */
 1.36766 +    winGetLastError,     /* xGetLastError */
 1.36767 +    winCurrentTimeInt64, /* xCurrentTimeInt64 */
 1.36768 +    winSetSystemCall,    /* xSetSystemCall */
 1.36769 +    winGetSystemCall,    /* xGetSystemCall */
 1.36770 +    winNextSystemCall,   /* xNextSystemCall */
 1.36771 +  };
 1.36772 +#endif
 1.36773 +
 1.36774 +  /* Double-check that the aSyscall[] array has been constructed
 1.36775 +  ** correctly.  See ticket [bb3a86e890c8e96ab] */
 1.36776 +  assert( ArraySize(aSyscall)==76 );
 1.36777 +
 1.36778 +  /* get memory map allocation granularity */
 1.36779 +  memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
 1.36780 +#if SQLITE_OS_WINRT
 1.36781 +  osGetNativeSystemInfo(&winSysInfo);
 1.36782 +#else
 1.36783 +  osGetSystemInfo(&winSysInfo);
 1.36784 +#endif
 1.36785 +  assert( winSysInfo.dwAllocationGranularity>0 );
 1.36786 +  assert( winSysInfo.dwPageSize>0 );
 1.36787 +
 1.36788 +  sqlite3_vfs_register(&winVfs, 1);
 1.36789 +
 1.36790 +#if defined(SQLITE_WIN32_HAS_WIDE)
 1.36791 +  sqlite3_vfs_register(&winLongPathVfs, 0);
 1.36792 +#endif
 1.36793 +
 1.36794 +  return SQLITE_OK; 
 1.36795 +}
 1.36796 +
 1.36797 +SQLITE_API int sqlite3_os_end(void){ 
 1.36798 +#if SQLITE_OS_WINRT
 1.36799 +  if( sleepObj!=NULL ){
 1.36800 +    osCloseHandle(sleepObj);
 1.36801 +    sleepObj = NULL;
 1.36802 +  }
 1.36803 +#endif
 1.36804 +  return SQLITE_OK;
 1.36805 +}
 1.36806 +
 1.36807 +#endif /* SQLITE_OS_WIN */
 1.36808 +
 1.36809 +/************** End of os_win.c **********************************************/
 1.36810 +/************** Begin file bitvec.c ******************************************/
 1.36811 +/*
 1.36812 +** 2008 February 16
 1.36813 +**
 1.36814 +** The author disclaims copyright to this source code.  In place of
 1.36815 +** a legal notice, here is a blessing:
 1.36816 +**
 1.36817 +**    May you do good and not evil.
 1.36818 +**    May you find forgiveness for yourself and forgive others.
 1.36819 +**    May you share freely, never taking more than you give.
 1.36820 +**
 1.36821 +*************************************************************************
 1.36822 +** This file implements an object that represents a fixed-length
 1.36823 +** bitmap.  Bits are numbered starting with 1.
 1.36824 +**
 1.36825 +** A bitmap is used to record which pages of a database file have been
 1.36826 +** journalled during a transaction, or which pages have the "dont-write"
 1.36827 +** property.  Usually only a few pages are meet either condition.
 1.36828 +** So the bitmap is usually sparse and has low cardinality.
 1.36829 +** But sometimes (for example when during a DROP of a large table) most
 1.36830 +** or all of the pages in a database can get journalled.  In those cases, 
 1.36831 +** the bitmap becomes dense with high cardinality.  The algorithm needs 
 1.36832 +** to handle both cases well.
 1.36833 +**
 1.36834 +** The size of the bitmap is fixed when the object is created.
 1.36835 +**
 1.36836 +** All bits are clear when the bitmap is created.  Individual bits
 1.36837 +** may be set or cleared one at a time.
 1.36838 +**
 1.36839 +** Test operations are about 100 times more common that set operations.
 1.36840 +** Clear operations are exceedingly rare.  There are usually between
 1.36841 +** 5 and 500 set operations per Bitvec object, though the number of sets can
 1.36842 +** sometimes grow into tens of thousands or larger.  The size of the
 1.36843 +** Bitvec object is the number of pages in the database file at the
 1.36844 +** start of a transaction, and is thus usually less than a few thousand,
 1.36845 +** but can be as large as 2 billion for a really big database.
 1.36846 +*/
 1.36847 +
 1.36848 +/* Size of the Bitvec structure in bytes. */
 1.36849 +#define BITVEC_SZ        512
 1.36850 +
 1.36851 +/* Round the union size down to the nearest pointer boundary, since that's how 
 1.36852 +** it will be aligned within the Bitvec struct. */
 1.36853 +#define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
 1.36854 +
 1.36855 +/* Type of the array "element" for the bitmap representation. 
 1.36856 +** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
 1.36857 +** Setting this to the "natural word" size of your CPU may improve
 1.36858 +** performance. */
 1.36859 +#define BITVEC_TELEM     u8
 1.36860 +/* Size, in bits, of the bitmap element. */
 1.36861 +#define BITVEC_SZELEM    8
 1.36862 +/* Number of elements in a bitmap array. */
 1.36863 +#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
 1.36864 +/* Number of bits in the bitmap array. */
 1.36865 +#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
 1.36866 +
 1.36867 +/* Number of u32 values in hash table. */
 1.36868 +#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
 1.36869 +/* Maximum number of entries in hash table before 
 1.36870 +** sub-dividing and re-hashing. */
 1.36871 +#define BITVEC_MXHASH    (BITVEC_NINT/2)
 1.36872 +/* Hashing function for the aHash representation.
 1.36873 +** Empirical testing showed that the *37 multiplier 
 1.36874 +** (an arbitrary prime)in the hash function provided 
 1.36875 +** no fewer collisions than the no-op *1. */
 1.36876 +#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
 1.36877 +
 1.36878 +#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
 1.36879 +
 1.36880 +
 1.36881 +/*
 1.36882 +** A bitmap is an instance of the following structure.
 1.36883 +**
 1.36884 +** This bitmap records the existence of zero or more bits
 1.36885 +** with values between 1 and iSize, inclusive.
 1.36886 +**
 1.36887 +** There are three possible representations of the bitmap.
 1.36888 +** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
 1.36889 +** bitmap.  The least significant bit is bit 1.
 1.36890 +**
 1.36891 +** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
 1.36892 +** a hash table that will hold up to BITVEC_MXHASH distinct values.
 1.36893 +**
 1.36894 +** Otherwise, the value i is redirected into one of BITVEC_NPTR
 1.36895 +** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
 1.36896 +** handles up to iDivisor separate values of i.  apSub[0] holds
 1.36897 +** values between 1 and iDivisor.  apSub[1] holds values between
 1.36898 +** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
 1.36899 +** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
 1.36900 +** to hold deal with values between 1 and iDivisor.
 1.36901 +*/
 1.36902 +struct Bitvec {
 1.36903 +  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
 1.36904 +  u32 nSet;       /* Number of bits that are set - only valid for aHash
 1.36905 +                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
 1.36906 +                  ** this would be 125. */
 1.36907 +  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
 1.36908 +                  /* Should >=0 for apSub element. */
 1.36909 +                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
 1.36910 +                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
 1.36911 +  union {
 1.36912 +    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
 1.36913 +    u32 aHash[BITVEC_NINT];      /* Hash table representation */
 1.36914 +    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
 1.36915 +  } u;
 1.36916 +};
 1.36917 +
 1.36918 +/*
 1.36919 +** Create a new bitmap object able to handle bits between 0 and iSize,
 1.36920 +** inclusive.  Return a pointer to the new object.  Return NULL if 
 1.36921 +** malloc fails.
 1.36922 +*/
 1.36923 +SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
 1.36924 +  Bitvec *p;
 1.36925 +  assert( sizeof(*p)==BITVEC_SZ );
 1.36926 +  p = sqlite3MallocZero( sizeof(*p) );
 1.36927 +  if( p ){
 1.36928 +    p->iSize = iSize;
 1.36929 +  }
 1.36930 +  return p;
 1.36931 +}
 1.36932 +
 1.36933 +/*
 1.36934 +** Check to see if the i-th bit is set.  Return true or false.
 1.36935 +** If p is NULL (if the bitmap has not been created) or if
 1.36936 +** i is out of range, then return false.
 1.36937 +*/
 1.36938 +SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
 1.36939 +  if( p==0 ) return 0;
 1.36940 +  if( i>p->iSize || i==0 ) return 0;
 1.36941 +  i--;
 1.36942 +  while( p->iDivisor ){
 1.36943 +    u32 bin = i/p->iDivisor;
 1.36944 +    i = i%p->iDivisor;
 1.36945 +    p = p->u.apSub[bin];
 1.36946 +    if (!p) {
 1.36947 +      return 0;
 1.36948 +    }
 1.36949 +  }
 1.36950 +  if( p->iSize<=BITVEC_NBIT ){
 1.36951 +    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
 1.36952 +  } else{
 1.36953 +    u32 h = BITVEC_HASH(i++);
 1.36954 +    while( p->u.aHash[h] ){
 1.36955 +      if( p->u.aHash[h]==i ) return 1;
 1.36956 +      h = (h+1) % BITVEC_NINT;
 1.36957 +    }
 1.36958 +    return 0;
 1.36959 +  }
 1.36960 +}
 1.36961 +
 1.36962 +/*
 1.36963 +** Set the i-th bit.  Return 0 on success and an error code if
 1.36964 +** anything goes wrong.
 1.36965 +**
 1.36966 +** This routine might cause sub-bitmaps to be allocated.  Failing
 1.36967 +** to get the memory needed to hold the sub-bitmap is the only
 1.36968 +** that can go wrong with an insert, assuming p and i are valid.
 1.36969 +**
 1.36970 +** The calling function must ensure that p is a valid Bitvec object
 1.36971 +** and that the value for "i" is within range of the Bitvec object.
 1.36972 +** Otherwise the behavior is undefined.
 1.36973 +*/
 1.36974 +SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
 1.36975 +  u32 h;
 1.36976 +  if( p==0 ) return SQLITE_OK;
 1.36977 +  assert( i>0 );
 1.36978 +  assert( i<=p->iSize );
 1.36979 +  i--;
 1.36980 +  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
 1.36981 +    u32 bin = i/p->iDivisor;
 1.36982 +    i = i%p->iDivisor;
 1.36983 +    if( p->u.apSub[bin]==0 ){
 1.36984 +      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
 1.36985 +      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
 1.36986 +    }
 1.36987 +    p = p->u.apSub[bin];
 1.36988 +  }
 1.36989 +  if( p->iSize<=BITVEC_NBIT ){
 1.36990 +    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
 1.36991 +    return SQLITE_OK;
 1.36992 +  }
 1.36993 +  h = BITVEC_HASH(i++);
 1.36994 +  /* if there wasn't a hash collision, and this doesn't */
 1.36995 +  /* completely fill the hash, then just add it without */
 1.36996 +  /* worring about sub-dividing and re-hashing. */
 1.36997 +  if( !p->u.aHash[h] ){
 1.36998 +    if (p->nSet<(BITVEC_NINT-1)) {
 1.36999 +      goto bitvec_set_end;
 1.37000 +    } else {
 1.37001 +      goto bitvec_set_rehash;
 1.37002 +    }
 1.37003 +  }
 1.37004 +  /* there was a collision, check to see if it's already */
 1.37005 +  /* in hash, if not, try to find a spot for it */
 1.37006 +  do {
 1.37007 +    if( p->u.aHash[h]==i ) return SQLITE_OK;
 1.37008 +    h++;
 1.37009 +    if( h>=BITVEC_NINT ) h = 0;
 1.37010 +  } while( p->u.aHash[h] );
 1.37011 +  /* we didn't find it in the hash.  h points to the first */
 1.37012 +  /* available free spot. check to see if this is going to */
 1.37013 +  /* make our hash too "full".  */
 1.37014 +bitvec_set_rehash:
 1.37015 +  if( p->nSet>=BITVEC_MXHASH ){
 1.37016 +    unsigned int j;
 1.37017 +    int rc;
 1.37018 +    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
 1.37019 +    if( aiValues==0 ){
 1.37020 +      return SQLITE_NOMEM;
 1.37021 +    }else{
 1.37022 +      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
 1.37023 +      memset(p->u.apSub, 0, sizeof(p->u.apSub));
 1.37024 +      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
 1.37025 +      rc = sqlite3BitvecSet(p, i);
 1.37026 +      for(j=0; j<BITVEC_NINT; j++){
 1.37027 +        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
 1.37028 +      }
 1.37029 +      sqlite3StackFree(0, aiValues);
 1.37030 +      return rc;
 1.37031 +    }
 1.37032 +  }
 1.37033 +bitvec_set_end:
 1.37034 +  p->nSet++;
 1.37035 +  p->u.aHash[h] = i;
 1.37036 +  return SQLITE_OK;
 1.37037 +}
 1.37038 +
 1.37039 +/*
 1.37040 +** Clear the i-th bit.
 1.37041 +**
 1.37042 +** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
 1.37043 +** that BitvecClear can use to rebuilt its hash table.
 1.37044 +*/
 1.37045 +SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
 1.37046 +  if( p==0 ) return;
 1.37047 +  assert( i>0 );
 1.37048 +  i--;
 1.37049 +  while( p->iDivisor ){
 1.37050 +    u32 bin = i/p->iDivisor;
 1.37051 +    i = i%p->iDivisor;
 1.37052 +    p = p->u.apSub[bin];
 1.37053 +    if (!p) {
 1.37054 +      return;
 1.37055 +    }
 1.37056 +  }
 1.37057 +  if( p->iSize<=BITVEC_NBIT ){
 1.37058 +    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
 1.37059 +  }else{
 1.37060 +    unsigned int j;
 1.37061 +    u32 *aiValues = pBuf;
 1.37062 +    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
 1.37063 +    memset(p->u.aHash, 0, sizeof(p->u.aHash));
 1.37064 +    p->nSet = 0;
 1.37065 +    for(j=0; j<BITVEC_NINT; j++){
 1.37066 +      if( aiValues[j] && aiValues[j]!=(i+1) ){
 1.37067 +        u32 h = BITVEC_HASH(aiValues[j]-1);
 1.37068 +        p->nSet++;
 1.37069 +        while( p->u.aHash[h] ){
 1.37070 +          h++;
 1.37071 +          if( h>=BITVEC_NINT ) h = 0;
 1.37072 +        }
 1.37073 +        p->u.aHash[h] = aiValues[j];
 1.37074 +      }
 1.37075 +    }
 1.37076 +  }
 1.37077 +}
 1.37078 +
 1.37079 +/*
 1.37080 +** Destroy a bitmap object.  Reclaim all memory used.
 1.37081 +*/
 1.37082 +SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
 1.37083 +  if( p==0 ) return;
 1.37084 +  if( p->iDivisor ){
 1.37085 +    unsigned int i;
 1.37086 +    for(i=0; i<BITVEC_NPTR; i++){
 1.37087 +      sqlite3BitvecDestroy(p->u.apSub[i]);
 1.37088 +    }
 1.37089 +  }
 1.37090 +  sqlite3_free(p);
 1.37091 +}
 1.37092 +
 1.37093 +/*
 1.37094 +** Return the value of the iSize parameter specified when Bitvec *p
 1.37095 +** was created.
 1.37096 +*/
 1.37097 +SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
 1.37098 +  return p->iSize;
 1.37099 +}
 1.37100 +
 1.37101 +#ifndef SQLITE_OMIT_BUILTIN_TEST
 1.37102 +/*
 1.37103 +** Let V[] be an array of unsigned characters sufficient to hold
 1.37104 +** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
 1.37105 +** Then the following macros can be used to set, clear, or test
 1.37106 +** individual bits within V.
 1.37107 +*/
 1.37108 +#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
 1.37109 +#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
 1.37110 +#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
 1.37111 +
 1.37112 +/*
 1.37113 +** This routine runs an extensive test of the Bitvec code.
 1.37114 +**
 1.37115 +** The input is an array of integers that acts as a program
 1.37116 +** to test the Bitvec.  The integers are opcodes followed
 1.37117 +** by 0, 1, or 3 operands, depending on the opcode.  Another
 1.37118 +** opcode follows immediately after the last operand.
 1.37119 +**
 1.37120 +** There are 6 opcodes numbered from 0 through 5.  0 is the
 1.37121 +** "halt" opcode and causes the test to end.
 1.37122 +**
 1.37123 +**    0          Halt and return the number of errors
 1.37124 +**    1 N S X    Set N bits beginning with S and incrementing by X
 1.37125 +**    2 N S X    Clear N bits beginning with S and incrementing by X
 1.37126 +**    3 N        Set N randomly chosen bits
 1.37127 +**    4 N        Clear N randomly chosen bits
 1.37128 +**    5 N S X    Set N bits from S increment X in array only, not in bitvec
 1.37129 +**
 1.37130 +** The opcodes 1 through 4 perform set and clear operations are performed
 1.37131 +** on both a Bitvec object and on a linear array of bits obtained from malloc.
 1.37132 +** Opcode 5 works on the linear array only, not on the Bitvec.
 1.37133 +** Opcode 5 is used to deliberately induce a fault in order to
 1.37134 +** confirm that error detection works.
 1.37135 +**
 1.37136 +** At the conclusion of the test the linear array is compared
 1.37137 +** against the Bitvec object.  If there are any differences,
 1.37138 +** an error is returned.  If they are the same, zero is returned.
 1.37139 +**
 1.37140 +** If a memory allocation error occurs, return -1.
 1.37141 +*/
 1.37142 +SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
 1.37143 +  Bitvec *pBitvec = 0;
 1.37144 +  unsigned char *pV = 0;
 1.37145 +  int rc = -1;
 1.37146 +  int i, nx, pc, op;
 1.37147 +  void *pTmpSpace;
 1.37148 +
 1.37149 +  /* Allocate the Bitvec to be tested and a linear array of
 1.37150 +  ** bits to act as the reference */
 1.37151 +  pBitvec = sqlite3BitvecCreate( sz );
 1.37152 +  pV = sqlite3MallocZero( (sz+7)/8 + 1 );
 1.37153 +  pTmpSpace = sqlite3_malloc(BITVEC_SZ);
 1.37154 +  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
 1.37155 +
 1.37156 +  /* NULL pBitvec tests */
 1.37157 +  sqlite3BitvecSet(0, 1);
 1.37158 +  sqlite3BitvecClear(0, 1, pTmpSpace);
 1.37159 +
 1.37160 +  /* Run the program */
 1.37161 +  pc = 0;
 1.37162 +  while( (op = aOp[pc])!=0 ){
 1.37163 +    switch( op ){
 1.37164 +      case 1:
 1.37165 +      case 2:
 1.37166 +      case 5: {
 1.37167 +        nx = 4;
 1.37168 +        i = aOp[pc+2] - 1;
 1.37169 +        aOp[pc+2] += aOp[pc+3];
 1.37170 +        break;
 1.37171 +      }
 1.37172 +      case 3:
 1.37173 +      case 4: 
 1.37174 +      default: {
 1.37175 +        nx = 2;
 1.37176 +        sqlite3_randomness(sizeof(i), &i);
 1.37177 +        break;
 1.37178 +      }
 1.37179 +    }
 1.37180 +    if( (--aOp[pc+1]) > 0 ) nx = 0;
 1.37181 +    pc += nx;
 1.37182 +    i = (i & 0x7fffffff)%sz;
 1.37183 +    if( (op & 1)!=0 ){
 1.37184 +      SETBIT(pV, (i+1));
 1.37185 +      if( op!=5 ){
 1.37186 +        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
 1.37187 +      }
 1.37188 +    }else{
 1.37189 +      CLEARBIT(pV, (i+1));
 1.37190 +      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
 1.37191 +    }
 1.37192 +  }
 1.37193 +
 1.37194 +  /* Test to make sure the linear array exactly matches the
 1.37195 +  ** Bitvec object.  Start with the assumption that they do
 1.37196 +  ** match (rc==0).  Change rc to non-zero if a discrepancy
 1.37197 +  ** is found.
 1.37198 +  */
 1.37199 +  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
 1.37200 +          + sqlite3BitvecTest(pBitvec, 0)
 1.37201 +          + (sqlite3BitvecSize(pBitvec) - sz);
 1.37202 +  for(i=1; i<=sz; i++){
 1.37203 +    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
 1.37204 +      rc = i;
 1.37205 +      break;
 1.37206 +    }
 1.37207 +  }
 1.37208 +
 1.37209 +  /* Free allocated structure */
 1.37210 +bitvec_end:
 1.37211 +  sqlite3_free(pTmpSpace);
 1.37212 +  sqlite3_free(pV);
 1.37213 +  sqlite3BitvecDestroy(pBitvec);
 1.37214 +  return rc;
 1.37215 +}
 1.37216 +#endif /* SQLITE_OMIT_BUILTIN_TEST */
 1.37217 +
 1.37218 +/************** End of bitvec.c **********************************************/
 1.37219 +/************** Begin file pcache.c ******************************************/
 1.37220 +/*
 1.37221 +** 2008 August 05
 1.37222 +**
 1.37223 +** The author disclaims copyright to this source code.  In place of
 1.37224 +** a legal notice, here is a blessing:
 1.37225 +**
 1.37226 +**    May you do good and not evil.
 1.37227 +**    May you find forgiveness for yourself and forgive others.
 1.37228 +**    May you share freely, never taking more than you give.
 1.37229 +**
 1.37230 +*************************************************************************
 1.37231 +** This file implements that page cache.
 1.37232 +*/
 1.37233 +
 1.37234 +/*
 1.37235 +** A complete page cache is an instance of this structure.
 1.37236 +*/
 1.37237 +struct PCache {
 1.37238 +  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
 1.37239 +  PgHdr *pSynced;                     /* Last synced page in dirty page list */
 1.37240 +  int nRef;                           /* Number of referenced pages */
 1.37241 +  int szCache;                        /* Configured cache size */
 1.37242 +  int szPage;                         /* Size of every page in this cache */
 1.37243 +  int szExtra;                        /* Size of extra space for each page */
 1.37244 +  u8 bPurgeable;                      /* True if pages are on backing store */
 1.37245 +  u8 eCreate;                         /* eCreate value for for xFetch() */
 1.37246 +  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
 1.37247 +  void *pStress;                      /* Argument to xStress */
 1.37248 +  sqlite3_pcache *pCache;             /* Pluggable cache module */
 1.37249 +  PgHdr *pPage1;                      /* Reference to page 1 */
 1.37250 +};
 1.37251 +
 1.37252 +/*
 1.37253 +** Some of the assert() macros in this code are too expensive to run
 1.37254 +** even during normal debugging.  Use them only rarely on long-running
 1.37255 +** tests.  Enable the expensive asserts using the
 1.37256 +** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
 1.37257 +*/
 1.37258 +#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
 1.37259 +# define expensive_assert(X)  assert(X)
 1.37260 +#else
 1.37261 +# define expensive_assert(X)
 1.37262 +#endif
 1.37263 +
 1.37264 +/********************************** Linked List Management ********************/
 1.37265 +
 1.37266 +#if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
 1.37267 +/*
 1.37268 +** Check that the pCache->pSynced variable is set correctly. If it
 1.37269 +** is not, either fail an assert or return zero. Otherwise, return
 1.37270 +** non-zero. This is only used in debugging builds, as follows:
 1.37271 +**
 1.37272 +**   expensive_assert( pcacheCheckSynced(pCache) );
 1.37273 +*/
 1.37274 +static int pcacheCheckSynced(PCache *pCache){
 1.37275 +  PgHdr *p;
 1.37276 +  for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
 1.37277 +    assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
 1.37278 +  }
 1.37279 +  return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
 1.37280 +}
 1.37281 +#endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
 1.37282 +
 1.37283 +/*
 1.37284 +** Remove page pPage from the list of dirty pages.
 1.37285 +*/
 1.37286 +static void pcacheRemoveFromDirtyList(PgHdr *pPage){
 1.37287 +  PCache *p = pPage->pCache;
 1.37288 +
 1.37289 +  assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
 1.37290 +  assert( pPage->pDirtyPrev || pPage==p->pDirty );
 1.37291 +
 1.37292 +  /* Update the PCache1.pSynced variable if necessary. */
 1.37293 +  if( p->pSynced==pPage ){
 1.37294 +    PgHdr *pSynced = pPage->pDirtyPrev;
 1.37295 +    while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
 1.37296 +      pSynced = pSynced->pDirtyPrev;
 1.37297 +    }
 1.37298 +    p->pSynced = pSynced;
 1.37299 +  }
 1.37300 +
 1.37301 +  if( pPage->pDirtyNext ){
 1.37302 +    pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
 1.37303 +  }else{
 1.37304 +    assert( pPage==p->pDirtyTail );
 1.37305 +    p->pDirtyTail = pPage->pDirtyPrev;
 1.37306 +  }
 1.37307 +  if( pPage->pDirtyPrev ){
 1.37308 +    pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
 1.37309 +  }else{
 1.37310 +    assert( pPage==p->pDirty );
 1.37311 +    p->pDirty = pPage->pDirtyNext;
 1.37312 +    if( p->pDirty==0 && p->bPurgeable ){
 1.37313 +      assert( p->eCreate==1 );
 1.37314 +      p->eCreate = 2;
 1.37315 +    }
 1.37316 +  }
 1.37317 +  pPage->pDirtyNext = 0;
 1.37318 +  pPage->pDirtyPrev = 0;
 1.37319 +
 1.37320 +  expensive_assert( pcacheCheckSynced(p) );
 1.37321 +}
 1.37322 +
 1.37323 +/*
 1.37324 +** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
 1.37325 +** pPage).
 1.37326 +*/
 1.37327 +static void pcacheAddToDirtyList(PgHdr *pPage){
 1.37328 +  PCache *p = pPage->pCache;
 1.37329 +
 1.37330 +  assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
 1.37331 +
 1.37332 +  pPage->pDirtyNext = p->pDirty;
 1.37333 +  if( pPage->pDirtyNext ){
 1.37334 +    assert( pPage->pDirtyNext->pDirtyPrev==0 );
 1.37335 +    pPage->pDirtyNext->pDirtyPrev = pPage;
 1.37336 +  }else if( p->bPurgeable ){
 1.37337 +    assert( p->eCreate==2 );
 1.37338 +    p->eCreate = 1;
 1.37339 +  }
 1.37340 +  p->pDirty = pPage;
 1.37341 +  if( !p->pDirtyTail ){
 1.37342 +    p->pDirtyTail = pPage;
 1.37343 +  }
 1.37344 +  if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
 1.37345 +    p->pSynced = pPage;
 1.37346 +  }
 1.37347 +  expensive_assert( pcacheCheckSynced(p) );
 1.37348 +}
 1.37349 +
 1.37350 +/*
 1.37351 +** Wrapper around the pluggable caches xUnpin method. If the cache is
 1.37352 +** being used for an in-memory database, this function is a no-op.
 1.37353 +*/
 1.37354 +static void pcacheUnpin(PgHdr *p){
 1.37355 +  PCache *pCache = p->pCache;
 1.37356 +  if( pCache->bPurgeable ){
 1.37357 +    if( p->pgno==1 ){
 1.37358 +      pCache->pPage1 = 0;
 1.37359 +    }
 1.37360 +    sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
 1.37361 +  }
 1.37362 +}
 1.37363 +
 1.37364 +/*************************************************** General Interfaces ******
 1.37365 +**
 1.37366 +** Initialize and shutdown the page cache subsystem. Neither of these 
 1.37367 +** functions are threadsafe.
 1.37368 +*/
 1.37369 +SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
 1.37370 +  if( sqlite3GlobalConfig.pcache2.xInit==0 ){
 1.37371 +    /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
 1.37372 +    ** built-in default page cache is used instead of the application defined
 1.37373 +    ** page cache. */
 1.37374 +    sqlite3PCacheSetDefault();
 1.37375 +  }
 1.37376 +  return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
 1.37377 +}
 1.37378 +SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
 1.37379 +  if( sqlite3GlobalConfig.pcache2.xShutdown ){
 1.37380 +    /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
 1.37381 +    sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
 1.37382 +  }
 1.37383 +}
 1.37384 +
 1.37385 +/*
 1.37386 +** Return the size in bytes of a PCache object.
 1.37387 +*/
 1.37388 +SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
 1.37389 +
 1.37390 +/*
 1.37391 +** Create a new PCache object. Storage space to hold the object
 1.37392 +** has already been allocated and is passed in as the p pointer. 
 1.37393 +** The caller discovers how much space needs to be allocated by 
 1.37394 +** calling sqlite3PcacheSize().
 1.37395 +*/
 1.37396 +SQLITE_PRIVATE void sqlite3PcacheOpen(
 1.37397 +  int szPage,                  /* Size of every page */
 1.37398 +  int szExtra,                 /* Extra space associated with each page */
 1.37399 +  int bPurgeable,              /* True if pages are on backing store */
 1.37400 +  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
 1.37401 +  void *pStress,               /* Argument to xStress */
 1.37402 +  PCache *p                    /* Preallocated space for the PCache */
 1.37403 +){
 1.37404 +  memset(p, 0, sizeof(PCache));
 1.37405 +  p->szPage = szPage;
 1.37406 +  p->szExtra = szExtra;
 1.37407 +  p->bPurgeable = bPurgeable;
 1.37408 +  p->eCreate = 2;
 1.37409 +  p->xStress = xStress;
 1.37410 +  p->pStress = pStress;
 1.37411 +  p->szCache = 100;
 1.37412 +}
 1.37413 +
 1.37414 +/*
 1.37415 +** Change the page size for PCache object. The caller must ensure that there
 1.37416 +** are no outstanding page references when this function is called.
 1.37417 +*/
 1.37418 +SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
 1.37419 +  assert( pCache->nRef==0 && pCache->pDirty==0 );
 1.37420 +  if( pCache->pCache ){
 1.37421 +    sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
 1.37422 +    pCache->pCache = 0;
 1.37423 +    pCache->pPage1 = 0;
 1.37424 +  }
 1.37425 +  pCache->szPage = szPage;
 1.37426 +}
 1.37427 +
 1.37428 +/*
 1.37429 +** Compute the number of pages of cache requested.
 1.37430 +*/
 1.37431 +static int numberOfCachePages(PCache *p){
 1.37432 +  if( p->szCache>=0 ){
 1.37433 +    return p->szCache;
 1.37434 +  }else{
 1.37435 +    return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
 1.37436 +  }
 1.37437 +}
 1.37438 +
 1.37439 +/*
 1.37440 +** Try to obtain a page from the cache.
 1.37441 +*/
 1.37442 +SQLITE_PRIVATE int sqlite3PcacheFetch(
 1.37443 +  PCache *pCache,       /* Obtain the page from this cache */
 1.37444 +  Pgno pgno,            /* Page number to obtain */
 1.37445 +  int createFlag,       /* If true, create page if it does not exist already */
 1.37446 +  PgHdr **ppPage        /* Write the page here */
 1.37447 +){
 1.37448 +  sqlite3_pcache_page *pPage;
 1.37449 +  PgHdr *pPgHdr = 0;
 1.37450 +  int eCreate;
 1.37451 +
 1.37452 +  assert( pCache!=0 );
 1.37453 +  assert( createFlag==1 || createFlag==0 );
 1.37454 +  assert( pgno>0 );
 1.37455 +
 1.37456 +  /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
 1.37457 +  ** allocate it now.
 1.37458 +  */
 1.37459 +  if( !pCache->pCache ){
 1.37460 +    sqlite3_pcache *p;
 1.37461 +    if( !createFlag ){
 1.37462 +      *ppPage = 0;
 1.37463 +      return SQLITE_OK;
 1.37464 +    }
 1.37465 +    p = sqlite3GlobalConfig.pcache2.xCreate(
 1.37466 +        pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
 1.37467 +    );
 1.37468 +    if( !p ){
 1.37469 +      return SQLITE_NOMEM;
 1.37470 +    }
 1.37471 +    sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
 1.37472 +    pCache->pCache = p;
 1.37473 +  }
 1.37474 +
 1.37475 +  /* eCreate defines what to do if the page does not exist.
 1.37476 +  **    0     Do not allocate a new page.  (createFlag==0)
 1.37477 +  **    1     Allocate a new page if doing so is inexpensive.
 1.37478 +  **          (createFlag==1 AND bPurgeable AND pDirty)
 1.37479 +  **    2     Allocate a new page even it doing so is difficult.
 1.37480 +  **          (createFlag==1 AND !(bPurgeable AND pDirty)
 1.37481 +  */
 1.37482 +  eCreate = createFlag==0 ? 0 : pCache->eCreate;
 1.37483 +  assert( (createFlag*(1+(!pCache->bPurgeable||!pCache->pDirty)))==eCreate );
 1.37484 +  pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
 1.37485 +  if( !pPage && eCreate==1 ){
 1.37486 +    PgHdr *pPg;
 1.37487 +
 1.37488 +    /* Find a dirty page to write-out and recycle. First try to find a 
 1.37489 +    ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
 1.37490 +    ** cleared), but if that is not possible settle for any other 
 1.37491 +    ** unreferenced dirty page.
 1.37492 +    */
 1.37493 +    expensive_assert( pcacheCheckSynced(pCache) );
 1.37494 +    for(pPg=pCache->pSynced; 
 1.37495 +        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
 1.37496 +        pPg=pPg->pDirtyPrev
 1.37497 +    );
 1.37498 +    pCache->pSynced = pPg;
 1.37499 +    if( !pPg ){
 1.37500 +      for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
 1.37501 +    }
 1.37502 +    if( pPg ){
 1.37503 +      int rc;
 1.37504 +#ifdef SQLITE_LOG_CACHE_SPILL
 1.37505 +      sqlite3_log(SQLITE_FULL, 
 1.37506 +                  "spill page %d making room for %d - cache used: %d/%d",
 1.37507 +                  pPg->pgno, pgno,
 1.37508 +                  sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
 1.37509 +                  numberOfCachePages(pCache));
 1.37510 +#endif
 1.37511 +      rc = pCache->xStress(pCache->pStress, pPg);
 1.37512 +      if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
 1.37513 +        return rc;
 1.37514 +      }
 1.37515 +    }
 1.37516 +
 1.37517 +    pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
 1.37518 +  }
 1.37519 +
 1.37520 +  if( pPage ){
 1.37521 +    pPgHdr = (PgHdr *)pPage->pExtra;
 1.37522 +
 1.37523 +    if( !pPgHdr->pPage ){
 1.37524 +      memset(pPgHdr, 0, sizeof(PgHdr));
 1.37525 +      pPgHdr->pPage = pPage;
 1.37526 +      pPgHdr->pData = pPage->pBuf;
 1.37527 +      pPgHdr->pExtra = (void *)&pPgHdr[1];
 1.37528 +      memset(pPgHdr->pExtra, 0, pCache->szExtra);
 1.37529 +      pPgHdr->pCache = pCache;
 1.37530 +      pPgHdr->pgno = pgno;
 1.37531 +    }
 1.37532 +    assert( pPgHdr->pCache==pCache );
 1.37533 +    assert( pPgHdr->pgno==pgno );
 1.37534 +    assert( pPgHdr->pData==pPage->pBuf );
 1.37535 +    assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
 1.37536 +
 1.37537 +    if( 0==pPgHdr->nRef ){
 1.37538 +      pCache->nRef++;
 1.37539 +    }
 1.37540 +    pPgHdr->nRef++;
 1.37541 +    if( pgno==1 ){
 1.37542 +      pCache->pPage1 = pPgHdr;
 1.37543 +    }
 1.37544 +  }
 1.37545 +  *ppPage = pPgHdr;
 1.37546 +  return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
 1.37547 +}
 1.37548 +
 1.37549 +/*
 1.37550 +** Decrement the reference count on a page. If the page is clean and the
 1.37551 +** reference count drops to 0, then it is made elible for recycling.
 1.37552 +*/
 1.37553 +SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
 1.37554 +  assert( p->nRef>0 );
 1.37555 +  p->nRef--;
 1.37556 +  if( p->nRef==0 ){
 1.37557 +    PCache *pCache = p->pCache;
 1.37558 +    pCache->nRef--;
 1.37559 +    if( (p->flags&PGHDR_DIRTY)==0 ){
 1.37560 +      pcacheUnpin(p);
 1.37561 +    }else{
 1.37562 +      /* Move the page to the head of the dirty list. */
 1.37563 +      pcacheRemoveFromDirtyList(p);
 1.37564 +      pcacheAddToDirtyList(p);
 1.37565 +    }
 1.37566 +  }
 1.37567 +}
 1.37568 +
 1.37569 +/*
 1.37570 +** Increase the reference count of a supplied page by 1.
 1.37571 +*/
 1.37572 +SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
 1.37573 +  assert(p->nRef>0);
 1.37574 +  p->nRef++;
 1.37575 +}
 1.37576 +
 1.37577 +/*
 1.37578 +** Drop a page from the cache. There must be exactly one reference to the
 1.37579 +** page. This function deletes that reference, so after it returns the
 1.37580 +** page pointed to by p is invalid.
 1.37581 +*/
 1.37582 +SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
 1.37583 +  PCache *pCache;
 1.37584 +  assert( p->nRef==1 );
 1.37585 +  if( p->flags&PGHDR_DIRTY ){
 1.37586 +    pcacheRemoveFromDirtyList(p);
 1.37587 +  }
 1.37588 +  pCache = p->pCache;
 1.37589 +  pCache->nRef--;
 1.37590 +  if( p->pgno==1 ){
 1.37591 +    pCache->pPage1 = 0;
 1.37592 +  }
 1.37593 +  sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
 1.37594 +}
 1.37595 +
 1.37596 +/*
 1.37597 +** Make sure the page is marked as dirty. If it isn't dirty already,
 1.37598 +** make it so.
 1.37599 +*/
 1.37600 +SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
 1.37601 +  p->flags &= ~PGHDR_DONT_WRITE;
 1.37602 +  assert( p->nRef>0 );
 1.37603 +  if( 0==(p->flags & PGHDR_DIRTY) ){
 1.37604 +    p->flags |= PGHDR_DIRTY;
 1.37605 +    pcacheAddToDirtyList( p);
 1.37606 +  }
 1.37607 +}
 1.37608 +
 1.37609 +/*
 1.37610 +** Make sure the page is marked as clean. If it isn't clean already,
 1.37611 +** make it so.
 1.37612 +*/
 1.37613 +SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
 1.37614 +  if( (p->flags & PGHDR_DIRTY) ){
 1.37615 +    pcacheRemoveFromDirtyList(p);
 1.37616 +    p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
 1.37617 +    if( p->nRef==0 ){
 1.37618 +      pcacheUnpin(p);
 1.37619 +    }
 1.37620 +  }
 1.37621 +}
 1.37622 +
 1.37623 +/*
 1.37624 +** Make every page in the cache clean.
 1.37625 +*/
 1.37626 +SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
 1.37627 +  PgHdr *p;
 1.37628 +  while( (p = pCache->pDirty)!=0 ){
 1.37629 +    sqlite3PcacheMakeClean(p);
 1.37630 +  }
 1.37631 +}
 1.37632 +
 1.37633 +/*
 1.37634 +** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
 1.37635 +*/
 1.37636 +SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
 1.37637 +  PgHdr *p;
 1.37638 +  for(p=pCache->pDirty; p; p=p->pDirtyNext){
 1.37639 +    p->flags &= ~PGHDR_NEED_SYNC;
 1.37640 +  }
 1.37641 +  pCache->pSynced = pCache->pDirtyTail;
 1.37642 +}
 1.37643 +
 1.37644 +/*
 1.37645 +** Change the page number of page p to newPgno. 
 1.37646 +*/
 1.37647 +SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
 1.37648 +  PCache *pCache = p->pCache;
 1.37649 +  assert( p->nRef>0 );
 1.37650 +  assert( newPgno>0 );
 1.37651 +  sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
 1.37652 +  p->pgno = newPgno;
 1.37653 +  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
 1.37654 +    pcacheRemoveFromDirtyList(p);
 1.37655 +    pcacheAddToDirtyList(p);
 1.37656 +  }
 1.37657 +}
 1.37658 +
 1.37659 +/*
 1.37660 +** Drop every cache entry whose page number is greater than "pgno". The
 1.37661 +** caller must ensure that there are no outstanding references to any pages
 1.37662 +** other than page 1 with a page number greater than pgno.
 1.37663 +**
 1.37664 +** If there is a reference to page 1 and the pgno parameter passed to this
 1.37665 +** function is 0, then the data area associated with page 1 is zeroed, but
 1.37666 +** the page object is not dropped.
 1.37667 +*/
 1.37668 +SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
 1.37669 +  if( pCache->pCache ){
 1.37670 +    PgHdr *p;
 1.37671 +    PgHdr *pNext;
 1.37672 +    for(p=pCache->pDirty; p; p=pNext){
 1.37673 +      pNext = p->pDirtyNext;
 1.37674 +      /* This routine never gets call with a positive pgno except right
 1.37675 +      ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
 1.37676 +      ** it must be that pgno==0.
 1.37677 +      */
 1.37678 +      assert( p->pgno>0 );
 1.37679 +      if( ALWAYS(p->pgno>pgno) ){
 1.37680 +        assert( p->flags&PGHDR_DIRTY );
 1.37681 +        sqlite3PcacheMakeClean(p);
 1.37682 +      }
 1.37683 +    }
 1.37684 +    if( pgno==0 && pCache->pPage1 ){
 1.37685 +      memset(pCache->pPage1->pData, 0, pCache->szPage);
 1.37686 +      pgno = 1;
 1.37687 +    }
 1.37688 +    sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
 1.37689 +  }
 1.37690 +}
 1.37691 +
 1.37692 +/*
 1.37693 +** Close a cache.
 1.37694 +*/
 1.37695 +SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
 1.37696 +  if( pCache->pCache ){
 1.37697 +    sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
 1.37698 +  }
 1.37699 +}
 1.37700 +
 1.37701 +/* 
 1.37702 +** Discard the contents of the cache.
 1.37703 +*/
 1.37704 +SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
 1.37705 +  sqlite3PcacheTruncate(pCache, 0);
 1.37706 +}
 1.37707 +
 1.37708 +/*
 1.37709 +** Merge two lists of pages connected by pDirty and in pgno order.
 1.37710 +** Do not both fixing the pDirtyPrev pointers.
 1.37711 +*/
 1.37712 +static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
 1.37713 +  PgHdr result, *pTail;
 1.37714 +  pTail = &result;
 1.37715 +  while( pA && pB ){
 1.37716 +    if( pA->pgno<pB->pgno ){
 1.37717 +      pTail->pDirty = pA;
 1.37718 +      pTail = pA;
 1.37719 +      pA = pA->pDirty;
 1.37720 +    }else{
 1.37721 +      pTail->pDirty = pB;
 1.37722 +      pTail = pB;
 1.37723 +      pB = pB->pDirty;
 1.37724 +    }
 1.37725 +  }
 1.37726 +  if( pA ){
 1.37727 +    pTail->pDirty = pA;
 1.37728 +  }else if( pB ){
 1.37729 +    pTail->pDirty = pB;
 1.37730 +  }else{
 1.37731 +    pTail->pDirty = 0;
 1.37732 +  }
 1.37733 +  return result.pDirty;
 1.37734 +}
 1.37735 +
 1.37736 +/*
 1.37737 +** Sort the list of pages in accending order by pgno.  Pages are
 1.37738 +** connected by pDirty pointers.  The pDirtyPrev pointers are
 1.37739 +** corrupted by this sort.
 1.37740 +**
 1.37741 +** Since there cannot be more than 2^31 distinct pages in a database,
 1.37742 +** there cannot be more than 31 buckets required by the merge sorter.
 1.37743 +** One extra bucket is added to catch overflow in case something
 1.37744 +** ever changes to make the previous sentence incorrect.
 1.37745 +*/
 1.37746 +#define N_SORT_BUCKET  32
 1.37747 +static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
 1.37748 +  PgHdr *a[N_SORT_BUCKET], *p;
 1.37749 +  int i;
 1.37750 +  memset(a, 0, sizeof(a));
 1.37751 +  while( pIn ){
 1.37752 +    p = pIn;
 1.37753 +    pIn = p->pDirty;
 1.37754 +    p->pDirty = 0;
 1.37755 +    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
 1.37756 +      if( a[i]==0 ){
 1.37757 +        a[i] = p;
 1.37758 +        break;
 1.37759 +      }else{
 1.37760 +        p = pcacheMergeDirtyList(a[i], p);
 1.37761 +        a[i] = 0;
 1.37762 +      }
 1.37763 +    }
 1.37764 +    if( NEVER(i==N_SORT_BUCKET-1) ){
 1.37765 +      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
 1.37766 +      ** the input list.  But that is impossible.
 1.37767 +      */
 1.37768 +      a[i] = pcacheMergeDirtyList(a[i], p);
 1.37769 +    }
 1.37770 +  }
 1.37771 +  p = a[0];
 1.37772 +  for(i=1; i<N_SORT_BUCKET; i++){
 1.37773 +    p = pcacheMergeDirtyList(p, a[i]);
 1.37774 +  }
 1.37775 +  return p;
 1.37776 +}
 1.37777 +
 1.37778 +/*
 1.37779 +** Return a list of all dirty pages in the cache, sorted by page number.
 1.37780 +*/
 1.37781 +SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
 1.37782 +  PgHdr *p;
 1.37783 +  for(p=pCache->pDirty; p; p=p->pDirtyNext){
 1.37784 +    p->pDirty = p->pDirtyNext;
 1.37785 +  }
 1.37786 +  return pcacheSortDirtyList(pCache->pDirty);
 1.37787 +}
 1.37788 +
 1.37789 +/* 
 1.37790 +** Return the total number of referenced pages held by the cache.
 1.37791 +*/
 1.37792 +SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
 1.37793 +  return pCache->nRef;
 1.37794 +}
 1.37795 +
 1.37796 +/*
 1.37797 +** Return the number of references to the page supplied as an argument.
 1.37798 +*/
 1.37799 +SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
 1.37800 +  return p->nRef;
 1.37801 +}
 1.37802 +
 1.37803 +/* 
 1.37804 +** Return the total number of pages in the cache.
 1.37805 +*/
 1.37806 +SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
 1.37807 +  int nPage = 0;
 1.37808 +  if( pCache->pCache ){
 1.37809 +    nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
 1.37810 +  }
 1.37811 +  return nPage;
 1.37812 +}
 1.37813 +
 1.37814 +#ifdef SQLITE_TEST
 1.37815 +/*
 1.37816 +** Get the suggested cache-size value.
 1.37817 +*/
 1.37818 +SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
 1.37819 +  return numberOfCachePages(pCache);
 1.37820 +}
 1.37821 +#endif
 1.37822 +
 1.37823 +/*
 1.37824 +** Set the suggested cache-size value.
 1.37825 +*/
 1.37826 +SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
 1.37827 +  pCache->szCache = mxPage;
 1.37828 +  if( pCache->pCache ){
 1.37829 +    sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
 1.37830 +                                           numberOfCachePages(pCache));
 1.37831 +  }
 1.37832 +}
 1.37833 +
 1.37834 +/*
 1.37835 +** Free up as much memory as possible from the page cache.
 1.37836 +*/
 1.37837 +SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
 1.37838 +  if( pCache->pCache ){
 1.37839 +    sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
 1.37840 +  }
 1.37841 +}
 1.37842 +
 1.37843 +#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
 1.37844 +/*
 1.37845 +** For all dirty pages currently in the cache, invoke the specified
 1.37846 +** callback. This is only used if the SQLITE_CHECK_PAGES macro is
 1.37847 +** defined.
 1.37848 +*/
 1.37849 +SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
 1.37850 +  PgHdr *pDirty;
 1.37851 +  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
 1.37852 +    xIter(pDirty);
 1.37853 +  }
 1.37854 +}
 1.37855 +#endif
 1.37856 +
 1.37857 +/************** End of pcache.c **********************************************/
 1.37858 +/************** Begin file pcache1.c *****************************************/
 1.37859 +/*
 1.37860 +** 2008 November 05
 1.37861 +**
 1.37862 +** The author disclaims copyright to this source code.  In place of
 1.37863 +** a legal notice, here is a blessing:
 1.37864 +**
 1.37865 +**    May you do good and not evil.
 1.37866 +**    May you find forgiveness for yourself and forgive others.
 1.37867 +**    May you share freely, never taking more than you give.
 1.37868 +**
 1.37869 +*************************************************************************
 1.37870 +**
 1.37871 +** This file implements the default page cache implementation (the
 1.37872 +** sqlite3_pcache interface). It also contains part of the implementation
 1.37873 +** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
 1.37874 +** If the default page cache implementation is overriden, then neither of
 1.37875 +** these two features are available.
 1.37876 +*/
 1.37877 +
 1.37878 +
 1.37879 +typedef struct PCache1 PCache1;
 1.37880 +typedef struct PgHdr1 PgHdr1;
 1.37881 +typedef struct PgFreeslot PgFreeslot;
 1.37882 +typedef struct PGroup PGroup;
 1.37883 +
 1.37884 +/* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set 
 1.37885 +** of one or more PCaches that are able to recycle each others unpinned
 1.37886 +** pages when they are under memory pressure.  A PGroup is an instance of
 1.37887 +** the following object.
 1.37888 +**
 1.37889 +** This page cache implementation works in one of two modes:
 1.37890 +**
 1.37891 +**   (1)  Every PCache is the sole member of its own PGroup.  There is
 1.37892 +**        one PGroup per PCache.
 1.37893 +**
 1.37894 +**   (2)  There is a single global PGroup that all PCaches are a member
 1.37895 +**        of.
 1.37896 +**
 1.37897 +** Mode 1 uses more memory (since PCache instances are not able to rob
 1.37898 +** unused pages from other PCaches) but it also operates without a mutex,
 1.37899 +** and is therefore often faster.  Mode 2 requires a mutex in order to be
 1.37900 +** threadsafe, but recycles pages more efficiently.
 1.37901 +**
 1.37902 +** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
 1.37903 +** PGroup which is the pcache1.grp global variable and its mutex is
 1.37904 +** SQLITE_MUTEX_STATIC_LRU.
 1.37905 +*/
 1.37906 +struct PGroup {
 1.37907 +  sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
 1.37908 +  unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
 1.37909 +  unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
 1.37910 +  unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
 1.37911 +  unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
 1.37912 +  PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
 1.37913 +};
 1.37914 +
 1.37915 +/* Each page cache is an instance of the following object.  Every
 1.37916 +** open database file (including each in-memory database and each
 1.37917 +** temporary or transient database) has a single page cache which
 1.37918 +** is an instance of this object.
 1.37919 +**
 1.37920 +** Pointers to structures of this type are cast and returned as 
 1.37921 +** opaque sqlite3_pcache* handles.
 1.37922 +*/
 1.37923 +struct PCache1 {
 1.37924 +  /* Cache configuration parameters. Page size (szPage) and the purgeable
 1.37925 +  ** flag (bPurgeable) are set when the cache is created. nMax may be 
 1.37926 +  ** modified at any time by a call to the pcache1Cachesize() method.
 1.37927 +  ** The PGroup mutex must be held when accessing nMax.
 1.37928 +  */
 1.37929 +  PGroup *pGroup;                     /* PGroup this cache belongs to */
 1.37930 +  int szPage;                         /* Size of allocated pages in bytes */
 1.37931 +  int szExtra;                        /* Size of extra space in bytes */
 1.37932 +  int bPurgeable;                     /* True if cache is purgeable */
 1.37933 +  unsigned int nMin;                  /* Minimum number of pages reserved */
 1.37934 +  unsigned int nMax;                  /* Configured "cache_size" value */
 1.37935 +  unsigned int n90pct;                /* nMax*9/10 */
 1.37936 +  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
 1.37937 +
 1.37938 +  /* Hash table of all pages. The following variables may only be accessed
 1.37939 +  ** when the accessor is holding the PGroup mutex.
 1.37940 +  */
 1.37941 +  unsigned int nRecyclable;           /* Number of pages in the LRU list */
 1.37942 +  unsigned int nPage;                 /* Total number of pages in apHash */
 1.37943 +  unsigned int nHash;                 /* Number of slots in apHash[] */
 1.37944 +  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
 1.37945 +};
 1.37946 +
 1.37947 +/*
 1.37948 +** Each cache entry is represented by an instance of the following 
 1.37949 +** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
 1.37950 +** PgHdr1.pCache->szPage bytes is allocated directly before this structure 
 1.37951 +** in memory.
 1.37952 +*/
 1.37953 +struct PgHdr1 {
 1.37954 +  sqlite3_pcache_page page;
 1.37955 +  unsigned int iKey;             /* Key value (page number) */
 1.37956 +  u8 isPinned;                   /* Page in use, not on the LRU list */
 1.37957 +  PgHdr1 *pNext;                 /* Next in hash table chain */
 1.37958 +  PCache1 *pCache;               /* Cache that currently owns this page */
 1.37959 +  PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
 1.37960 +  PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
 1.37961 +};
 1.37962 +
 1.37963 +/*
 1.37964 +** Free slots in the allocator used to divide up the buffer provided using
 1.37965 +** the SQLITE_CONFIG_PAGECACHE mechanism.
 1.37966 +*/
 1.37967 +struct PgFreeslot {
 1.37968 +  PgFreeslot *pNext;  /* Next free slot */
 1.37969 +};
 1.37970 +
 1.37971 +/*
 1.37972 +** Global data used by this cache.
 1.37973 +*/
 1.37974 +static SQLITE_WSD struct PCacheGlobal {
 1.37975 +  PGroup grp;                    /* The global PGroup for mode (2) */
 1.37976 +
 1.37977 +  /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
 1.37978 +  ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
 1.37979 +  ** fixed at sqlite3_initialize() time and do not require mutex protection.
 1.37980 +  ** The nFreeSlot and pFree values do require mutex protection.
 1.37981 +  */
 1.37982 +  int isInit;                    /* True if initialized */
 1.37983 +  int szSlot;                    /* Size of each free slot */
 1.37984 +  int nSlot;                     /* The number of pcache slots */
 1.37985 +  int nReserve;                  /* Try to keep nFreeSlot above this */
 1.37986 +  void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
 1.37987 +  /* Above requires no mutex.  Use mutex below for variable that follow. */
 1.37988 +  sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
 1.37989 +  PgFreeslot *pFree;             /* Free page blocks */
 1.37990 +  int nFreeSlot;                 /* Number of unused pcache slots */
 1.37991 +  /* The following value requires a mutex to change.  We skip the mutex on
 1.37992 +  ** reading because (1) most platforms read a 32-bit integer atomically and
 1.37993 +  ** (2) even if an incorrect value is read, no great harm is done since this
 1.37994 +  ** is really just an optimization. */
 1.37995 +  int bUnderPressure;            /* True if low on PAGECACHE memory */
 1.37996 +} pcache1_g;
 1.37997 +
 1.37998 +/*
 1.37999 +** All code in this file should access the global structure above via the
 1.38000 +** alias "pcache1". This ensures that the WSD emulation is used when
 1.38001 +** compiling for systems that do not support real WSD.
 1.38002 +*/
 1.38003 +#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
 1.38004 +
 1.38005 +/*
 1.38006 +** Macros to enter and leave the PCache LRU mutex.
 1.38007 +*/
 1.38008 +#define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
 1.38009 +#define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
 1.38010 +
 1.38011 +/******************************************************************************/
 1.38012 +/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
 1.38013 +
 1.38014 +/*
 1.38015 +** This function is called during initialization if a static buffer is 
 1.38016 +** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
 1.38017 +** verb to sqlite3_config(). Parameter pBuf points to an allocation large
 1.38018 +** enough to contain 'n' buffers of 'sz' bytes each.
 1.38019 +**
 1.38020 +** This routine is called from sqlite3_initialize() and so it is guaranteed
 1.38021 +** to be serialized already.  There is no need for further mutexing.
 1.38022 +*/
 1.38023 +SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
 1.38024 +  if( pcache1.isInit ){
 1.38025 +    PgFreeslot *p;
 1.38026 +    sz = ROUNDDOWN8(sz);
 1.38027 +    pcache1.szSlot = sz;
 1.38028 +    pcache1.nSlot = pcache1.nFreeSlot = n;
 1.38029 +    pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
 1.38030 +    pcache1.pStart = pBuf;
 1.38031 +    pcache1.pFree = 0;
 1.38032 +    pcache1.bUnderPressure = 0;
 1.38033 +    while( n-- ){
 1.38034 +      p = (PgFreeslot*)pBuf;
 1.38035 +      p->pNext = pcache1.pFree;
 1.38036 +      pcache1.pFree = p;
 1.38037 +      pBuf = (void*)&((char*)pBuf)[sz];
 1.38038 +    }
 1.38039 +    pcache1.pEnd = pBuf;
 1.38040 +  }
 1.38041 +}
 1.38042 +
 1.38043 +/*
 1.38044 +** Malloc function used within this file to allocate space from the buffer
 1.38045 +** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
 1.38046 +** such buffer exists or there is no space left in it, this function falls 
 1.38047 +** back to sqlite3Malloc().
 1.38048 +**
 1.38049 +** Multiple threads can run this routine at the same time.  Global variables
 1.38050 +** in pcache1 need to be protected via mutex.
 1.38051 +*/
 1.38052 +static void *pcache1Alloc(int nByte){
 1.38053 +  void *p = 0;
 1.38054 +  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
 1.38055 +  sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
 1.38056 +  if( nByte<=pcache1.szSlot ){
 1.38057 +    sqlite3_mutex_enter(pcache1.mutex);
 1.38058 +    p = (PgHdr1 *)pcache1.pFree;
 1.38059 +    if( p ){
 1.38060 +      pcache1.pFree = pcache1.pFree->pNext;
 1.38061 +      pcache1.nFreeSlot--;
 1.38062 +      pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
 1.38063 +      assert( pcache1.nFreeSlot>=0 );
 1.38064 +      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
 1.38065 +    }
 1.38066 +    sqlite3_mutex_leave(pcache1.mutex);
 1.38067 +  }
 1.38068 +  if( p==0 ){
 1.38069 +    /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
 1.38070 +    ** it from sqlite3Malloc instead.
 1.38071 +    */
 1.38072 +    p = sqlite3Malloc(nByte);
 1.38073 +#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
 1.38074 +    if( p ){
 1.38075 +      int sz = sqlite3MallocSize(p);
 1.38076 +      sqlite3_mutex_enter(pcache1.mutex);
 1.38077 +      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
 1.38078 +      sqlite3_mutex_leave(pcache1.mutex);
 1.38079 +    }
 1.38080 +#endif
 1.38081 +    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
 1.38082 +  }
 1.38083 +  return p;
 1.38084 +}
 1.38085 +
 1.38086 +/*
 1.38087 +** Free an allocated buffer obtained from pcache1Alloc().
 1.38088 +*/
 1.38089 +static int pcache1Free(void *p){
 1.38090 +  int nFreed = 0;
 1.38091 +  if( p==0 ) return 0;
 1.38092 +  if( p>=pcache1.pStart && p<pcache1.pEnd ){
 1.38093 +    PgFreeslot *pSlot;
 1.38094 +    sqlite3_mutex_enter(pcache1.mutex);
 1.38095 +    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
 1.38096 +    pSlot = (PgFreeslot*)p;
 1.38097 +    pSlot->pNext = pcache1.pFree;
 1.38098 +    pcache1.pFree = pSlot;
 1.38099 +    pcache1.nFreeSlot++;
 1.38100 +    pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
 1.38101 +    assert( pcache1.nFreeSlot<=pcache1.nSlot );
 1.38102 +    sqlite3_mutex_leave(pcache1.mutex);
 1.38103 +  }else{
 1.38104 +    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
 1.38105 +    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
 1.38106 +    nFreed = sqlite3MallocSize(p);
 1.38107 +#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
 1.38108 +    sqlite3_mutex_enter(pcache1.mutex);
 1.38109 +    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
 1.38110 +    sqlite3_mutex_leave(pcache1.mutex);
 1.38111 +#endif
 1.38112 +    sqlite3_free(p);
 1.38113 +  }
 1.38114 +  return nFreed;
 1.38115 +}
 1.38116 +
 1.38117 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
 1.38118 +/*
 1.38119 +** Return the size of a pcache allocation
 1.38120 +*/
 1.38121 +static int pcache1MemSize(void *p){
 1.38122 +  if( p>=pcache1.pStart && p<pcache1.pEnd ){
 1.38123 +    return pcache1.szSlot;
 1.38124 +  }else{
 1.38125 +    int iSize;
 1.38126 +    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
 1.38127 +    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
 1.38128 +    iSize = sqlite3MallocSize(p);
 1.38129 +    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
 1.38130 +    return iSize;
 1.38131 +  }
 1.38132 +}
 1.38133 +#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
 1.38134 +
 1.38135 +/*
 1.38136 +** Allocate a new page object initially associated with cache pCache.
 1.38137 +*/
 1.38138 +static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
 1.38139 +  PgHdr1 *p = 0;
 1.38140 +  void *pPg;
 1.38141 +
 1.38142 +  /* The group mutex must be released before pcache1Alloc() is called. This
 1.38143 +  ** is because it may call sqlite3_release_memory(), which assumes that 
 1.38144 +  ** this mutex is not held. */
 1.38145 +  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
 1.38146 +  pcache1LeaveMutex(pCache->pGroup);
 1.38147 +#ifdef SQLITE_PCACHE_SEPARATE_HEADER
 1.38148 +  pPg = pcache1Alloc(pCache->szPage);
 1.38149 +  p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
 1.38150 +  if( !pPg || !p ){
 1.38151 +    pcache1Free(pPg);
 1.38152 +    sqlite3_free(p);
 1.38153 +    pPg = 0;
 1.38154 +  }
 1.38155 +#else
 1.38156 +  pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
 1.38157 +  p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
 1.38158 +#endif
 1.38159 +  pcache1EnterMutex(pCache->pGroup);
 1.38160 +
 1.38161 +  if( pPg ){
 1.38162 +    p->page.pBuf = pPg;
 1.38163 +    p->page.pExtra = &p[1];
 1.38164 +    if( pCache->bPurgeable ){
 1.38165 +      pCache->pGroup->nCurrentPage++;
 1.38166 +    }
 1.38167 +    return p;
 1.38168 +  }
 1.38169 +  return 0;
 1.38170 +}
 1.38171 +
 1.38172 +/*
 1.38173 +** Free a page object allocated by pcache1AllocPage().
 1.38174 +**
 1.38175 +** The pointer is allowed to be NULL, which is prudent.  But it turns out
 1.38176 +** that the current implementation happens to never call this routine
 1.38177 +** with a NULL pointer, so we mark the NULL test with ALWAYS().
 1.38178 +*/
 1.38179 +static void pcache1FreePage(PgHdr1 *p){
 1.38180 +  if( ALWAYS(p) ){
 1.38181 +    PCache1 *pCache = p->pCache;
 1.38182 +    assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
 1.38183 +    pcache1Free(p->page.pBuf);
 1.38184 +#ifdef SQLITE_PCACHE_SEPARATE_HEADER
 1.38185 +    sqlite3_free(p);
 1.38186 +#endif
 1.38187 +    if( pCache->bPurgeable ){
 1.38188 +      pCache->pGroup->nCurrentPage--;
 1.38189 +    }
 1.38190 +  }
 1.38191 +}
 1.38192 +
 1.38193 +/*
 1.38194 +** Malloc function used by SQLite to obtain space from the buffer configured
 1.38195 +** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
 1.38196 +** exists, this function falls back to sqlite3Malloc().
 1.38197 +*/
 1.38198 +SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
 1.38199 +  return pcache1Alloc(sz);
 1.38200 +}
 1.38201 +
 1.38202 +/*
 1.38203 +** Free an allocated buffer obtained from sqlite3PageMalloc().
 1.38204 +*/
 1.38205 +SQLITE_PRIVATE void sqlite3PageFree(void *p){
 1.38206 +  pcache1Free(p);
 1.38207 +}
 1.38208 +
 1.38209 +
 1.38210 +/*
 1.38211 +** Return true if it desirable to avoid allocating a new page cache
 1.38212 +** entry.
 1.38213 +**
 1.38214 +** If memory was allocated specifically to the page cache using
 1.38215 +** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
 1.38216 +** it is desirable to avoid allocating a new page cache entry because
 1.38217 +** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
 1.38218 +** for all page cache needs and we should not need to spill the
 1.38219 +** allocation onto the heap.
 1.38220 +**
 1.38221 +** Or, the heap is used for all page cache memory but the heap is
 1.38222 +** under memory pressure, then again it is desirable to avoid
 1.38223 +** allocating a new page cache entry in order to avoid stressing
 1.38224 +** the heap even further.
 1.38225 +*/
 1.38226 +static int pcache1UnderMemoryPressure(PCache1 *pCache){
 1.38227 +  if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
 1.38228 +    return pcache1.bUnderPressure;
 1.38229 +  }else{
 1.38230 +    return sqlite3HeapNearlyFull();
 1.38231 +  }
 1.38232 +}
 1.38233 +
 1.38234 +/******************************************************************************/
 1.38235 +/******** General Implementation Functions ************************************/
 1.38236 +
 1.38237 +/*
 1.38238 +** This function is used to resize the hash table used by the cache passed
 1.38239 +** as the first argument.
 1.38240 +**
 1.38241 +** The PCache mutex must be held when this function is called.
 1.38242 +*/
 1.38243 +static int pcache1ResizeHash(PCache1 *p){
 1.38244 +  PgHdr1 **apNew;
 1.38245 +  unsigned int nNew;
 1.38246 +  unsigned int i;
 1.38247 +
 1.38248 +  assert( sqlite3_mutex_held(p->pGroup->mutex) );
 1.38249 +
 1.38250 +  nNew = p->nHash*2;
 1.38251 +  if( nNew<256 ){
 1.38252 +    nNew = 256;
 1.38253 +  }
 1.38254 +
 1.38255 +  pcache1LeaveMutex(p->pGroup);
 1.38256 +  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
 1.38257 +  apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
 1.38258 +  if( p->nHash ){ sqlite3EndBenignMalloc(); }
 1.38259 +  pcache1EnterMutex(p->pGroup);
 1.38260 +  if( apNew ){
 1.38261 +    for(i=0; i<p->nHash; i++){
 1.38262 +      PgHdr1 *pPage;
 1.38263 +      PgHdr1 *pNext = p->apHash[i];
 1.38264 +      while( (pPage = pNext)!=0 ){
 1.38265 +        unsigned int h = pPage->iKey % nNew;
 1.38266 +        pNext = pPage->pNext;
 1.38267 +        pPage->pNext = apNew[h];
 1.38268 +        apNew[h] = pPage;
 1.38269 +      }
 1.38270 +    }
 1.38271 +    sqlite3_free(p->apHash);
 1.38272 +    p->apHash = apNew;
 1.38273 +    p->nHash = nNew;
 1.38274 +  }
 1.38275 +
 1.38276 +  return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
 1.38277 +}
 1.38278 +
 1.38279 +/*
 1.38280 +** This function is used internally to remove the page pPage from the 
 1.38281 +** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
 1.38282 +** LRU list, then this function is a no-op.
 1.38283 +**
 1.38284 +** The PGroup mutex must be held when this function is called.
 1.38285 +*/
 1.38286 +static void pcache1PinPage(PgHdr1 *pPage){
 1.38287 +  PCache1 *pCache;
 1.38288 +  PGroup *pGroup;
 1.38289 +
 1.38290 +  assert( pPage!=0 );
 1.38291 +  assert( pPage->isPinned==0 );
 1.38292 +  pCache = pPage->pCache;
 1.38293 +  pGroup = pCache->pGroup;
 1.38294 +  assert( pPage->pLruNext || pPage==pGroup->pLruTail );
 1.38295 +  assert( pPage->pLruPrev || pPage==pGroup->pLruHead );
 1.38296 +  assert( sqlite3_mutex_held(pGroup->mutex) );
 1.38297 +  if( pPage->pLruPrev ){
 1.38298 +    pPage->pLruPrev->pLruNext = pPage->pLruNext;
 1.38299 +  }else{
 1.38300 +    pGroup->pLruHead = pPage->pLruNext;
 1.38301 +  }
 1.38302 +  if( pPage->pLruNext ){
 1.38303 +    pPage->pLruNext->pLruPrev = pPage->pLruPrev;
 1.38304 +  }else{
 1.38305 +    pGroup->pLruTail = pPage->pLruPrev;
 1.38306 +  }
 1.38307 +  pPage->pLruNext = 0;
 1.38308 +  pPage->pLruPrev = 0;
 1.38309 +  pPage->isPinned = 1;
 1.38310 +  pCache->nRecyclable--;
 1.38311 +}
 1.38312 +
 1.38313 +
 1.38314 +/*
 1.38315 +** Remove the page supplied as an argument from the hash table 
 1.38316 +** (PCache1.apHash structure) that it is currently stored in.
 1.38317 +**
 1.38318 +** The PGroup mutex must be held when this function is called.
 1.38319 +*/
 1.38320 +static void pcache1RemoveFromHash(PgHdr1 *pPage){
 1.38321 +  unsigned int h;
 1.38322 +  PCache1 *pCache = pPage->pCache;
 1.38323 +  PgHdr1 **pp;
 1.38324 +
 1.38325 +  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
 1.38326 +  h = pPage->iKey % pCache->nHash;
 1.38327 +  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
 1.38328 +  *pp = (*pp)->pNext;
 1.38329 +
 1.38330 +  pCache->nPage--;
 1.38331 +}
 1.38332 +
 1.38333 +/*
 1.38334 +** If there are currently more than nMaxPage pages allocated, try
 1.38335 +** to recycle pages to reduce the number allocated to nMaxPage.
 1.38336 +*/
 1.38337 +static void pcache1EnforceMaxPage(PGroup *pGroup){
 1.38338 +  assert( sqlite3_mutex_held(pGroup->mutex) );
 1.38339 +  while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
 1.38340 +    PgHdr1 *p = pGroup->pLruTail;
 1.38341 +    assert( p->pCache->pGroup==pGroup );
 1.38342 +    assert( p->isPinned==0 );
 1.38343 +    pcache1PinPage(p);
 1.38344 +    pcache1RemoveFromHash(p);
 1.38345 +    pcache1FreePage(p);
 1.38346 +  }
 1.38347 +}
 1.38348 +
 1.38349 +/*
 1.38350 +** Discard all pages from cache pCache with a page number (key value) 
 1.38351 +** greater than or equal to iLimit. Any pinned pages that meet this 
 1.38352 +** criteria are unpinned before they are discarded.
 1.38353 +**
 1.38354 +** The PCache mutex must be held when this function is called.
 1.38355 +*/
 1.38356 +static void pcache1TruncateUnsafe(
 1.38357 +  PCache1 *pCache,             /* The cache to truncate */
 1.38358 +  unsigned int iLimit          /* Drop pages with this pgno or larger */
 1.38359 +){
 1.38360 +  TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
 1.38361 +  unsigned int h;
 1.38362 +  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
 1.38363 +  for(h=0; h<pCache->nHash; h++){
 1.38364 +    PgHdr1 **pp = &pCache->apHash[h]; 
 1.38365 +    PgHdr1 *pPage;
 1.38366 +    while( (pPage = *pp)!=0 ){
 1.38367 +      if( pPage->iKey>=iLimit ){
 1.38368 +        pCache->nPage--;
 1.38369 +        *pp = pPage->pNext;
 1.38370 +        if( !pPage->isPinned ) pcache1PinPage(pPage);
 1.38371 +        pcache1FreePage(pPage);
 1.38372 +      }else{
 1.38373 +        pp = &pPage->pNext;
 1.38374 +        TESTONLY( nPage++; )
 1.38375 +      }
 1.38376 +    }
 1.38377 +  }
 1.38378 +  assert( pCache->nPage==nPage );
 1.38379 +}
 1.38380 +
 1.38381 +/******************************************************************************/
 1.38382 +/******** sqlite3_pcache Methods **********************************************/
 1.38383 +
 1.38384 +/*
 1.38385 +** Implementation of the sqlite3_pcache.xInit method.
 1.38386 +*/
 1.38387 +static int pcache1Init(void *NotUsed){
 1.38388 +  UNUSED_PARAMETER(NotUsed);
 1.38389 +  assert( pcache1.isInit==0 );
 1.38390 +  memset(&pcache1, 0, sizeof(pcache1));
 1.38391 +  if( sqlite3GlobalConfig.bCoreMutex ){
 1.38392 +    pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
 1.38393 +    pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
 1.38394 +  }
 1.38395 +  pcache1.grp.mxPinned = 10;
 1.38396 +  pcache1.isInit = 1;
 1.38397 +  return SQLITE_OK;
 1.38398 +}
 1.38399 +
 1.38400 +/*
 1.38401 +** Implementation of the sqlite3_pcache.xShutdown method.
 1.38402 +** Note that the static mutex allocated in xInit does 
 1.38403 +** not need to be freed.
 1.38404 +*/
 1.38405 +static void pcache1Shutdown(void *NotUsed){
 1.38406 +  UNUSED_PARAMETER(NotUsed);
 1.38407 +  assert( pcache1.isInit!=0 );
 1.38408 +  memset(&pcache1, 0, sizeof(pcache1));
 1.38409 +}
 1.38410 +
 1.38411 +/*
 1.38412 +** Implementation of the sqlite3_pcache.xCreate method.
 1.38413 +**
 1.38414 +** Allocate a new cache.
 1.38415 +*/
 1.38416 +static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
 1.38417 +  PCache1 *pCache;      /* The newly created page cache */
 1.38418 +  PGroup *pGroup;       /* The group the new page cache will belong to */
 1.38419 +  int sz;               /* Bytes of memory required to allocate the new cache */
 1.38420 +
 1.38421 +  /*
 1.38422 +  ** The separateCache variable is true if each PCache has its own private
 1.38423 +  ** PGroup.  In other words, separateCache is true for mode (1) where no
 1.38424 +  ** mutexing is required.
 1.38425 +  **
 1.38426 +  **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
 1.38427 +  **
 1.38428 +  **   *  Always use a unified cache in single-threaded applications
 1.38429 +  **
 1.38430 +  **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
 1.38431 +  **      use separate caches (mode-1)
 1.38432 +  */
 1.38433 +#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
 1.38434 +  const int separateCache = 0;
 1.38435 +#else
 1.38436 +  int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
 1.38437 +#endif
 1.38438 +
 1.38439 +  assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
 1.38440 +  assert( szExtra < 300 );
 1.38441 +
 1.38442 +  sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
 1.38443 +  pCache = (PCache1 *)sqlite3MallocZero(sz);
 1.38444 +  if( pCache ){
 1.38445 +    if( separateCache ){
 1.38446 +      pGroup = (PGroup*)&pCache[1];
 1.38447 +      pGroup->mxPinned = 10;
 1.38448 +    }else{
 1.38449 +      pGroup = &pcache1.grp;
 1.38450 +    }
 1.38451 +    pCache->pGroup = pGroup;
 1.38452 +    pCache->szPage = szPage;
 1.38453 +    pCache->szExtra = szExtra;
 1.38454 +    pCache->bPurgeable = (bPurgeable ? 1 : 0);
 1.38455 +    if( bPurgeable ){
 1.38456 +      pCache->nMin = 10;
 1.38457 +      pcache1EnterMutex(pGroup);
 1.38458 +      pGroup->nMinPage += pCache->nMin;
 1.38459 +      pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
 1.38460 +      pcache1LeaveMutex(pGroup);
 1.38461 +    }
 1.38462 +  }
 1.38463 +  return (sqlite3_pcache *)pCache;
 1.38464 +}
 1.38465 +
 1.38466 +/*
 1.38467 +** Implementation of the sqlite3_pcache.xCachesize method. 
 1.38468 +**
 1.38469 +** Configure the cache_size limit for a cache.
 1.38470 +*/
 1.38471 +static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
 1.38472 +  PCache1 *pCache = (PCache1 *)p;
 1.38473 +  if( pCache->bPurgeable ){
 1.38474 +    PGroup *pGroup = pCache->pGroup;
 1.38475 +    pcache1EnterMutex(pGroup);
 1.38476 +    pGroup->nMaxPage += (nMax - pCache->nMax);
 1.38477 +    pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
 1.38478 +    pCache->nMax = nMax;
 1.38479 +    pCache->n90pct = pCache->nMax*9/10;
 1.38480 +    pcache1EnforceMaxPage(pGroup);
 1.38481 +    pcache1LeaveMutex(pGroup);
 1.38482 +  }
 1.38483 +}
 1.38484 +
 1.38485 +/*
 1.38486 +** Implementation of the sqlite3_pcache.xShrink method. 
 1.38487 +**
 1.38488 +** Free up as much memory as possible.
 1.38489 +*/
 1.38490 +static void pcache1Shrink(sqlite3_pcache *p){
 1.38491 +  PCache1 *pCache = (PCache1*)p;
 1.38492 +  if( pCache->bPurgeable ){
 1.38493 +    PGroup *pGroup = pCache->pGroup;
 1.38494 +    int savedMaxPage;
 1.38495 +    pcache1EnterMutex(pGroup);
 1.38496 +    savedMaxPage = pGroup->nMaxPage;
 1.38497 +    pGroup->nMaxPage = 0;
 1.38498 +    pcache1EnforceMaxPage(pGroup);
 1.38499 +    pGroup->nMaxPage = savedMaxPage;
 1.38500 +    pcache1LeaveMutex(pGroup);
 1.38501 +  }
 1.38502 +}
 1.38503 +
 1.38504 +/*
 1.38505 +** Implementation of the sqlite3_pcache.xPagecount method. 
 1.38506 +*/
 1.38507 +static int pcache1Pagecount(sqlite3_pcache *p){
 1.38508 +  int n;
 1.38509 +  PCache1 *pCache = (PCache1*)p;
 1.38510 +  pcache1EnterMutex(pCache->pGroup);
 1.38511 +  n = pCache->nPage;
 1.38512 +  pcache1LeaveMutex(pCache->pGroup);
 1.38513 +  return n;
 1.38514 +}
 1.38515 +
 1.38516 +/*
 1.38517 +** Implementation of the sqlite3_pcache.xFetch method. 
 1.38518 +**
 1.38519 +** Fetch a page by key value.
 1.38520 +**
 1.38521 +** Whether or not a new page may be allocated by this function depends on
 1.38522 +** the value of the createFlag argument.  0 means do not allocate a new
 1.38523 +** page.  1 means allocate a new page if space is easily available.  2 
 1.38524 +** means to try really hard to allocate a new page.
 1.38525 +**
 1.38526 +** For a non-purgeable cache (a cache used as the storage for an in-memory
 1.38527 +** database) there is really no difference between createFlag 1 and 2.  So
 1.38528 +** the calling function (pcache.c) will never have a createFlag of 1 on
 1.38529 +** a non-purgeable cache.
 1.38530 +**
 1.38531 +** There are three different approaches to obtaining space for a page,
 1.38532 +** depending on the value of parameter createFlag (which may be 0, 1 or 2).
 1.38533 +**
 1.38534 +**   1. Regardless of the value of createFlag, the cache is searched for a 
 1.38535 +**      copy of the requested page. If one is found, it is returned.
 1.38536 +**
 1.38537 +**   2. If createFlag==0 and the page is not already in the cache, NULL is
 1.38538 +**      returned.
 1.38539 +**
 1.38540 +**   3. If createFlag is 1, and the page is not already in the cache, then
 1.38541 +**      return NULL (do not allocate a new page) if any of the following
 1.38542 +**      conditions are true:
 1.38543 +**
 1.38544 +**       (a) the number of pages pinned by the cache is greater than
 1.38545 +**           PCache1.nMax, or
 1.38546 +**
 1.38547 +**       (b) the number of pages pinned by the cache is greater than
 1.38548 +**           the sum of nMax for all purgeable caches, less the sum of 
 1.38549 +**           nMin for all other purgeable caches, or
 1.38550 +**
 1.38551 +**   4. If none of the first three conditions apply and the cache is marked
 1.38552 +**      as purgeable, and if one of the following is true:
 1.38553 +**
 1.38554 +**       (a) The number of pages allocated for the cache is already 
 1.38555 +**           PCache1.nMax, or
 1.38556 +**
 1.38557 +**       (b) The number of pages allocated for all purgeable caches is
 1.38558 +**           already equal to or greater than the sum of nMax for all
 1.38559 +**           purgeable caches,
 1.38560 +**
 1.38561 +**       (c) The system is under memory pressure and wants to avoid
 1.38562 +**           unnecessary pages cache entry allocations
 1.38563 +**
 1.38564 +**      then attempt to recycle a page from the LRU list. If it is the right
 1.38565 +**      size, return the recycled buffer. Otherwise, free the buffer and
 1.38566 +**      proceed to step 5. 
 1.38567 +**
 1.38568 +**   5. Otherwise, allocate and return a new page buffer.
 1.38569 +*/
 1.38570 +static sqlite3_pcache_page *pcache1Fetch(
 1.38571 +  sqlite3_pcache *p, 
 1.38572 +  unsigned int iKey, 
 1.38573 +  int createFlag
 1.38574 +){
 1.38575 +  unsigned int nPinned;
 1.38576 +  PCache1 *pCache = (PCache1 *)p;
 1.38577 +  PGroup *pGroup;
 1.38578 +  PgHdr1 *pPage = 0;
 1.38579 +
 1.38580 +  assert( offsetof(PgHdr1,page)==0 );
 1.38581 +  assert( pCache->bPurgeable || createFlag!=1 );
 1.38582 +  assert( pCache->bPurgeable || pCache->nMin==0 );
 1.38583 +  assert( pCache->bPurgeable==0 || pCache->nMin==10 );
 1.38584 +  assert( pCache->nMin==0 || pCache->bPurgeable );
 1.38585 +  pcache1EnterMutex(pGroup = pCache->pGroup);
 1.38586 +
 1.38587 +  /* Step 1: Search the hash table for an existing entry. */
 1.38588 +  if( pCache->nHash>0 ){
 1.38589 +    unsigned int h = iKey % pCache->nHash;
 1.38590 +    for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
 1.38591 +  }
 1.38592 +
 1.38593 +  /* Step 2: Abort if no existing page is found and createFlag is 0 */
 1.38594 +  if( pPage ){
 1.38595 +    if( !pPage->isPinned ) pcache1PinPage(pPage);
 1.38596 +    goto fetch_out;
 1.38597 +  }
 1.38598 +  if( createFlag==0 ){
 1.38599 +    goto fetch_out;
 1.38600 +  }
 1.38601 +
 1.38602 +  /* The pGroup local variable will normally be initialized by the
 1.38603 +  ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
 1.38604 +  ** then pcache1EnterMutex() is a no-op, so we have to initialize the
 1.38605 +  ** local variable here.  Delaying the initialization of pGroup is an
 1.38606 +  ** optimization:  The common case is to exit the module before reaching
 1.38607 +  ** this point.
 1.38608 +  */
 1.38609 +#ifdef SQLITE_MUTEX_OMIT
 1.38610 +  pGroup = pCache->pGroup;
 1.38611 +#endif
 1.38612 +
 1.38613 +  /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
 1.38614 +  assert( pCache->nPage >= pCache->nRecyclable );
 1.38615 +  nPinned = pCache->nPage - pCache->nRecyclable;
 1.38616 +  assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
 1.38617 +  assert( pCache->n90pct == pCache->nMax*9/10 );
 1.38618 +  if( createFlag==1 && (
 1.38619 +        nPinned>=pGroup->mxPinned
 1.38620 +     || nPinned>=pCache->n90pct
 1.38621 +     || pcache1UnderMemoryPressure(pCache)
 1.38622 +  )){
 1.38623 +    goto fetch_out;
 1.38624 +  }
 1.38625 +
 1.38626 +  if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
 1.38627 +    goto fetch_out;
 1.38628 +  }
 1.38629 +  assert( pCache->nHash>0 && pCache->apHash );
 1.38630 +
 1.38631 +  /* Step 4. Try to recycle a page. */
 1.38632 +  if( pCache->bPurgeable && pGroup->pLruTail && (
 1.38633 +         (pCache->nPage+1>=pCache->nMax)
 1.38634 +      || pGroup->nCurrentPage>=pGroup->nMaxPage
 1.38635 +      || pcache1UnderMemoryPressure(pCache)
 1.38636 +  )){
 1.38637 +    PCache1 *pOther;
 1.38638 +    pPage = pGroup->pLruTail;
 1.38639 +    assert( pPage->isPinned==0 );
 1.38640 +    pcache1RemoveFromHash(pPage);
 1.38641 +    pcache1PinPage(pPage);
 1.38642 +    pOther = pPage->pCache;
 1.38643 +
 1.38644 +    /* We want to verify that szPage and szExtra are the same for pOther
 1.38645 +    ** and pCache.  Assert that we can verify this by comparing sums. */
 1.38646 +    assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
 1.38647 +    assert( pCache->szExtra<512 );
 1.38648 +    assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
 1.38649 +    assert( pOther->szExtra<512 );
 1.38650 +
 1.38651 +    if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
 1.38652 +      pcache1FreePage(pPage);
 1.38653 +      pPage = 0;
 1.38654 +    }else{
 1.38655 +      pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
 1.38656 +    }
 1.38657 +  }
 1.38658 +
 1.38659 +  /* Step 5. If a usable page buffer has still not been found, 
 1.38660 +  ** attempt to allocate a new one. 
 1.38661 +  */
 1.38662 +  if( !pPage ){
 1.38663 +    if( createFlag==1 ) sqlite3BeginBenignMalloc();
 1.38664 +    pPage = pcache1AllocPage(pCache);
 1.38665 +    if( createFlag==1 ) sqlite3EndBenignMalloc();
 1.38666 +  }
 1.38667 +
 1.38668 +  if( pPage ){
 1.38669 +    unsigned int h = iKey % pCache->nHash;
 1.38670 +    pCache->nPage++;
 1.38671 +    pPage->iKey = iKey;
 1.38672 +    pPage->pNext = pCache->apHash[h];
 1.38673 +    pPage->pCache = pCache;
 1.38674 +    pPage->pLruPrev = 0;
 1.38675 +    pPage->pLruNext = 0;
 1.38676 +    pPage->isPinned = 1;
 1.38677 +    *(void **)pPage->page.pExtra = 0;
 1.38678 +    pCache->apHash[h] = pPage;
 1.38679 +  }
 1.38680 +
 1.38681 +fetch_out:
 1.38682 +  if( pPage && iKey>pCache->iMaxKey ){
 1.38683 +    pCache->iMaxKey = iKey;
 1.38684 +  }
 1.38685 +  pcache1LeaveMutex(pGroup);
 1.38686 +  return (sqlite3_pcache_page*)pPage;
 1.38687 +}
 1.38688 +
 1.38689 +
 1.38690 +/*
 1.38691 +** Implementation of the sqlite3_pcache.xUnpin method.
 1.38692 +**
 1.38693 +** Mark a page as unpinned (eligible for asynchronous recycling).
 1.38694 +*/
 1.38695 +static void pcache1Unpin(
 1.38696 +  sqlite3_pcache *p, 
 1.38697 +  sqlite3_pcache_page *pPg, 
 1.38698 +  int reuseUnlikely
 1.38699 +){
 1.38700 +  PCache1 *pCache = (PCache1 *)p;
 1.38701 +  PgHdr1 *pPage = (PgHdr1 *)pPg;
 1.38702 +  PGroup *pGroup = pCache->pGroup;
 1.38703 + 
 1.38704 +  assert( pPage->pCache==pCache );
 1.38705 +  pcache1EnterMutex(pGroup);
 1.38706 +
 1.38707 +  /* It is an error to call this function if the page is already 
 1.38708 +  ** part of the PGroup LRU list.
 1.38709 +  */
 1.38710 +  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
 1.38711 +  assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
 1.38712 +  assert( pPage->isPinned==1 );
 1.38713 +
 1.38714 +  if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
 1.38715 +    pcache1RemoveFromHash(pPage);
 1.38716 +    pcache1FreePage(pPage);
 1.38717 +  }else{
 1.38718 +    /* Add the page to the PGroup LRU list. */
 1.38719 +    if( pGroup->pLruHead ){
 1.38720 +      pGroup->pLruHead->pLruPrev = pPage;
 1.38721 +      pPage->pLruNext = pGroup->pLruHead;
 1.38722 +      pGroup->pLruHead = pPage;
 1.38723 +    }else{
 1.38724 +      pGroup->pLruTail = pPage;
 1.38725 +      pGroup->pLruHead = pPage;
 1.38726 +    }
 1.38727 +    pCache->nRecyclable++;
 1.38728 +    pPage->isPinned = 0;
 1.38729 +  }
 1.38730 +
 1.38731 +  pcache1LeaveMutex(pCache->pGroup);
 1.38732 +}
 1.38733 +
 1.38734 +/*
 1.38735 +** Implementation of the sqlite3_pcache.xRekey method. 
 1.38736 +*/
 1.38737 +static void pcache1Rekey(
 1.38738 +  sqlite3_pcache *p,
 1.38739 +  sqlite3_pcache_page *pPg,
 1.38740 +  unsigned int iOld,
 1.38741 +  unsigned int iNew
 1.38742 +){
 1.38743 +  PCache1 *pCache = (PCache1 *)p;
 1.38744 +  PgHdr1 *pPage = (PgHdr1 *)pPg;
 1.38745 +  PgHdr1 **pp;
 1.38746 +  unsigned int h; 
 1.38747 +  assert( pPage->iKey==iOld );
 1.38748 +  assert( pPage->pCache==pCache );
 1.38749 +
 1.38750 +  pcache1EnterMutex(pCache->pGroup);
 1.38751 +
 1.38752 +  h = iOld%pCache->nHash;
 1.38753 +  pp = &pCache->apHash[h];
 1.38754 +  while( (*pp)!=pPage ){
 1.38755 +    pp = &(*pp)->pNext;
 1.38756 +  }
 1.38757 +  *pp = pPage->pNext;
 1.38758 +
 1.38759 +  h = iNew%pCache->nHash;
 1.38760 +  pPage->iKey = iNew;
 1.38761 +  pPage->pNext = pCache->apHash[h];
 1.38762 +  pCache->apHash[h] = pPage;
 1.38763 +  if( iNew>pCache->iMaxKey ){
 1.38764 +    pCache->iMaxKey = iNew;
 1.38765 +  }
 1.38766 +
 1.38767 +  pcache1LeaveMutex(pCache->pGroup);
 1.38768 +}
 1.38769 +
 1.38770 +/*
 1.38771 +** Implementation of the sqlite3_pcache.xTruncate method. 
 1.38772 +**
 1.38773 +** Discard all unpinned pages in the cache with a page number equal to
 1.38774 +** or greater than parameter iLimit. Any pinned pages with a page number
 1.38775 +** equal to or greater than iLimit are implicitly unpinned.
 1.38776 +*/
 1.38777 +static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
 1.38778 +  PCache1 *pCache = (PCache1 *)p;
 1.38779 +  pcache1EnterMutex(pCache->pGroup);
 1.38780 +  if( iLimit<=pCache->iMaxKey ){
 1.38781 +    pcache1TruncateUnsafe(pCache, iLimit);
 1.38782 +    pCache->iMaxKey = iLimit-1;
 1.38783 +  }
 1.38784 +  pcache1LeaveMutex(pCache->pGroup);
 1.38785 +}
 1.38786 +
 1.38787 +/*
 1.38788 +** Implementation of the sqlite3_pcache.xDestroy method. 
 1.38789 +**
 1.38790 +** Destroy a cache allocated using pcache1Create().
 1.38791 +*/
 1.38792 +static void pcache1Destroy(sqlite3_pcache *p){
 1.38793 +  PCache1 *pCache = (PCache1 *)p;
 1.38794 +  PGroup *pGroup = pCache->pGroup;
 1.38795 +  assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
 1.38796 +  pcache1EnterMutex(pGroup);
 1.38797 +  pcache1TruncateUnsafe(pCache, 0);
 1.38798 +  assert( pGroup->nMaxPage >= pCache->nMax );
 1.38799 +  pGroup->nMaxPage -= pCache->nMax;
 1.38800 +  assert( pGroup->nMinPage >= pCache->nMin );
 1.38801 +  pGroup->nMinPage -= pCache->nMin;
 1.38802 +  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
 1.38803 +  pcache1EnforceMaxPage(pGroup);
 1.38804 +  pcache1LeaveMutex(pGroup);
 1.38805 +  sqlite3_free(pCache->apHash);
 1.38806 +  sqlite3_free(pCache);
 1.38807 +}
 1.38808 +
 1.38809 +/*
 1.38810 +** This function is called during initialization (sqlite3_initialize()) to
 1.38811 +** install the default pluggable cache module, assuming the user has not
 1.38812 +** already provided an alternative.
 1.38813 +*/
 1.38814 +SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
 1.38815 +  static const sqlite3_pcache_methods2 defaultMethods = {
 1.38816 +    1,                       /* iVersion */
 1.38817 +    0,                       /* pArg */
 1.38818 +    pcache1Init,             /* xInit */
 1.38819 +    pcache1Shutdown,         /* xShutdown */
 1.38820 +    pcache1Create,           /* xCreate */
 1.38821 +    pcache1Cachesize,        /* xCachesize */
 1.38822 +    pcache1Pagecount,        /* xPagecount */
 1.38823 +    pcache1Fetch,            /* xFetch */
 1.38824 +    pcache1Unpin,            /* xUnpin */
 1.38825 +    pcache1Rekey,            /* xRekey */
 1.38826 +    pcache1Truncate,         /* xTruncate */
 1.38827 +    pcache1Destroy,          /* xDestroy */
 1.38828 +    pcache1Shrink            /* xShrink */
 1.38829 +  };
 1.38830 +  sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
 1.38831 +}
 1.38832 +
 1.38833 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
 1.38834 +/*
 1.38835 +** This function is called to free superfluous dynamically allocated memory
 1.38836 +** held by the pager system. Memory in use by any SQLite pager allocated
 1.38837 +** by the current thread may be sqlite3_free()ed.
 1.38838 +**
 1.38839 +** nReq is the number of bytes of memory required. Once this much has
 1.38840 +** been released, the function returns. The return value is the total number 
 1.38841 +** of bytes of memory released.
 1.38842 +*/
 1.38843 +SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
 1.38844 +  int nFree = 0;
 1.38845 +  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
 1.38846 +  assert( sqlite3_mutex_notheld(pcache1.mutex) );
 1.38847 +  if( pcache1.pStart==0 ){
 1.38848 +    PgHdr1 *p;
 1.38849 +    pcache1EnterMutex(&pcache1.grp);
 1.38850 +    while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
 1.38851 +      nFree += pcache1MemSize(p->page.pBuf);
 1.38852 +#ifdef SQLITE_PCACHE_SEPARATE_HEADER
 1.38853 +      nFree += sqlite3MemSize(p);
 1.38854 +#endif
 1.38855 +      assert( p->isPinned==0 );
 1.38856 +      pcache1PinPage(p);
 1.38857 +      pcache1RemoveFromHash(p);
 1.38858 +      pcache1FreePage(p);
 1.38859 +    }
 1.38860 +    pcache1LeaveMutex(&pcache1.grp);
 1.38861 +  }
 1.38862 +  return nFree;
 1.38863 +}
 1.38864 +#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
 1.38865 +
 1.38866 +#ifdef SQLITE_TEST
 1.38867 +/*
 1.38868 +** This function is used by test procedures to inspect the internal state
 1.38869 +** of the global cache.
 1.38870 +*/
 1.38871 +SQLITE_PRIVATE void sqlite3PcacheStats(
 1.38872 +  int *pnCurrent,      /* OUT: Total number of pages cached */
 1.38873 +  int *pnMax,          /* OUT: Global maximum cache size */
 1.38874 +  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
 1.38875 +  int *pnRecyclable    /* OUT: Total number of pages available for recycling */
 1.38876 +){
 1.38877 +  PgHdr1 *p;
 1.38878 +  int nRecyclable = 0;
 1.38879 +  for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
 1.38880 +    assert( p->isPinned==0 );
 1.38881 +    nRecyclable++;
 1.38882 +  }
 1.38883 +  *pnCurrent = pcache1.grp.nCurrentPage;
 1.38884 +  *pnMax = (int)pcache1.grp.nMaxPage;
 1.38885 +  *pnMin = (int)pcache1.grp.nMinPage;
 1.38886 +  *pnRecyclable = nRecyclable;
 1.38887 +}
 1.38888 +#endif
 1.38889 +
 1.38890 +/************** End of pcache1.c *********************************************/
 1.38891 +/************** Begin file rowset.c ******************************************/
 1.38892 +/*
 1.38893 +** 2008 December 3
 1.38894 +**
 1.38895 +** The author disclaims copyright to this source code.  In place of
 1.38896 +** a legal notice, here is a blessing:
 1.38897 +**
 1.38898 +**    May you do good and not evil.
 1.38899 +**    May you find forgiveness for yourself and forgive others.
 1.38900 +**    May you share freely, never taking more than you give.
 1.38901 +**
 1.38902 +*************************************************************************
 1.38903 +**
 1.38904 +** This module implements an object we call a "RowSet".
 1.38905 +**
 1.38906 +** The RowSet object is a collection of rowids.  Rowids
 1.38907 +** are inserted into the RowSet in an arbitrary order.  Inserts
 1.38908 +** can be intermixed with tests to see if a given rowid has been
 1.38909 +** previously inserted into the RowSet.
 1.38910 +**
 1.38911 +** After all inserts are finished, it is possible to extract the
 1.38912 +** elements of the RowSet in sorted order.  Once this extraction
 1.38913 +** process has started, no new elements may be inserted.
 1.38914 +**
 1.38915 +** Hence, the primitive operations for a RowSet are:
 1.38916 +**
 1.38917 +**    CREATE
 1.38918 +**    INSERT
 1.38919 +**    TEST
 1.38920 +**    SMALLEST
 1.38921 +**    DESTROY
 1.38922 +**
 1.38923 +** The CREATE and DESTROY primitives are the constructor and destructor,
 1.38924 +** obviously.  The INSERT primitive adds a new element to the RowSet.
 1.38925 +** TEST checks to see if an element is already in the RowSet.  SMALLEST
 1.38926 +** extracts the least value from the RowSet.
 1.38927 +**
 1.38928 +** The INSERT primitive might allocate additional memory.  Memory is
 1.38929 +** allocated in chunks so most INSERTs do no allocation.  There is an 
 1.38930 +** upper bound on the size of allocated memory.  No memory is freed
 1.38931 +** until DESTROY.
 1.38932 +**
 1.38933 +** The TEST primitive includes a "batch" number.  The TEST primitive
 1.38934 +** will only see elements that were inserted before the last change
 1.38935 +** in the batch number.  In other words, if an INSERT occurs between
 1.38936 +** two TESTs where the TESTs have the same batch nubmer, then the
 1.38937 +** value added by the INSERT will not be visible to the second TEST.
 1.38938 +** The initial batch number is zero, so if the very first TEST contains
 1.38939 +** a non-zero batch number, it will see all prior INSERTs.
 1.38940 +**
 1.38941 +** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
 1.38942 +** that is attempted.
 1.38943 +**
 1.38944 +** The cost of an INSERT is roughly constant.  (Sometime new memory
 1.38945 +** has to be allocated on an INSERT.)  The cost of a TEST with a new
 1.38946 +** batch number is O(NlogN) where N is the number of elements in the RowSet.
 1.38947 +** The cost of a TEST using the same batch number is O(logN).  The cost
 1.38948 +** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
 1.38949 +** primitives are constant time.  The cost of DESTROY is O(N).
 1.38950 +**
 1.38951 +** There is an added cost of O(N) when switching between TEST and
 1.38952 +** SMALLEST primitives.
 1.38953 +*/
 1.38954 +
 1.38955 +
 1.38956 +/*
 1.38957 +** Target size for allocation chunks.
 1.38958 +*/
 1.38959 +#define ROWSET_ALLOCATION_SIZE 1024
 1.38960 +
 1.38961 +/*
 1.38962 +** The number of rowset entries per allocation chunk.
 1.38963 +*/
 1.38964 +#define ROWSET_ENTRY_PER_CHUNK  \
 1.38965 +                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
 1.38966 +
 1.38967 +/*
 1.38968 +** Each entry in a RowSet is an instance of the following object.
 1.38969 +**
 1.38970 +** This same object is reused to store a linked list of trees of RowSetEntry
 1.38971 +** objects.  In that alternative use, pRight points to the next entry
 1.38972 +** in the list, pLeft points to the tree, and v is unused.  The
 1.38973 +** RowSet.pForest value points to the head of this forest list.
 1.38974 +*/
 1.38975 +struct RowSetEntry {            
 1.38976 +  i64 v;                        /* ROWID value for this entry */
 1.38977 +  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
 1.38978 +  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
 1.38979 +};
 1.38980 +
 1.38981 +/*
 1.38982 +** RowSetEntry objects are allocated in large chunks (instances of the
 1.38983 +** following structure) to reduce memory allocation overhead.  The
 1.38984 +** chunks are kept on a linked list so that they can be deallocated
 1.38985 +** when the RowSet is destroyed.
 1.38986 +*/
 1.38987 +struct RowSetChunk {
 1.38988 +  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
 1.38989 +  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
 1.38990 +};
 1.38991 +
 1.38992 +/*
 1.38993 +** A RowSet in an instance of the following structure.
 1.38994 +**
 1.38995 +** A typedef of this structure if found in sqliteInt.h.
 1.38996 +*/
 1.38997 +struct RowSet {
 1.38998 +  struct RowSetChunk *pChunk;    /* List of all chunk allocations */
 1.38999 +  sqlite3 *db;                   /* The database connection */
 1.39000 +  struct RowSetEntry *pEntry;    /* List of entries using pRight */
 1.39001 +  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
 1.39002 +  struct RowSetEntry *pFresh;    /* Source of new entry objects */
 1.39003 +  struct RowSetEntry *pForest;   /* List of binary trees of entries */
 1.39004 +  u16 nFresh;                    /* Number of objects on pFresh */
 1.39005 +  u8 rsFlags;                    /* Various flags */
 1.39006 +  u8 iBatch;                     /* Current insert batch */
 1.39007 +};
 1.39008 +
 1.39009 +/*
 1.39010 +** Allowed values for RowSet.rsFlags
 1.39011 +*/
 1.39012 +#define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
 1.39013 +#define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
 1.39014 +
 1.39015 +/*
 1.39016 +** Turn bulk memory into a RowSet object.  N bytes of memory
 1.39017 +** are available at pSpace.  The db pointer is used as a memory context
 1.39018 +** for any subsequent allocations that need to occur.
 1.39019 +** Return a pointer to the new RowSet object.
 1.39020 +**
 1.39021 +** It must be the case that N is sufficient to make a Rowset.  If not
 1.39022 +** an assertion fault occurs.
 1.39023 +** 
 1.39024 +** If N is larger than the minimum, use the surplus as an initial
 1.39025 +** allocation of entries available to be filled.
 1.39026 +*/
 1.39027 +SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
 1.39028 +  RowSet *p;
 1.39029 +  assert( N >= ROUND8(sizeof(*p)) );
 1.39030 +  p = pSpace;
 1.39031 +  p->pChunk = 0;
 1.39032 +  p->db = db;
 1.39033 +  p->pEntry = 0;
 1.39034 +  p->pLast = 0;
 1.39035 +  p->pForest = 0;
 1.39036 +  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
 1.39037 +  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
 1.39038 +  p->rsFlags = ROWSET_SORTED;
 1.39039 +  p->iBatch = 0;
 1.39040 +  return p;
 1.39041 +}
 1.39042 +
 1.39043 +/*
 1.39044 +** Deallocate all chunks from a RowSet.  This frees all memory that
 1.39045 +** the RowSet has allocated over its lifetime.  This routine is
 1.39046 +** the destructor for the RowSet.
 1.39047 +*/
 1.39048 +SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
 1.39049 +  struct RowSetChunk *pChunk, *pNextChunk;
 1.39050 +  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
 1.39051 +    pNextChunk = pChunk->pNextChunk;
 1.39052 +    sqlite3DbFree(p->db, pChunk);
 1.39053 +  }
 1.39054 +  p->pChunk = 0;
 1.39055 +  p->nFresh = 0;
 1.39056 +  p->pEntry = 0;
 1.39057 +  p->pLast = 0;
 1.39058 +  p->pForest = 0;
 1.39059 +  p->rsFlags = ROWSET_SORTED;
 1.39060 +}
 1.39061 +
 1.39062 +/*
 1.39063 +** Allocate a new RowSetEntry object that is associated with the
 1.39064 +** given RowSet.  Return a pointer to the new and completely uninitialized
 1.39065 +** objected.
 1.39066 +**
 1.39067 +** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
 1.39068 +** routine returns NULL.
 1.39069 +*/
 1.39070 +static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
 1.39071 +  assert( p!=0 );
 1.39072 +  if( p->nFresh==0 ){
 1.39073 +    struct RowSetChunk *pNew;
 1.39074 +    pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
 1.39075 +    if( pNew==0 ){
 1.39076 +      return 0;
 1.39077 +    }
 1.39078 +    pNew->pNextChunk = p->pChunk;
 1.39079 +    p->pChunk = pNew;
 1.39080 +    p->pFresh = pNew->aEntry;
 1.39081 +    p->nFresh = ROWSET_ENTRY_PER_CHUNK;
 1.39082 +  }
 1.39083 +  p->nFresh--;
 1.39084 +  return p->pFresh++;
 1.39085 +}
 1.39086 +
 1.39087 +/*
 1.39088 +** Insert a new value into a RowSet.
 1.39089 +**
 1.39090 +** The mallocFailed flag of the database connection is set if a
 1.39091 +** memory allocation fails.
 1.39092 +*/
 1.39093 +SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
 1.39094 +  struct RowSetEntry *pEntry;  /* The new entry */
 1.39095 +  struct RowSetEntry *pLast;   /* The last prior entry */
 1.39096 +
 1.39097 +  /* This routine is never called after sqlite3RowSetNext() */
 1.39098 +  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
 1.39099 +
 1.39100 +  pEntry = rowSetEntryAlloc(p);
 1.39101 +  if( pEntry==0 ) return;
 1.39102 +  pEntry->v = rowid;
 1.39103 +  pEntry->pRight = 0;
 1.39104 +  pLast = p->pLast;
 1.39105 +  if( pLast ){
 1.39106 +    if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
 1.39107 +      p->rsFlags &= ~ROWSET_SORTED;
 1.39108 +    }
 1.39109 +    pLast->pRight = pEntry;
 1.39110 +  }else{
 1.39111 +    p->pEntry = pEntry;
 1.39112 +  }
 1.39113 +  p->pLast = pEntry;
 1.39114 +}
 1.39115 +
 1.39116 +/*
 1.39117 +** Merge two lists of RowSetEntry objects.  Remove duplicates.
 1.39118 +**
 1.39119 +** The input lists are connected via pRight pointers and are 
 1.39120 +** assumed to each already be in sorted order.
 1.39121 +*/
 1.39122 +static struct RowSetEntry *rowSetEntryMerge(
 1.39123 +  struct RowSetEntry *pA,    /* First sorted list to be merged */
 1.39124 +  struct RowSetEntry *pB     /* Second sorted list to be merged */
 1.39125 +){
 1.39126 +  struct RowSetEntry head;
 1.39127 +  struct RowSetEntry *pTail;
 1.39128 +
 1.39129 +  pTail = &head;
 1.39130 +  while( pA && pB ){
 1.39131 +    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
 1.39132 +    assert( pB->pRight==0 || pB->v<=pB->pRight->v );
 1.39133 +    if( pA->v<pB->v ){
 1.39134 +      pTail->pRight = pA;
 1.39135 +      pA = pA->pRight;
 1.39136 +      pTail = pTail->pRight;
 1.39137 +    }else if( pB->v<pA->v ){
 1.39138 +      pTail->pRight = pB;
 1.39139 +      pB = pB->pRight;
 1.39140 +      pTail = pTail->pRight;
 1.39141 +    }else{
 1.39142 +      pA = pA->pRight;
 1.39143 +    }
 1.39144 +  }
 1.39145 +  if( pA ){
 1.39146 +    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
 1.39147 +    pTail->pRight = pA;
 1.39148 +  }else{
 1.39149 +    assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
 1.39150 +    pTail->pRight = pB;
 1.39151 +  }
 1.39152 +  return head.pRight;
 1.39153 +}
 1.39154 +
 1.39155 +/*
 1.39156 +** Sort all elements on the list of RowSetEntry objects into order of
 1.39157 +** increasing v.
 1.39158 +*/ 
 1.39159 +static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
 1.39160 +  unsigned int i;
 1.39161 +  struct RowSetEntry *pNext, *aBucket[40];
 1.39162 +
 1.39163 +  memset(aBucket, 0, sizeof(aBucket));
 1.39164 +  while( pIn ){
 1.39165 +    pNext = pIn->pRight;
 1.39166 +    pIn->pRight = 0;
 1.39167 +    for(i=0; aBucket[i]; i++){
 1.39168 +      pIn = rowSetEntryMerge(aBucket[i], pIn);
 1.39169 +      aBucket[i] = 0;
 1.39170 +    }
 1.39171 +    aBucket[i] = pIn;
 1.39172 +    pIn = pNext;
 1.39173 +  }
 1.39174 +  pIn = 0;
 1.39175 +  for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
 1.39176 +    pIn = rowSetEntryMerge(pIn, aBucket[i]);
 1.39177 +  }
 1.39178 +  return pIn;
 1.39179 +}
 1.39180 +
 1.39181 +
 1.39182 +/*
 1.39183 +** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
 1.39184 +** Convert this tree into a linked list connected by the pRight pointers
 1.39185 +** and return pointers to the first and last elements of the new list.
 1.39186 +*/
 1.39187 +static void rowSetTreeToList(
 1.39188 +  struct RowSetEntry *pIn,         /* Root of the input tree */
 1.39189 +  struct RowSetEntry **ppFirst,    /* Write head of the output list here */
 1.39190 +  struct RowSetEntry **ppLast      /* Write tail of the output list here */
 1.39191 +){
 1.39192 +  assert( pIn!=0 );
 1.39193 +  if( pIn->pLeft ){
 1.39194 +    struct RowSetEntry *p;
 1.39195 +    rowSetTreeToList(pIn->pLeft, ppFirst, &p);
 1.39196 +    p->pRight = pIn;
 1.39197 +  }else{
 1.39198 +    *ppFirst = pIn;
 1.39199 +  }
 1.39200 +  if( pIn->pRight ){
 1.39201 +    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
 1.39202 +  }else{
 1.39203 +    *ppLast = pIn;
 1.39204 +  }
 1.39205 +  assert( (*ppLast)->pRight==0 );
 1.39206 +}
 1.39207 +
 1.39208 +
 1.39209 +/*
 1.39210 +** Convert a sorted list of elements (connected by pRight) into a binary
 1.39211 +** tree with depth of iDepth.  A depth of 1 means the tree contains a single
 1.39212 +** node taken from the head of *ppList.  A depth of 2 means a tree with
 1.39213 +** three nodes.  And so forth.
 1.39214 +**
 1.39215 +** Use as many entries from the input list as required and update the
 1.39216 +** *ppList to point to the unused elements of the list.  If the input
 1.39217 +** list contains too few elements, then construct an incomplete tree
 1.39218 +** and leave *ppList set to NULL.
 1.39219 +**
 1.39220 +** Return a pointer to the root of the constructed binary tree.
 1.39221 +*/
 1.39222 +static struct RowSetEntry *rowSetNDeepTree(
 1.39223 +  struct RowSetEntry **ppList,
 1.39224 +  int iDepth
 1.39225 +){
 1.39226 +  struct RowSetEntry *p;         /* Root of the new tree */
 1.39227 +  struct RowSetEntry *pLeft;     /* Left subtree */
 1.39228 +  if( *ppList==0 ){
 1.39229 +    return 0;
 1.39230 +  }
 1.39231 +  if( iDepth==1 ){
 1.39232 +    p = *ppList;
 1.39233 +    *ppList = p->pRight;
 1.39234 +    p->pLeft = p->pRight = 0;
 1.39235 +    return p;
 1.39236 +  }
 1.39237 +  pLeft = rowSetNDeepTree(ppList, iDepth-1);
 1.39238 +  p = *ppList;
 1.39239 +  if( p==0 ){
 1.39240 +    return pLeft;
 1.39241 +  }
 1.39242 +  p->pLeft = pLeft;
 1.39243 +  *ppList = p->pRight;
 1.39244 +  p->pRight = rowSetNDeepTree(ppList, iDepth-1);
 1.39245 +  return p;
 1.39246 +}
 1.39247 +
 1.39248 +/*
 1.39249 +** Convert a sorted list of elements into a binary tree. Make the tree
 1.39250 +** as deep as it needs to be in order to contain the entire list.
 1.39251 +*/
 1.39252 +static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
 1.39253 +  int iDepth;           /* Depth of the tree so far */
 1.39254 +  struct RowSetEntry *p;       /* Current tree root */
 1.39255 +  struct RowSetEntry *pLeft;   /* Left subtree */
 1.39256 +
 1.39257 +  assert( pList!=0 );
 1.39258 +  p = pList;
 1.39259 +  pList = p->pRight;
 1.39260 +  p->pLeft = p->pRight = 0;
 1.39261 +  for(iDepth=1; pList; iDepth++){
 1.39262 +    pLeft = p;
 1.39263 +    p = pList;
 1.39264 +    pList = p->pRight;
 1.39265 +    p->pLeft = pLeft;
 1.39266 +    p->pRight = rowSetNDeepTree(&pList, iDepth);
 1.39267 +  }
 1.39268 +  return p;
 1.39269 +}
 1.39270 +
 1.39271 +/*
 1.39272 +** Take all the entries on p->pEntry and on the trees in p->pForest and
 1.39273 +** sort them all together into one big ordered list on p->pEntry.
 1.39274 +**
 1.39275 +** This routine should only be called once in the life of a RowSet.
 1.39276 +*/
 1.39277 +static void rowSetToList(RowSet *p){
 1.39278 +
 1.39279 +  /* This routine is called only once */
 1.39280 +  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
 1.39281 +
 1.39282 +  if( (p->rsFlags & ROWSET_SORTED)==0 ){
 1.39283 +    p->pEntry = rowSetEntrySort(p->pEntry);
 1.39284 +  }
 1.39285 +
 1.39286 +  /* While this module could theoretically support it, sqlite3RowSetNext()
 1.39287 +  ** is never called after sqlite3RowSetText() for the same RowSet.  So
 1.39288 +  ** there is never a forest to deal with.  Should this change, simply
 1.39289 +  ** remove the assert() and the #if 0. */
 1.39290 +  assert( p->pForest==0 );
 1.39291 +#if 0
 1.39292 +  while( p->pForest ){
 1.39293 +    struct RowSetEntry *pTree = p->pForest->pLeft;
 1.39294 +    if( pTree ){
 1.39295 +      struct RowSetEntry *pHead, *pTail;
 1.39296 +      rowSetTreeToList(pTree, &pHead, &pTail);
 1.39297 +      p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
 1.39298 +    }
 1.39299 +    p->pForest = p->pForest->pRight;
 1.39300 +  }
 1.39301 +#endif
 1.39302 +  p->rsFlags |= ROWSET_NEXT;  /* Verify this routine is never called again */
 1.39303 +}
 1.39304 +
 1.39305 +/*
 1.39306 +** Extract the smallest element from the RowSet.
 1.39307 +** Write the element into *pRowid.  Return 1 on success.  Return
 1.39308 +** 0 if the RowSet is already empty.
 1.39309 +**
 1.39310 +** After this routine has been called, the sqlite3RowSetInsert()
 1.39311 +** routine may not be called again.  
 1.39312 +*/
 1.39313 +SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
 1.39314 +  assert( p!=0 );
 1.39315 +
 1.39316 +  /* Merge the forest into a single sorted list on first call */
 1.39317 +  if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
 1.39318 +
 1.39319 +  /* Return the next entry on the list */
 1.39320 +  if( p->pEntry ){
 1.39321 +    *pRowid = p->pEntry->v;
 1.39322 +    p->pEntry = p->pEntry->pRight;
 1.39323 +    if( p->pEntry==0 ){
 1.39324 +      sqlite3RowSetClear(p);
 1.39325 +    }
 1.39326 +    return 1;
 1.39327 +  }else{
 1.39328 +    return 0;
 1.39329 +  }
 1.39330 +}
 1.39331 +
 1.39332 +/*
 1.39333 +** Check to see if element iRowid was inserted into the rowset as
 1.39334 +** part of any insert batch prior to iBatch.  Return 1 or 0.
 1.39335 +**
 1.39336 +** If this is the first test of a new batch and if there exist entires
 1.39337 +** on pRowSet->pEntry, then sort those entires into the forest at
 1.39338 +** pRowSet->pForest so that they can be tested.
 1.39339 +*/
 1.39340 +SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
 1.39341 +  struct RowSetEntry *p, *pTree;
 1.39342 +
 1.39343 +  /* This routine is never called after sqlite3RowSetNext() */
 1.39344 +  assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
 1.39345 +
 1.39346 +  /* Sort entries into the forest on the first test of a new batch 
 1.39347 +  */
 1.39348 +  if( iBatch!=pRowSet->iBatch ){
 1.39349 +    p = pRowSet->pEntry;
 1.39350 +    if( p ){
 1.39351 +      struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
 1.39352 +      if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
 1.39353 +        p = rowSetEntrySort(p);
 1.39354 +      }
 1.39355 +      for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
 1.39356 +        ppPrevTree = &pTree->pRight;
 1.39357 +        if( pTree->pLeft==0 ){
 1.39358 +          pTree->pLeft = rowSetListToTree(p);
 1.39359 +          break;
 1.39360 +        }else{
 1.39361 +          struct RowSetEntry *pAux, *pTail;
 1.39362 +          rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
 1.39363 +          pTree->pLeft = 0;
 1.39364 +          p = rowSetEntryMerge(pAux, p);
 1.39365 +        }
 1.39366 +      }
 1.39367 +      if( pTree==0 ){
 1.39368 +        *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
 1.39369 +        if( pTree ){
 1.39370 +          pTree->v = 0;
 1.39371 +          pTree->pRight = 0;
 1.39372 +          pTree->pLeft = rowSetListToTree(p);
 1.39373 +        }
 1.39374 +      }
 1.39375 +      pRowSet->pEntry = 0;
 1.39376 +      pRowSet->pLast = 0;
 1.39377 +      pRowSet->rsFlags |= ROWSET_SORTED;
 1.39378 +    }
 1.39379 +    pRowSet->iBatch = iBatch;
 1.39380 +  }
 1.39381 +
 1.39382 +  /* Test to see if the iRowid value appears anywhere in the forest.
 1.39383 +  ** Return 1 if it does and 0 if not.
 1.39384 +  */
 1.39385 +  for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
 1.39386 +    p = pTree->pLeft;
 1.39387 +    while( p ){
 1.39388 +      if( p->v<iRowid ){
 1.39389 +        p = p->pRight;
 1.39390 +      }else if( p->v>iRowid ){
 1.39391 +        p = p->pLeft;
 1.39392 +      }else{
 1.39393 +        return 1;
 1.39394 +      }
 1.39395 +    }
 1.39396 +  }
 1.39397 +  return 0;
 1.39398 +}
 1.39399 +
 1.39400 +/************** End of rowset.c **********************************************/
 1.39401 +/************** Begin file pager.c *******************************************/
 1.39402 +/*
 1.39403 +** 2001 September 15
 1.39404 +**
 1.39405 +** The author disclaims copyright to this source code.  In place of
 1.39406 +** a legal notice, here is a blessing:
 1.39407 +**
 1.39408 +**    May you do good and not evil.
 1.39409 +**    May you find forgiveness for yourself and forgive others.
 1.39410 +**    May you share freely, never taking more than you give.
 1.39411 +**
 1.39412 +*************************************************************************
 1.39413 +** This is the implementation of the page cache subsystem or "pager".
 1.39414 +** 
 1.39415 +** The pager is used to access a database disk file.  It implements
 1.39416 +** atomic commit and rollback through the use of a journal file that
 1.39417 +** is separate from the database file.  The pager also implements file
 1.39418 +** locking to prevent two processes from writing the same database
 1.39419 +** file simultaneously, or one process from reading the database while
 1.39420 +** another is writing.
 1.39421 +*/
 1.39422 +#ifndef SQLITE_OMIT_DISKIO
 1.39423 +/************** Include wal.h in the middle of pager.c ***********************/
 1.39424 +/************** Begin file wal.h *********************************************/
 1.39425 +/*
 1.39426 +** 2010 February 1
 1.39427 +**
 1.39428 +** The author disclaims copyright to this source code.  In place of
 1.39429 +** a legal notice, here is a blessing:
 1.39430 +**
 1.39431 +**    May you do good and not evil.
 1.39432 +**    May you find forgiveness for yourself and forgive others.
 1.39433 +**    May you share freely, never taking more than you give.
 1.39434 +**
 1.39435 +*************************************************************************
 1.39436 +** This header file defines the interface to the write-ahead logging 
 1.39437 +** system. Refer to the comments below and the header comment attached to 
 1.39438 +** the implementation of each function in log.c for further details.
 1.39439 +*/
 1.39440 +
 1.39441 +#ifndef _WAL_H_
 1.39442 +#define _WAL_H_
 1.39443 +
 1.39444 +
 1.39445 +/* Additional values that can be added to the sync_flags argument of
 1.39446 +** sqlite3WalFrames():
 1.39447 +*/
 1.39448 +#define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
 1.39449 +#define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
 1.39450 +
 1.39451 +#ifdef SQLITE_OMIT_WAL
 1.39452 +# define sqlite3WalOpen(x,y,z)                   0
 1.39453 +# define sqlite3WalLimit(x,y)
 1.39454 +# define sqlite3WalClose(w,x,y,z)                0
 1.39455 +# define sqlite3WalBeginReadTransaction(y,z)     0
 1.39456 +# define sqlite3WalEndReadTransaction(z)
 1.39457 +# define sqlite3WalDbsize(y)                     0
 1.39458 +# define sqlite3WalBeginWriteTransaction(y)      0
 1.39459 +# define sqlite3WalEndWriteTransaction(x)        0
 1.39460 +# define sqlite3WalUndo(x,y,z)                   0
 1.39461 +# define sqlite3WalSavepoint(y,z)
 1.39462 +# define sqlite3WalSavepointUndo(y,z)            0
 1.39463 +# define sqlite3WalFrames(u,v,w,x,y,z)           0
 1.39464 +# define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
 1.39465 +# define sqlite3WalCallback(z)                   0
 1.39466 +# define sqlite3WalExclusiveMode(y,z)            0
 1.39467 +# define sqlite3WalHeapMemory(z)                 0
 1.39468 +# define sqlite3WalFramesize(z)                  0
 1.39469 +# define sqlite3WalFindFrame(x,y,z)              0
 1.39470 +#else
 1.39471 +
 1.39472 +#define WAL_SAVEPOINT_NDATA 4
 1.39473 +
 1.39474 +/* Connection to a write-ahead log (WAL) file. 
 1.39475 +** There is one object of this type for each pager. 
 1.39476 +*/
 1.39477 +typedef struct Wal Wal;
 1.39478 +
 1.39479 +/* Open and close a connection to a write-ahead log. */
 1.39480 +SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
 1.39481 +SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
 1.39482 +
 1.39483 +/* Set the limiting size of a WAL file. */
 1.39484 +SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
 1.39485 +
 1.39486 +/* Used by readers to open (lock) and close (unlock) a snapshot.  A 
 1.39487 +** snapshot is like a read-transaction.  It is the state of the database
 1.39488 +** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
 1.39489 +** preserves the current state even if the other threads or processes
 1.39490 +** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
 1.39491 +** transaction and releases the lock.
 1.39492 +*/
 1.39493 +SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
 1.39494 +SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
 1.39495 +
 1.39496 +/* Read a page from the write-ahead log, if it is present. */
 1.39497 +SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
 1.39498 +SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
 1.39499 +
 1.39500 +/* If the WAL is not empty, return the size of the database. */
 1.39501 +SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
 1.39502 +
 1.39503 +/* Obtain or release the WRITER lock. */
 1.39504 +SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
 1.39505 +SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
 1.39506 +
 1.39507 +/* Undo any frames written (but not committed) to the log */
 1.39508 +SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
 1.39509 +
 1.39510 +/* Return an integer that records the current (uncommitted) write
 1.39511 +** position in the WAL */
 1.39512 +SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
 1.39513 +
 1.39514 +/* Move the write position of the WAL back to iFrame.  Called in
 1.39515 +** response to a ROLLBACK TO command. */
 1.39516 +SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
 1.39517 +
 1.39518 +/* Write a frame or frames to the log. */
 1.39519 +SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
 1.39520 +
 1.39521 +/* Copy pages from the log to the database file */ 
 1.39522 +SQLITE_PRIVATE int sqlite3WalCheckpoint(
 1.39523 +  Wal *pWal,                      /* Write-ahead log connection */
 1.39524 +  int eMode,                      /* One of PASSIVE, FULL and RESTART */
 1.39525 +  int (*xBusy)(void*),            /* Function to call when busy */
 1.39526 +  void *pBusyArg,                 /* Context argument for xBusyHandler */
 1.39527 +  int sync_flags,                 /* Flags to sync db file with (or 0) */
 1.39528 +  int nBuf,                       /* Size of buffer nBuf */
 1.39529 +  u8 *zBuf,                       /* Temporary buffer to use */
 1.39530 +  int *pnLog,                     /* OUT: Number of frames in WAL */
 1.39531 +  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
 1.39532 +);
 1.39533 +
 1.39534 +/* Return the value to pass to a sqlite3_wal_hook callback, the
 1.39535 +** number of frames in the WAL at the point of the last commit since
 1.39536 +** sqlite3WalCallback() was called.  If no commits have occurred since
 1.39537 +** the last call, then return 0.
 1.39538 +*/
 1.39539 +SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
 1.39540 +
 1.39541 +/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
 1.39542 +** by the pager layer on the database file.
 1.39543 +*/
 1.39544 +SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
 1.39545 +
 1.39546 +/* Return true if the argument is non-NULL and the WAL module is using
 1.39547 +** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
 1.39548 +** WAL module is using shared-memory, return false. 
 1.39549 +*/
 1.39550 +SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
 1.39551 +
 1.39552 +#ifdef SQLITE_ENABLE_ZIPVFS
 1.39553 +/* If the WAL file is not empty, return the number of bytes of content
 1.39554 +** stored in each frame (i.e. the db page-size when the WAL was created).
 1.39555 +*/
 1.39556 +SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
 1.39557 +#endif
 1.39558 +
 1.39559 +#endif /* ifndef SQLITE_OMIT_WAL */
 1.39560 +#endif /* _WAL_H_ */
 1.39561 +
 1.39562 +/************** End of wal.h *************************************************/
 1.39563 +/************** Continuing where we left off in pager.c **********************/
 1.39564 +
 1.39565 +
 1.39566 +/******************* NOTES ON THE DESIGN OF THE PAGER ************************
 1.39567 +**
 1.39568 +** This comment block describes invariants that hold when using a rollback
 1.39569 +** journal.  These invariants do not apply for journal_mode=WAL,
 1.39570 +** journal_mode=MEMORY, or journal_mode=OFF.
 1.39571 +**
 1.39572 +** Within this comment block, a page is deemed to have been synced
 1.39573 +** automatically as soon as it is written when PRAGMA synchronous=OFF.
 1.39574 +** Otherwise, the page is not synced until the xSync method of the VFS
 1.39575 +** is called successfully on the file containing the page.
 1.39576 +**
 1.39577 +** Definition:  A page of the database file is said to be "overwriteable" if
 1.39578 +** one or more of the following are true about the page:
 1.39579 +** 
 1.39580 +**     (a)  The original content of the page as it was at the beginning of
 1.39581 +**          the transaction has been written into the rollback journal and
 1.39582 +**          synced.
 1.39583 +** 
 1.39584 +**     (b)  The page was a freelist leaf page at the start of the transaction.
 1.39585 +** 
 1.39586 +**     (c)  The page number is greater than the largest page that existed in
 1.39587 +**          the database file at the start of the transaction.
 1.39588 +** 
 1.39589 +** (1) A page of the database file is never overwritten unless one of the
 1.39590 +**     following are true:
 1.39591 +** 
 1.39592 +**     (a) The page and all other pages on the same sector are overwriteable.
 1.39593 +** 
 1.39594 +**     (b) The atomic page write optimization is enabled, and the entire
 1.39595 +**         transaction other than the update of the transaction sequence
 1.39596 +**         number consists of a single page change.
 1.39597 +** 
 1.39598 +** (2) The content of a page written into the rollback journal exactly matches
 1.39599 +**     both the content in the database when the rollback journal was written
 1.39600 +**     and the content in the database at the beginning of the current
 1.39601 +**     transaction.
 1.39602 +** 
 1.39603 +** (3) Writes to the database file are an integer multiple of the page size
 1.39604 +**     in length and are aligned on a page boundary.
 1.39605 +** 
 1.39606 +** (4) Reads from the database file are either aligned on a page boundary and
 1.39607 +**     an integer multiple of the page size in length or are taken from the
 1.39608 +**     first 100 bytes of the database file.
 1.39609 +** 
 1.39610 +** (5) All writes to the database file are synced prior to the rollback journal
 1.39611 +**     being deleted, truncated, or zeroed.
 1.39612 +** 
 1.39613 +** (6) If a master journal file is used, then all writes to the database file
 1.39614 +**     are synced prior to the master journal being deleted.
 1.39615 +** 
 1.39616 +** Definition: Two databases (or the same database at two points it time)
 1.39617 +** are said to be "logically equivalent" if they give the same answer to
 1.39618 +** all queries.  Note in particular the content of freelist leaf
 1.39619 +** pages can be changed arbitarily without effecting the logical equivalence
 1.39620 +** of the database.
 1.39621 +** 
 1.39622 +** (7) At any time, if any subset, including the empty set and the total set,
 1.39623 +**     of the unsynced changes to a rollback journal are removed and the 
 1.39624 +**     journal is rolled back, the resulting database file will be logical
 1.39625 +**     equivalent to the database file at the beginning of the transaction.
 1.39626 +** 
 1.39627 +** (8) When a transaction is rolled back, the xTruncate method of the VFS
 1.39628 +**     is called to restore the database file to the same size it was at
 1.39629 +**     the beginning of the transaction.  (In some VFSes, the xTruncate
 1.39630 +**     method is a no-op, but that does not change the fact the SQLite will
 1.39631 +**     invoke it.)
 1.39632 +** 
 1.39633 +** (9) Whenever the database file is modified, at least one bit in the range
 1.39634 +**     of bytes from 24 through 39 inclusive will be changed prior to releasing
 1.39635 +**     the EXCLUSIVE lock, thus signaling other connections on the same
 1.39636 +**     database to flush their caches.
 1.39637 +**
 1.39638 +** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
 1.39639 +**      than one billion transactions.
 1.39640 +**
 1.39641 +** (11) A database file is well-formed at the beginning and at the conclusion
 1.39642 +**      of every transaction.
 1.39643 +**
 1.39644 +** (12) An EXCLUSIVE lock is held on the database file when writing to
 1.39645 +**      the database file.
 1.39646 +**
 1.39647 +** (13) A SHARED lock is held on the database file while reading any
 1.39648 +**      content out of the database file.
 1.39649 +**
 1.39650 +******************************************************************************/
 1.39651 +
 1.39652 +/*
 1.39653 +** Macros for troubleshooting.  Normally turned off
 1.39654 +*/
 1.39655 +#if 0
 1.39656 +int sqlite3PagerTrace=1;  /* True to enable tracing */
 1.39657 +#define sqlite3DebugPrintf printf
 1.39658 +#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
 1.39659 +#else
 1.39660 +#define PAGERTRACE(X)
 1.39661 +#endif
 1.39662 +
 1.39663 +/*
 1.39664 +** The following two macros are used within the PAGERTRACE() macros above
 1.39665 +** to print out file-descriptors. 
 1.39666 +**
 1.39667 +** PAGERID() takes a pointer to a Pager struct as its argument. The
 1.39668 +** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
 1.39669 +** struct as its argument.
 1.39670 +*/
 1.39671 +#define PAGERID(p) ((int)(p->fd))
 1.39672 +#define FILEHANDLEID(fd) ((int)fd)
 1.39673 +
 1.39674 +/*
 1.39675 +** The Pager.eState variable stores the current 'state' of a pager. A
 1.39676 +** pager may be in any one of the seven states shown in the following
 1.39677 +** state diagram.
 1.39678 +**
 1.39679 +**                            OPEN <------+------+
 1.39680 +**                              |         |      |
 1.39681 +**                              V         |      |
 1.39682 +**               +---------> READER-------+      |
 1.39683 +**               |              |                |
 1.39684 +**               |              V                |
 1.39685 +**               |<-------WRITER_LOCKED------> ERROR
 1.39686 +**               |              |                ^  
 1.39687 +**               |              V                |
 1.39688 +**               |<------WRITER_CACHEMOD-------->|
 1.39689 +**               |              |                |
 1.39690 +**               |              V                |
 1.39691 +**               |<-------WRITER_DBMOD---------->|
 1.39692 +**               |              |                |
 1.39693 +**               |              V                |
 1.39694 +**               +<------WRITER_FINISHED-------->+
 1.39695 +**
 1.39696 +**
 1.39697 +** List of state transitions and the C [function] that performs each:
 1.39698 +** 
 1.39699 +**   OPEN              -> READER              [sqlite3PagerSharedLock]
 1.39700 +**   READER            -> OPEN                [pager_unlock]
 1.39701 +**
 1.39702 +**   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
 1.39703 +**   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
 1.39704 +**   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
 1.39705 +**   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
 1.39706 +**   WRITER_***        -> READER              [pager_end_transaction]
 1.39707 +**
 1.39708 +**   WRITER_***        -> ERROR               [pager_error]
 1.39709 +**   ERROR             -> OPEN                [pager_unlock]
 1.39710 +** 
 1.39711 +**
 1.39712 +**  OPEN:
 1.39713 +**
 1.39714 +**    The pager starts up in this state. Nothing is guaranteed in this
 1.39715 +**    state - the file may or may not be locked and the database size is
 1.39716 +**    unknown. The database may not be read or written.
 1.39717 +**
 1.39718 +**    * No read or write transaction is active.
 1.39719 +**    * Any lock, or no lock at all, may be held on the database file.
 1.39720 +**    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
 1.39721 +**
 1.39722 +**  READER:
 1.39723 +**
 1.39724 +**    In this state all the requirements for reading the database in 
 1.39725 +**    rollback (non-WAL) mode are met. Unless the pager is (or recently
 1.39726 +**    was) in exclusive-locking mode, a user-level read transaction is 
 1.39727 +**    open. The database size is known in this state.
 1.39728 +**
 1.39729 +**    A connection running with locking_mode=normal enters this state when
 1.39730 +**    it opens a read-transaction on the database and returns to state
 1.39731 +**    OPEN after the read-transaction is completed. However a connection
 1.39732 +**    running in locking_mode=exclusive (including temp databases) remains in
 1.39733 +**    this state even after the read-transaction is closed. The only way
 1.39734 +**    a locking_mode=exclusive connection can transition from READER to OPEN
 1.39735 +**    is via the ERROR state (see below).
 1.39736 +** 
 1.39737 +**    * A read transaction may be active (but a write-transaction cannot).
 1.39738 +**    * A SHARED or greater lock is held on the database file.
 1.39739 +**    * The dbSize variable may be trusted (even if a user-level read 
 1.39740 +**      transaction is not active). The dbOrigSize and dbFileSize variables
 1.39741 +**      may not be trusted at this point.
 1.39742 +**    * If the database is a WAL database, then the WAL connection is open.
 1.39743 +**    * Even if a read-transaction is not open, it is guaranteed that 
 1.39744 +**      there is no hot-journal in the file-system.
 1.39745 +**
 1.39746 +**  WRITER_LOCKED:
 1.39747 +**
 1.39748 +**    The pager moves to this state from READER when a write-transaction
 1.39749 +**    is first opened on the database. In WRITER_LOCKED state, all locks 
 1.39750 +**    required to start a write-transaction are held, but no actual 
 1.39751 +**    modifications to the cache or database have taken place.
 1.39752 +**
 1.39753 +**    In rollback mode, a RESERVED or (if the transaction was opened with 
 1.39754 +**    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
 1.39755 +**    moving to this state, but the journal file is not written to or opened 
 1.39756 +**    to in this state. If the transaction is committed or rolled back while 
 1.39757 +**    in WRITER_LOCKED state, all that is required is to unlock the database 
 1.39758 +**    file.
 1.39759 +**
 1.39760 +**    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
 1.39761 +**    If the connection is running with locking_mode=exclusive, an attempt
 1.39762 +**    is made to obtain an EXCLUSIVE lock on the database file.
 1.39763 +**
 1.39764 +**    * A write transaction is active.
 1.39765 +**    * If the connection is open in rollback-mode, a RESERVED or greater 
 1.39766 +**      lock is held on the database file.
 1.39767 +**    * If the connection is open in WAL-mode, a WAL write transaction
 1.39768 +**      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
 1.39769 +**      called).
 1.39770 +**    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
 1.39771 +**    * The contents of the pager cache have not been modified.
 1.39772 +**    * The journal file may or may not be open.
 1.39773 +**    * Nothing (not even the first header) has been written to the journal.
 1.39774 +**
 1.39775 +**  WRITER_CACHEMOD:
 1.39776 +**
 1.39777 +**    A pager moves from WRITER_LOCKED state to this state when a page is
 1.39778 +**    first modified by the upper layer. In rollback mode the journal file
 1.39779 +**    is opened (if it is not already open) and a header written to the
 1.39780 +**    start of it. The database file on disk has not been modified.
 1.39781 +**
 1.39782 +**    * A write transaction is active.
 1.39783 +**    * A RESERVED or greater lock is held on the database file.
 1.39784 +**    * The journal file is open and the first header has been written 
 1.39785 +**      to it, but the header has not been synced to disk.
 1.39786 +**    * The contents of the page cache have been modified.
 1.39787 +**
 1.39788 +**  WRITER_DBMOD:
 1.39789 +**
 1.39790 +**    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
 1.39791 +**    when it modifies the contents of the database file. WAL connections
 1.39792 +**    never enter this state (since they do not modify the database file,
 1.39793 +**    just the log file).
 1.39794 +**
 1.39795 +**    * A write transaction is active.
 1.39796 +**    * An EXCLUSIVE or greater lock is held on the database file.
 1.39797 +**    * The journal file is open and the first header has been written 
 1.39798 +**      and synced to disk.
 1.39799 +**    * The contents of the page cache have been modified (and possibly
 1.39800 +**      written to disk).
 1.39801 +**
 1.39802 +**  WRITER_FINISHED:
 1.39803 +**
 1.39804 +**    It is not possible for a WAL connection to enter this state.
 1.39805 +**
 1.39806 +**    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
 1.39807 +**    state after the entire transaction has been successfully written into the
 1.39808 +**    database file. In this state the transaction may be committed simply
 1.39809 +**    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
 1.39810 +**    not possible to modify the database further. At this point, the upper 
 1.39811 +**    layer must either commit or rollback the transaction.
 1.39812 +**
 1.39813 +**    * A write transaction is active.
 1.39814 +**    * An EXCLUSIVE or greater lock is held on the database file.
 1.39815 +**    * All writing and syncing of journal and database data has finished.
 1.39816 +**      If no error occurred, all that remains is to finalize the journal to
 1.39817 +**      commit the transaction. If an error did occur, the caller will need
 1.39818 +**      to rollback the transaction. 
 1.39819 +**
 1.39820 +**  ERROR:
 1.39821 +**
 1.39822 +**    The ERROR state is entered when an IO or disk-full error (including
 1.39823 +**    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it 
 1.39824 +**    difficult to be sure that the in-memory pager state (cache contents, 
 1.39825 +**    db size etc.) are consistent with the contents of the file-system.
 1.39826 +**
 1.39827 +**    Temporary pager files may enter the ERROR state, but in-memory pagers
 1.39828 +**    cannot.
 1.39829 +**
 1.39830 +**    For example, if an IO error occurs while performing a rollback, 
 1.39831 +**    the contents of the page-cache may be left in an inconsistent state.
 1.39832 +**    At this point it would be dangerous to change back to READER state
 1.39833 +**    (as usually happens after a rollback). Any subsequent readers might
 1.39834 +**    report database corruption (due to the inconsistent cache), and if
 1.39835 +**    they upgrade to writers, they may inadvertently corrupt the database
 1.39836 +**    file. To avoid this hazard, the pager switches into the ERROR state
 1.39837 +**    instead of READER following such an error.
 1.39838 +**
 1.39839 +**    Once it has entered the ERROR state, any attempt to use the pager
 1.39840 +**    to read or write data returns an error. Eventually, once all 
 1.39841 +**    outstanding transactions have been abandoned, the pager is able to
 1.39842 +**    transition back to OPEN state, discarding the contents of the 
 1.39843 +**    page-cache and any other in-memory state at the same time. Everything
 1.39844 +**    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
 1.39845 +**    when a read-transaction is next opened on the pager (transitioning
 1.39846 +**    the pager into READER state). At that point the system has recovered 
 1.39847 +**    from the error.
 1.39848 +**
 1.39849 +**    Specifically, the pager jumps into the ERROR state if:
 1.39850 +**
 1.39851 +**      1. An error occurs while attempting a rollback. This happens in
 1.39852 +**         function sqlite3PagerRollback().
 1.39853 +**
 1.39854 +**      2. An error occurs while attempting to finalize a journal file
 1.39855 +**         following a commit in function sqlite3PagerCommitPhaseTwo().
 1.39856 +**
 1.39857 +**      3. An error occurs while attempting to write to the journal or
 1.39858 +**         database file in function pagerStress() in order to free up
 1.39859 +**         memory.
 1.39860 +**
 1.39861 +**    In other cases, the error is returned to the b-tree layer. The b-tree
 1.39862 +**    layer then attempts a rollback operation. If the error condition 
 1.39863 +**    persists, the pager enters the ERROR state via condition (1) above.
 1.39864 +**
 1.39865 +**    Condition (3) is necessary because it can be triggered by a read-only
 1.39866 +**    statement executed within a transaction. In this case, if the error
 1.39867 +**    code were simply returned to the user, the b-tree layer would not
 1.39868 +**    automatically attempt a rollback, as it assumes that an error in a
 1.39869 +**    read-only statement cannot leave the pager in an internally inconsistent 
 1.39870 +**    state.
 1.39871 +**
 1.39872 +**    * The Pager.errCode variable is set to something other than SQLITE_OK.
 1.39873 +**    * There are one or more outstanding references to pages (after the
 1.39874 +**      last reference is dropped the pager should move back to OPEN state).
 1.39875 +**    * The pager is not an in-memory pager.
 1.39876 +**    
 1.39877 +**
 1.39878 +** Notes:
 1.39879 +**
 1.39880 +**   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
 1.39881 +**     connection is open in WAL mode. A WAL connection is always in one
 1.39882 +**     of the first four states.
 1.39883 +**
 1.39884 +**   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
 1.39885 +**     state. There are two exceptions: immediately after exclusive-mode has
 1.39886 +**     been turned on (and before any read or write transactions are 
 1.39887 +**     executed), and when the pager is leaving the "error state".
 1.39888 +**
 1.39889 +**   * See also: assert_pager_state().
 1.39890 +*/
 1.39891 +#define PAGER_OPEN                  0
 1.39892 +#define PAGER_READER                1
 1.39893 +#define PAGER_WRITER_LOCKED         2
 1.39894 +#define PAGER_WRITER_CACHEMOD       3
 1.39895 +#define PAGER_WRITER_DBMOD          4
 1.39896 +#define PAGER_WRITER_FINISHED       5
 1.39897 +#define PAGER_ERROR                 6
 1.39898 +
 1.39899 +/*
 1.39900 +** The Pager.eLock variable is almost always set to one of the 
 1.39901 +** following locking-states, according to the lock currently held on
 1.39902 +** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
 1.39903 +** This variable is kept up to date as locks are taken and released by
 1.39904 +** the pagerLockDb() and pagerUnlockDb() wrappers.
 1.39905 +**
 1.39906 +** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
 1.39907 +** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
 1.39908 +** the operation was successful. In these circumstances pagerLockDb() and
 1.39909 +** pagerUnlockDb() take a conservative approach - eLock is always updated
 1.39910 +** when unlocking the file, and only updated when locking the file if the
 1.39911 +** VFS call is successful. This way, the Pager.eLock variable may be set
 1.39912 +** to a less exclusive (lower) value than the lock that is actually held
 1.39913 +** at the system level, but it is never set to a more exclusive value.
 1.39914 +**
 1.39915 +** This is usually safe. If an xUnlock fails or appears to fail, there may 
 1.39916 +** be a few redundant xLock() calls or a lock may be held for longer than
 1.39917 +** required, but nothing really goes wrong.
 1.39918 +**
 1.39919 +** The exception is when the database file is unlocked as the pager moves
 1.39920 +** from ERROR to OPEN state. At this point there may be a hot-journal file 
 1.39921 +** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
 1.39922 +** transition, by the same pager or any other). If the call to xUnlock()
 1.39923 +** fails at this point and the pager is left holding an EXCLUSIVE lock, this
 1.39924 +** can confuse the call to xCheckReservedLock() call made later as part
 1.39925 +** of hot-journal detection.
 1.39926 +**
 1.39927 +** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
 1.39928 +** lock held by this process or any others". So xCheckReservedLock may 
 1.39929 +** return true because the caller itself is holding an EXCLUSIVE lock (but
 1.39930 +** doesn't know it because of a previous error in xUnlock). If this happens
 1.39931 +** a hot-journal may be mistaken for a journal being created by an active
 1.39932 +** transaction in another process, causing SQLite to read from the database
 1.39933 +** without rolling it back.
 1.39934 +**
 1.39935 +** To work around this, if a call to xUnlock() fails when unlocking the
 1.39936 +** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
 1.39937 +** is only changed back to a real locking state after a successful call
 1.39938 +** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
 1.39939 +** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
 1.39940 +** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
 1.39941 +** lock on the database file before attempting to roll it back. See function
 1.39942 +** PagerSharedLock() for more detail.
 1.39943 +**
 1.39944 +** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
 1.39945 +** PAGER_OPEN state.
 1.39946 +*/
 1.39947 +#define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
 1.39948 +
 1.39949 +/*
 1.39950 +** A macro used for invoking the codec if there is one
 1.39951 +*/
 1.39952 +#ifdef SQLITE_HAS_CODEC
 1.39953 +# define CODEC1(P,D,N,X,E) \
 1.39954 +    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
 1.39955 +# define CODEC2(P,D,N,X,E,O) \
 1.39956 +    if( P->xCodec==0 ){ O=(char*)D; }else \
 1.39957 +    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
 1.39958 +#else
 1.39959 +# define CODEC1(P,D,N,X,E)   /* NO-OP */
 1.39960 +# define CODEC2(P,D,N,X,E,O) O=(char*)D
 1.39961 +#endif
 1.39962 +
 1.39963 +/*
 1.39964 +** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
 1.39965 +** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
 1.39966 +** This could conceivably cause corruption following a power failure on
 1.39967 +** such a system. This is currently an undocumented limit.
 1.39968 +*/
 1.39969 +#define MAX_SECTOR_SIZE 0x10000
 1.39970 +
 1.39971 +/*
 1.39972 +** An instance of the following structure is allocated for each active
 1.39973 +** savepoint and statement transaction in the system. All such structures
 1.39974 +** are stored in the Pager.aSavepoint[] array, which is allocated and
 1.39975 +** resized using sqlite3Realloc().
 1.39976 +**
 1.39977 +** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
 1.39978 +** set to 0. If a journal-header is written into the main journal while
 1.39979 +** the savepoint is active, then iHdrOffset is set to the byte offset 
 1.39980 +** immediately following the last journal record written into the main
 1.39981 +** journal before the journal-header. This is required during savepoint
 1.39982 +** rollback (see pagerPlaybackSavepoint()).
 1.39983 +*/
 1.39984 +typedef struct PagerSavepoint PagerSavepoint;
 1.39985 +struct PagerSavepoint {
 1.39986 +  i64 iOffset;                 /* Starting offset in main journal */
 1.39987 +  i64 iHdrOffset;              /* See above */
 1.39988 +  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
 1.39989 +  Pgno nOrig;                  /* Original number of pages in file */
 1.39990 +  Pgno iSubRec;                /* Index of first record in sub-journal */
 1.39991 +#ifndef SQLITE_OMIT_WAL
 1.39992 +  u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
 1.39993 +#endif
 1.39994 +};
 1.39995 +
 1.39996 +/*
 1.39997 +** Bits of the Pager.doNotSpill flag.  See further description below.
 1.39998 +*/
 1.39999 +#define SPILLFLAG_OFF         0x01      /* Never spill cache.  Set via pragma */
 1.40000 +#define SPILLFLAG_ROLLBACK    0x02      /* Current rolling back, so do not spill */
 1.40001 +#define SPILLFLAG_NOSYNC      0x04      /* Spill is ok, but do not sync */
 1.40002 +
 1.40003 +/*
 1.40004 +** A open page cache is an instance of struct Pager. A description of
 1.40005 +** some of the more important member variables follows:
 1.40006 +**
 1.40007 +** eState
 1.40008 +**
 1.40009 +**   The current 'state' of the pager object. See the comment and state
 1.40010 +**   diagram above for a description of the pager state.
 1.40011 +**
 1.40012 +** eLock
 1.40013 +**
 1.40014 +**   For a real on-disk database, the current lock held on the database file -
 1.40015 +**   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
 1.40016 +**
 1.40017 +**   For a temporary or in-memory database (neither of which require any
 1.40018 +**   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
 1.40019 +**   databases always have Pager.exclusiveMode==1, this tricks the pager
 1.40020 +**   logic into thinking that it already has all the locks it will ever
 1.40021 +**   need (and no reason to release them).
 1.40022 +**
 1.40023 +**   In some (obscure) circumstances, this variable may also be set to
 1.40024 +**   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
 1.40025 +**   details.
 1.40026 +**
 1.40027 +** changeCountDone
 1.40028 +**
 1.40029 +**   This boolean variable is used to make sure that the change-counter 
 1.40030 +**   (the 4-byte header field at byte offset 24 of the database file) is 
 1.40031 +**   not updated more often than necessary. 
 1.40032 +**
 1.40033 +**   It is set to true when the change-counter field is updated, which 
 1.40034 +**   can only happen if an exclusive lock is held on the database file.
 1.40035 +**   It is cleared (set to false) whenever an exclusive lock is 
 1.40036 +**   relinquished on the database file. Each time a transaction is committed,
 1.40037 +**   The changeCountDone flag is inspected. If it is true, the work of
 1.40038 +**   updating the change-counter is omitted for the current transaction.
 1.40039 +**
 1.40040 +**   This mechanism means that when running in exclusive mode, a connection 
 1.40041 +**   need only update the change-counter once, for the first transaction
 1.40042 +**   committed.
 1.40043 +**
 1.40044 +** setMaster
 1.40045 +**
 1.40046 +**   When PagerCommitPhaseOne() is called to commit a transaction, it may
 1.40047 +**   (or may not) specify a master-journal name to be written into the 
 1.40048 +**   journal file before it is synced to disk.
 1.40049 +**
 1.40050 +**   Whether or not a journal file contains a master-journal pointer affects 
 1.40051 +**   the way in which the journal file is finalized after the transaction is 
 1.40052 +**   committed or rolled back when running in "journal_mode=PERSIST" mode.
 1.40053 +**   If a journal file does not contain a master-journal pointer, it is
 1.40054 +**   finalized by overwriting the first journal header with zeroes. If
 1.40055 +**   it does contain a master-journal pointer the journal file is finalized 
 1.40056 +**   by truncating it to zero bytes, just as if the connection were 
 1.40057 +**   running in "journal_mode=truncate" mode.
 1.40058 +**
 1.40059 +**   Journal files that contain master journal pointers cannot be finalized
 1.40060 +**   simply by overwriting the first journal-header with zeroes, as the
 1.40061 +**   master journal pointer could interfere with hot-journal rollback of any
 1.40062 +**   subsequently interrupted transaction that reuses the journal file.
 1.40063 +**
 1.40064 +**   The flag is cleared as soon as the journal file is finalized (either
 1.40065 +**   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
 1.40066 +**   journal file from being successfully finalized, the setMaster flag
 1.40067 +**   is cleared anyway (and the pager will move to ERROR state).
 1.40068 +**
 1.40069 +** doNotSpill
 1.40070 +**
 1.40071 +**   This variables control the behavior of cache-spills  (calls made by
 1.40072 +**   the pcache module to the pagerStress() routine to write cached data
 1.40073 +**   to the file-system in order to free up memory).
 1.40074 +**
 1.40075 +**   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
 1.40076 +**   writing to the database from pagerStress() is disabled altogether.
 1.40077 +**   The SPILLFLAG_ROLLBACK case is done in a very obscure case that
 1.40078 +**   comes up during savepoint rollback that requires the pcache module
 1.40079 +**   to allocate a new page to prevent the journal file from being written
 1.40080 +**   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
 1.40081 +**   case is a user preference.
 1.40082 +** 
 1.40083 +**   If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress()
 1.40084 +**   is permitted, but syncing the journal file is not. This flag is set
 1.40085 +**   by sqlite3PagerWrite() when the file-system sector-size is larger than
 1.40086 +**   the database page-size in order to prevent a journal sync from happening 
 1.40087 +**   in between the journalling of two pages on the same sector. 
 1.40088 +**
 1.40089 +** subjInMemory
 1.40090 +**
 1.40091 +**   This is a boolean variable. If true, then any required sub-journal
 1.40092 +**   is opened as an in-memory journal file. If false, then in-memory
 1.40093 +**   sub-journals are only used for in-memory pager files.
 1.40094 +**
 1.40095 +**   This variable is updated by the upper layer each time a new 
 1.40096 +**   write-transaction is opened.
 1.40097 +**
 1.40098 +** dbSize, dbOrigSize, dbFileSize
 1.40099 +**
 1.40100 +**   Variable dbSize is set to the number of pages in the database file.
 1.40101 +**   It is valid in PAGER_READER and higher states (all states except for
 1.40102 +**   OPEN and ERROR). 
 1.40103 +**
 1.40104 +**   dbSize is set based on the size of the database file, which may be 
 1.40105 +**   larger than the size of the database (the value stored at offset
 1.40106 +**   28 of the database header by the btree). If the size of the file
 1.40107 +**   is not an integer multiple of the page-size, the value stored in
 1.40108 +**   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
 1.40109 +**   Except, any file that is greater than 0 bytes in size is considered
 1.40110 +**   to have at least one page. (i.e. a 1KB file with 2K page-size leads
 1.40111 +**   to dbSize==1).
 1.40112 +**
 1.40113 +**   During a write-transaction, if pages with page-numbers greater than
 1.40114 +**   dbSize are modified in the cache, dbSize is updated accordingly.
 1.40115 +**   Similarly, if the database is truncated using PagerTruncateImage(), 
 1.40116 +**   dbSize is updated.
 1.40117 +**
 1.40118 +**   Variables dbOrigSize and dbFileSize are valid in states 
 1.40119 +**   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
 1.40120 +**   variable at the start of the transaction. It is used during rollback,
 1.40121 +**   and to determine whether or not pages need to be journalled before
 1.40122 +**   being modified.
 1.40123 +**
 1.40124 +**   Throughout a write-transaction, dbFileSize contains the size of
 1.40125 +**   the file on disk in pages. It is set to a copy of dbSize when the
 1.40126 +**   write-transaction is first opened, and updated when VFS calls are made
 1.40127 +**   to write or truncate the database file on disk. 
 1.40128 +**
 1.40129 +**   The only reason the dbFileSize variable is required is to suppress 
 1.40130 +**   unnecessary calls to xTruncate() after committing a transaction. If, 
 1.40131 +**   when a transaction is committed, the dbFileSize variable indicates 
 1.40132 +**   that the database file is larger than the database image (Pager.dbSize), 
 1.40133 +**   pager_truncate() is called. The pager_truncate() call uses xFilesize()
 1.40134 +**   to measure the database file on disk, and then truncates it if required.
 1.40135 +**   dbFileSize is not used when rolling back a transaction. In this case
 1.40136 +**   pager_truncate() is called unconditionally (which means there may be
 1.40137 +**   a call to xFilesize() that is not strictly required). In either case,
 1.40138 +**   pager_truncate() may cause the file to become smaller or larger.
 1.40139 +**
 1.40140 +** dbHintSize
 1.40141 +**
 1.40142 +**   The dbHintSize variable is used to limit the number of calls made to
 1.40143 +**   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
 1.40144 +**
 1.40145 +**   dbHintSize is set to a copy of the dbSize variable when a
 1.40146 +**   write-transaction is opened (at the same time as dbFileSize and
 1.40147 +**   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
 1.40148 +**   dbHintSize is increased to the number of pages that correspond to the
 1.40149 +**   size-hint passed to the method call. See pager_write_pagelist() for 
 1.40150 +**   details.
 1.40151 +**
 1.40152 +** errCode
 1.40153 +**
 1.40154 +**   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
 1.40155 +**   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
 1.40156 +**   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX 
 1.40157 +**   sub-codes.
 1.40158 +*/
 1.40159 +struct Pager {
 1.40160 +  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
 1.40161 +  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
 1.40162 +  u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
 1.40163 +  u8 useJournal;              /* Use a rollback journal on this file */
 1.40164 +  u8 noSync;                  /* Do not sync the journal if true */
 1.40165 +  u8 fullSync;                /* Do extra syncs of the journal for robustness */
 1.40166 +  u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
 1.40167 +  u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
 1.40168 +  u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
 1.40169 +  u8 tempFile;                /* zFilename is a temporary file */
 1.40170 +  u8 readOnly;                /* True for a read-only database */
 1.40171 +  u8 memDb;                   /* True to inhibit all file I/O */
 1.40172 +
 1.40173 +  /**************************************************************************
 1.40174 +  ** The following block contains those class members that change during
 1.40175 +  ** routine opertion.  Class members not in this block are either fixed
 1.40176 +  ** when the pager is first created or else only change when there is a
 1.40177 +  ** significant mode change (such as changing the page_size, locking_mode,
 1.40178 +  ** or the journal_mode).  From another view, these class members describe
 1.40179 +  ** the "state" of the pager, while other class members describe the
 1.40180 +  ** "configuration" of the pager.
 1.40181 +  */
 1.40182 +  u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
 1.40183 +  u8 eLock;                   /* Current lock held on database file */
 1.40184 +  u8 changeCountDone;         /* Set after incrementing the change-counter */
 1.40185 +  u8 setMaster;               /* True if a m-j name has been written to jrnl */
 1.40186 +  u8 doNotSpill;              /* Do not spill the cache when non-zero */
 1.40187 +  u8 subjInMemory;            /* True to use in-memory sub-journals */
 1.40188 +  Pgno dbSize;                /* Number of pages in the database */
 1.40189 +  Pgno dbOrigSize;            /* dbSize before the current transaction */
 1.40190 +  Pgno dbFileSize;            /* Number of pages in the database file */
 1.40191 +  Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
 1.40192 +  int errCode;                /* One of several kinds of errors */
 1.40193 +  int nRec;                   /* Pages journalled since last j-header written */
 1.40194 +  u32 cksumInit;              /* Quasi-random value added to every checksum */
 1.40195 +  u32 nSubRec;                /* Number of records written to sub-journal */
 1.40196 +  Bitvec *pInJournal;         /* One bit for each page in the database file */
 1.40197 +  sqlite3_file *fd;           /* File descriptor for database */
 1.40198 +  sqlite3_file *jfd;          /* File descriptor for main journal */
 1.40199 +  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
 1.40200 +  i64 journalOff;             /* Current write offset in the journal file */
 1.40201 +  i64 journalHdr;             /* Byte offset to previous journal header */
 1.40202 +  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
 1.40203 +  PagerSavepoint *aSavepoint; /* Array of active savepoints */
 1.40204 +  int nSavepoint;             /* Number of elements in aSavepoint[] */
 1.40205 +  char dbFileVers[16];        /* Changes whenever database file changes */
 1.40206 +
 1.40207 +  u8 bUseFetch;               /* True to use xFetch() */
 1.40208 +  int nMmapOut;               /* Number of mmap pages currently outstanding */
 1.40209 +  sqlite3_int64 szMmap;       /* Desired maximum mmap size */
 1.40210 +  PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
 1.40211 +  /*
 1.40212 +  ** End of the routinely-changing class members
 1.40213 +  ***************************************************************************/
 1.40214 +
 1.40215 +  u16 nExtra;                 /* Add this many bytes to each in-memory page */
 1.40216 +  i16 nReserve;               /* Number of unused bytes at end of each page */
 1.40217 +  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
 1.40218 +  u32 sectorSize;             /* Assumed sector size during rollback */
 1.40219 +  int pageSize;               /* Number of bytes in a page */
 1.40220 +  Pgno mxPgno;                /* Maximum allowed size of the database */
 1.40221 +  i64 journalSizeLimit;       /* Size limit for persistent journal files */
 1.40222 +  char *zFilename;            /* Name of the database file */
 1.40223 +  char *zJournal;             /* Name of the journal file */
 1.40224 +  int (*xBusyHandler)(void*); /* Function to call when busy */
 1.40225 +  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
 1.40226 +  int aStat[3];               /* Total cache hits, misses and writes */
 1.40227 +#ifdef SQLITE_TEST
 1.40228 +  int nRead;                  /* Database pages read */
 1.40229 +#endif
 1.40230 +  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
 1.40231 +#ifdef SQLITE_HAS_CODEC
 1.40232 +  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
 1.40233 +  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
 1.40234 +  void (*xCodecFree)(void*);             /* Destructor for the codec */
 1.40235 +  void *pCodec;               /* First argument to xCodec... methods */
 1.40236 +#endif
 1.40237 +  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
 1.40238 +  PCache *pPCache;            /* Pointer to page cache object */
 1.40239 +#ifndef SQLITE_OMIT_WAL
 1.40240 +  Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
 1.40241 +  char *zWal;                 /* File name for write-ahead log */
 1.40242 +#endif
 1.40243 +};
 1.40244 +
 1.40245 +/*
 1.40246 +** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
 1.40247 +** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS 
 1.40248 +** or CACHE_WRITE to sqlite3_db_status().
 1.40249 +*/
 1.40250 +#define PAGER_STAT_HIT   0
 1.40251 +#define PAGER_STAT_MISS  1
 1.40252 +#define PAGER_STAT_WRITE 2
 1.40253 +
 1.40254 +/*
 1.40255 +** The following global variables hold counters used for
 1.40256 +** testing purposes only.  These variables do not exist in
 1.40257 +** a non-testing build.  These variables are not thread-safe.
 1.40258 +*/
 1.40259 +#ifdef SQLITE_TEST
 1.40260 +SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
 1.40261 +SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
 1.40262 +SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
 1.40263 +# define PAGER_INCR(v)  v++
 1.40264 +#else
 1.40265 +# define PAGER_INCR(v)
 1.40266 +#endif
 1.40267 +
 1.40268 +
 1.40269 +
 1.40270 +/*
 1.40271 +** Journal files begin with the following magic string.  The data
 1.40272 +** was obtained from /dev/random.  It is used only as a sanity check.
 1.40273 +**
 1.40274 +** Since version 2.8.0, the journal format contains additional sanity
 1.40275 +** checking information.  If the power fails while the journal is being
 1.40276 +** written, semi-random garbage data might appear in the journal
 1.40277 +** file after power is restored.  If an attempt is then made
 1.40278 +** to roll the journal back, the database could be corrupted.  The additional
 1.40279 +** sanity checking data is an attempt to discover the garbage in the
 1.40280 +** journal and ignore it.
 1.40281 +**
 1.40282 +** The sanity checking information for the new journal format consists
 1.40283 +** of a 32-bit checksum on each page of data.  The checksum covers both
 1.40284 +** the page number and the pPager->pageSize bytes of data for the page.
 1.40285 +** This cksum is initialized to a 32-bit random value that appears in the
 1.40286 +** journal file right after the header.  The random initializer is important,
 1.40287 +** because garbage data that appears at the end of a journal is likely
 1.40288 +** data that was once in other files that have now been deleted.  If the
 1.40289 +** garbage data came from an obsolete journal file, the checksums might
 1.40290 +** be correct.  But by initializing the checksum to random value which
 1.40291 +** is different for every journal, we minimize that risk.
 1.40292 +*/
 1.40293 +static const unsigned char aJournalMagic[] = {
 1.40294 +  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
 1.40295 +};
 1.40296 +
 1.40297 +/*
 1.40298 +** The size of the of each page record in the journal is given by
 1.40299 +** the following macro.
 1.40300 +*/
 1.40301 +#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
 1.40302 +
 1.40303 +/*
 1.40304 +** The journal header size for this pager. This is usually the same 
 1.40305 +** size as a single disk sector. See also setSectorSize().
 1.40306 +*/
 1.40307 +#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
 1.40308 +
 1.40309 +/*
 1.40310 +** The macro MEMDB is true if we are dealing with an in-memory database.
 1.40311 +** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
 1.40312 +** the value of MEMDB will be a constant and the compiler will optimize
 1.40313 +** out code that would never execute.
 1.40314 +*/
 1.40315 +#ifdef SQLITE_OMIT_MEMORYDB
 1.40316 +# define MEMDB 0
 1.40317 +#else
 1.40318 +# define MEMDB pPager->memDb
 1.40319 +#endif
 1.40320 +
 1.40321 +/*
 1.40322 +** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
 1.40323 +** interfaces to access the database using memory-mapped I/O.
 1.40324 +*/
 1.40325 +#if SQLITE_MAX_MMAP_SIZE>0
 1.40326 +# define USEFETCH(x) ((x)->bUseFetch)
 1.40327 +#else
 1.40328 +# define USEFETCH(x) 0
 1.40329 +#endif
 1.40330 +
 1.40331 +/*
 1.40332 +** The maximum legal page number is (2^31 - 1).
 1.40333 +*/
 1.40334 +#define PAGER_MAX_PGNO 2147483647
 1.40335 +
 1.40336 +/*
 1.40337 +** The argument to this macro is a file descriptor (type sqlite3_file*).
 1.40338 +** Return 0 if it is not open, or non-zero (but not 1) if it is.
 1.40339 +**
 1.40340 +** This is so that expressions can be written as:
 1.40341 +**
 1.40342 +**   if( isOpen(pPager->jfd) ){ ...
 1.40343 +**
 1.40344 +** instead of
 1.40345 +**
 1.40346 +**   if( pPager->jfd->pMethods ){ ...
 1.40347 +*/
 1.40348 +#define isOpen(pFd) ((pFd)->pMethods)
 1.40349 +
 1.40350 +/*
 1.40351 +** Return true if this pager uses a write-ahead log instead of the usual
 1.40352 +** rollback journal. Otherwise false.
 1.40353 +*/
 1.40354 +#ifndef SQLITE_OMIT_WAL
 1.40355 +static int pagerUseWal(Pager *pPager){
 1.40356 +  return (pPager->pWal!=0);
 1.40357 +}
 1.40358 +#else
 1.40359 +# define pagerUseWal(x) 0
 1.40360 +# define pagerRollbackWal(x) 0
 1.40361 +# define pagerWalFrames(v,w,x,y) 0
 1.40362 +# define pagerOpenWalIfPresent(z) SQLITE_OK
 1.40363 +# define pagerBeginReadTransaction(z) SQLITE_OK
 1.40364 +#endif
 1.40365 +
 1.40366 +#ifndef NDEBUG 
 1.40367 +/*
 1.40368 +** Usage:
 1.40369 +**
 1.40370 +**   assert( assert_pager_state(pPager) );
 1.40371 +**
 1.40372 +** This function runs many asserts to try to find inconsistencies in
 1.40373 +** the internal state of the Pager object.
 1.40374 +*/
 1.40375 +static int assert_pager_state(Pager *p){
 1.40376 +  Pager *pPager = p;
 1.40377 +
 1.40378 +  /* State must be valid. */
 1.40379 +  assert( p->eState==PAGER_OPEN
 1.40380 +       || p->eState==PAGER_READER
 1.40381 +       || p->eState==PAGER_WRITER_LOCKED
 1.40382 +       || p->eState==PAGER_WRITER_CACHEMOD
 1.40383 +       || p->eState==PAGER_WRITER_DBMOD
 1.40384 +       || p->eState==PAGER_WRITER_FINISHED
 1.40385 +       || p->eState==PAGER_ERROR
 1.40386 +  );
 1.40387 +
 1.40388 +  /* Regardless of the current state, a temp-file connection always behaves
 1.40389 +  ** as if it has an exclusive lock on the database file. It never updates
 1.40390 +  ** the change-counter field, so the changeCountDone flag is always set.
 1.40391 +  */
 1.40392 +  assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
 1.40393 +  assert( p->tempFile==0 || pPager->changeCountDone );
 1.40394 +
 1.40395 +  /* If the useJournal flag is clear, the journal-mode must be "OFF". 
 1.40396 +  ** And if the journal-mode is "OFF", the journal file must not be open.
 1.40397 +  */
 1.40398 +  assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
 1.40399 +  assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
 1.40400 +
 1.40401 +  /* Check that MEMDB implies noSync. And an in-memory journal. Since 
 1.40402 +  ** this means an in-memory pager performs no IO at all, it cannot encounter 
 1.40403 +  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing 
 1.40404 +  ** a journal file. (although the in-memory journal implementation may 
 1.40405 +  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It 
 1.40406 +  ** is therefore not possible for an in-memory pager to enter the ERROR 
 1.40407 +  ** state.
 1.40408 +  */
 1.40409 +  if( MEMDB ){
 1.40410 +    assert( p->noSync );
 1.40411 +    assert( p->journalMode==PAGER_JOURNALMODE_OFF 
 1.40412 +         || p->journalMode==PAGER_JOURNALMODE_MEMORY 
 1.40413 +    );
 1.40414 +    assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
 1.40415 +    assert( pagerUseWal(p)==0 );
 1.40416 +  }
 1.40417 +
 1.40418 +  /* If changeCountDone is set, a RESERVED lock or greater must be held
 1.40419 +  ** on the file.
 1.40420 +  */
 1.40421 +  assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
 1.40422 +  assert( p->eLock!=PENDING_LOCK );
 1.40423 +
 1.40424 +  switch( p->eState ){
 1.40425 +    case PAGER_OPEN:
 1.40426 +      assert( !MEMDB );
 1.40427 +      assert( pPager->errCode==SQLITE_OK );
 1.40428 +      assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
 1.40429 +      break;
 1.40430 +
 1.40431 +    case PAGER_READER:
 1.40432 +      assert( pPager->errCode==SQLITE_OK );
 1.40433 +      assert( p->eLock!=UNKNOWN_LOCK );
 1.40434 +      assert( p->eLock>=SHARED_LOCK );
 1.40435 +      break;
 1.40436 +
 1.40437 +    case PAGER_WRITER_LOCKED:
 1.40438 +      assert( p->eLock!=UNKNOWN_LOCK );
 1.40439 +      assert( pPager->errCode==SQLITE_OK );
 1.40440 +      if( !pagerUseWal(pPager) ){
 1.40441 +        assert( p->eLock>=RESERVED_LOCK );
 1.40442 +      }
 1.40443 +      assert( pPager->dbSize==pPager->dbOrigSize );
 1.40444 +      assert( pPager->dbOrigSize==pPager->dbFileSize );
 1.40445 +      assert( pPager->dbOrigSize==pPager->dbHintSize );
 1.40446 +      assert( pPager->setMaster==0 );
 1.40447 +      break;
 1.40448 +
 1.40449 +    case PAGER_WRITER_CACHEMOD:
 1.40450 +      assert( p->eLock!=UNKNOWN_LOCK );
 1.40451 +      assert( pPager->errCode==SQLITE_OK );
 1.40452 +      if( !pagerUseWal(pPager) ){
 1.40453 +        /* It is possible that if journal_mode=wal here that neither the
 1.40454 +        ** journal file nor the WAL file are open. This happens during
 1.40455 +        ** a rollback transaction that switches from journal_mode=off
 1.40456 +        ** to journal_mode=wal.
 1.40457 +        */
 1.40458 +        assert( p->eLock>=RESERVED_LOCK );
 1.40459 +        assert( isOpen(p->jfd) 
 1.40460 +             || p->journalMode==PAGER_JOURNALMODE_OFF 
 1.40461 +             || p->journalMode==PAGER_JOURNALMODE_WAL 
 1.40462 +        );
 1.40463 +      }
 1.40464 +      assert( pPager->dbOrigSize==pPager->dbFileSize );
 1.40465 +      assert( pPager->dbOrigSize==pPager->dbHintSize );
 1.40466 +      break;
 1.40467 +
 1.40468 +    case PAGER_WRITER_DBMOD:
 1.40469 +      assert( p->eLock==EXCLUSIVE_LOCK );
 1.40470 +      assert( pPager->errCode==SQLITE_OK );
 1.40471 +      assert( !pagerUseWal(pPager) );
 1.40472 +      assert( p->eLock>=EXCLUSIVE_LOCK );
 1.40473 +      assert( isOpen(p->jfd) 
 1.40474 +           || p->journalMode==PAGER_JOURNALMODE_OFF 
 1.40475 +           || p->journalMode==PAGER_JOURNALMODE_WAL 
 1.40476 +      );
 1.40477 +      assert( pPager->dbOrigSize<=pPager->dbHintSize );
 1.40478 +      break;
 1.40479 +
 1.40480 +    case PAGER_WRITER_FINISHED:
 1.40481 +      assert( p->eLock==EXCLUSIVE_LOCK );
 1.40482 +      assert( pPager->errCode==SQLITE_OK );
 1.40483 +      assert( !pagerUseWal(pPager) );
 1.40484 +      assert( isOpen(p->jfd) 
 1.40485 +           || p->journalMode==PAGER_JOURNALMODE_OFF 
 1.40486 +           || p->journalMode==PAGER_JOURNALMODE_WAL 
 1.40487 +      );
 1.40488 +      break;
 1.40489 +
 1.40490 +    case PAGER_ERROR:
 1.40491 +      /* There must be at least one outstanding reference to the pager if
 1.40492 +      ** in ERROR state. Otherwise the pager should have already dropped
 1.40493 +      ** back to OPEN state.
 1.40494 +      */
 1.40495 +      assert( pPager->errCode!=SQLITE_OK );
 1.40496 +      assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
 1.40497 +      break;
 1.40498 +  }
 1.40499 +
 1.40500 +  return 1;
 1.40501 +}
 1.40502 +#endif /* ifndef NDEBUG */
 1.40503 +
 1.40504 +#ifdef SQLITE_DEBUG 
 1.40505 +/*
 1.40506 +** Return a pointer to a human readable string in a static buffer
 1.40507 +** containing the state of the Pager object passed as an argument. This
 1.40508 +** is intended to be used within debuggers. For example, as an alternative
 1.40509 +** to "print *pPager" in gdb:
 1.40510 +**
 1.40511 +** (gdb) printf "%s", print_pager_state(pPager)
 1.40512 +*/
 1.40513 +static char *print_pager_state(Pager *p){
 1.40514 +  static char zRet[1024];
 1.40515 +
 1.40516 +  sqlite3_snprintf(1024, zRet,
 1.40517 +      "Filename:      %s\n"
 1.40518 +      "State:         %s errCode=%d\n"
 1.40519 +      "Lock:          %s\n"
 1.40520 +      "Locking mode:  locking_mode=%s\n"
 1.40521 +      "Journal mode:  journal_mode=%s\n"
 1.40522 +      "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
 1.40523 +      "Journal:       journalOff=%lld journalHdr=%lld\n"
 1.40524 +      "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
 1.40525 +      , p->zFilename
 1.40526 +      , p->eState==PAGER_OPEN            ? "OPEN" :
 1.40527 +        p->eState==PAGER_READER          ? "READER" :
 1.40528 +        p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
 1.40529 +        p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
 1.40530 +        p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
 1.40531 +        p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
 1.40532 +        p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
 1.40533 +      , (int)p->errCode
 1.40534 +      , p->eLock==NO_LOCK         ? "NO_LOCK" :
 1.40535 +        p->eLock==RESERVED_LOCK   ? "RESERVED" :
 1.40536 +        p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
 1.40537 +        p->eLock==SHARED_LOCK     ? "SHARED" :
 1.40538 +        p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
 1.40539 +      , p->exclusiveMode ? "exclusive" : "normal"
 1.40540 +      , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
 1.40541 +        p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
 1.40542 +        p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
 1.40543 +        p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
 1.40544 +        p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
 1.40545 +        p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
 1.40546 +      , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
 1.40547 +      , p->journalOff, p->journalHdr
 1.40548 +      , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
 1.40549 +  );
 1.40550 +
 1.40551 +  return zRet;
 1.40552 +}
 1.40553 +#endif
 1.40554 +
 1.40555 +/*
 1.40556 +** Return true if it is necessary to write page *pPg into the sub-journal.
 1.40557 +** A page needs to be written into the sub-journal if there exists one
 1.40558 +** or more open savepoints for which:
 1.40559 +**
 1.40560 +**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
 1.40561 +**   * The bit corresponding to the page-number is not set in
 1.40562 +**     PagerSavepoint.pInSavepoint.
 1.40563 +*/
 1.40564 +static int subjRequiresPage(PgHdr *pPg){
 1.40565 +  Pager *pPager = pPg->pPager;
 1.40566 +  PagerSavepoint *p;
 1.40567 +  Pgno pgno = pPg->pgno;
 1.40568 +  int i;
 1.40569 +  for(i=0; i<pPager->nSavepoint; i++){
 1.40570 +    p = &pPager->aSavepoint[i];
 1.40571 +    if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
 1.40572 +      return 1;
 1.40573 +    }
 1.40574 +  }
 1.40575 +  return 0;
 1.40576 +}
 1.40577 +
 1.40578 +/*
 1.40579 +** Return true if the page is already in the journal file.
 1.40580 +*/
 1.40581 +static int pageInJournal(Pager *pPager, PgHdr *pPg){
 1.40582 +  return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
 1.40583 +}
 1.40584 +
 1.40585 +/*
 1.40586 +** Read a 32-bit integer from the given file descriptor.  Store the integer
 1.40587 +** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
 1.40588 +** error code is something goes wrong.
 1.40589 +**
 1.40590 +** All values are stored on disk as big-endian.
 1.40591 +*/
 1.40592 +static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
 1.40593 +  unsigned char ac[4];
 1.40594 +  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
 1.40595 +  if( rc==SQLITE_OK ){
 1.40596 +    *pRes = sqlite3Get4byte(ac);
 1.40597 +  }
 1.40598 +  return rc;
 1.40599 +}
 1.40600 +
 1.40601 +/*
 1.40602 +** Write a 32-bit integer into a string buffer in big-endian byte order.
 1.40603 +*/
 1.40604 +#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
 1.40605 +
 1.40606 +
 1.40607 +/*
 1.40608 +** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
 1.40609 +** on success or an error code is something goes wrong.
 1.40610 +*/
 1.40611 +static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
 1.40612 +  char ac[4];
 1.40613 +  put32bits(ac, val);
 1.40614 +  return sqlite3OsWrite(fd, ac, 4, offset);
 1.40615 +}
 1.40616 +
 1.40617 +/*
 1.40618 +** Unlock the database file to level eLock, which must be either NO_LOCK
 1.40619 +** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
 1.40620 +** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
 1.40621 +**
 1.40622 +** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
 1.40623 +** called, do not modify it. See the comment above the #define of 
 1.40624 +** UNKNOWN_LOCK for an explanation of this.
 1.40625 +*/
 1.40626 +static int pagerUnlockDb(Pager *pPager, int eLock){
 1.40627 +  int rc = SQLITE_OK;
 1.40628 +
 1.40629 +  assert( !pPager->exclusiveMode || pPager->eLock==eLock );
 1.40630 +  assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
 1.40631 +  assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
 1.40632 +  if( isOpen(pPager->fd) ){
 1.40633 +    assert( pPager->eLock>=eLock );
 1.40634 +    rc = sqlite3OsUnlock(pPager->fd, eLock);
 1.40635 +    if( pPager->eLock!=UNKNOWN_LOCK ){
 1.40636 +      pPager->eLock = (u8)eLock;
 1.40637 +    }
 1.40638 +    IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
 1.40639 +  }
 1.40640 +  return rc;
 1.40641 +}
 1.40642 +
 1.40643 +/*
 1.40644 +** Lock the database file to level eLock, which must be either SHARED_LOCK,
 1.40645 +** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
 1.40646 +** Pager.eLock variable to the new locking state. 
 1.40647 +**
 1.40648 +** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
 1.40649 +** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
 1.40650 +** See the comment above the #define of UNKNOWN_LOCK for an explanation 
 1.40651 +** of this.
 1.40652 +*/
 1.40653 +static int pagerLockDb(Pager *pPager, int eLock){
 1.40654 +  int rc = SQLITE_OK;
 1.40655 +
 1.40656 +  assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
 1.40657 +  if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
 1.40658 +    rc = sqlite3OsLock(pPager->fd, eLock);
 1.40659 +    if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
 1.40660 +      pPager->eLock = (u8)eLock;
 1.40661 +      IOTRACE(("LOCK %p %d\n", pPager, eLock))
 1.40662 +    }
 1.40663 +  }
 1.40664 +  return rc;
 1.40665 +}
 1.40666 +
 1.40667 +/*
 1.40668 +** This function determines whether or not the atomic-write optimization
 1.40669 +** can be used with this pager. The optimization can be used if:
 1.40670 +**
 1.40671 +**  (a) the value returned by OsDeviceCharacteristics() indicates that
 1.40672 +**      a database page may be written atomically, and
 1.40673 +**  (b) the value returned by OsSectorSize() is less than or equal
 1.40674 +**      to the page size.
 1.40675 +**
 1.40676 +** The optimization is also always enabled for temporary files. It is
 1.40677 +** an error to call this function if pPager is opened on an in-memory
 1.40678 +** database.
 1.40679 +**
 1.40680 +** If the optimization cannot be used, 0 is returned. If it can be used,
 1.40681 +** then the value returned is the size of the journal file when it
 1.40682 +** contains rollback data for exactly one page.
 1.40683 +*/
 1.40684 +#ifdef SQLITE_ENABLE_ATOMIC_WRITE
 1.40685 +static int jrnlBufferSize(Pager *pPager){
 1.40686 +  assert( !MEMDB );
 1.40687 +  if( !pPager->tempFile ){
 1.40688 +    int dc;                           /* Device characteristics */
 1.40689 +    int nSector;                      /* Sector size */
 1.40690 +    int szPage;                       /* Page size */
 1.40691 +
 1.40692 +    assert( isOpen(pPager->fd) );
 1.40693 +    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
 1.40694 +    nSector = pPager->sectorSize;
 1.40695 +    szPage = pPager->pageSize;
 1.40696 +
 1.40697 +    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
 1.40698 +    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
 1.40699 +    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
 1.40700 +      return 0;
 1.40701 +    }
 1.40702 +  }
 1.40703 +
 1.40704 +  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
 1.40705 +}
 1.40706 +#endif
 1.40707 +
 1.40708 +/*
 1.40709 +** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
 1.40710 +** on the cache using a hash function.  This is used for testing
 1.40711 +** and debugging only.
 1.40712 +*/
 1.40713 +#ifdef SQLITE_CHECK_PAGES
 1.40714 +/*
 1.40715 +** Return a 32-bit hash of the page data for pPage.
 1.40716 +*/
 1.40717 +static u32 pager_datahash(int nByte, unsigned char *pData){
 1.40718 +  u32 hash = 0;
 1.40719 +  int i;
 1.40720 +  for(i=0; i<nByte; i++){
 1.40721 +    hash = (hash*1039) + pData[i];
 1.40722 +  }
 1.40723 +  return hash;
 1.40724 +}
 1.40725 +static u32 pager_pagehash(PgHdr *pPage){
 1.40726 +  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
 1.40727 +}
 1.40728 +static void pager_set_pagehash(PgHdr *pPage){
 1.40729 +  pPage->pageHash = pager_pagehash(pPage);
 1.40730 +}
 1.40731 +
 1.40732 +/*
 1.40733 +** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
 1.40734 +** is defined, and NDEBUG is not defined, an assert() statement checks
 1.40735 +** that the page is either dirty or still matches the calculated page-hash.
 1.40736 +*/
 1.40737 +#define CHECK_PAGE(x) checkPage(x)
 1.40738 +static void checkPage(PgHdr *pPg){
 1.40739 +  Pager *pPager = pPg->pPager;
 1.40740 +  assert( pPager->eState!=PAGER_ERROR );
 1.40741 +  assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
 1.40742 +}
 1.40743 +
 1.40744 +#else
 1.40745 +#define pager_datahash(X,Y)  0
 1.40746 +#define pager_pagehash(X)  0
 1.40747 +#define pager_set_pagehash(X)
 1.40748 +#define CHECK_PAGE(x)
 1.40749 +#endif  /* SQLITE_CHECK_PAGES */
 1.40750 +
 1.40751 +/*
 1.40752 +** When this is called the journal file for pager pPager must be open.
 1.40753 +** This function attempts to read a master journal file name from the 
 1.40754 +** end of the file and, if successful, copies it into memory supplied 
 1.40755 +** by the caller. See comments above writeMasterJournal() for the format
 1.40756 +** used to store a master journal file name at the end of a journal file.
 1.40757 +**
 1.40758 +** zMaster must point to a buffer of at least nMaster bytes allocated by
 1.40759 +** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
 1.40760 +** enough space to write the master journal name). If the master journal
 1.40761 +** name in the journal is longer than nMaster bytes (including a
 1.40762 +** nul-terminator), then this is handled as if no master journal name
 1.40763 +** were present in the journal.
 1.40764 +**
 1.40765 +** If a master journal file name is present at the end of the journal
 1.40766 +** file, then it is copied into the buffer pointed to by zMaster. A
 1.40767 +** nul-terminator byte is appended to the buffer following the master
 1.40768 +** journal file name.
 1.40769 +**
 1.40770 +** If it is determined that no master journal file name is present 
 1.40771 +** zMaster[0] is set to 0 and SQLITE_OK returned.
 1.40772 +**
 1.40773 +** If an error occurs while reading from the journal file, an SQLite
 1.40774 +** error code is returned.
 1.40775 +*/
 1.40776 +static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
 1.40777 +  int rc;                    /* Return code */
 1.40778 +  u32 len;                   /* Length in bytes of master journal name */
 1.40779 +  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
 1.40780 +  u32 cksum;                 /* MJ checksum value read from journal */
 1.40781 +  u32 u;                     /* Unsigned loop counter */
 1.40782 +  unsigned char aMagic[8];   /* A buffer to hold the magic header */
 1.40783 +  zMaster[0] = '\0';
 1.40784 +
 1.40785 +  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
 1.40786 +   || szJ<16
 1.40787 +   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
 1.40788 +   || len>=nMaster 
 1.40789 +   || len==0 
 1.40790 +   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
 1.40791 +   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
 1.40792 +   || memcmp(aMagic, aJournalMagic, 8)
 1.40793 +   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
 1.40794 +  ){
 1.40795 +    return rc;
 1.40796 +  }
 1.40797 +
 1.40798 +  /* See if the checksum matches the master journal name */
 1.40799 +  for(u=0; u<len; u++){
 1.40800 +    cksum -= zMaster[u];
 1.40801 +  }
 1.40802 +  if( cksum ){
 1.40803 +    /* If the checksum doesn't add up, then one or more of the disk sectors
 1.40804 +    ** containing the master journal filename is corrupted. This means
 1.40805 +    ** definitely roll back, so just return SQLITE_OK and report a (nul)
 1.40806 +    ** master-journal filename.
 1.40807 +    */
 1.40808 +    len = 0;
 1.40809 +  }
 1.40810 +  zMaster[len] = '\0';
 1.40811 +   
 1.40812 +  return SQLITE_OK;
 1.40813 +}
 1.40814 +
 1.40815 +/*
 1.40816 +** Return the offset of the sector boundary at or immediately 
 1.40817 +** following the value in pPager->journalOff, assuming a sector 
 1.40818 +** size of pPager->sectorSize bytes.
 1.40819 +**
 1.40820 +** i.e for a sector size of 512:
 1.40821 +**
 1.40822 +**   Pager.journalOff          Return value
 1.40823 +**   ---------------------------------------
 1.40824 +**   0                         0
 1.40825 +**   512                       512
 1.40826 +**   100                       512
 1.40827 +**   2000                      2048
 1.40828 +** 
 1.40829 +*/
 1.40830 +static i64 journalHdrOffset(Pager *pPager){
 1.40831 +  i64 offset = 0;
 1.40832 +  i64 c = pPager->journalOff;
 1.40833 +  if( c ){
 1.40834 +    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
 1.40835 +  }
 1.40836 +  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
 1.40837 +  assert( offset>=c );
 1.40838 +  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
 1.40839 +  return offset;
 1.40840 +}
 1.40841 +
 1.40842 +/*
 1.40843 +** The journal file must be open when this function is called.
 1.40844 +**
 1.40845 +** This function is a no-op if the journal file has not been written to
 1.40846 +** within the current transaction (i.e. if Pager.journalOff==0).
 1.40847 +**
 1.40848 +** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
 1.40849 +** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
 1.40850 +** zero the 28-byte header at the start of the journal file. In either case, 
 1.40851 +** if the pager is not in no-sync mode, sync the journal file immediately 
 1.40852 +** after writing or truncating it.
 1.40853 +**
 1.40854 +** If Pager.journalSizeLimit is set to a positive, non-zero value, and
 1.40855 +** following the truncation or zeroing described above the size of the 
 1.40856 +** journal file in bytes is larger than this value, then truncate the
 1.40857 +** journal file to Pager.journalSizeLimit bytes. The journal file does
 1.40858 +** not need to be synced following this operation.
 1.40859 +**
 1.40860 +** If an IO error occurs, abandon processing and return the IO error code.
 1.40861 +** Otherwise, return SQLITE_OK.
 1.40862 +*/
 1.40863 +static int zeroJournalHdr(Pager *pPager, int doTruncate){
 1.40864 +  int rc = SQLITE_OK;                               /* Return code */
 1.40865 +  assert( isOpen(pPager->jfd) );
 1.40866 +  if( pPager->journalOff ){
 1.40867 +    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
 1.40868 +
 1.40869 +    IOTRACE(("JZEROHDR %p\n", pPager))
 1.40870 +    if( doTruncate || iLimit==0 ){
 1.40871 +      rc = sqlite3OsTruncate(pPager->jfd, 0);
 1.40872 +    }else{
 1.40873 +      static const char zeroHdr[28] = {0};
 1.40874 +      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
 1.40875 +    }
 1.40876 +    if( rc==SQLITE_OK && !pPager->noSync ){
 1.40877 +      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
 1.40878 +    }
 1.40879 +
 1.40880 +    /* At this point the transaction is committed but the write lock 
 1.40881 +    ** is still held on the file. If there is a size limit configured for 
 1.40882 +    ** the persistent journal and the journal file currently consumes more
 1.40883 +    ** space than that limit allows for, truncate it now. There is no need
 1.40884 +    ** to sync the file following this operation.
 1.40885 +    */
 1.40886 +    if( rc==SQLITE_OK && iLimit>0 ){
 1.40887 +      i64 sz;
 1.40888 +      rc = sqlite3OsFileSize(pPager->jfd, &sz);
 1.40889 +      if( rc==SQLITE_OK && sz>iLimit ){
 1.40890 +        rc = sqlite3OsTruncate(pPager->jfd, iLimit);
 1.40891 +      }
 1.40892 +    }
 1.40893 +  }
 1.40894 +  return rc;
 1.40895 +}
 1.40896 +
 1.40897 +/*
 1.40898 +** The journal file must be open when this routine is called. A journal
 1.40899 +** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
 1.40900 +** current location.
 1.40901 +**
 1.40902 +** The format for the journal header is as follows:
 1.40903 +** - 8 bytes: Magic identifying journal format.
 1.40904 +** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
 1.40905 +** - 4 bytes: Random number used for page hash.
 1.40906 +** - 4 bytes: Initial database page count.
 1.40907 +** - 4 bytes: Sector size used by the process that wrote this journal.
 1.40908 +** - 4 bytes: Database page size.
 1.40909 +** 
 1.40910 +** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
 1.40911 +*/
 1.40912 +static int writeJournalHdr(Pager *pPager){
 1.40913 +  int rc = SQLITE_OK;                 /* Return code */
 1.40914 +  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
 1.40915 +  u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
 1.40916 +  u32 nWrite;                         /* Bytes of header sector written */
 1.40917 +  int ii;                             /* Loop counter */
 1.40918 +
 1.40919 +  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
 1.40920 +
 1.40921 +  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
 1.40922 +    nHeader = JOURNAL_HDR_SZ(pPager);
 1.40923 +  }
 1.40924 +
 1.40925 +  /* If there are active savepoints and any of them were created 
 1.40926 +  ** since the most recent journal header was written, update the 
 1.40927 +  ** PagerSavepoint.iHdrOffset fields now.
 1.40928 +  */
 1.40929 +  for(ii=0; ii<pPager->nSavepoint; ii++){
 1.40930 +    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
 1.40931 +      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
 1.40932 +    }
 1.40933 +  }
 1.40934 +
 1.40935 +  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
 1.40936 +
 1.40937 +  /* 
 1.40938 +  ** Write the nRec Field - the number of page records that follow this
 1.40939 +  ** journal header. Normally, zero is written to this value at this time.
 1.40940 +  ** After the records are added to the journal (and the journal synced, 
 1.40941 +  ** if in full-sync mode), the zero is overwritten with the true number
 1.40942 +  ** of records (see syncJournal()).
 1.40943 +  **
 1.40944 +  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
 1.40945 +  ** reading the journal this value tells SQLite to assume that the
 1.40946 +  ** rest of the journal file contains valid page records. This assumption
 1.40947 +  ** is dangerous, as if a failure occurred whilst writing to the journal
 1.40948 +  ** file it may contain some garbage data. There are two scenarios
 1.40949 +  ** where this risk can be ignored:
 1.40950 +  **
 1.40951 +  **   * When the pager is in no-sync mode. Corruption can follow a
 1.40952 +  **     power failure in this case anyway.
 1.40953 +  **
 1.40954 +  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
 1.40955 +  **     that garbage data is never appended to the journal file.
 1.40956 +  */
 1.40957 +  assert( isOpen(pPager->fd) || pPager->noSync );
 1.40958 +  if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
 1.40959 +   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
 1.40960 +  ){
 1.40961 +    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
 1.40962 +    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
 1.40963 +  }else{
 1.40964 +    memset(zHeader, 0, sizeof(aJournalMagic)+4);
 1.40965 +  }
 1.40966 +
 1.40967 +  /* The random check-hash initializer */ 
 1.40968 +  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
 1.40969 +  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
 1.40970 +  /* The initial database size */
 1.40971 +  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
 1.40972 +  /* The assumed sector size for this process */
 1.40973 +  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
 1.40974 +
 1.40975 +  /* The page size */
 1.40976 +  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
 1.40977 +
 1.40978 +  /* Initializing the tail of the buffer is not necessary.  Everything
 1.40979 +  ** works find if the following memset() is omitted.  But initializing
 1.40980 +  ** the memory prevents valgrind from complaining, so we are willing to
 1.40981 +  ** take the performance hit.
 1.40982 +  */
 1.40983 +  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
 1.40984 +         nHeader-(sizeof(aJournalMagic)+20));
 1.40985 +
 1.40986 +  /* In theory, it is only necessary to write the 28 bytes that the 
 1.40987 +  ** journal header consumes to the journal file here. Then increment the 
 1.40988 +  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
 1.40989 +  ** record is written to the following sector (leaving a gap in the file
 1.40990 +  ** that will be implicitly filled in by the OS).
 1.40991 +  **
 1.40992 +  ** However it has been discovered that on some systems this pattern can 
 1.40993 +  ** be significantly slower than contiguously writing data to the file,
 1.40994 +  ** even if that means explicitly writing data to the block of 
 1.40995 +  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
 1.40996 +  ** is done. 
 1.40997 +  **
 1.40998 +  ** The loop is required here in case the sector-size is larger than the 
 1.40999 +  ** database page size. Since the zHeader buffer is only Pager.pageSize
 1.41000 +  ** bytes in size, more than one call to sqlite3OsWrite() may be required
 1.41001 +  ** to populate the entire journal header sector.
 1.41002 +  */ 
 1.41003 +  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
 1.41004 +    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
 1.41005 +    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
 1.41006 +    assert( pPager->journalHdr <= pPager->journalOff );
 1.41007 +    pPager->journalOff += nHeader;
 1.41008 +  }
 1.41009 +
 1.41010 +  return rc;
 1.41011 +}
 1.41012 +
 1.41013 +/*
 1.41014 +** The journal file must be open when this is called. A journal header file
 1.41015 +** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
 1.41016 +** file. The current location in the journal file is given by
 1.41017 +** pPager->journalOff. See comments above function writeJournalHdr() for
 1.41018 +** a description of the journal header format.
 1.41019 +**
 1.41020 +** If the header is read successfully, *pNRec is set to the number of
 1.41021 +** page records following this header and *pDbSize is set to the size of the
 1.41022 +** database before the transaction began, in pages. Also, pPager->cksumInit
 1.41023 +** is set to the value read from the journal header. SQLITE_OK is returned
 1.41024 +** in this case.
 1.41025 +**
 1.41026 +** If the journal header file appears to be corrupted, SQLITE_DONE is
 1.41027 +** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
 1.41028 +** cannot be read from the journal file an error code is returned.
 1.41029 +*/
 1.41030 +static int readJournalHdr(
 1.41031 +  Pager *pPager,               /* Pager object */
 1.41032 +  int isHot,
 1.41033 +  i64 journalSize,             /* Size of the open journal file in bytes */
 1.41034 +  u32 *pNRec,                  /* OUT: Value read from the nRec field */
 1.41035 +  u32 *pDbSize                 /* OUT: Value of original database size field */
 1.41036 +){
 1.41037 +  int rc;                      /* Return code */
 1.41038 +  unsigned char aMagic[8];     /* A buffer to hold the magic header */
 1.41039 +  i64 iHdrOff;                 /* Offset of journal header being read */
 1.41040 +
 1.41041 +  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
 1.41042 +
 1.41043 +  /* Advance Pager.journalOff to the start of the next sector. If the
 1.41044 +  ** journal file is too small for there to be a header stored at this
 1.41045 +  ** point, return SQLITE_DONE.
 1.41046 +  */
 1.41047 +  pPager->journalOff = journalHdrOffset(pPager);
 1.41048 +  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
 1.41049 +    return SQLITE_DONE;
 1.41050 +  }
 1.41051 +  iHdrOff = pPager->journalOff;
 1.41052 +
 1.41053 +  /* Read in the first 8 bytes of the journal header. If they do not match
 1.41054 +  ** the  magic string found at the start of each journal header, return
 1.41055 +  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
 1.41056 +  ** proceed.
 1.41057 +  */
 1.41058 +  if( isHot || iHdrOff!=pPager->journalHdr ){
 1.41059 +    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
 1.41060 +    if( rc ){
 1.41061 +      return rc;
 1.41062 +    }
 1.41063 +    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
 1.41064 +      return SQLITE_DONE;
 1.41065 +    }
 1.41066 +  }
 1.41067 +
 1.41068 +  /* Read the first three 32-bit fields of the journal header: The nRec
 1.41069 +  ** field, the checksum-initializer and the database size at the start
 1.41070 +  ** of the transaction. Return an error code if anything goes wrong.
 1.41071 +  */
 1.41072 +  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
 1.41073 +   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
 1.41074 +   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
 1.41075 +  ){
 1.41076 +    return rc;
 1.41077 +  }
 1.41078 +
 1.41079 +  if( pPager->journalOff==0 ){
 1.41080 +    u32 iPageSize;               /* Page-size field of journal header */
 1.41081 +    u32 iSectorSize;             /* Sector-size field of journal header */
 1.41082 +
 1.41083 +    /* Read the page-size and sector-size journal header fields. */
 1.41084 +    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
 1.41085 +     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
 1.41086 +    ){
 1.41087 +      return rc;
 1.41088 +    }
 1.41089 +
 1.41090 +    /* Versions of SQLite prior to 3.5.8 set the page-size field of the
 1.41091 +    ** journal header to zero. In this case, assume that the Pager.pageSize
 1.41092 +    ** variable is already set to the correct page size.
 1.41093 +    */
 1.41094 +    if( iPageSize==0 ){
 1.41095 +      iPageSize = pPager->pageSize;
 1.41096 +    }
 1.41097 +
 1.41098 +    /* Check that the values read from the page-size and sector-size fields
 1.41099 +    ** are within range. To be 'in range', both values need to be a power
 1.41100 +    ** of two greater than or equal to 512 or 32, and not greater than their 
 1.41101 +    ** respective compile time maximum limits.
 1.41102 +    */
 1.41103 +    if( iPageSize<512                  || iSectorSize<32
 1.41104 +     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
 1.41105 +     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
 1.41106 +    ){
 1.41107 +      /* If the either the page-size or sector-size in the journal-header is 
 1.41108 +      ** invalid, then the process that wrote the journal-header must have 
 1.41109 +      ** crashed before the header was synced. In this case stop reading 
 1.41110 +      ** the journal file here.
 1.41111 +      */
 1.41112 +      return SQLITE_DONE;
 1.41113 +    }
 1.41114 +
 1.41115 +    /* Update the page-size to match the value read from the journal. 
 1.41116 +    ** Use a testcase() macro to make sure that malloc failure within 
 1.41117 +    ** PagerSetPagesize() is tested.
 1.41118 +    */
 1.41119 +    rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
 1.41120 +    testcase( rc!=SQLITE_OK );
 1.41121 +
 1.41122 +    /* Update the assumed sector-size to match the value used by 
 1.41123 +    ** the process that created this journal. If this journal was
 1.41124 +    ** created by a process other than this one, then this routine
 1.41125 +    ** is being called from within pager_playback(). The local value
 1.41126 +    ** of Pager.sectorSize is restored at the end of that routine.
 1.41127 +    */
 1.41128 +    pPager->sectorSize = iSectorSize;
 1.41129 +  }
 1.41130 +
 1.41131 +  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
 1.41132 +  return rc;
 1.41133 +}
 1.41134 +
 1.41135 +
 1.41136 +/*
 1.41137 +** Write the supplied master journal name into the journal file for pager
 1.41138 +** pPager at the current location. The master journal name must be the last
 1.41139 +** thing written to a journal file. If the pager is in full-sync mode, the
 1.41140 +** journal file descriptor is advanced to the next sector boundary before
 1.41141 +** anything is written. The format is:
 1.41142 +**
 1.41143 +**   + 4 bytes: PAGER_MJ_PGNO.
 1.41144 +**   + N bytes: Master journal filename in utf-8.
 1.41145 +**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
 1.41146 +**   + 4 bytes: Master journal name checksum.
 1.41147 +**   + 8 bytes: aJournalMagic[].
 1.41148 +**
 1.41149 +** The master journal page checksum is the sum of the bytes in the master
 1.41150 +** journal name, where each byte is interpreted as a signed 8-bit integer.
 1.41151 +**
 1.41152 +** If zMaster is a NULL pointer (occurs for a single database transaction), 
 1.41153 +** this call is a no-op.
 1.41154 +*/
 1.41155 +static int writeMasterJournal(Pager *pPager, const char *zMaster){
 1.41156 +  int rc;                          /* Return code */
 1.41157 +  int nMaster;                     /* Length of string zMaster */
 1.41158 +  i64 iHdrOff;                     /* Offset of header in journal file */
 1.41159 +  i64 jrnlSize;                    /* Size of journal file on disk */
 1.41160 +  u32 cksum = 0;                   /* Checksum of string zMaster */
 1.41161 +
 1.41162 +  assert( pPager->setMaster==0 );
 1.41163 +  assert( !pagerUseWal(pPager) );
 1.41164 +
 1.41165 +  if( !zMaster 
 1.41166 +   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
 1.41167 +   || pPager->journalMode==PAGER_JOURNALMODE_OFF 
 1.41168 +  ){
 1.41169 +    return SQLITE_OK;
 1.41170 +  }
 1.41171 +  pPager->setMaster = 1;
 1.41172 +  assert( isOpen(pPager->jfd) );
 1.41173 +  assert( pPager->journalHdr <= pPager->journalOff );
 1.41174 +
 1.41175 +  /* Calculate the length in bytes and the checksum of zMaster */
 1.41176 +  for(nMaster=0; zMaster[nMaster]; nMaster++){
 1.41177 +    cksum += zMaster[nMaster];
 1.41178 +  }
 1.41179 +
 1.41180 +  /* If in full-sync mode, advance to the next disk sector before writing
 1.41181 +  ** the master journal name. This is in case the previous page written to
 1.41182 +  ** the journal has already been synced.
 1.41183 +  */
 1.41184 +  if( pPager->fullSync ){
 1.41185 +    pPager->journalOff = journalHdrOffset(pPager);
 1.41186 +  }
 1.41187 +  iHdrOff = pPager->journalOff;
 1.41188 +
 1.41189 +  /* Write the master journal data to the end of the journal file. If
 1.41190 +  ** an error occurs, return the error code to the caller.
 1.41191 +  */
 1.41192 +  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
 1.41193 +   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
 1.41194 +   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
 1.41195 +   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
 1.41196 +   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
 1.41197 +  ){
 1.41198 +    return rc;
 1.41199 +  }
 1.41200 +  pPager->journalOff += (nMaster+20);
 1.41201 +
 1.41202 +  /* If the pager is in peristent-journal mode, then the physical 
 1.41203 +  ** journal-file may extend past the end of the master-journal name
 1.41204 +  ** and 8 bytes of magic data just written to the file. This is 
 1.41205 +  ** dangerous because the code to rollback a hot-journal file
 1.41206 +  ** will not be able to find the master-journal name to determine 
 1.41207 +  ** whether or not the journal is hot. 
 1.41208 +  **
 1.41209 +  ** Easiest thing to do in this scenario is to truncate the journal 
 1.41210 +  ** file to the required size.
 1.41211 +  */ 
 1.41212 +  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
 1.41213 +   && jrnlSize>pPager->journalOff
 1.41214 +  ){
 1.41215 +    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
 1.41216 +  }
 1.41217 +  return rc;
 1.41218 +}
 1.41219 +
 1.41220 +/*
 1.41221 +** Find a page in the hash table given its page number. Return
 1.41222 +** a pointer to the page or NULL if the requested page is not 
 1.41223 +** already in memory.
 1.41224 +*/
 1.41225 +static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
 1.41226 +  PgHdr *p = 0;                     /* Return value */
 1.41227 +
 1.41228 +  /* It is not possible for a call to PcacheFetch() with createFlag==0 to
 1.41229 +  ** fail, since no attempt to allocate dynamic memory will be made.
 1.41230 +  */
 1.41231 +  (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
 1.41232 +  return p;
 1.41233 +}
 1.41234 +
 1.41235 +/*
 1.41236 +** Discard the entire contents of the in-memory page-cache.
 1.41237 +*/
 1.41238 +static void pager_reset(Pager *pPager){
 1.41239 +  sqlite3BackupRestart(pPager->pBackup);
 1.41240 +  sqlite3PcacheClear(pPager->pPCache);
 1.41241 +}
 1.41242 +
 1.41243 +/*
 1.41244 +** Free all structures in the Pager.aSavepoint[] array and set both
 1.41245 +** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
 1.41246 +** if it is open and the pager is not in exclusive mode.
 1.41247 +*/
 1.41248 +static void releaseAllSavepoints(Pager *pPager){
 1.41249 +  int ii;               /* Iterator for looping through Pager.aSavepoint */
 1.41250 +  for(ii=0; ii<pPager->nSavepoint; ii++){
 1.41251 +    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
 1.41252 +  }
 1.41253 +  if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
 1.41254 +    sqlite3OsClose(pPager->sjfd);
 1.41255 +  }
 1.41256 +  sqlite3_free(pPager->aSavepoint);
 1.41257 +  pPager->aSavepoint = 0;
 1.41258 +  pPager->nSavepoint = 0;
 1.41259 +  pPager->nSubRec = 0;
 1.41260 +}
 1.41261 +
 1.41262 +/*
 1.41263 +** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
 1.41264 +** bitvecs of all open savepoints. Return SQLITE_OK if successful
 1.41265 +** or SQLITE_NOMEM if a malloc failure occurs.
 1.41266 +*/
 1.41267 +static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
 1.41268 +  int ii;                   /* Loop counter */
 1.41269 +  int rc = SQLITE_OK;       /* Result code */
 1.41270 +
 1.41271 +  for(ii=0; ii<pPager->nSavepoint; ii++){
 1.41272 +    PagerSavepoint *p = &pPager->aSavepoint[ii];
 1.41273 +    if( pgno<=p->nOrig ){
 1.41274 +      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
 1.41275 +      testcase( rc==SQLITE_NOMEM );
 1.41276 +      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
 1.41277 +    }
 1.41278 +  }
 1.41279 +  return rc;
 1.41280 +}
 1.41281 +
 1.41282 +/*
 1.41283 +** This function is a no-op if the pager is in exclusive mode and not
 1.41284 +** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
 1.41285 +** state.
 1.41286 +**
 1.41287 +** If the pager is not in exclusive-access mode, the database file is
 1.41288 +** completely unlocked. If the file is unlocked and the file-system does
 1.41289 +** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
 1.41290 +** closed (if it is open).
 1.41291 +**
 1.41292 +** If the pager is in ERROR state when this function is called, the 
 1.41293 +** contents of the pager cache are discarded before switching back to 
 1.41294 +** the OPEN state. Regardless of whether the pager is in exclusive-mode
 1.41295 +** or not, any journal file left in the file-system will be treated
 1.41296 +** as a hot-journal and rolled back the next time a read-transaction
 1.41297 +** is opened (by this or by any other connection).
 1.41298 +*/
 1.41299 +static void pager_unlock(Pager *pPager){
 1.41300 +
 1.41301 +  assert( pPager->eState==PAGER_READER 
 1.41302 +       || pPager->eState==PAGER_OPEN 
 1.41303 +       || pPager->eState==PAGER_ERROR 
 1.41304 +  );
 1.41305 +
 1.41306 +  sqlite3BitvecDestroy(pPager->pInJournal);
 1.41307 +  pPager->pInJournal = 0;
 1.41308 +  releaseAllSavepoints(pPager);
 1.41309 +
 1.41310 +  if( pagerUseWal(pPager) ){
 1.41311 +    assert( !isOpen(pPager->jfd) );
 1.41312 +    sqlite3WalEndReadTransaction(pPager->pWal);
 1.41313 +    pPager->eState = PAGER_OPEN;
 1.41314 +  }else if( !pPager->exclusiveMode ){
 1.41315 +    int rc;                       /* Error code returned by pagerUnlockDb() */
 1.41316 +    int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
 1.41317 +
 1.41318 +    /* If the operating system support deletion of open files, then
 1.41319 +    ** close the journal file when dropping the database lock.  Otherwise
 1.41320 +    ** another connection with journal_mode=delete might delete the file
 1.41321 +    ** out from under us.
 1.41322 +    */
 1.41323 +    assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
 1.41324 +    assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
 1.41325 +    assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
 1.41326 +    assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
 1.41327 +    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
 1.41328 +    assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
 1.41329 +    if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
 1.41330 +     || 1!=(pPager->journalMode & 5)
 1.41331 +    ){
 1.41332 +      sqlite3OsClose(pPager->jfd);
 1.41333 +    }
 1.41334 +
 1.41335 +    /* If the pager is in the ERROR state and the call to unlock the database
 1.41336 +    ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
 1.41337 +    ** above the #define for UNKNOWN_LOCK for an explanation of why this
 1.41338 +    ** is necessary.
 1.41339 +    */
 1.41340 +    rc = pagerUnlockDb(pPager, NO_LOCK);
 1.41341 +    if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
 1.41342 +      pPager->eLock = UNKNOWN_LOCK;
 1.41343 +    }
 1.41344 +
 1.41345 +    /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
 1.41346 +    ** without clearing the error code. This is intentional - the error
 1.41347 +    ** code is cleared and the cache reset in the block below.
 1.41348 +    */
 1.41349 +    assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
 1.41350 +    pPager->changeCountDone = 0;
 1.41351 +    pPager->eState = PAGER_OPEN;
 1.41352 +  }
 1.41353 +
 1.41354 +  /* If Pager.errCode is set, the contents of the pager cache cannot be
 1.41355 +  ** trusted. Now that there are no outstanding references to the pager,
 1.41356 +  ** it can safely move back to PAGER_OPEN state. This happens in both
 1.41357 +  ** normal and exclusive-locking mode.
 1.41358 +  */
 1.41359 +  if( pPager->errCode ){
 1.41360 +    assert( !MEMDB );
 1.41361 +    pager_reset(pPager);
 1.41362 +    pPager->changeCountDone = pPager->tempFile;
 1.41363 +    pPager->eState = PAGER_OPEN;
 1.41364 +    pPager->errCode = SQLITE_OK;
 1.41365 +    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
 1.41366 +  }
 1.41367 +
 1.41368 +  pPager->journalOff = 0;
 1.41369 +  pPager->journalHdr = 0;
 1.41370 +  pPager->setMaster = 0;
 1.41371 +}
 1.41372 +
 1.41373 +/*
 1.41374 +** This function is called whenever an IOERR or FULL error that requires
 1.41375 +** the pager to transition into the ERROR state may ahve occurred.
 1.41376 +** The first argument is a pointer to the pager structure, the second 
 1.41377 +** the error-code about to be returned by a pager API function. The 
 1.41378 +** value returned is a copy of the second argument to this function. 
 1.41379 +**
 1.41380 +** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
 1.41381 +** IOERR sub-codes, the pager enters the ERROR state and the error code
 1.41382 +** is stored in Pager.errCode. While the pager remains in the ERROR state,
 1.41383 +** all major API calls on the Pager will immediately return Pager.errCode.
 1.41384 +**
 1.41385 +** The ERROR state indicates that the contents of the pager-cache 
 1.41386 +** cannot be trusted. This state can be cleared by completely discarding 
 1.41387 +** the contents of the pager-cache. If a transaction was active when
 1.41388 +** the persistent error occurred, then the rollback journal may need
 1.41389 +** to be replayed to restore the contents of the database file (as if
 1.41390 +** it were a hot-journal).
 1.41391 +*/
 1.41392 +static int pager_error(Pager *pPager, int rc){
 1.41393 +  int rc2 = rc & 0xff;
 1.41394 +  assert( rc==SQLITE_OK || !MEMDB );
 1.41395 +  assert(
 1.41396 +       pPager->errCode==SQLITE_FULL ||
 1.41397 +       pPager->errCode==SQLITE_OK ||
 1.41398 +       (pPager->errCode & 0xff)==SQLITE_IOERR
 1.41399 +  );
 1.41400 +  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
 1.41401 +    pPager->errCode = rc;
 1.41402 +    pPager->eState = PAGER_ERROR;
 1.41403 +  }
 1.41404 +  return rc;
 1.41405 +}
 1.41406 +
 1.41407 +static int pager_truncate(Pager *pPager, Pgno nPage);
 1.41408 +
 1.41409 +/*
 1.41410 +** This routine ends a transaction. A transaction is usually ended by 
 1.41411 +** either a COMMIT or a ROLLBACK operation. This routine may be called 
 1.41412 +** after rollback of a hot-journal, or if an error occurs while opening
 1.41413 +** the journal file or writing the very first journal-header of a
 1.41414 +** database transaction.
 1.41415 +** 
 1.41416 +** This routine is never called in PAGER_ERROR state. If it is called
 1.41417 +** in PAGER_NONE or PAGER_SHARED state and the lock held is less
 1.41418 +** exclusive than a RESERVED lock, it is a no-op.
 1.41419 +**
 1.41420 +** Otherwise, any active savepoints are released.
 1.41421 +**
 1.41422 +** If the journal file is open, then it is "finalized". Once a journal 
 1.41423 +** file has been finalized it is not possible to use it to roll back a 
 1.41424 +** transaction. Nor will it be considered to be a hot-journal by this
 1.41425 +** or any other database connection. Exactly how a journal is finalized
 1.41426 +** depends on whether or not the pager is running in exclusive mode and
 1.41427 +** the current journal-mode (Pager.journalMode value), as follows:
 1.41428 +**
 1.41429 +**   journalMode==MEMORY
 1.41430 +**     Journal file descriptor is simply closed. This destroys an 
 1.41431 +**     in-memory journal.
 1.41432 +**
 1.41433 +**   journalMode==TRUNCATE
 1.41434 +**     Journal file is truncated to zero bytes in size.
 1.41435 +**
 1.41436 +**   journalMode==PERSIST
 1.41437 +**     The first 28 bytes of the journal file are zeroed. This invalidates
 1.41438 +**     the first journal header in the file, and hence the entire journal
 1.41439 +**     file. An invalid journal file cannot be rolled back.
 1.41440 +**
 1.41441 +**   journalMode==DELETE
 1.41442 +**     The journal file is closed and deleted using sqlite3OsDelete().
 1.41443 +**
 1.41444 +**     If the pager is running in exclusive mode, this method of finalizing
 1.41445 +**     the journal file is never used. Instead, if the journalMode is
 1.41446 +**     DELETE and the pager is in exclusive mode, the method described under
 1.41447 +**     journalMode==PERSIST is used instead.
 1.41448 +**
 1.41449 +** After the journal is finalized, the pager moves to PAGER_READER state.
 1.41450 +** If running in non-exclusive rollback mode, the lock on the file is 
 1.41451 +** downgraded to a SHARED_LOCK.
 1.41452 +**
 1.41453 +** SQLITE_OK is returned if no error occurs. If an error occurs during
 1.41454 +** any of the IO operations to finalize the journal file or unlock the
 1.41455 +** database then the IO error code is returned to the user. If the 
 1.41456 +** operation to finalize the journal file fails, then the code still
 1.41457 +** tries to unlock the database file if not in exclusive mode. If the
 1.41458 +** unlock operation fails as well, then the first error code related
 1.41459 +** to the first error encountered (the journal finalization one) is
 1.41460 +** returned.
 1.41461 +*/
 1.41462 +static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
 1.41463 +  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
 1.41464 +  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
 1.41465 +
 1.41466 +  /* Do nothing if the pager does not have an open write transaction
 1.41467 +  ** or at least a RESERVED lock. This function may be called when there
 1.41468 +  ** is no write-transaction active but a RESERVED or greater lock is
 1.41469 +  ** held under two circumstances:
 1.41470 +  **
 1.41471 +  **   1. After a successful hot-journal rollback, it is called with
 1.41472 +  **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
 1.41473 +  **
 1.41474 +  **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
 1.41475 +  **      lock switches back to locking_mode=normal and then executes a
 1.41476 +  **      read-transaction, this function is called with eState==PAGER_READER 
 1.41477 +  **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
 1.41478 +  */
 1.41479 +  assert( assert_pager_state(pPager) );
 1.41480 +  assert( pPager->eState!=PAGER_ERROR );
 1.41481 +  if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
 1.41482 +    return SQLITE_OK;
 1.41483 +  }
 1.41484 +
 1.41485 +  releaseAllSavepoints(pPager);
 1.41486 +  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
 1.41487 +  if( isOpen(pPager->jfd) ){
 1.41488 +    assert( !pagerUseWal(pPager) );
 1.41489 +
 1.41490 +    /* Finalize the journal file. */
 1.41491 +    if( sqlite3IsMemJournal(pPager->jfd) ){
 1.41492 +      assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
 1.41493 +      sqlite3OsClose(pPager->jfd);
 1.41494 +    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
 1.41495 +      if( pPager->journalOff==0 ){
 1.41496 +        rc = SQLITE_OK;
 1.41497 +      }else{
 1.41498 +        rc = sqlite3OsTruncate(pPager->jfd, 0);
 1.41499 +      }
 1.41500 +      pPager->journalOff = 0;
 1.41501 +    }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
 1.41502 +      || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
 1.41503 +    ){
 1.41504 +      rc = zeroJournalHdr(pPager, hasMaster);
 1.41505 +      pPager->journalOff = 0;
 1.41506 +    }else{
 1.41507 +      /* This branch may be executed with Pager.journalMode==MEMORY if
 1.41508 +      ** a hot-journal was just rolled back. In this case the journal
 1.41509 +      ** file should be closed and deleted. If this connection writes to
 1.41510 +      ** the database file, it will do so using an in-memory journal. 
 1.41511 +      */
 1.41512 +      int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
 1.41513 +      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
 1.41514 +           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
 1.41515 +           || pPager->journalMode==PAGER_JOURNALMODE_WAL 
 1.41516 +      );
 1.41517 +      sqlite3OsClose(pPager->jfd);
 1.41518 +      if( bDelete ){
 1.41519 +        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
 1.41520 +      }
 1.41521 +    }
 1.41522 +  }
 1.41523 +
 1.41524 +#ifdef SQLITE_CHECK_PAGES
 1.41525 +  sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
 1.41526 +  if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
 1.41527 +    PgHdr *p = pager_lookup(pPager, 1);
 1.41528 +    if( p ){
 1.41529 +      p->pageHash = 0;
 1.41530 +      sqlite3PagerUnrefNotNull(p);
 1.41531 +    }
 1.41532 +  }
 1.41533 +#endif
 1.41534 +
 1.41535 +  sqlite3BitvecDestroy(pPager->pInJournal);
 1.41536 +  pPager->pInJournal = 0;
 1.41537 +  pPager->nRec = 0;
 1.41538 +  sqlite3PcacheCleanAll(pPager->pPCache);
 1.41539 +  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
 1.41540 +
 1.41541 +  if( pagerUseWal(pPager) ){
 1.41542 +    /* Drop the WAL write-lock, if any. Also, if the connection was in 
 1.41543 +    ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
 1.41544 +    ** lock held on the database file.
 1.41545 +    */
 1.41546 +    rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
 1.41547 +    assert( rc2==SQLITE_OK );
 1.41548 +  }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
 1.41549 +    /* This branch is taken when committing a transaction in rollback-journal
 1.41550 +    ** mode if the database file on disk is larger than the database image.
 1.41551 +    ** At this point the journal has been finalized and the transaction 
 1.41552 +    ** successfully committed, but the EXCLUSIVE lock is still held on the
 1.41553 +    ** file. So it is safe to truncate the database file to its minimum
 1.41554 +    ** required size.  */
 1.41555 +    assert( pPager->eLock==EXCLUSIVE_LOCK );
 1.41556 +    rc = pager_truncate(pPager, pPager->dbSize);
 1.41557 +  }
 1.41558 +
 1.41559 +  if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
 1.41560 +    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
 1.41561 +    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
 1.41562 +  }
 1.41563 +
 1.41564 +  if( !pPager->exclusiveMode 
 1.41565 +   && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
 1.41566 +  ){
 1.41567 +    rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
 1.41568 +    pPager->changeCountDone = 0;
 1.41569 +  }
 1.41570 +  pPager->eState = PAGER_READER;
 1.41571 +  pPager->setMaster = 0;
 1.41572 +
 1.41573 +  return (rc==SQLITE_OK?rc2:rc);
 1.41574 +}
 1.41575 +
 1.41576 +/*
 1.41577 +** Execute a rollback if a transaction is active and unlock the 
 1.41578 +** database file. 
 1.41579 +**
 1.41580 +** If the pager has already entered the ERROR state, do not attempt 
 1.41581 +** the rollback at this time. Instead, pager_unlock() is called. The
 1.41582 +** call to pager_unlock() will discard all in-memory pages, unlock
 1.41583 +** the database file and move the pager back to OPEN state. If this 
 1.41584 +** means that there is a hot-journal left in the file-system, the next 
 1.41585 +** connection to obtain a shared lock on the pager (which may be this one) 
 1.41586 +** will roll it back.
 1.41587 +**
 1.41588 +** If the pager has not already entered the ERROR state, but an IO or
 1.41589 +** malloc error occurs during a rollback, then this will itself cause 
 1.41590 +** the pager to enter the ERROR state. Which will be cleared by the
 1.41591 +** call to pager_unlock(), as described above.
 1.41592 +*/
 1.41593 +static void pagerUnlockAndRollback(Pager *pPager){
 1.41594 +  if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
 1.41595 +    assert( assert_pager_state(pPager) );
 1.41596 +    if( pPager->eState>=PAGER_WRITER_LOCKED ){
 1.41597 +      sqlite3BeginBenignMalloc();
 1.41598 +      sqlite3PagerRollback(pPager);
 1.41599 +      sqlite3EndBenignMalloc();
 1.41600 +    }else if( !pPager->exclusiveMode ){
 1.41601 +      assert( pPager->eState==PAGER_READER );
 1.41602 +      pager_end_transaction(pPager, 0, 0);
 1.41603 +    }
 1.41604 +  }
 1.41605 +  pager_unlock(pPager);
 1.41606 +}
 1.41607 +
 1.41608 +/*
 1.41609 +** Parameter aData must point to a buffer of pPager->pageSize bytes
 1.41610 +** of data. Compute and return a checksum based ont the contents of the 
 1.41611 +** page of data and the current value of pPager->cksumInit.
 1.41612 +**
 1.41613 +** This is not a real checksum. It is really just the sum of the 
 1.41614 +** random initial value (pPager->cksumInit) and every 200th byte
 1.41615 +** of the page data, starting with byte offset (pPager->pageSize%200).
 1.41616 +** Each byte is interpreted as an 8-bit unsigned integer.
 1.41617 +**
 1.41618 +** Changing the formula used to compute this checksum results in an
 1.41619 +** incompatible journal file format.
 1.41620 +**
 1.41621 +** If journal corruption occurs due to a power failure, the most likely 
 1.41622 +** scenario is that one end or the other of the record will be changed. 
 1.41623 +** It is much less likely that the two ends of the journal record will be
 1.41624 +** correct and the middle be corrupt.  Thus, this "checksum" scheme,
 1.41625 +** though fast and simple, catches the mostly likely kind of corruption.
 1.41626 +*/
 1.41627 +static u32 pager_cksum(Pager *pPager, const u8 *aData){
 1.41628 +  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
 1.41629 +  int i = pPager->pageSize-200;          /* Loop counter */
 1.41630 +  while( i>0 ){
 1.41631 +    cksum += aData[i];
 1.41632 +    i -= 200;
 1.41633 +  }
 1.41634 +  return cksum;
 1.41635 +}
 1.41636 +
 1.41637 +/*
 1.41638 +** Report the current page size and number of reserved bytes back
 1.41639 +** to the codec.
 1.41640 +*/
 1.41641 +#ifdef SQLITE_HAS_CODEC
 1.41642 +static void pagerReportSize(Pager *pPager){
 1.41643 +  if( pPager->xCodecSizeChng ){
 1.41644 +    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
 1.41645 +                           (int)pPager->nReserve);
 1.41646 +  }
 1.41647 +}
 1.41648 +#else
 1.41649 +# define pagerReportSize(X)     /* No-op if we do not support a codec */
 1.41650 +#endif
 1.41651 +
 1.41652 +/*
 1.41653 +** Read a single page from either the journal file (if isMainJrnl==1) or
 1.41654 +** from the sub-journal (if isMainJrnl==0) and playback that page.
 1.41655 +** The page begins at offset *pOffset into the file. The *pOffset
 1.41656 +** value is increased to the start of the next page in the journal.
 1.41657 +**
 1.41658 +** The main rollback journal uses checksums - the statement journal does 
 1.41659 +** not.
 1.41660 +**
 1.41661 +** If the page number of the page record read from the (sub-)journal file
 1.41662 +** is greater than the current value of Pager.dbSize, then playback is
 1.41663 +** skipped and SQLITE_OK is returned.
 1.41664 +**
 1.41665 +** If pDone is not NULL, then it is a record of pages that have already
 1.41666 +** been played back.  If the page at *pOffset has already been played back
 1.41667 +** (if the corresponding pDone bit is set) then skip the playback.
 1.41668 +** Make sure the pDone bit corresponding to the *pOffset page is set
 1.41669 +** prior to returning.
 1.41670 +**
 1.41671 +** If the page record is successfully read from the (sub-)journal file
 1.41672 +** and played back, then SQLITE_OK is returned. If an IO error occurs
 1.41673 +** while reading the record from the (sub-)journal file or while writing
 1.41674 +** to the database file, then the IO error code is returned. If data
 1.41675 +** is successfully read from the (sub-)journal file but appears to be
 1.41676 +** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
 1.41677 +** two circumstances:
 1.41678 +** 
 1.41679 +**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
 1.41680 +**   * If the record is being rolled back from the main journal file
 1.41681 +**     and the checksum field does not match the record content.
 1.41682 +**
 1.41683 +** Neither of these two scenarios are possible during a savepoint rollback.
 1.41684 +**
 1.41685 +** If this is a savepoint rollback, then memory may have to be dynamically
 1.41686 +** allocated by this function. If this is the case and an allocation fails,
 1.41687 +** SQLITE_NOMEM is returned.
 1.41688 +*/
 1.41689 +static int pager_playback_one_page(
 1.41690 +  Pager *pPager,                /* The pager being played back */
 1.41691 +  i64 *pOffset,                 /* Offset of record to playback */
 1.41692 +  Bitvec *pDone,                /* Bitvec of pages already played back */
 1.41693 +  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
 1.41694 +  int isSavepnt                 /* True for a savepoint rollback */
 1.41695 +){
 1.41696 +  int rc;
 1.41697 +  PgHdr *pPg;                   /* An existing page in the cache */
 1.41698 +  Pgno pgno;                    /* The page number of a page in journal */
 1.41699 +  u32 cksum;                    /* Checksum used for sanity checking */
 1.41700 +  char *aData;                  /* Temporary storage for the page */
 1.41701 +  sqlite3_file *jfd;            /* The file descriptor for the journal file */
 1.41702 +  int isSynced;                 /* True if journal page is synced */
 1.41703 +
 1.41704 +  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
 1.41705 +  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
 1.41706 +  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
 1.41707 +  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
 1.41708 +
 1.41709 +  aData = pPager->pTmpSpace;
 1.41710 +  assert( aData );         /* Temp storage must have already been allocated */
 1.41711 +  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
 1.41712 +
 1.41713 +  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
 1.41714 +  ** or savepoint rollback done at the request of the caller) or this is
 1.41715 +  ** a hot-journal rollback. If it is a hot-journal rollback, the pager
 1.41716 +  ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
 1.41717 +  ** only reads from the main journal, not the sub-journal.
 1.41718 +  */
 1.41719 +  assert( pPager->eState>=PAGER_WRITER_CACHEMOD
 1.41720 +       || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
 1.41721 +  );
 1.41722 +  assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
 1.41723 +
 1.41724 +  /* Read the page number and page data from the journal or sub-journal
 1.41725 +  ** file. Return an error code to the caller if an IO error occurs.
 1.41726 +  */
 1.41727 +  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
 1.41728 +  rc = read32bits(jfd, *pOffset, &pgno);
 1.41729 +  if( rc!=SQLITE_OK ) return rc;
 1.41730 +  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
 1.41731 +  if( rc!=SQLITE_OK ) return rc;
 1.41732 +  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
 1.41733 +
 1.41734 +  /* Sanity checking on the page.  This is more important that I originally
 1.41735 +  ** thought.  If a power failure occurs while the journal is being written,
 1.41736 +  ** it could cause invalid data to be written into the journal.  We need to
 1.41737 +  ** detect this invalid data (with high probability) and ignore it.
 1.41738 +  */
 1.41739 +  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
 1.41740 +    assert( !isSavepnt );
 1.41741 +    return SQLITE_DONE;
 1.41742 +  }
 1.41743 +  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
 1.41744 +    return SQLITE_OK;
 1.41745 +  }
 1.41746 +  if( isMainJrnl ){
 1.41747 +    rc = read32bits(jfd, (*pOffset)-4, &cksum);
 1.41748 +    if( rc ) return rc;
 1.41749 +    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
 1.41750 +      return SQLITE_DONE;
 1.41751 +    }
 1.41752 +  }
 1.41753 +
 1.41754 +  /* If this page has already been played by before during the current
 1.41755 +  ** rollback, then don't bother to play it back again.
 1.41756 +  */
 1.41757 +  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
 1.41758 +    return rc;
 1.41759 +  }
 1.41760 +
 1.41761 +  /* When playing back page 1, restore the nReserve setting
 1.41762 +  */
 1.41763 +  if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
 1.41764 +    pPager->nReserve = ((u8*)aData)[20];
 1.41765 +    pagerReportSize(pPager);
 1.41766 +  }
 1.41767 +
 1.41768 +  /* If the pager is in CACHEMOD state, then there must be a copy of this
 1.41769 +  ** page in the pager cache. In this case just update the pager cache,
 1.41770 +  ** not the database file. The page is left marked dirty in this case.
 1.41771 +  **
 1.41772 +  ** An exception to the above rule: If the database is in no-sync mode
 1.41773 +  ** and a page is moved during an incremental vacuum then the page may
 1.41774 +  ** not be in the pager cache. Later: if a malloc() or IO error occurs
 1.41775 +  ** during a Movepage() call, then the page may not be in the cache
 1.41776 +  ** either. So the condition described in the above paragraph is not
 1.41777 +  ** assert()able.
 1.41778 +  **
 1.41779 +  ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
 1.41780 +  ** pager cache if it exists and the main file. The page is then marked 
 1.41781 +  ** not dirty. Since this code is only executed in PAGER_OPEN state for
 1.41782 +  ** a hot-journal rollback, it is guaranteed that the page-cache is empty
 1.41783 +  ** if the pager is in OPEN state.
 1.41784 +  **
 1.41785 +  ** Ticket #1171:  The statement journal might contain page content that is
 1.41786 +  ** different from the page content at the start of the transaction.
 1.41787 +  ** This occurs when a page is changed prior to the start of a statement
 1.41788 +  ** then changed again within the statement.  When rolling back such a
 1.41789 +  ** statement we must not write to the original database unless we know
 1.41790 +  ** for certain that original page contents are synced into the main rollback
 1.41791 +  ** journal.  Otherwise, a power loss might leave modified data in the
 1.41792 +  ** database file without an entry in the rollback journal that can
 1.41793 +  ** restore the database to its original form.  Two conditions must be
 1.41794 +  ** met before writing to the database files. (1) the database must be
 1.41795 +  ** locked.  (2) we know that the original page content is fully synced
 1.41796 +  ** in the main journal either because the page is not in cache or else
 1.41797 +  ** the page is marked as needSync==0.
 1.41798 +  **
 1.41799 +  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
 1.41800 +  ** is possible to fail a statement on a database that does not yet exist.
 1.41801 +  ** Do not attempt to write if database file has never been opened.
 1.41802 +  */
 1.41803 +  if( pagerUseWal(pPager) ){
 1.41804 +    pPg = 0;
 1.41805 +  }else{
 1.41806 +    pPg = pager_lookup(pPager, pgno);
 1.41807 +  }
 1.41808 +  assert( pPg || !MEMDB );
 1.41809 +  assert( pPager->eState!=PAGER_OPEN || pPg==0 );
 1.41810 +  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
 1.41811 +           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
 1.41812 +           (isMainJrnl?"main-journal":"sub-journal")
 1.41813 +  ));
 1.41814 +  if( isMainJrnl ){
 1.41815 +    isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
 1.41816 +  }else{
 1.41817 +    isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
 1.41818 +  }
 1.41819 +  if( isOpen(pPager->fd)
 1.41820 +   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
 1.41821 +   && isSynced
 1.41822 +  ){
 1.41823 +    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
 1.41824 +    testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
 1.41825 +    assert( !pagerUseWal(pPager) );
 1.41826 +    rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
 1.41827 +    if( pgno>pPager->dbFileSize ){
 1.41828 +      pPager->dbFileSize = pgno;
 1.41829 +    }
 1.41830 +    if( pPager->pBackup ){
 1.41831 +      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
 1.41832 +      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
 1.41833 +      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
 1.41834 +    }
 1.41835 +  }else if( !isMainJrnl && pPg==0 ){
 1.41836 +    /* If this is a rollback of a savepoint and data was not written to
 1.41837 +    ** the database and the page is not in-memory, there is a potential
 1.41838 +    ** problem. When the page is next fetched by the b-tree layer, it 
 1.41839 +    ** will be read from the database file, which may or may not be 
 1.41840 +    ** current. 
 1.41841 +    **
 1.41842 +    ** There are a couple of different ways this can happen. All are quite
 1.41843 +    ** obscure. When running in synchronous mode, this can only happen 
 1.41844 +    ** if the page is on the free-list at the start of the transaction, then
 1.41845 +    ** populated, then moved using sqlite3PagerMovepage().
 1.41846 +    **
 1.41847 +    ** The solution is to add an in-memory page to the cache containing
 1.41848 +    ** the data just read from the sub-journal. Mark the page as dirty 
 1.41849 +    ** and if the pager requires a journal-sync, then mark the page as 
 1.41850 +    ** requiring a journal-sync before it is written.
 1.41851 +    */
 1.41852 +    assert( isSavepnt );
 1.41853 +    assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
 1.41854 +    pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
 1.41855 +    rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
 1.41856 +    assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
 1.41857 +    pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
 1.41858 +    if( rc!=SQLITE_OK ) return rc;
 1.41859 +    pPg->flags &= ~PGHDR_NEED_READ;
 1.41860 +    sqlite3PcacheMakeDirty(pPg);
 1.41861 +  }
 1.41862 +  if( pPg ){
 1.41863 +    /* No page should ever be explicitly rolled back that is in use, except
 1.41864 +    ** for page 1 which is held in use in order to keep the lock on the
 1.41865 +    ** database active. However such a page may be rolled back as a result
 1.41866 +    ** of an internal error resulting in an automatic call to
 1.41867 +    ** sqlite3PagerRollback().
 1.41868 +    */
 1.41869 +    void *pData;
 1.41870 +    pData = pPg->pData;
 1.41871 +    memcpy(pData, (u8*)aData, pPager->pageSize);
 1.41872 +    pPager->xReiniter(pPg);
 1.41873 +    if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
 1.41874 +      /* If the contents of this page were just restored from the main 
 1.41875 +      ** journal file, then its content must be as they were when the 
 1.41876 +      ** transaction was first opened. In this case we can mark the page
 1.41877 +      ** as clean, since there will be no need to write it out to the
 1.41878 +      ** database.
 1.41879 +      **
 1.41880 +      ** There is one exception to this rule. If the page is being rolled
 1.41881 +      ** back as part of a savepoint (or statement) rollback from an 
 1.41882 +      ** unsynced portion of the main journal file, then it is not safe
 1.41883 +      ** to mark the page as clean. This is because marking the page as
 1.41884 +      ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
 1.41885 +      ** already in the journal file (recorded in Pager.pInJournal) and
 1.41886 +      ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
 1.41887 +      ** again within this transaction, it will be marked as dirty but
 1.41888 +      ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
 1.41889 +      ** be written out into the database file before its journal file
 1.41890 +      ** segment is synced. If a crash occurs during or following this,
 1.41891 +      ** database corruption may ensue.
 1.41892 +      */
 1.41893 +      assert( !pagerUseWal(pPager) );
 1.41894 +      sqlite3PcacheMakeClean(pPg);
 1.41895 +    }
 1.41896 +    pager_set_pagehash(pPg);
 1.41897 +
 1.41898 +    /* If this was page 1, then restore the value of Pager.dbFileVers.
 1.41899 +    ** Do this before any decoding. */
 1.41900 +    if( pgno==1 ){
 1.41901 +      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
 1.41902 +    }
 1.41903 +
 1.41904 +    /* Decode the page just read from disk */
 1.41905 +    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
 1.41906 +    sqlite3PcacheRelease(pPg);
 1.41907 +  }
 1.41908 +  return rc;
 1.41909 +}
 1.41910 +
 1.41911 +/*
 1.41912 +** Parameter zMaster is the name of a master journal file. A single journal
 1.41913 +** file that referred to the master journal file has just been rolled back.
 1.41914 +** This routine checks if it is possible to delete the master journal file,
 1.41915 +** and does so if it is.
 1.41916 +**
 1.41917 +** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
 1.41918 +** available for use within this function.
 1.41919 +**
 1.41920 +** When a master journal file is created, it is populated with the names 
 1.41921 +** of all of its child journals, one after another, formatted as utf-8 
 1.41922 +** encoded text. The end of each child journal file is marked with a 
 1.41923 +** nul-terminator byte (0x00). i.e. the entire contents of a master journal
 1.41924 +** file for a transaction involving two databases might be:
 1.41925 +**
 1.41926 +**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
 1.41927 +**
 1.41928 +** A master journal file may only be deleted once all of its child 
 1.41929 +** journals have been rolled back.
 1.41930 +**
 1.41931 +** This function reads the contents of the master-journal file into 
 1.41932 +** memory and loops through each of the child journal names. For
 1.41933 +** each child journal, it checks if:
 1.41934 +**
 1.41935 +**   * if the child journal exists, and if so
 1.41936 +**   * if the child journal contains a reference to master journal 
 1.41937 +**     file zMaster
 1.41938 +**
 1.41939 +** If a child journal can be found that matches both of the criteria
 1.41940 +** above, this function returns without doing anything. Otherwise, if
 1.41941 +** no such child journal can be found, file zMaster is deleted from
 1.41942 +** the file-system using sqlite3OsDelete().
 1.41943 +**
 1.41944 +** If an IO error within this function, an error code is returned. This
 1.41945 +** function allocates memory by calling sqlite3Malloc(). If an allocation
 1.41946 +** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
 1.41947 +** occur, SQLITE_OK is returned.
 1.41948 +**
 1.41949 +** TODO: This function allocates a single block of memory to load
 1.41950 +** the entire contents of the master journal file. This could be
 1.41951 +** a couple of kilobytes or so - potentially larger than the page 
 1.41952 +** size.
 1.41953 +*/
 1.41954 +static int pager_delmaster(Pager *pPager, const char *zMaster){
 1.41955 +  sqlite3_vfs *pVfs = pPager->pVfs;
 1.41956 +  int rc;                   /* Return code */
 1.41957 +  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
 1.41958 +  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
 1.41959 +  char *zMasterJournal = 0; /* Contents of master journal file */
 1.41960 +  i64 nMasterJournal;       /* Size of master journal file */
 1.41961 +  char *zJournal;           /* Pointer to one journal within MJ file */
 1.41962 +  char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
 1.41963 +  int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
 1.41964 +
 1.41965 +  /* Allocate space for both the pJournal and pMaster file descriptors.
 1.41966 +  ** If successful, open the master journal file for reading.
 1.41967 +  */
 1.41968 +  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
 1.41969 +  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
 1.41970 +  if( !pMaster ){
 1.41971 +    rc = SQLITE_NOMEM;
 1.41972 +  }else{
 1.41973 +    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
 1.41974 +    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
 1.41975 +  }
 1.41976 +  if( rc!=SQLITE_OK ) goto delmaster_out;
 1.41977 +
 1.41978 +  /* Load the entire master journal file into space obtained from
 1.41979 +  ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
 1.41980 +  ** sufficient space (in zMasterPtr) to hold the names of master
 1.41981 +  ** journal files extracted from regular rollback-journals.
 1.41982 +  */
 1.41983 +  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
 1.41984 +  if( rc!=SQLITE_OK ) goto delmaster_out;
 1.41985 +  nMasterPtr = pVfs->mxPathname+1;
 1.41986 +  zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
 1.41987 +  if( !zMasterJournal ){
 1.41988 +    rc = SQLITE_NOMEM;
 1.41989 +    goto delmaster_out;
 1.41990 +  }
 1.41991 +  zMasterPtr = &zMasterJournal[nMasterJournal+1];
 1.41992 +  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
 1.41993 +  if( rc!=SQLITE_OK ) goto delmaster_out;
 1.41994 +  zMasterJournal[nMasterJournal] = 0;
 1.41995 +
 1.41996 +  zJournal = zMasterJournal;
 1.41997 +  while( (zJournal-zMasterJournal)<nMasterJournal ){
 1.41998 +    int exists;
 1.41999 +    rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
 1.42000 +    if( rc!=SQLITE_OK ){
 1.42001 +      goto delmaster_out;
 1.42002 +    }
 1.42003 +    if( exists ){
 1.42004 +      /* One of the journals pointed to by the master journal exists.
 1.42005 +      ** Open it and check if it points at the master journal. If
 1.42006 +      ** so, return without deleting the master journal file.
 1.42007 +      */
 1.42008 +      int c;
 1.42009 +      int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
 1.42010 +      rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
 1.42011 +      if( rc!=SQLITE_OK ){
 1.42012 +        goto delmaster_out;
 1.42013 +      }
 1.42014 +
 1.42015 +      rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
 1.42016 +      sqlite3OsClose(pJournal);
 1.42017 +      if( rc!=SQLITE_OK ){
 1.42018 +        goto delmaster_out;
 1.42019 +      }
 1.42020 +
 1.42021 +      c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
 1.42022 +      if( c ){
 1.42023 +        /* We have a match. Do not delete the master journal file. */
 1.42024 +        goto delmaster_out;
 1.42025 +      }
 1.42026 +    }
 1.42027 +    zJournal += (sqlite3Strlen30(zJournal)+1);
 1.42028 +  }
 1.42029 + 
 1.42030 +  sqlite3OsClose(pMaster);
 1.42031 +  rc = sqlite3OsDelete(pVfs, zMaster, 0);
 1.42032 +
 1.42033 +delmaster_out:
 1.42034 +  sqlite3_free(zMasterJournal);
 1.42035 +  if( pMaster ){
 1.42036 +    sqlite3OsClose(pMaster);
 1.42037 +    assert( !isOpen(pJournal) );
 1.42038 +    sqlite3_free(pMaster);
 1.42039 +  }
 1.42040 +  return rc;
 1.42041 +}
 1.42042 +
 1.42043 +
 1.42044 +/*
 1.42045 +** This function is used to change the actual size of the database 
 1.42046 +** file in the file-system. This only happens when committing a transaction,
 1.42047 +** or rolling back a transaction (including rolling back a hot-journal).
 1.42048 +**
 1.42049 +** If the main database file is not open, or the pager is not in either
 1.42050 +** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
 1.42051 +** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
 1.42052 +** If the file on disk is currently larger than nPage pages, then use the VFS
 1.42053 +** xTruncate() method to truncate it.
 1.42054 +**
 1.42055 +** Or, it might might be the case that the file on disk is smaller than 
 1.42056 +** nPage pages. Some operating system implementations can get confused if 
 1.42057 +** you try to truncate a file to some size that is larger than it 
 1.42058 +** currently is, so detect this case and write a single zero byte to 
 1.42059 +** the end of the new file instead.
 1.42060 +**
 1.42061 +** If successful, return SQLITE_OK. If an IO error occurs while modifying
 1.42062 +** the database file, return the error code to the caller.
 1.42063 +*/
 1.42064 +static int pager_truncate(Pager *pPager, Pgno nPage){
 1.42065 +  int rc = SQLITE_OK;
 1.42066 +  assert( pPager->eState!=PAGER_ERROR );
 1.42067 +  assert( pPager->eState!=PAGER_READER );
 1.42068 +  
 1.42069 +  if( isOpen(pPager->fd) 
 1.42070 +   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
 1.42071 +  ){
 1.42072 +    i64 currentSize, newSize;
 1.42073 +    int szPage = pPager->pageSize;
 1.42074 +    assert( pPager->eLock==EXCLUSIVE_LOCK );
 1.42075 +    /* TODO: Is it safe to use Pager.dbFileSize here? */
 1.42076 +    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
 1.42077 +    newSize = szPage*(i64)nPage;
 1.42078 +    if( rc==SQLITE_OK && currentSize!=newSize ){
 1.42079 +      if( currentSize>newSize ){
 1.42080 +        rc = sqlite3OsTruncate(pPager->fd, newSize);
 1.42081 +      }else if( (currentSize+szPage)<=newSize ){
 1.42082 +        char *pTmp = pPager->pTmpSpace;
 1.42083 +        memset(pTmp, 0, szPage);
 1.42084 +        testcase( (newSize-szPage) == currentSize );
 1.42085 +        testcase( (newSize-szPage) >  currentSize );
 1.42086 +        rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
 1.42087 +      }
 1.42088 +      if( rc==SQLITE_OK ){
 1.42089 +        pPager->dbFileSize = nPage;
 1.42090 +      }
 1.42091 +    }
 1.42092 +  }
 1.42093 +  return rc;
 1.42094 +}
 1.42095 +
 1.42096 +/*
 1.42097 +** Return a sanitized version of the sector-size of OS file pFile. The
 1.42098 +** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
 1.42099 +*/
 1.42100 +SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
 1.42101 +  int iRet = sqlite3OsSectorSize(pFile);
 1.42102 +  if( iRet<32 ){
 1.42103 +    iRet = 512;
 1.42104 +  }else if( iRet>MAX_SECTOR_SIZE ){
 1.42105 +    assert( MAX_SECTOR_SIZE>=512 );
 1.42106 +    iRet = MAX_SECTOR_SIZE;
 1.42107 +  }
 1.42108 +  return iRet;
 1.42109 +}
 1.42110 +
 1.42111 +/*
 1.42112 +** Set the value of the Pager.sectorSize variable for the given
 1.42113 +** pager based on the value returned by the xSectorSize method
 1.42114 +** of the open database file. The sector size will be used used 
 1.42115 +** to determine the size and alignment of journal header and 
 1.42116 +** master journal pointers within created journal files.
 1.42117 +**
 1.42118 +** For temporary files the effective sector size is always 512 bytes.
 1.42119 +**
 1.42120 +** Otherwise, for non-temporary files, the effective sector size is
 1.42121 +** the value returned by the xSectorSize() method rounded up to 32 if
 1.42122 +** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
 1.42123 +** is greater than MAX_SECTOR_SIZE.
 1.42124 +**
 1.42125 +** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
 1.42126 +** the effective sector size to its minimum value (512).  The purpose of
 1.42127 +** pPager->sectorSize is to define the "blast radius" of bytes that
 1.42128 +** might change if a crash occurs while writing to a single byte in
 1.42129 +** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
 1.42130 +** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
 1.42131 +** size.  For backwards compatibility of the rollback journal file format,
 1.42132 +** we cannot reduce the effective sector size below 512.
 1.42133 +*/
 1.42134 +static void setSectorSize(Pager *pPager){
 1.42135 +  assert( isOpen(pPager->fd) || pPager->tempFile );
 1.42136 +
 1.42137 +  if( pPager->tempFile
 1.42138 +   || (sqlite3OsDeviceCharacteristics(pPager->fd) & 
 1.42139 +              SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
 1.42140 +  ){
 1.42141 +    /* Sector size doesn't matter for temporary files. Also, the file
 1.42142 +    ** may not have been opened yet, in which case the OsSectorSize()
 1.42143 +    ** call will segfault. */
 1.42144 +    pPager->sectorSize = 512;
 1.42145 +  }else{
 1.42146 +    pPager->sectorSize = sqlite3SectorSize(pPager->fd);
 1.42147 +  }
 1.42148 +}
 1.42149 +
 1.42150 +/*
 1.42151 +** Playback the journal and thus restore the database file to
 1.42152 +** the state it was in before we started making changes.  
 1.42153 +**
 1.42154 +** The journal file format is as follows: 
 1.42155 +**
 1.42156 +**  (1)  8 byte prefix.  A copy of aJournalMagic[].
 1.42157 +**  (2)  4 byte big-endian integer which is the number of valid page records
 1.42158 +**       in the journal.  If this value is 0xffffffff, then compute the
 1.42159 +**       number of page records from the journal size.
 1.42160 +**  (3)  4 byte big-endian integer which is the initial value for the 
 1.42161 +**       sanity checksum.
 1.42162 +**  (4)  4 byte integer which is the number of pages to truncate the
 1.42163 +**       database to during a rollback.
 1.42164 +**  (5)  4 byte big-endian integer which is the sector size.  The header
 1.42165 +**       is this many bytes in size.
 1.42166 +**  (6)  4 byte big-endian integer which is the page size.
 1.42167 +**  (7)  zero padding out to the next sector size.
 1.42168 +**  (8)  Zero or more pages instances, each as follows:
 1.42169 +**        +  4 byte page number.
 1.42170 +**        +  pPager->pageSize bytes of data.
 1.42171 +**        +  4 byte checksum
 1.42172 +**
 1.42173 +** When we speak of the journal header, we mean the first 7 items above.
 1.42174 +** Each entry in the journal is an instance of the 8th item.
 1.42175 +**
 1.42176 +** Call the value from the second bullet "nRec".  nRec is the number of
 1.42177 +** valid page entries in the journal.  In most cases, you can compute the
 1.42178 +** value of nRec from the size of the journal file.  But if a power
 1.42179 +** failure occurred while the journal was being written, it could be the
 1.42180 +** case that the size of the journal file had already been increased but
 1.42181 +** the extra entries had not yet made it safely to disk.  In such a case,
 1.42182 +** the value of nRec computed from the file size would be too large.  For
 1.42183 +** that reason, we always use the nRec value in the header.
 1.42184 +**
 1.42185 +** If the nRec value is 0xffffffff it means that nRec should be computed
 1.42186 +** from the file size.  This value is used when the user selects the
 1.42187 +** no-sync option for the journal.  A power failure could lead to corruption
 1.42188 +** in this case.  But for things like temporary table (which will be
 1.42189 +** deleted when the power is restored) we don't care.  
 1.42190 +**
 1.42191 +** If the file opened as the journal file is not a well-formed
 1.42192 +** journal file then all pages up to the first corrupted page are rolled
 1.42193 +** back (or no pages if the journal header is corrupted). The journal file
 1.42194 +** is then deleted and SQLITE_OK returned, just as if no corruption had
 1.42195 +** been encountered.
 1.42196 +**
 1.42197 +** If an I/O or malloc() error occurs, the journal-file is not deleted
 1.42198 +** and an error code is returned.
 1.42199 +**
 1.42200 +** The isHot parameter indicates that we are trying to rollback a journal
 1.42201 +** that might be a hot journal.  Or, it could be that the journal is 
 1.42202 +** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
 1.42203 +** If the journal really is hot, reset the pager cache prior rolling
 1.42204 +** back any content.  If the journal is merely persistent, no reset is
 1.42205 +** needed.
 1.42206 +*/
 1.42207 +static int pager_playback(Pager *pPager, int isHot){
 1.42208 +  sqlite3_vfs *pVfs = pPager->pVfs;
 1.42209 +  i64 szJ;                 /* Size of the journal file in bytes */
 1.42210 +  u32 nRec;                /* Number of Records in the journal */
 1.42211 +  u32 u;                   /* Unsigned loop counter */
 1.42212 +  Pgno mxPg = 0;           /* Size of the original file in pages */
 1.42213 +  int rc;                  /* Result code of a subroutine */
 1.42214 +  int res = 1;             /* Value returned by sqlite3OsAccess() */
 1.42215 +  char *zMaster = 0;       /* Name of master journal file if any */
 1.42216 +  int needPagerReset;      /* True to reset page prior to first page rollback */
 1.42217 +  int nPlayback = 0;       /* Total number of pages restored from journal */
 1.42218 +
 1.42219 +  /* Figure out how many records are in the journal.  Abort early if
 1.42220 +  ** the journal is empty.
 1.42221 +  */
 1.42222 +  assert( isOpen(pPager->jfd) );
 1.42223 +  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
 1.42224 +  if( rc!=SQLITE_OK ){
 1.42225 +    goto end_playback;
 1.42226 +  }
 1.42227 +
 1.42228 +  /* Read the master journal name from the journal, if it is present.
 1.42229 +  ** If a master journal file name is specified, but the file is not
 1.42230 +  ** present on disk, then the journal is not hot and does not need to be
 1.42231 +  ** played back.
 1.42232 +  **
 1.42233 +  ** TODO: Technically the following is an error because it assumes that
 1.42234 +  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
 1.42235 +  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
 1.42236 +  **  mxPathname is 512, which is the same as the minimum allowable value
 1.42237 +  ** for pageSize.
 1.42238 +  */
 1.42239 +  zMaster = pPager->pTmpSpace;
 1.42240 +  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
 1.42241 +  if( rc==SQLITE_OK && zMaster[0] ){
 1.42242 +    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
 1.42243 +  }
 1.42244 +  zMaster = 0;
 1.42245 +  if( rc!=SQLITE_OK || !res ){
 1.42246 +    goto end_playback;
 1.42247 +  }
 1.42248 +  pPager->journalOff = 0;
 1.42249 +  needPagerReset = isHot;
 1.42250 +
 1.42251 +  /* This loop terminates either when a readJournalHdr() or 
 1.42252 +  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
 1.42253 +  ** occurs. 
 1.42254 +  */
 1.42255 +  while( 1 ){
 1.42256 +    /* Read the next journal header from the journal file.  If there are
 1.42257 +    ** not enough bytes left in the journal file for a complete header, or
 1.42258 +    ** it is corrupted, then a process must have failed while writing it.
 1.42259 +    ** This indicates nothing more needs to be rolled back.
 1.42260 +    */
 1.42261 +    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
 1.42262 +    if( rc!=SQLITE_OK ){ 
 1.42263 +      if( rc==SQLITE_DONE ){
 1.42264 +        rc = SQLITE_OK;
 1.42265 +      }
 1.42266 +      goto end_playback;
 1.42267 +    }
 1.42268 +
 1.42269 +    /* If nRec is 0xffffffff, then this journal was created by a process
 1.42270 +    ** working in no-sync mode. This means that the rest of the journal
 1.42271 +    ** file consists of pages, there are no more journal headers. Compute
 1.42272 +    ** the value of nRec based on this assumption.
 1.42273 +    */
 1.42274 +    if( nRec==0xffffffff ){
 1.42275 +      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
 1.42276 +      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
 1.42277 +    }
 1.42278 +
 1.42279 +    /* If nRec is 0 and this rollback is of a transaction created by this
 1.42280 +    ** process and if this is the final header in the journal, then it means
 1.42281 +    ** that this part of the journal was being filled but has not yet been
 1.42282 +    ** synced to disk.  Compute the number of pages based on the remaining
 1.42283 +    ** size of the file.
 1.42284 +    **
 1.42285 +    ** The third term of the test was added to fix ticket #2565.
 1.42286 +    ** When rolling back a hot journal, nRec==0 always means that the next
 1.42287 +    ** chunk of the journal contains zero pages to be rolled back.  But
 1.42288 +    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
 1.42289 +    ** the journal, it means that the journal might contain additional
 1.42290 +    ** pages that need to be rolled back and that the number of pages 
 1.42291 +    ** should be computed based on the journal file size.
 1.42292 +    */
 1.42293 +    if( nRec==0 && !isHot &&
 1.42294 +        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
 1.42295 +      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
 1.42296 +    }
 1.42297 +
 1.42298 +    /* If this is the first header read from the journal, truncate the
 1.42299 +    ** database file back to its original size.
 1.42300 +    */
 1.42301 +    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
 1.42302 +      rc = pager_truncate(pPager, mxPg);
 1.42303 +      if( rc!=SQLITE_OK ){
 1.42304 +        goto end_playback;
 1.42305 +      }
 1.42306 +      pPager->dbSize = mxPg;
 1.42307 +    }
 1.42308 +
 1.42309 +    /* Copy original pages out of the journal and back into the 
 1.42310 +    ** database file and/or page cache.
 1.42311 +    */
 1.42312 +    for(u=0; u<nRec; u++){
 1.42313 +      if( needPagerReset ){
 1.42314 +        pager_reset(pPager);
 1.42315 +        needPagerReset = 0;
 1.42316 +      }
 1.42317 +      rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
 1.42318 +      if( rc==SQLITE_OK ){
 1.42319 +        nPlayback++;
 1.42320 +      }else{
 1.42321 +        if( rc==SQLITE_DONE ){
 1.42322 +          pPager->journalOff = szJ;
 1.42323 +          break;
 1.42324 +        }else if( rc==SQLITE_IOERR_SHORT_READ ){
 1.42325 +          /* If the journal has been truncated, simply stop reading and
 1.42326 +          ** processing the journal. This might happen if the journal was
 1.42327 +          ** not completely written and synced prior to a crash.  In that
 1.42328 +          ** case, the database should have never been written in the
 1.42329 +          ** first place so it is OK to simply abandon the rollback. */
 1.42330 +          rc = SQLITE_OK;
 1.42331 +          goto end_playback;
 1.42332 +        }else{
 1.42333 +          /* If we are unable to rollback, quit and return the error
 1.42334 +          ** code.  This will cause the pager to enter the error state
 1.42335 +          ** so that no further harm will be done.  Perhaps the next
 1.42336 +          ** process to come along will be able to rollback the database.
 1.42337 +          */
 1.42338 +          goto end_playback;
 1.42339 +        }
 1.42340 +      }
 1.42341 +    }
 1.42342 +  }
 1.42343 +  /*NOTREACHED*/
 1.42344 +  assert( 0 );
 1.42345 +
 1.42346 +end_playback:
 1.42347 +  /* Following a rollback, the database file should be back in its original
 1.42348 +  ** state prior to the start of the transaction, so invoke the
 1.42349 +  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
 1.42350 +  ** assertion that the transaction counter was modified.
 1.42351 +  */
 1.42352 +#ifdef SQLITE_DEBUG
 1.42353 +  if( pPager->fd->pMethods ){
 1.42354 +    sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
 1.42355 +  }
 1.42356 +#endif
 1.42357 +
 1.42358 +  /* If this playback is happening automatically as a result of an IO or 
 1.42359 +  ** malloc error that occurred after the change-counter was updated but 
 1.42360 +  ** before the transaction was committed, then the change-counter 
 1.42361 +  ** modification may just have been reverted. If this happens in exclusive 
 1.42362 +  ** mode, then subsequent transactions performed by the connection will not
 1.42363 +  ** update the change-counter at all. This may lead to cache inconsistency
 1.42364 +  ** problems for other processes at some point in the future. So, just
 1.42365 +  ** in case this has happened, clear the changeCountDone flag now.
 1.42366 +  */
 1.42367 +  pPager->changeCountDone = pPager->tempFile;
 1.42368 +
 1.42369 +  if( rc==SQLITE_OK ){
 1.42370 +    zMaster = pPager->pTmpSpace;
 1.42371 +    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
 1.42372 +    testcase( rc!=SQLITE_OK );
 1.42373 +  }
 1.42374 +  if( rc==SQLITE_OK
 1.42375 +   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
 1.42376 +  ){
 1.42377 +    rc = sqlite3PagerSync(pPager, 0);
 1.42378 +  }
 1.42379 +  if( rc==SQLITE_OK ){
 1.42380 +    rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
 1.42381 +    testcase( rc!=SQLITE_OK );
 1.42382 +  }
 1.42383 +  if( rc==SQLITE_OK && zMaster[0] && res ){
 1.42384 +    /* If there was a master journal and this routine will return success,
 1.42385 +    ** see if it is possible to delete the master journal.
 1.42386 +    */
 1.42387 +    rc = pager_delmaster(pPager, zMaster);
 1.42388 +    testcase( rc!=SQLITE_OK );
 1.42389 +  }
 1.42390 +  if( isHot && nPlayback ){
 1.42391 +    sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
 1.42392 +                nPlayback, pPager->zJournal);
 1.42393 +  }
 1.42394 +
 1.42395 +  /* The Pager.sectorSize variable may have been updated while rolling
 1.42396 +  ** back a journal created by a process with a different sector size
 1.42397 +  ** value. Reset it to the correct value for this process.
 1.42398 +  */
 1.42399 +  setSectorSize(pPager);
 1.42400 +  return rc;
 1.42401 +}
 1.42402 +
 1.42403 +
 1.42404 +/*
 1.42405 +** Read the content for page pPg out of the database file and into 
 1.42406 +** pPg->pData. A shared lock or greater must be held on the database
 1.42407 +** file before this function is called.
 1.42408 +**
 1.42409 +** If page 1 is read, then the value of Pager.dbFileVers[] is set to
 1.42410 +** the value read from the database file.
 1.42411 +**
 1.42412 +** If an IO error occurs, then the IO error is returned to the caller.
 1.42413 +** Otherwise, SQLITE_OK is returned.
 1.42414 +*/
 1.42415 +static int readDbPage(PgHdr *pPg, u32 iFrame){
 1.42416 +  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
 1.42417 +  Pgno pgno = pPg->pgno;       /* Page number to read */
 1.42418 +  int rc = SQLITE_OK;          /* Return code */
 1.42419 +  int pgsz = pPager->pageSize; /* Number of bytes to read */
 1.42420 +
 1.42421 +  assert( pPager->eState>=PAGER_READER && !MEMDB );
 1.42422 +  assert( isOpen(pPager->fd) );
 1.42423 +
 1.42424 +#ifndef SQLITE_OMIT_WAL
 1.42425 +  if( iFrame ){
 1.42426 +    /* Try to pull the page from the write-ahead log. */
 1.42427 +    rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
 1.42428 +  }else
 1.42429 +#endif
 1.42430 +  {
 1.42431 +    i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
 1.42432 +    rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
 1.42433 +    if( rc==SQLITE_IOERR_SHORT_READ ){
 1.42434 +      rc = SQLITE_OK;
 1.42435 +    }
 1.42436 +  }
 1.42437 +
 1.42438 +  if( pgno==1 ){
 1.42439 +    if( rc ){
 1.42440 +      /* If the read is unsuccessful, set the dbFileVers[] to something
 1.42441 +      ** that will never be a valid file version.  dbFileVers[] is a copy
 1.42442 +      ** of bytes 24..39 of the database.  Bytes 28..31 should always be
 1.42443 +      ** zero or the size of the database in page. Bytes 32..35 and 35..39
 1.42444 +      ** should be page numbers which are never 0xffffffff.  So filling
 1.42445 +      ** pPager->dbFileVers[] with all 0xff bytes should suffice.
 1.42446 +      **
 1.42447 +      ** For an encrypted database, the situation is more complex:  bytes
 1.42448 +      ** 24..39 of the database are white noise.  But the probability of
 1.42449 +      ** white noising equaling 16 bytes of 0xff is vanishingly small so
 1.42450 +      ** we should still be ok.
 1.42451 +      */
 1.42452 +      memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
 1.42453 +    }else{
 1.42454 +      u8 *dbFileVers = &((u8*)pPg->pData)[24];
 1.42455 +      memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
 1.42456 +    }
 1.42457 +  }
 1.42458 +  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
 1.42459 +
 1.42460 +  PAGER_INCR(sqlite3_pager_readdb_count);
 1.42461 +  PAGER_INCR(pPager->nRead);
 1.42462 +  IOTRACE(("PGIN %p %d\n", pPager, pgno));
 1.42463 +  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
 1.42464 +               PAGERID(pPager), pgno, pager_pagehash(pPg)));
 1.42465 +
 1.42466 +  return rc;
 1.42467 +}
 1.42468 +
 1.42469 +/*
 1.42470 +** Update the value of the change-counter at offsets 24 and 92 in
 1.42471 +** the header and the sqlite version number at offset 96.
 1.42472 +**
 1.42473 +** This is an unconditional update.  See also the pager_incr_changecounter()
 1.42474 +** routine which only updates the change-counter if the update is actually
 1.42475 +** needed, as determined by the pPager->changeCountDone state variable.
 1.42476 +*/
 1.42477 +static void pager_write_changecounter(PgHdr *pPg){
 1.42478 +  u32 change_counter;
 1.42479 +
 1.42480 +  /* Increment the value just read and write it back to byte 24. */
 1.42481 +  change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
 1.42482 +  put32bits(((char*)pPg->pData)+24, change_counter);
 1.42483 +
 1.42484 +  /* Also store the SQLite version number in bytes 96..99 and in
 1.42485 +  ** bytes 92..95 store the change counter for which the version number
 1.42486 +  ** is valid. */
 1.42487 +  put32bits(((char*)pPg->pData)+92, change_counter);
 1.42488 +  put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
 1.42489 +}
 1.42490 +
 1.42491 +#ifndef SQLITE_OMIT_WAL
 1.42492 +/*
 1.42493 +** This function is invoked once for each page that has already been 
 1.42494 +** written into the log file when a WAL transaction is rolled back.
 1.42495 +** Parameter iPg is the page number of said page. The pCtx argument 
 1.42496 +** is actually a pointer to the Pager structure.
 1.42497 +**
 1.42498 +** If page iPg is present in the cache, and has no outstanding references,
 1.42499 +** it is discarded. Otherwise, if there are one or more outstanding
 1.42500 +** references, the page content is reloaded from the database. If the
 1.42501 +** attempt to reload content from the database is required and fails, 
 1.42502 +** return an SQLite error code. Otherwise, SQLITE_OK.
 1.42503 +*/
 1.42504 +static int pagerUndoCallback(void *pCtx, Pgno iPg){
 1.42505 +  int rc = SQLITE_OK;
 1.42506 +  Pager *pPager = (Pager *)pCtx;
 1.42507 +  PgHdr *pPg;
 1.42508 +
 1.42509 +  assert( pagerUseWal(pPager) );
 1.42510 +  pPg = sqlite3PagerLookup(pPager, iPg);
 1.42511 +  if( pPg ){
 1.42512 +    if( sqlite3PcachePageRefcount(pPg)==1 ){
 1.42513 +      sqlite3PcacheDrop(pPg);
 1.42514 +    }else{
 1.42515 +      u32 iFrame = 0;
 1.42516 +      rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
 1.42517 +      if( rc==SQLITE_OK ){
 1.42518 +        rc = readDbPage(pPg, iFrame);
 1.42519 +      }
 1.42520 +      if( rc==SQLITE_OK ){
 1.42521 +        pPager->xReiniter(pPg);
 1.42522 +      }
 1.42523 +      sqlite3PagerUnrefNotNull(pPg);
 1.42524 +    }
 1.42525 +  }
 1.42526 +
 1.42527 +  /* Normally, if a transaction is rolled back, any backup processes are
 1.42528 +  ** updated as data is copied out of the rollback journal and into the
 1.42529 +  ** database. This is not generally possible with a WAL database, as
 1.42530 +  ** rollback involves simply truncating the log file. Therefore, if one
 1.42531 +  ** or more frames have already been written to the log (and therefore 
 1.42532 +  ** also copied into the backup databases) as part of this transaction,
 1.42533 +  ** the backups must be restarted.
 1.42534 +  */
 1.42535 +  sqlite3BackupRestart(pPager->pBackup);
 1.42536 +
 1.42537 +  return rc;
 1.42538 +}
 1.42539 +
 1.42540 +/*
 1.42541 +** This function is called to rollback a transaction on a WAL database.
 1.42542 +*/
 1.42543 +static int pagerRollbackWal(Pager *pPager){
 1.42544 +  int rc;                         /* Return Code */
 1.42545 +  PgHdr *pList;                   /* List of dirty pages to revert */
 1.42546 +
 1.42547 +  /* For all pages in the cache that are currently dirty or have already
 1.42548 +  ** been written (but not committed) to the log file, do one of the 
 1.42549 +  ** following:
 1.42550 +  **
 1.42551 +  **   + Discard the cached page (if refcount==0), or
 1.42552 +  **   + Reload page content from the database (if refcount>0).
 1.42553 +  */
 1.42554 +  pPager->dbSize = pPager->dbOrigSize;
 1.42555 +  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
 1.42556 +  pList = sqlite3PcacheDirtyList(pPager->pPCache);
 1.42557 +  while( pList && rc==SQLITE_OK ){
 1.42558 +    PgHdr *pNext = pList->pDirty;
 1.42559 +    rc = pagerUndoCallback((void *)pPager, pList->pgno);
 1.42560 +    pList = pNext;
 1.42561 +  }
 1.42562 +
 1.42563 +  return rc;
 1.42564 +}
 1.42565 +
 1.42566 +/*
 1.42567 +** This function is a wrapper around sqlite3WalFrames(). As well as logging
 1.42568 +** the contents of the list of pages headed by pList (connected by pDirty),
 1.42569 +** this function notifies any active backup processes that the pages have
 1.42570 +** changed. 
 1.42571 +**
 1.42572 +** The list of pages passed into this routine is always sorted by page number.
 1.42573 +** Hence, if page 1 appears anywhere on the list, it will be the first page.
 1.42574 +*/ 
 1.42575 +static int pagerWalFrames(
 1.42576 +  Pager *pPager,                  /* Pager object */
 1.42577 +  PgHdr *pList,                   /* List of frames to log */
 1.42578 +  Pgno nTruncate,                 /* Database size after this commit */
 1.42579 +  int isCommit                    /* True if this is a commit */
 1.42580 +){
 1.42581 +  int rc;                         /* Return code */
 1.42582 +  int nList;                      /* Number of pages in pList */
 1.42583 +#if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
 1.42584 +  PgHdr *p;                       /* For looping over pages */
 1.42585 +#endif
 1.42586 +
 1.42587 +  assert( pPager->pWal );
 1.42588 +  assert( pList );
 1.42589 +#ifdef SQLITE_DEBUG
 1.42590 +  /* Verify that the page list is in accending order */
 1.42591 +  for(p=pList; p && p->pDirty; p=p->pDirty){
 1.42592 +    assert( p->pgno < p->pDirty->pgno );
 1.42593 +  }
 1.42594 +#endif
 1.42595 +
 1.42596 +  assert( pList->pDirty==0 || isCommit );
 1.42597 +  if( isCommit ){
 1.42598 +    /* If a WAL transaction is being committed, there is no point in writing
 1.42599 +    ** any pages with page numbers greater than nTruncate into the WAL file.
 1.42600 +    ** They will never be read by any client. So remove them from the pDirty
 1.42601 +    ** list here. */
 1.42602 +    PgHdr *p;
 1.42603 +    PgHdr **ppNext = &pList;
 1.42604 +    nList = 0;
 1.42605 +    for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
 1.42606 +      if( p->pgno<=nTruncate ){
 1.42607 +        ppNext = &p->pDirty;
 1.42608 +        nList++;
 1.42609 +      }
 1.42610 +    }
 1.42611 +    assert( pList );
 1.42612 +  }else{
 1.42613 +    nList = 1;
 1.42614 +  }
 1.42615 +  pPager->aStat[PAGER_STAT_WRITE] += nList;
 1.42616 +
 1.42617 +  if( pList->pgno==1 ) pager_write_changecounter(pList);
 1.42618 +  rc = sqlite3WalFrames(pPager->pWal, 
 1.42619 +      pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
 1.42620 +  );
 1.42621 +  if( rc==SQLITE_OK && pPager->pBackup ){
 1.42622 +    PgHdr *p;
 1.42623 +    for(p=pList; p; p=p->pDirty){
 1.42624 +      sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
 1.42625 +    }
 1.42626 +  }
 1.42627 +
 1.42628 +#ifdef SQLITE_CHECK_PAGES
 1.42629 +  pList = sqlite3PcacheDirtyList(pPager->pPCache);
 1.42630 +  for(p=pList; p; p=p->pDirty){
 1.42631 +    pager_set_pagehash(p);
 1.42632 +  }
 1.42633 +#endif
 1.42634 +
 1.42635 +  return rc;
 1.42636 +}
 1.42637 +
 1.42638 +/*
 1.42639 +** Begin a read transaction on the WAL.
 1.42640 +**
 1.42641 +** This routine used to be called "pagerOpenSnapshot()" because it essentially
 1.42642 +** makes a snapshot of the database at the current point in time and preserves
 1.42643 +** that snapshot for use by the reader in spite of concurrently changes by
 1.42644 +** other writers or checkpointers.
 1.42645 +*/
 1.42646 +static int pagerBeginReadTransaction(Pager *pPager){
 1.42647 +  int rc;                         /* Return code */
 1.42648 +  int changed = 0;                /* True if cache must be reset */
 1.42649 +
 1.42650 +  assert( pagerUseWal(pPager) );
 1.42651 +  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
 1.42652 +
 1.42653 +  /* sqlite3WalEndReadTransaction() was not called for the previous
 1.42654 +  ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
 1.42655 +  ** are in locking_mode=NORMAL and EndRead() was previously called,
 1.42656 +  ** the duplicate call is harmless.
 1.42657 +  */
 1.42658 +  sqlite3WalEndReadTransaction(pPager->pWal);
 1.42659 +
 1.42660 +  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
 1.42661 +  if( rc!=SQLITE_OK || changed ){
 1.42662 +    pager_reset(pPager);
 1.42663 +    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
 1.42664 +  }
 1.42665 +
 1.42666 +  return rc;
 1.42667 +}
 1.42668 +#endif
 1.42669 +
 1.42670 +/*
 1.42671 +** This function is called as part of the transition from PAGER_OPEN
 1.42672 +** to PAGER_READER state to determine the size of the database file
 1.42673 +** in pages (assuming the page size currently stored in Pager.pageSize).
 1.42674 +**
 1.42675 +** If no error occurs, SQLITE_OK is returned and the size of the database
 1.42676 +** in pages is stored in *pnPage. Otherwise, an error code (perhaps
 1.42677 +** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
 1.42678 +*/
 1.42679 +static int pagerPagecount(Pager *pPager, Pgno *pnPage){
 1.42680 +  Pgno nPage;                     /* Value to return via *pnPage */
 1.42681 +
 1.42682 +  /* Query the WAL sub-system for the database size. The WalDbsize()
 1.42683 +  ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
 1.42684 +  ** if the database size is not available. The database size is not
 1.42685 +  ** available from the WAL sub-system if the log file is empty or
 1.42686 +  ** contains no valid committed transactions.
 1.42687 +  */
 1.42688 +  assert( pPager->eState==PAGER_OPEN );
 1.42689 +  assert( pPager->eLock>=SHARED_LOCK );
 1.42690 +  nPage = sqlite3WalDbsize(pPager->pWal);
 1.42691 +
 1.42692 +  /* If the database size was not available from the WAL sub-system,
 1.42693 +  ** determine it based on the size of the database file. If the size
 1.42694 +  ** of the database file is not an integer multiple of the page-size,
 1.42695 +  ** round down to the nearest page. Except, any file larger than 0
 1.42696 +  ** bytes in size is considered to contain at least one page.
 1.42697 +  */
 1.42698 +  if( nPage==0 ){
 1.42699 +    i64 n = 0;                    /* Size of db file in bytes */
 1.42700 +    assert( isOpen(pPager->fd) || pPager->tempFile );
 1.42701 +    if( isOpen(pPager->fd) ){
 1.42702 +      int rc = sqlite3OsFileSize(pPager->fd, &n);
 1.42703 +      if( rc!=SQLITE_OK ){
 1.42704 +        return rc;
 1.42705 +      }
 1.42706 +    }
 1.42707 +    nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
 1.42708 +  }
 1.42709 +
 1.42710 +  /* If the current number of pages in the file is greater than the
 1.42711 +  ** configured maximum pager number, increase the allowed limit so
 1.42712 +  ** that the file can be read.
 1.42713 +  */
 1.42714 +  if( nPage>pPager->mxPgno ){
 1.42715 +    pPager->mxPgno = (Pgno)nPage;
 1.42716 +  }
 1.42717 +
 1.42718 +  *pnPage = nPage;
 1.42719 +  return SQLITE_OK;
 1.42720 +}
 1.42721 +
 1.42722 +#ifndef SQLITE_OMIT_WAL
 1.42723 +/*
 1.42724 +** Check if the *-wal file that corresponds to the database opened by pPager
 1.42725 +** exists if the database is not empy, or verify that the *-wal file does
 1.42726 +** not exist (by deleting it) if the database file is empty.
 1.42727 +**
 1.42728 +** If the database is not empty and the *-wal file exists, open the pager
 1.42729 +** in WAL mode.  If the database is empty or if no *-wal file exists and
 1.42730 +** if no error occurs, make sure Pager.journalMode is not set to
 1.42731 +** PAGER_JOURNALMODE_WAL.
 1.42732 +**
 1.42733 +** Return SQLITE_OK or an error code.
 1.42734 +**
 1.42735 +** The caller must hold a SHARED lock on the database file to call this
 1.42736 +** function. Because an EXCLUSIVE lock on the db file is required to delete 
 1.42737 +** a WAL on a none-empty database, this ensures there is no race condition 
 1.42738 +** between the xAccess() below and an xDelete() being executed by some 
 1.42739 +** other connection.
 1.42740 +*/
 1.42741 +static int pagerOpenWalIfPresent(Pager *pPager){
 1.42742 +  int rc = SQLITE_OK;
 1.42743 +  assert( pPager->eState==PAGER_OPEN );
 1.42744 +  assert( pPager->eLock>=SHARED_LOCK );
 1.42745 +
 1.42746 +  if( !pPager->tempFile ){
 1.42747 +    int isWal;                    /* True if WAL file exists */
 1.42748 +    Pgno nPage;                   /* Size of the database file */
 1.42749 +
 1.42750 +    rc = pagerPagecount(pPager, &nPage);
 1.42751 +    if( rc ) return rc;
 1.42752 +    if( nPage==0 ){
 1.42753 +      rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
 1.42754 +      if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
 1.42755 +      isWal = 0;
 1.42756 +    }else{
 1.42757 +      rc = sqlite3OsAccess(
 1.42758 +          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
 1.42759 +      );
 1.42760 +    }
 1.42761 +    if( rc==SQLITE_OK ){
 1.42762 +      if( isWal ){
 1.42763 +        testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
 1.42764 +        rc = sqlite3PagerOpenWal(pPager, 0);
 1.42765 +      }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
 1.42766 +        pPager->journalMode = PAGER_JOURNALMODE_DELETE;
 1.42767 +      }
 1.42768 +    }
 1.42769 +  }
 1.42770 +  return rc;
 1.42771 +}
 1.42772 +#endif
 1.42773 +
 1.42774 +/*
 1.42775 +** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
 1.42776 +** the entire master journal file. The case pSavepoint==NULL occurs when 
 1.42777 +** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
 1.42778 +** savepoint.
 1.42779 +**
 1.42780 +** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
 1.42781 +** being rolled back), then the rollback consists of up to three stages,
 1.42782 +** performed in the order specified:
 1.42783 +**
 1.42784 +**   * Pages are played back from the main journal starting at byte
 1.42785 +**     offset PagerSavepoint.iOffset and continuing to 
 1.42786 +**     PagerSavepoint.iHdrOffset, or to the end of the main journal
 1.42787 +**     file if PagerSavepoint.iHdrOffset is zero.
 1.42788 +**
 1.42789 +**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
 1.42790 +**     back starting from the journal header immediately following 
 1.42791 +**     PagerSavepoint.iHdrOffset to the end of the main journal file.
 1.42792 +**
 1.42793 +**   * Pages are then played back from the sub-journal file, starting
 1.42794 +**     with the PagerSavepoint.iSubRec and continuing to the end of
 1.42795 +**     the journal file.
 1.42796 +**
 1.42797 +** Throughout the rollback process, each time a page is rolled back, the
 1.42798 +** corresponding bit is set in a bitvec structure (variable pDone in the
 1.42799 +** implementation below). This is used to ensure that a page is only
 1.42800 +** rolled back the first time it is encountered in either journal.
 1.42801 +**
 1.42802 +** If pSavepoint is NULL, then pages are only played back from the main
 1.42803 +** journal file. There is no need for a bitvec in this case.
 1.42804 +**
 1.42805 +** In either case, before playback commences the Pager.dbSize variable
 1.42806 +** is reset to the value that it held at the start of the savepoint 
 1.42807 +** (or transaction). No page with a page-number greater than this value
 1.42808 +** is played back. If one is encountered it is simply skipped.
 1.42809 +*/
 1.42810 +static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
 1.42811 +  i64 szJ;                 /* Effective size of the main journal */
 1.42812 +  i64 iHdrOff;             /* End of first segment of main-journal records */
 1.42813 +  int rc = SQLITE_OK;      /* Return code */
 1.42814 +  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
 1.42815 +
 1.42816 +  assert( pPager->eState!=PAGER_ERROR );
 1.42817 +  assert( pPager->eState>=PAGER_WRITER_LOCKED );
 1.42818 +
 1.42819 +  /* Allocate a bitvec to use to store the set of pages rolled back */
 1.42820 +  if( pSavepoint ){
 1.42821 +    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
 1.42822 +    if( !pDone ){
 1.42823 +      return SQLITE_NOMEM;
 1.42824 +    }
 1.42825 +  }
 1.42826 +
 1.42827 +  /* Set the database size back to the value it was before the savepoint 
 1.42828 +  ** being reverted was opened.
 1.42829 +  */
 1.42830 +  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
 1.42831 +  pPager->changeCountDone = pPager->tempFile;
 1.42832 +
 1.42833 +  if( !pSavepoint && pagerUseWal(pPager) ){
 1.42834 +    return pagerRollbackWal(pPager);
 1.42835 +  }
 1.42836 +
 1.42837 +  /* Use pPager->journalOff as the effective size of the main rollback
 1.42838 +  ** journal.  The actual file might be larger than this in
 1.42839 +  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
 1.42840 +  ** past pPager->journalOff is off-limits to us.
 1.42841 +  */
 1.42842 +  szJ = pPager->journalOff;
 1.42843 +  assert( pagerUseWal(pPager)==0 || szJ==0 );
 1.42844 +
 1.42845 +  /* Begin by rolling back records from the main journal starting at
 1.42846 +  ** PagerSavepoint.iOffset and continuing to the next journal header.
 1.42847 +  ** There might be records in the main journal that have a page number
 1.42848 +  ** greater than the current database size (pPager->dbSize) but those
 1.42849 +  ** will be skipped automatically.  Pages are added to pDone as they
 1.42850 +  ** are played back.
 1.42851 +  */
 1.42852 +  if( pSavepoint && !pagerUseWal(pPager) ){
 1.42853 +    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
 1.42854 +    pPager->journalOff = pSavepoint->iOffset;
 1.42855 +    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
 1.42856 +      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
 1.42857 +    }
 1.42858 +    assert( rc!=SQLITE_DONE );
 1.42859 +  }else{
 1.42860 +    pPager->journalOff = 0;
 1.42861 +  }
 1.42862 +
 1.42863 +  /* Continue rolling back records out of the main journal starting at
 1.42864 +  ** the first journal header seen and continuing until the effective end
 1.42865 +  ** of the main journal file.  Continue to skip out-of-range pages and
 1.42866 +  ** continue adding pages rolled back to pDone.
 1.42867 +  */
 1.42868 +  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
 1.42869 +    u32 ii;            /* Loop counter */
 1.42870 +    u32 nJRec = 0;     /* Number of Journal Records */
 1.42871 +    u32 dummy;
 1.42872 +    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
 1.42873 +    assert( rc!=SQLITE_DONE );
 1.42874 +
 1.42875 +    /*
 1.42876 +    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
 1.42877 +    ** test is related to ticket #2565.  See the discussion in the
 1.42878 +    ** pager_playback() function for additional information.
 1.42879 +    */
 1.42880 +    if( nJRec==0 
 1.42881 +     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
 1.42882 +    ){
 1.42883 +      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
 1.42884 +    }
 1.42885 +    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
 1.42886 +      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
 1.42887 +    }
 1.42888 +    assert( rc!=SQLITE_DONE );
 1.42889 +  }
 1.42890 +  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
 1.42891 +
 1.42892 +  /* Finally,  rollback pages from the sub-journal.  Page that were
 1.42893 +  ** previously rolled back out of the main journal (and are hence in pDone)
 1.42894 +  ** will be skipped.  Out-of-range pages are also skipped.
 1.42895 +  */
 1.42896 +  if( pSavepoint ){
 1.42897 +    u32 ii;            /* Loop counter */
 1.42898 +    i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
 1.42899 +
 1.42900 +    if( pagerUseWal(pPager) ){
 1.42901 +      rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
 1.42902 +    }
 1.42903 +    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
 1.42904 +      assert( offset==(i64)ii*(4+pPager->pageSize) );
 1.42905 +      rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
 1.42906 +    }
 1.42907 +    assert( rc!=SQLITE_DONE );
 1.42908 +  }
 1.42909 +
 1.42910 +  sqlite3BitvecDestroy(pDone);
 1.42911 +  if( rc==SQLITE_OK ){
 1.42912 +    pPager->journalOff = szJ;
 1.42913 +  }
 1.42914 +
 1.42915 +  return rc;
 1.42916 +}
 1.42917 +
 1.42918 +/*
 1.42919 +** Change the maximum number of in-memory pages that are allowed.
 1.42920 +*/
 1.42921 +SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
 1.42922 +  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
 1.42923 +}
 1.42924 +
 1.42925 +/*
 1.42926 +** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
 1.42927 +*/
 1.42928 +static void pagerFixMaplimit(Pager *pPager){
 1.42929 +#if SQLITE_MAX_MMAP_SIZE>0
 1.42930 +  sqlite3_file *fd = pPager->fd;
 1.42931 +  if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
 1.42932 +    sqlite3_int64 sz;
 1.42933 +    sz = pPager->szMmap;
 1.42934 +    pPager->bUseFetch = (sz>0);
 1.42935 +    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
 1.42936 +  }
 1.42937 +#endif
 1.42938 +}
 1.42939 +
 1.42940 +/*
 1.42941 +** Change the maximum size of any memory mapping made of the database file.
 1.42942 +*/
 1.42943 +SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
 1.42944 +  pPager->szMmap = szMmap;
 1.42945 +  pagerFixMaplimit(pPager);
 1.42946 +}
 1.42947 +
 1.42948 +/*
 1.42949 +** Free as much memory as possible from the pager.
 1.42950 +*/
 1.42951 +SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
 1.42952 +  sqlite3PcacheShrink(pPager->pPCache);
 1.42953 +}
 1.42954 +
 1.42955 +/*
 1.42956 +** Adjust settings of the pager to those specified in the pgFlags parameter.
 1.42957 +**
 1.42958 +** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
 1.42959 +** of the database to damage due to OS crashes or power failures by
 1.42960 +** changing the number of syncs()s when writing the journals.
 1.42961 +** There are three levels:
 1.42962 +**
 1.42963 +**    OFF       sqlite3OsSync() is never called.  This is the default
 1.42964 +**              for temporary and transient files.
 1.42965 +**
 1.42966 +**    NORMAL    The journal is synced once before writes begin on the
 1.42967 +**              database.  This is normally adequate protection, but
 1.42968 +**              it is theoretically possible, though very unlikely,
 1.42969 +**              that an inopertune power failure could leave the journal
 1.42970 +**              in a state which would cause damage to the database
 1.42971 +**              when it is rolled back.
 1.42972 +**
 1.42973 +**    FULL      The journal is synced twice before writes begin on the
 1.42974 +**              database (with some additional information - the nRec field
 1.42975 +**              of the journal header - being written in between the two
 1.42976 +**              syncs).  If we assume that writing a
 1.42977 +**              single disk sector is atomic, then this mode provides
 1.42978 +**              assurance that the journal will not be corrupted to the
 1.42979 +**              point of causing damage to the database during rollback.
 1.42980 +**
 1.42981 +** The above is for a rollback-journal mode.  For WAL mode, OFF continues
 1.42982 +** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
 1.42983 +** prior to the start of checkpoint and that the database file is synced
 1.42984 +** at the conclusion of the checkpoint if the entire content of the WAL
 1.42985 +** was written back into the database.  But no sync operations occur for
 1.42986 +** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
 1.42987 +** file is synced following each commit operation, in addition to the
 1.42988 +** syncs associated with NORMAL.
 1.42989 +**
 1.42990 +** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
 1.42991 +** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
 1.42992 +** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
 1.42993 +** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
 1.42994 +** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
 1.42995 +** synchronous=FULL versus synchronous=NORMAL setting determines when
 1.42996 +** the xSync primitive is called and is relevant to all platforms.
 1.42997 +**
 1.42998 +** Numeric values associated with these states are OFF==1, NORMAL=2,
 1.42999 +** and FULL=3.
 1.43000 +*/
 1.43001 +#ifndef SQLITE_OMIT_PAGER_PRAGMAS
 1.43002 +SQLITE_PRIVATE void sqlite3PagerSetFlags(
 1.43003 +  Pager *pPager,        /* The pager to set safety level for */
 1.43004 +  unsigned pgFlags      /* Various flags */
 1.43005 +){
 1.43006 +  unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
 1.43007 +  assert( level>=1 && level<=3 );
 1.43008 +  pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
 1.43009 +  pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
 1.43010 +  if( pPager->noSync ){
 1.43011 +    pPager->syncFlags = 0;
 1.43012 +    pPager->ckptSyncFlags = 0;
 1.43013 +  }else if( pgFlags & PAGER_FULLFSYNC ){
 1.43014 +    pPager->syncFlags = SQLITE_SYNC_FULL;
 1.43015 +    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
 1.43016 +  }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
 1.43017 +    pPager->syncFlags = SQLITE_SYNC_NORMAL;
 1.43018 +    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
 1.43019 +  }else{
 1.43020 +    pPager->syncFlags = SQLITE_SYNC_NORMAL;
 1.43021 +    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
 1.43022 +  }
 1.43023 +  pPager->walSyncFlags = pPager->syncFlags;
 1.43024 +  if( pPager->fullSync ){
 1.43025 +    pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
 1.43026 +  }
 1.43027 +  if( pgFlags & PAGER_CACHESPILL ){
 1.43028 +    pPager->doNotSpill &= ~SPILLFLAG_OFF;
 1.43029 +  }else{
 1.43030 +    pPager->doNotSpill |= SPILLFLAG_OFF;
 1.43031 +  }
 1.43032 +}
 1.43033 +#endif
 1.43034 +
 1.43035 +/*
 1.43036 +** The following global variable is incremented whenever the library
 1.43037 +** attempts to open a temporary file.  This information is used for
 1.43038 +** testing and analysis only.  
 1.43039 +*/
 1.43040 +#ifdef SQLITE_TEST
 1.43041 +SQLITE_API int sqlite3_opentemp_count = 0;
 1.43042 +#endif
 1.43043 +
 1.43044 +/*
 1.43045 +** Open a temporary file.
 1.43046 +**
 1.43047 +** Write the file descriptor into *pFile. Return SQLITE_OK on success 
 1.43048 +** or some other error code if we fail. The OS will automatically 
 1.43049 +** delete the temporary file when it is closed.
 1.43050 +**
 1.43051 +** The flags passed to the VFS layer xOpen() call are those specified
 1.43052 +** by parameter vfsFlags ORed with the following:
 1.43053 +**
 1.43054 +**     SQLITE_OPEN_READWRITE
 1.43055 +**     SQLITE_OPEN_CREATE
 1.43056 +**     SQLITE_OPEN_EXCLUSIVE
 1.43057 +**     SQLITE_OPEN_DELETEONCLOSE
 1.43058 +*/
 1.43059 +static int pagerOpentemp(
 1.43060 +  Pager *pPager,        /* The pager object */
 1.43061 +  sqlite3_file *pFile,  /* Write the file descriptor here */
 1.43062 +  int vfsFlags          /* Flags passed through to the VFS */
 1.43063 +){
 1.43064 +  int rc;               /* Return code */
 1.43065 +
 1.43066 +#ifdef SQLITE_TEST
 1.43067 +  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
 1.43068 +#endif
 1.43069 +
 1.43070 +  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
 1.43071 +            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
 1.43072 +  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
 1.43073 +  assert( rc!=SQLITE_OK || isOpen(pFile) );
 1.43074 +  return rc;
 1.43075 +}
 1.43076 +
 1.43077 +/*
 1.43078 +** Set the busy handler function.
 1.43079 +**
 1.43080 +** The pager invokes the busy-handler if sqlite3OsLock() returns 
 1.43081 +** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
 1.43082 +** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
 1.43083 +** lock. It does *not* invoke the busy handler when upgrading from
 1.43084 +** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
 1.43085 +** (which occurs during hot-journal rollback). Summary:
 1.43086 +**
 1.43087 +**   Transition                        | Invokes xBusyHandler
 1.43088 +**   --------------------------------------------------------
 1.43089 +**   NO_LOCK       -> SHARED_LOCK      | Yes
 1.43090 +**   SHARED_LOCK   -> RESERVED_LOCK    | No
 1.43091 +**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
 1.43092 +**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
 1.43093 +**
 1.43094 +** If the busy-handler callback returns non-zero, the lock is 
 1.43095 +** retried. If it returns zero, then the SQLITE_BUSY error is
 1.43096 +** returned to the caller of the pager API function.
 1.43097 +*/
 1.43098 +SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
 1.43099 +  Pager *pPager,                       /* Pager object */
 1.43100 +  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
 1.43101 +  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
 1.43102 +){
 1.43103 +  pPager->xBusyHandler = xBusyHandler;
 1.43104 +  pPager->pBusyHandlerArg = pBusyHandlerArg;
 1.43105 +
 1.43106 +  if( isOpen(pPager->fd) ){
 1.43107 +    void **ap = (void **)&pPager->xBusyHandler;
 1.43108 +    assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
 1.43109 +    assert( ap[1]==pBusyHandlerArg );
 1.43110 +    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
 1.43111 +  }
 1.43112 +}
 1.43113 +
 1.43114 +/*
 1.43115 +** Change the page size used by the Pager object. The new page size 
 1.43116 +** is passed in *pPageSize.
 1.43117 +**
 1.43118 +** If the pager is in the error state when this function is called, it
 1.43119 +** is a no-op. The value returned is the error state error code (i.e. 
 1.43120 +** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
 1.43121 +**
 1.43122 +** Otherwise, if all of the following are true:
 1.43123 +**
 1.43124 +**   * the new page size (value of *pPageSize) is valid (a power 
 1.43125 +**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
 1.43126 +**
 1.43127 +**   * there are no outstanding page references, and
 1.43128 +**
 1.43129 +**   * the database is either not an in-memory database or it is
 1.43130 +**     an in-memory database that currently consists of zero pages.
 1.43131 +**
 1.43132 +** then the pager object page size is set to *pPageSize.
 1.43133 +**
 1.43134 +** If the page size is changed, then this function uses sqlite3PagerMalloc() 
 1.43135 +** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
 1.43136 +** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
 1.43137 +** In all other cases, SQLITE_OK is returned.
 1.43138 +**
 1.43139 +** If the page size is not changed, either because one of the enumerated
 1.43140 +** conditions above is not true, the pager was in error state when this
 1.43141 +** function was called, or because the memory allocation attempt failed, 
 1.43142 +** then *pPageSize is set to the old, retained page size before returning.
 1.43143 +*/
 1.43144 +SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
 1.43145 +  int rc = SQLITE_OK;
 1.43146 +
 1.43147 +  /* It is not possible to do a full assert_pager_state() here, as this
 1.43148 +  ** function may be called from within PagerOpen(), before the state
 1.43149 +  ** of the Pager object is internally consistent.
 1.43150 +  **
 1.43151 +  ** At one point this function returned an error if the pager was in 
 1.43152 +  ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
 1.43153 +  ** there is at least one outstanding page reference, this function
 1.43154 +  ** is a no-op for that case anyhow.
 1.43155 +  */
 1.43156 +
 1.43157 +  u32 pageSize = *pPageSize;
 1.43158 +  assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
 1.43159 +  if( (pPager->memDb==0 || pPager->dbSize==0)
 1.43160 +   && sqlite3PcacheRefCount(pPager->pPCache)==0 
 1.43161 +   && pageSize && pageSize!=(u32)pPager->pageSize 
 1.43162 +  ){
 1.43163 +    char *pNew = NULL;             /* New temp space */
 1.43164 +    i64 nByte = 0;
 1.43165 +
 1.43166 +    if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
 1.43167 +      rc = sqlite3OsFileSize(pPager->fd, &nByte);
 1.43168 +    }
 1.43169 +    if( rc==SQLITE_OK ){
 1.43170 +      pNew = (char *)sqlite3PageMalloc(pageSize);
 1.43171 +      if( !pNew ) rc = SQLITE_NOMEM;
 1.43172 +    }
 1.43173 +
 1.43174 +    if( rc==SQLITE_OK ){
 1.43175 +      pager_reset(pPager);
 1.43176 +      pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
 1.43177 +      pPager->pageSize = pageSize;
 1.43178 +      sqlite3PageFree(pPager->pTmpSpace);
 1.43179 +      pPager->pTmpSpace = pNew;
 1.43180 +      sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
 1.43181 +    }
 1.43182 +  }
 1.43183 +
 1.43184 +  *pPageSize = pPager->pageSize;
 1.43185 +  if( rc==SQLITE_OK ){
 1.43186 +    if( nReserve<0 ) nReserve = pPager->nReserve;
 1.43187 +    assert( nReserve>=0 && nReserve<1000 );
 1.43188 +    pPager->nReserve = (i16)nReserve;
 1.43189 +    pagerReportSize(pPager);
 1.43190 +    pagerFixMaplimit(pPager);
 1.43191 +  }
 1.43192 +  return rc;
 1.43193 +}
 1.43194 +
 1.43195 +/*
 1.43196 +** Return a pointer to the "temporary page" buffer held internally
 1.43197 +** by the pager.  This is a buffer that is big enough to hold the
 1.43198 +** entire content of a database page.  This buffer is used internally
 1.43199 +** during rollback and will be overwritten whenever a rollback
 1.43200 +** occurs.  But other modules are free to use it too, as long as
 1.43201 +** no rollbacks are happening.
 1.43202 +*/
 1.43203 +SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
 1.43204 +  return pPager->pTmpSpace;
 1.43205 +}
 1.43206 +
 1.43207 +/*
 1.43208 +** Attempt to set the maximum database page count if mxPage is positive. 
 1.43209 +** Make no changes if mxPage is zero or negative.  And never reduce the
 1.43210 +** maximum page count below the current size of the database.
 1.43211 +**
 1.43212 +** Regardless of mxPage, return the current maximum page count.
 1.43213 +*/
 1.43214 +SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
 1.43215 +  if( mxPage>0 ){
 1.43216 +    pPager->mxPgno = mxPage;
 1.43217 +  }
 1.43218 +  assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
 1.43219 +  assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
 1.43220 +  return pPager->mxPgno;
 1.43221 +}
 1.43222 +
 1.43223 +/*
 1.43224 +** The following set of routines are used to disable the simulated
 1.43225 +** I/O error mechanism.  These routines are used to avoid simulated
 1.43226 +** errors in places where we do not care about errors.
 1.43227 +**
 1.43228 +** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
 1.43229 +** and generate no code.
 1.43230 +*/
 1.43231 +#ifdef SQLITE_TEST
 1.43232 +SQLITE_API extern int sqlite3_io_error_pending;
 1.43233 +SQLITE_API extern int sqlite3_io_error_hit;
 1.43234 +static int saved_cnt;
 1.43235 +void disable_simulated_io_errors(void){
 1.43236 +  saved_cnt = sqlite3_io_error_pending;
 1.43237 +  sqlite3_io_error_pending = -1;
 1.43238 +}
 1.43239 +void enable_simulated_io_errors(void){
 1.43240 +  sqlite3_io_error_pending = saved_cnt;
 1.43241 +}
 1.43242 +#else
 1.43243 +# define disable_simulated_io_errors()
 1.43244 +# define enable_simulated_io_errors()
 1.43245 +#endif
 1.43246 +
 1.43247 +/*
 1.43248 +** Read the first N bytes from the beginning of the file into memory
 1.43249 +** that pDest points to. 
 1.43250 +**
 1.43251 +** If the pager was opened on a transient file (zFilename==""), or
 1.43252 +** opened on a file less than N bytes in size, the output buffer is
 1.43253 +** zeroed and SQLITE_OK returned. The rationale for this is that this 
 1.43254 +** function is used to read database headers, and a new transient or
 1.43255 +** zero sized database has a header than consists entirely of zeroes.
 1.43256 +**
 1.43257 +** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
 1.43258 +** the error code is returned to the caller and the contents of the
 1.43259 +** output buffer undefined.
 1.43260 +*/
 1.43261 +SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
 1.43262 +  int rc = SQLITE_OK;
 1.43263 +  memset(pDest, 0, N);
 1.43264 +  assert( isOpen(pPager->fd) || pPager->tempFile );
 1.43265 +
 1.43266 +  /* This routine is only called by btree immediately after creating
 1.43267 +  ** the Pager object.  There has not been an opportunity to transition
 1.43268 +  ** to WAL mode yet.
 1.43269 +  */
 1.43270 +  assert( !pagerUseWal(pPager) );
 1.43271 +
 1.43272 +  if( isOpen(pPager->fd) ){
 1.43273 +    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
 1.43274 +    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
 1.43275 +    if( rc==SQLITE_IOERR_SHORT_READ ){
 1.43276 +      rc = SQLITE_OK;
 1.43277 +    }
 1.43278 +  }
 1.43279 +  return rc;
 1.43280 +}
 1.43281 +
 1.43282 +/*
 1.43283 +** This function may only be called when a read-transaction is open on
 1.43284 +** the pager. It returns the total number of pages in the database.
 1.43285 +**
 1.43286 +** However, if the file is between 1 and <page-size> bytes in size, then 
 1.43287 +** this is considered a 1 page file.
 1.43288 +*/
 1.43289 +SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
 1.43290 +  assert( pPager->eState>=PAGER_READER );
 1.43291 +  assert( pPager->eState!=PAGER_WRITER_FINISHED );
 1.43292 +  *pnPage = (int)pPager->dbSize;
 1.43293 +}
 1.43294 +
 1.43295 +
 1.43296 +/*
 1.43297 +** Try to obtain a lock of type locktype on the database file. If
 1.43298 +** a similar or greater lock is already held, this function is a no-op
 1.43299 +** (returning SQLITE_OK immediately).
 1.43300 +**
 1.43301 +** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
 1.43302 +** the busy callback if the lock is currently not available. Repeat 
 1.43303 +** until the busy callback returns false or until the attempt to 
 1.43304 +** obtain the lock succeeds.
 1.43305 +**
 1.43306 +** Return SQLITE_OK on success and an error code if we cannot obtain
 1.43307 +** the lock. If the lock is obtained successfully, set the Pager.state 
 1.43308 +** variable to locktype before returning.
 1.43309 +*/
 1.43310 +static int pager_wait_on_lock(Pager *pPager, int locktype){
 1.43311 +  int rc;                              /* Return code */
 1.43312 +
 1.43313 +  /* Check that this is either a no-op (because the requested lock is 
 1.43314 +  ** already held, or one of the transistions that the busy-handler
 1.43315 +  ** may be invoked during, according to the comment above
 1.43316 +  ** sqlite3PagerSetBusyhandler().
 1.43317 +  */
 1.43318 +  assert( (pPager->eLock>=locktype)
 1.43319 +       || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
 1.43320 +       || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
 1.43321 +  );
 1.43322 +
 1.43323 +  do {
 1.43324 +    rc = pagerLockDb(pPager, locktype);
 1.43325 +  }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
 1.43326 +  return rc;
 1.43327 +}
 1.43328 +
 1.43329 +/*
 1.43330 +** Function assertTruncateConstraint(pPager) checks that one of the 
 1.43331 +** following is true for all dirty pages currently in the page-cache:
 1.43332 +**
 1.43333 +**   a) The page number is less than or equal to the size of the 
 1.43334 +**      current database image, in pages, OR
 1.43335 +**
 1.43336 +**   b) if the page content were written at this time, it would not
 1.43337 +**      be necessary to write the current content out to the sub-journal
 1.43338 +**      (as determined by function subjRequiresPage()).
 1.43339 +**
 1.43340 +** If the condition asserted by this function were not true, and the
 1.43341 +** dirty page were to be discarded from the cache via the pagerStress()
 1.43342 +** routine, pagerStress() would not write the current page content to
 1.43343 +** the database file. If a savepoint transaction were rolled back after
 1.43344 +** this happened, the correct behavior would be to restore the current
 1.43345 +** content of the page. However, since this content is not present in either
 1.43346 +** the database file or the portion of the rollback journal and 
 1.43347 +** sub-journal rolled back the content could not be restored and the
 1.43348 +** database image would become corrupt. It is therefore fortunate that 
 1.43349 +** this circumstance cannot arise.
 1.43350 +*/
 1.43351 +#if defined(SQLITE_DEBUG)
 1.43352 +static void assertTruncateConstraintCb(PgHdr *pPg){
 1.43353 +  assert( pPg->flags&PGHDR_DIRTY );
 1.43354 +  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
 1.43355 +}
 1.43356 +static void assertTruncateConstraint(Pager *pPager){
 1.43357 +  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
 1.43358 +}
 1.43359 +#else
 1.43360 +# define assertTruncateConstraint(pPager)
 1.43361 +#endif
 1.43362 +
 1.43363 +/*
 1.43364 +** Truncate the in-memory database file image to nPage pages. This 
 1.43365 +** function does not actually modify the database file on disk. It 
 1.43366 +** just sets the internal state of the pager object so that the 
 1.43367 +** truncation will be done when the current transaction is committed.
 1.43368 +**
 1.43369 +** This function is only called right before committing a transaction.
 1.43370 +** Once this function has been called, the transaction must either be
 1.43371 +** rolled back or committed. It is not safe to call this function and
 1.43372 +** then continue writing to the database.
 1.43373 +*/
 1.43374 +SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
 1.43375 +  assert( pPager->dbSize>=nPage );
 1.43376 +  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
 1.43377 +  pPager->dbSize = nPage;
 1.43378 +
 1.43379 +  /* At one point the code here called assertTruncateConstraint() to
 1.43380 +  ** ensure that all pages being truncated away by this operation are,
 1.43381 +  ** if one or more savepoints are open, present in the savepoint 
 1.43382 +  ** journal so that they can be restored if the savepoint is rolled
 1.43383 +  ** back. This is no longer necessary as this function is now only
 1.43384 +  ** called right before committing a transaction. So although the 
 1.43385 +  ** Pager object may still have open savepoints (Pager.nSavepoint!=0), 
 1.43386 +  ** they cannot be rolled back. So the assertTruncateConstraint() call
 1.43387 +  ** is no longer correct. */
 1.43388 +}
 1.43389 +
 1.43390 +
 1.43391 +/*
 1.43392 +** This function is called before attempting a hot-journal rollback. It
 1.43393 +** syncs the journal file to disk, then sets pPager->journalHdr to the
 1.43394 +** size of the journal file so that the pager_playback() routine knows
 1.43395 +** that the entire journal file has been synced.
 1.43396 +**
 1.43397 +** Syncing a hot-journal to disk before attempting to roll it back ensures 
 1.43398 +** that if a power-failure occurs during the rollback, the process that
 1.43399 +** attempts rollback following system recovery sees the same journal
 1.43400 +** content as this process.
 1.43401 +**
 1.43402 +** If everything goes as planned, SQLITE_OK is returned. Otherwise, 
 1.43403 +** an SQLite error code.
 1.43404 +*/
 1.43405 +static int pagerSyncHotJournal(Pager *pPager){
 1.43406 +  int rc = SQLITE_OK;
 1.43407 +  if( !pPager->noSync ){
 1.43408 +    rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
 1.43409 +  }
 1.43410 +  if( rc==SQLITE_OK ){
 1.43411 +    rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
 1.43412 +  }
 1.43413 +  return rc;
 1.43414 +}
 1.43415 +
 1.43416 +/*
 1.43417 +** Obtain a reference to a memory mapped page object for page number pgno. 
 1.43418 +** The new object will use the pointer pData, obtained from xFetch().
 1.43419 +** If successful, set *ppPage to point to the new page reference
 1.43420 +** and return SQLITE_OK. Otherwise, return an SQLite error code and set
 1.43421 +** *ppPage to zero.
 1.43422 +**
 1.43423 +** Page references obtained by calling this function should be released
 1.43424 +** by calling pagerReleaseMapPage().
 1.43425 +*/
 1.43426 +static int pagerAcquireMapPage(
 1.43427 +  Pager *pPager,                  /* Pager object */
 1.43428 +  Pgno pgno,                      /* Page number */
 1.43429 +  void *pData,                    /* xFetch()'d data for this page */
 1.43430 +  PgHdr **ppPage                  /* OUT: Acquired page object */
 1.43431 +){
 1.43432 +  PgHdr *p;                       /* Memory mapped page to return */
 1.43433 +
 1.43434 +  if( pPager->pMmapFreelist ){
 1.43435 +    *ppPage = p = pPager->pMmapFreelist;
 1.43436 +    pPager->pMmapFreelist = p->pDirty;
 1.43437 +    p->pDirty = 0;
 1.43438 +    memset(p->pExtra, 0, pPager->nExtra);
 1.43439 +  }else{
 1.43440 +    *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
 1.43441 +    if( p==0 ){
 1.43442 +      sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
 1.43443 +      return SQLITE_NOMEM;
 1.43444 +    }
 1.43445 +    p->pExtra = (void *)&p[1];
 1.43446 +    p->flags = PGHDR_MMAP;
 1.43447 +    p->nRef = 1;
 1.43448 +    p->pPager = pPager;
 1.43449 +  }
 1.43450 +
 1.43451 +  assert( p->pExtra==(void *)&p[1] );
 1.43452 +  assert( p->pPage==0 );
 1.43453 +  assert( p->flags==PGHDR_MMAP );
 1.43454 +  assert( p->pPager==pPager );
 1.43455 +  assert( p->nRef==1 );
 1.43456 +
 1.43457 +  p->pgno = pgno;
 1.43458 +  p->pData = pData;
 1.43459 +  pPager->nMmapOut++;
 1.43460 +
 1.43461 +  return SQLITE_OK;
 1.43462 +}
 1.43463 +
 1.43464 +/*
 1.43465 +** Release a reference to page pPg. pPg must have been returned by an 
 1.43466 +** earlier call to pagerAcquireMapPage().
 1.43467 +*/
 1.43468 +static void pagerReleaseMapPage(PgHdr *pPg){
 1.43469 +  Pager *pPager = pPg->pPager;
 1.43470 +  pPager->nMmapOut--;
 1.43471 +  pPg->pDirty = pPager->pMmapFreelist;
 1.43472 +  pPager->pMmapFreelist = pPg;
 1.43473 +
 1.43474 +  assert( pPager->fd->pMethods->iVersion>=3 );
 1.43475 +  sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
 1.43476 +}
 1.43477 +
 1.43478 +/*
 1.43479 +** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
 1.43480 +*/
 1.43481 +static void pagerFreeMapHdrs(Pager *pPager){
 1.43482 +  PgHdr *p;
 1.43483 +  PgHdr *pNext;
 1.43484 +  for(p=pPager->pMmapFreelist; p; p=pNext){
 1.43485 +    pNext = p->pDirty;
 1.43486 +    sqlite3_free(p);
 1.43487 +  }
 1.43488 +}
 1.43489 +
 1.43490 +
 1.43491 +/*
 1.43492 +** Shutdown the page cache.  Free all memory and close all files.
 1.43493 +**
 1.43494 +** If a transaction was in progress when this routine is called, that
 1.43495 +** transaction is rolled back.  All outstanding pages are invalidated
 1.43496 +** and their memory is freed.  Any attempt to use a page associated
 1.43497 +** with this page cache after this function returns will likely
 1.43498 +** result in a coredump.
 1.43499 +**
 1.43500 +** This function always succeeds. If a transaction is active an attempt
 1.43501 +** is made to roll it back. If an error occurs during the rollback 
 1.43502 +** a hot journal may be left in the filesystem but no error is returned
 1.43503 +** to the caller.
 1.43504 +*/
 1.43505 +SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
 1.43506 +  u8 *pTmp = (u8 *)pPager->pTmpSpace;
 1.43507 +
 1.43508 +  assert( assert_pager_state(pPager) );
 1.43509 +  disable_simulated_io_errors();
 1.43510 +  sqlite3BeginBenignMalloc();
 1.43511 +  pagerFreeMapHdrs(pPager);
 1.43512 +  /* pPager->errCode = 0; */
 1.43513 +  pPager->exclusiveMode = 0;
 1.43514 +#ifndef SQLITE_OMIT_WAL
 1.43515 +  sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
 1.43516 +  pPager->pWal = 0;
 1.43517 +#endif
 1.43518 +  pager_reset(pPager);
 1.43519 +  if( MEMDB ){
 1.43520 +    pager_unlock(pPager);
 1.43521 +  }else{
 1.43522 +    /* If it is open, sync the journal file before calling UnlockAndRollback.
 1.43523 +    ** If this is not done, then an unsynced portion of the open journal 
 1.43524 +    ** file may be played back into the database. If a power failure occurs 
 1.43525 +    ** while this is happening, the database could become corrupt.
 1.43526 +    **
 1.43527 +    ** If an error occurs while trying to sync the journal, shift the pager
 1.43528 +    ** into the ERROR state. This causes UnlockAndRollback to unlock the
 1.43529 +    ** database and close the journal file without attempting to roll it
 1.43530 +    ** back or finalize it. The next database user will have to do hot-journal
 1.43531 +    ** rollback before accessing the database file.
 1.43532 +    */
 1.43533 +    if( isOpen(pPager->jfd) ){
 1.43534 +      pager_error(pPager, pagerSyncHotJournal(pPager));
 1.43535 +    }
 1.43536 +    pagerUnlockAndRollback(pPager);
 1.43537 +  }
 1.43538 +  sqlite3EndBenignMalloc();
 1.43539 +  enable_simulated_io_errors();
 1.43540 +  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
 1.43541 +  IOTRACE(("CLOSE %p\n", pPager))
 1.43542 +  sqlite3OsClose(pPager->jfd);
 1.43543 +  sqlite3OsClose(pPager->fd);
 1.43544 +  sqlite3PageFree(pTmp);
 1.43545 +  sqlite3PcacheClose(pPager->pPCache);
 1.43546 +
 1.43547 +#ifdef SQLITE_HAS_CODEC
 1.43548 +  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
 1.43549 +#endif
 1.43550 +
 1.43551 +  assert( !pPager->aSavepoint && !pPager->pInJournal );
 1.43552 +  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
 1.43553 +
 1.43554 +  sqlite3_free(pPager);
 1.43555 +  return SQLITE_OK;
 1.43556 +}
 1.43557 +
 1.43558 +#if !defined(NDEBUG) || defined(SQLITE_TEST)
 1.43559 +/*
 1.43560 +** Return the page number for page pPg.
 1.43561 +*/
 1.43562 +SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
 1.43563 +  return pPg->pgno;
 1.43564 +}
 1.43565 +#endif
 1.43566 +
 1.43567 +/*
 1.43568 +** Increment the reference count for page pPg.
 1.43569 +*/
 1.43570 +SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
 1.43571 +  sqlite3PcacheRef(pPg);
 1.43572 +}
 1.43573 +
 1.43574 +/*
 1.43575 +** Sync the journal. In other words, make sure all the pages that have
 1.43576 +** been written to the journal have actually reached the surface of the
 1.43577 +** disk and can be restored in the event of a hot-journal rollback.
 1.43578 +**
 1.43579 +** If the Pager.noSync flag is set, then this function is a no-op.
 1.43580 +** Otherwise, the actions required depend on the journal-mode and the 
 1.43581 +** device characteristics of the file-system, as follows:
 1.43582 +**
 1.43583 +**   * If the journal file is an in-memory journal file, no action need
 1.43584 +**     be taken.
 1.43585 +**
 1.43586 +**   * Otherwise, if the device does not support the SAFE_APPEND property,
 1.43587 +**     then the nRec field of the most recently written journal header
 1.43588 +**     is updated to contain the number of journal records that have
 1.43589 +**     been written following it. If the pager is operating in full-sync
 1.43590 +**     mode, then the journal file is synced before this field is updated.
 1.43591 +**
 1.43592 +**   * If the device does not support the SEQUENTIAL property, then 
 1.43593 +**     journal file is synced.
 1.43594 +**
 1.43595 +** Or, in pseudo-code:
 1.43596 +**
 1.43597 +**   if( NOT <in-memory journal> ){
 1.43598 +**     if( NOT SAFE_APPEND ){
 1.43599 +**       if( <full-sync mode> ) xSync(<journal file>);
 1.43600 +**       <update nRec field>
 1.43601 +**     } 
 1.43602 +**     if( NOT SEQUENTIAL ) xSync(<journal file>);
 1.43603 +**   }
 1.43604 +**
 1.43605 +** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
 1.43606 +** page currently held in memory before returning SQLITE_OK. If an IO
 1.43607 +** error is encountered, then the IO error code is returned to the caller.
 1.43608 +*/
 1.43609 +static int syncJournal(Pager *pPager, int newHdr){
 1.43610 +  int rc;                         /* Return code */
 1.43611 +
 1.43612 +  assert( pPager->eState==PAGER_WRITER_CACHEMOD
 1.43613 +       || pPager->eState==PAGER_WRITER_DBMOD
 1.43614 +  );
 1.43615 +  assert( assert_pager_state(pPager) );
 1.43616 +  assert( !pagerUseWal(pPager) );
 1.43617 +
 1.43618 +  rc = sqlite3PagerExclusiveLock(pPager);
 1.43619 +  if( rc!=SQLITE_OK ) return rc;
 1.43620 +
 1.43621 +  if( !pPager->noSync ){
 1.43622 +    assert( !pPager->tempFile );
 1.43623 +    if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
 1.43624 +      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
 1.43625 +      assert( isOpen(pPager->jfd) );
 1.43626 +
 1.43627 +      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
 1.43628 +        /* This block deals with an obscure problem. If the last connection
 1.43629 +        ** that wrote to this database was operating in persistent-journal
 1.43630 +        ** mode, then the journal file may at this point actually be larger
 1.43631 +        ** than Pager.journalOff bytes. If the next thing in the journal
 1.43632 +        ** file happens to be a journal-header (written as part of the
 1.43633 +        ** previous connection's transaction), and a crash or power-failure 
 1.43634 +        ** occurs after nRec is updated but before this connection writes 
 1.43635 +        ** anything else to the journal file (or commits/rolls back its 
 1.43636 +        ** transaction), then SQLite may become confused when doing the 
 1.43637 +        ** hot-journal rollback following recovery. It may roll back all
 1.43638 +        ** of this connections data, then proceed to rolling back the old,
 1.43639 +        ** out-of-date data that follows it. Database corruption.
 1.43640 +        **
 1.43641 +        ** To work around this, if the journal file does appear to contain
 1.43642 +        ** a valid header following Pager.journalOff, then write a 0x00
 1.43643 +        ** byte to the start of it to prevent it from being recognized.
 1.43644 +        **
 1.43645 +        ** Variable iNextHdrOffset is set to the offset at which this
 1.43646 +        ** problematic header will occur, if it exists. aMagic is used 
 1.43647 +        ** as a temporary buffer to inspect the first couple of bytes of
 1.43648 +        ** the potential journal header.
 1.43649 +        */
 1.43650 +        i64 iNextHdrOffset;
 1.43651 +        u8 aMagic[8];
 1.43652 +        u8 zHeader[sizeof(aJournalMagic)+4];
 1.43653 +
 1.43654 +        memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
 1.43655 +        put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
 1.43656 +
 1.43657 +        iNextHdrOffset = journalHdrOffset(pPager);
 1.43658 +        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
 1.43659 +        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
 1.43660 +          static const u8 zerobyte = 0;
 1.43661 +          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
 1.43662 +        }
 1.43663 +        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
 1.43664 +          return rc;
 1.43665 +        }
 1.43666 +
 1.43667 +        /* Write the nRec value into the journal file header. If in
 1.43668 +        ** full-synchronous mode, sync the journal first. This ensures that
 1.43669 +        ** all data has really hit the disk before nRec is updated to mark
 1.43670 +        ** it as a candidate for rollback.
 1.43671 +        **
 1.43672 +        ** This is not required if the persistent media supports the
 1.43673 +        ** SAFE_APPEND property. Because in this case it is not possible 
 1.43674 +        ** for garbage data to be appended to the file, the nRec field
 1.43675 +        ** is populated with 0xFFFFFFFF when the journal header is written
 1.43676 +        ** and never needs to be updated.
 1.43677 +        */
 1.43678 +        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
 1.43679 +          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
 1.43680 +          IOTRACE(("JSYNC %p\n", pPager))
 1.43681 +          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
 1.43682 +          if( rc!=SQLITE_OK ) return rc;
 1.43683 +        }
 1.43684 +        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
 1.43685 +        rc = sqlite3OsWrite(
 1.43686 +            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
 1.43687 +        );
 1.43688 +        if( rc!=SQLITE_OK ) return rc;
 1.43689 +      }
 1.43690 +      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
 1.43691 +        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
 1.43692 +        IOTRACE(("JSYNC %p\n", pPager))
 1.43693 +        rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| 
 1.43694 +          (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
 1.43695 +        );
 1.43696 +        if( rc!=SQLITE_OK ) return rc;
 1.43697 +      }
 1.43698 +
 1.43699 +      pPager->journalHdr = pPager->journalOff;
 1.43700 +      if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
 1.43701 +        pPager->nRec = 0;
 1.43702 +        rc = writeJournalHdr(pPager);
 1.43703 +        if( rc!=SQLITE_OK ) return rc;
 1.43704 +      }
 1.43705 +    }else{
 1.43706 +      pPager->journalHdr = pPager->journalOff;
 1.43707 +    }
 1.43708 +  }
 1.43709 +
 1.43710 +  /* Unless the pager is in noSync mode, the journal file was just 
 1.43711 +  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on 
 1.43712 +  ** all pages.
 1.43713 +  */
 1.43714 +  sqlite3PcacheClearSyncFlags(pPager->pPCache);
 1.43715 +  pPager->eState = PAGER_WRITER_DBMOD;
 1.43716 +  assert( assert_pager_state(pPager) );
 1.43717 +  return SQLITE_OK;
 1.43718 +}
 1.43719 +
 1.43720 +/*
 1.43721 +** The argument is the first in a linked list of dirty pages connected
 1.43722 +** by the PgHdr.pDirty pointer. This function writes each one of the
 1.43723 +** in-memory pages in the list to the database file. The argument may
 1.43724 +** be NULL, representing an empty list. In this case this function is
 1.43725 +** a no-op.
 1.43726 +**
 1.43727 +** The pager must hold at least a RESERVED lock when this function
 1.43728 +** is called. Before writing anything to the database file, this lock
 1.43729 +** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
 1.43730 +** SQLITE_BUSY is returned and no data is written to the database file.
 1.43731 +** 
 1.43732 +** If the pager is a temp-file pager and the actual file-system file
 1.43733 +** is not yet open, it is created and opened before any data is 
 1.43734 +** written out.
 1.43735 +**
 1.43736 +** Once the lock has been upgraded and, if necessary, the file opened,
 1.43737 +** the pages are written out to the database file in list order. Writing
 1.43738 +** a page is skipped if it meets either of the following criteria:
 1.43739 +**
 1.43740 +**   * The page number is greater than Pager.dbSize, or
 1.43741 +**   * The PGHDR_DONT_WRITE flag is set on the page.
 1.43742 +**
 1.43743 +** If writing out a page causes the database file to grow, Pager.dbFileSize
 1.43744 +** is updated accordingly. If page 1 is written out, then the value cached
 1.43745 +** in Pager.dbFileVers[] is updated to match the new value stored in
 1.43746 +** the database file.
 1.43747 +**
 1.43748 +** If everything is successful, SQLITE_OK is returned. If an IO error 
 1.43749 +** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
 1.43750 +** be obtained, SQLITE_BUSY is returned.
 1.43751 +*/
 1.43752 +static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
 1.43753 +  int rc = SQLITE_OK;                  /* Return code */
 1.43754 +
 1.43755 +  /* This function is only called for rollback pagers in WRITER_DBMOD state. */
 1.43756 +  assert( !pagerUseWal(pPager) );
 1.43757 +  assert( pPager->eState==PAGER_WRITER_DBMOD );
 1.43758 +  assert( pPager->eLock==EXCLUSIVE_LOCK );
 1.43759 +
 1.43760 +  /* If the file is a temp-file has not yet been opened, open it now. It
 1.43761 +  ** is not possible for rc to be other than SQLITE_OK if this branch
 1.43762 +  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
 1.43763 +  */
 1.43764 +  if( !isOpen(pPager->fd) ){
 1.43765 +    assert( pPager->tempFile && rc==SQLITE_OK );
 1.43766 +    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
 1.43767 +  }
 1.43768 +
 1.43769 +  /* Before the first write, give the VFS a hint of what the final
 1.43770 +  ** file size will be.
 1.43771 +  */
 1.43772 +  assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
 1.43773 +  if( rc==SQLITE_OK 
 1.43774 +   && pPager->dbHintSize<pPager->dbSize
 1.43775 +   && (pList->pDirty || pList->pgno>pPager->dbHintSize)
 1.43776 +  ){
 1.43777 +    sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
 1.43778 +    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
 1.43779 +    pPager->dbHintSize = pPager->dbSize;
 1.43780 +  }
 1.43781 +
 1.43782 +  while( rc==SQLITE_OK && pList ){
 1.43783 +    Pgno pgno = pList->pgno;
 1.43784 +
 1.43785 +    /* If there are dirty pages in the page cache with page numbers greater
 1.43786 +    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
 1.43787 +    ** make the file smaller (presumably by auto-vacuum code). Do not write
 1.43788 +    ** any such pages to the file.
 1.43789 +    **
 1.43790 +    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
 1.43791 +    ** set (set by sqlite3PagerDontWrite()).
 1.43792 +    */
 1.43793 +    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
 1.43794 +      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
 1.43795 +      char *pData;                                   /* Data to write */    
 1.43796 +
 1.43797 +      assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
 1.43798 +      if( pList->pgno==1 ) pager_write_changecounter(pList);
 1.43799 +
 1.43800 +      /* Encode the database */
 1.43801 +      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
 1.43802 +
 1.43803 +      /* Write out the page data. */
 1.43804 +      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
 1.43805 +
 1.43806 +      /* If page 1 was just written, update Pager.dbFileVers to match
 1.43807 +      ** the value now stored in the database file. If writing this 
 1.43808 +      ** page caused the database file to grow, update dbFileSize. 
 1.43809 +      */
 1.43810 +      if( pgno==1 ){
 1.43811 +        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
 1.43812 +      }
 1.43813 +      if( pgno>pPager->dbFileSize ){
 1.43814 +        pPager->dbFileSize = pgno;
 1.43815 +      }
 1.43816 +      pPager->aStat[PAGER_STAT_WRITE]++;
 1.43817 +
 1.43818 +      /* Update any backup objects copying the contents of this pager. */
 1.43819 +      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
 1.43820 +
 1.43821 +      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
 1.43822 +                   PAGERID(pPager), pgno, pager_pagehash(pList)));
 1.43823 +      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
 1.43824 +      PAGER_INCR(sqlite3_pager_writedb_count);
 1.43825 +    }else{
 1.43826 +      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
 1.43827 +    }
 1.43828 +    pager_set_pagehash(pList);
 1.43829 +    pList = pList->pDirty;
 1.43830 +  }
 1.43831 +
 1.43832 +  return rc;
 1.43833 +}
 1.43834 +
 1.43835 +/*
 1.43836 +** Ensure that the sub-journal file is open. If it is already open, this 
 1.43837 +** function is a no-op.
 1.43838 +**
 1.43839 +** SQLITE_OK is returned if everything goes according to plan. An 
 1.43840 +** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
 1.43841 +** fails.
 1.43842 +*/
 1.43843 +static int openSubJournal(Pager *pPager){
 1.43844 +  int rc = SQLITE_OK;
 1.43845 +  if( !isOpen(pPager->sjfd) ){
 1.43846 +    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
 1.43847 +      sqlite3MemJournalOpen(pPager->sjfd);
 1.43848 +    }else{
 1.43849 +      rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
 1.43850 +    }
 1.43851 +  }
 1.43852 +  return rc;
 1.43853 +}
 1.43854 +
 1.43855 +/*
 1.43856 +** Append a record of the current state of page pPg to the sub-journal. 
 1.43857 +** It is the callers responsibility to use subjRequiresPage() to check 
 1.43858 +** that it is really required before calling this function.
 1.43859 +**
 1.43860 +** If successful, set the bit corresponding to pPg->pgno in the bitvecs
 1.43861 +** for all open savepoints before returning.
 1.43862 +**
 1.43863 +** This function returns SQLITE_OK if everything is successful, an IO
 1.43864 +** error code if the attempt to write to the sub-journal fails, or 
 1.43865 +** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
 1.43866 +** bitvec.
 1.43867 +*/
 1.43868 +static int subjournalPage(PgHdr *pPg){
 1.43869 +  int rc = SQLITE_OK;
 1.43870 +  Pager *pPager = pPg->pPager;
 1.43871 +  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
 1.43872 +
 1.43873 +    /* Open the sub-journal, if it has not already been opened */
 1.43874 +    assert( pPager->useJournal );
 1.43875 +    assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
 1.43876 +    assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
 1.43877 +    assert( pagerUseWal(pPager) 
 1.43878 +         || pageInJournal(pPager, pPg) 
 1.43879 +         || pPg->pgno>pPager->dbOrigSize 
 1.43880 +    );
 1.43881 +    rc = openSubJournal(pPager);
 1.43882 +
 1.43883 +    /* If the sub-journal was opened successfully (or was already open),
 1.43884 +    ** write the journal record into the file.  */
 1.43885 +    if( rc==SQLITE_OK ){
 1.43886 +      void *pData = pPg->pData;
 1.43887 +      i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
 1.43888 +      char *pData2;
 1.43889 +  
 1.43890 +      CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
 1.43891 +      PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
 1.43892 +      rc = write32bits(pPager->sjfd, offset, pPg->pgno);
 1.43893 +      if( rc==SQLITE_OK ){
 1.43894 +        rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
 1.43895 +      }
 1.43896 +    }
 1.43897 +  }
 1.43898 +  if( rc==SQLITE_OK ){
 1.43899 +    pPager->nSubRec++;
 1.43900 +    assert( pPager->nSavepoint>0 );
 1.43901 +    rc = addToSavepointBitvecs(pPager, pPg->pgno);
 1.43902 +  }
 1.43903 +  return rc;
 1.43904 +}
 1.43905 +
 1.43906 +/*
 1.43907 +** This function is called by the pcache layer when it has reached some
 1.43908 +** soft memory limit. The first argument is a pointer to a Pager object
 1.43909 +** (cast as a void*). The pager is always 'purgeable' (not an in-memory
 1.43910 +** database). The second argument is a reference to a page that is 
 1.43911 +** currently dirty but has no outstanding references. The page
 1.43912 +** is always associated with the Pager object passed as the first 
 1.43913 +** argument.
 1.43914 +**
 1.43915 +** The job of this function is to make pPg clean by writing its contents
 1.43916 +** out to the database file, if possible. This may involve syncing the
 1.43917 +** journal file. 
 1.43918 +**
 1.43919 +** If successful, sqlite3PcacheMakeClean() is called on the page and
 1.43920 +** SQLITE_OK returned. If an IO error occurs while trying to make the
 1.43921 +** page clean, the IO error code is returned. If the page cannot be
 1.43922 +** made clean for some other reason, but no error occurs, then SQLITE_OK
 1.43923 +** is returned by sqlite3PcacheMakeClean() is not called.
 1.43924 +*/
 1.43925 +static int pagerStress(void *p, PgHdr *pPg){
 1.43926 +  Pager *pPager = (Pager *)p;
 1.43927 +  int rc = SQLITE_OK;
 1.43928 +
 1.43929 +  assert( pPg->pPager==pPager );
 1.43930 +  assert( pPg->flags&PGHDR_DIRTY );
 1.43931 +
 1.43932 +  /* The doNotSpill NOSYNC bit is set during times when doing a sync of
 1.43933 +  ** journal (and adding a new header) is not allowed.  This occurs
 1.43934 +  ** during calls to sqlite3PagerWrite() while trying to journal multiple
 1.43935 +  ** pages belonging to the same sector.
 1.43936 +  **
 1.43937 +  ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
 1.43938 +  ** regardless of whether or not a sync is required.  This is set during
 1.43939 +  ** a rollback or by user request, respectively.
 1.43940 +  **
 1.43941 +  ** Spilling is also prohibited when in an error state since that could
 1.43942 +  ** lead to database corruption.   In the current implementaton it 
 1.43943 +  ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
 1.43944 +  ** while in the error state, hence it is impossible for this routine to
 1.43945 +  ** be called in the error state.  Nevertheless, we include a NEVER()
 1.43946 +  ** test for the error state as a safeguard against future changes.
 1.43947 +  */
 1.43948 +  if( NEVER(pPager->errCode) ) return SQLITE_OK;
 1.43949 +  testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
 1.43950 +  testcase( pPager->doNotSpill & SPILLFLAG_OFF );
 1.43951 +  testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
 1.43952 +  if( pPager->doNotSpill
 1.43953 +   && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
 1.43954 +      || (pPg->flags & PGHDR_NEED_SYNC)!=0)
 1.43955 +  ){
 1.43956 +    return SQLITE_OK;
 1.43957 +  }
 1.43958 +
 1.43959 +  pPg->pDirty = 0;
 1.43960 +  if( pagerUseWal(pPager) ){
 1.43961 +    /* Write a single frame for this page to the log. */
 1.43962 +    if( subjRequiresPage(pPg) ){ 
 1.43963 +      rc = subjournalPage(pPg); 
 1.43964 +    }
 1.43965 +    if( rc==SQLITE_OK ){
 1.43966 +      rc = pagerWalFrames(pPager, pPg, 0, 0);
 1.43967 +    }
 1.43968 +  }else{
 1.43969 +  
 1.43970 +    /* Sync the journal file if required. */
 1.43971 +    if( pPg->flags&PGHDR_NEED_SYNC 
 1.43972 +     || pPager->eState==PAGER_WRITER_CACHEMOD
 1.43973 +    ){
 1.43974 +      rc = syncJournal(pPager, 1);
 1.43975 +    }
 1.43976 +  
 1.43977 +    /* If the page number of this page is larger than the current size of
 1.43978 +    ** the database image, it may need to be written to the sub-journal.
 1.43979 +    ** This is because the call to pager_write_pagelist() below will not
 1.43980 +    ** actually write data to the file in this case.
 1.43981 +    **
 1.43982 +    ** Consider the following sequence of events:
 1.43983 +    **
 1.43984 +    **   BEGIN;
 1.43985 +    **     <journal page X>
 1.43986 +    **     <modify page X>
 1.43987 +    **     SAVEPOINT sp;
 1.43988 +    **       <shrink database file to Y pages>
 1.43989 +    **       pagerStress(page X)
 1.43990 +    **     ROLLBACK TO sp;
 1.43991 +    **
 1.43992 +    ** If (X>Y), then when pagerStress is called page X will not be written
 1.43993 +    ** out to the database file, but will be dropped from the cache. Then,
 1.43994 +    ** following the "ROLLBACK TO sp" statement, reading page X will read
 1.43995 +    ** data from the database file. This will be the copy of page X as it
 1.43996 +    ** was when the transaction started, not as it was when "SAVEPOINT sp"
 1.43997 +    ** was executed.
 1.43998 +    **
 1.43999 +    ** The solution is to write the current data for page X into the 
 1.44000 +    ** sub-journal file now (if it is not already there), so that it will
 1.44001 +    ** be restored to its current value when the "ROLLBACK TO sp" is 
 1.44002 +    ** executed.
 1.44003 +    */
 1.44004 +    if( NEVER(
 1.44005 +        rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
 1.44006 +    ) ){
 1.44007 +      rc = subjournalPage(pPg);
 1.44008 +    }
 1.44009 +  
 1.44010 +    /* Write the contents of the page out to the database file. */
 1.44011 +    if( rc==SQLITE_OK ){
 1.44012 +      assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
 1.44013 +      rc = pager_write_pagelist(pPager, pPg);
 1.44014 +    }
 1.44015 +  }
 1.44016 +
 1.44017 +  /* Mark the page as clean. */
 1.44018 +  if( rc==SQLITE_OK ){
 1.44019 +    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
 1.44020 +    sqlite3PcacheMakeClean(pPg);
 1.44021 +  }
 1.44022 +
 1.44023 +  return pager_error(pPager, rc); 
 1.44024 +}
 1.44025 +
 1.44026 +
 1.44027 +/*
 1.44028 +** Allocate and initialize a new Pager object and put a pointer to it
 1.44029 +** in *ppPager. The pager should eventually be freed by passing it
 1.44030 +** to sqlite3PagerClose().
 1.44031 +**
 1.44032 +** The zFilename argument is the path to the database file to open.
 1.44033 +** If zFilename is NULL then a randomly-named temporary file is created
 1.44034 +** and used as the file to be cached. Temporary files are be deleted
 1.44035 +** automatically when they are closed. If zFilename is ":memory:" then 
 1.44036 +** all information is held in cache. It is never written to disk. 
 1.44037 +** This can be used to implement an in-memory database.
 1.44038 +**
 1.44039 +** The nExtra parameter specifies the number of bytes of space allocated
 1.44040 +** along with each page reference. This space is available to the user
 1.44041 +** via the sqlite3PagerGetExtra() API.
 1.44042 +**
 1.44043 +** The flags argument is used to specify properties that affect the
 1.44044 +** operation of the pager. It should be passed some bitwise combination
 1.44045 +** of the PAGER_* flags.
 1.44046 +**
 1.44047 +** The vfsFlags parameter is a bitmask to pass to the flags parameter
 1.44048 +** of the xOpen() method of the supplied VFS when opening files. 
 1.44049 +**
 1.44050 +** If the pager object is allocated and the specified file opened 
 1.44051 +** successfully, SQLITE_OK is returned and *ppPager set to point to
 1.44052 +** the new pager object. If an error occurs, *ppPager is set to NULL
 1.44053 +** and error code returned. This function may return SQLITE_NOMEM
 1.44054 +** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
 1.44055 +** various SQLITE_IO_XXX errors.
 1.44056 +*/
 1.44057 +SQLITE_PRIVATE int sqlite3PagerOpen(
 1.44058 +  sqlite3_vfs *pVfs,       /* The virtual file system to use */
 1.44059 +  Pager **ppPager,         /* OUT: Return the Pager structure here */
 1.44060 +  const char *zFilename,   /* Name of the database file to open */
 1.44061 +  int nExtra,              /* Extra bytes append to each in-memory page */
 1.44062 +  int flags,               /* flags controlling this file */
 1.44063 +  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
 1.44064 +  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
 1.44065 +){
 1.44066 +  u8 *pPtr;
 1.44067 +  Pager *pPager = 0;       /* Pager object to allocate and return */
 1.44068 +  int rc = SQLITE_OK;      /* Return code */
 1.44069 +  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
 1.44070 +  int memDb = 0;           /* True if this is an in-memory file */
 1.44071 +  int readOnly = 0;        /* True if this is a read-only file */
 1.44072 +  int journalFileSize;     /* Bytes to allocate for each journal fd */
 1.44073 +  char *zPathname = 0;     /* Full path to database file */
 1.44074 +  int nPathname = 0;       /* Number of bytes in zPathname */
 1.44075 +  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
 1.44076 +  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
 1.44077 +  u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
 1.44078 +  const char *zUri = 0;    /* URI args to copy */
 1.44079 +  int nUri = 0;            /* Number of bytes of URI args at *zUri */
 1.44080 +
 1.44081 +  /* Figure out how much space is required for each journal file-handle
 1.44082 +  ** (there are two of them, the main journal and the sub-journal). This
 1.44083 +  ** is the maximum space required for an in-memory journal file handle 
 1.44084 +  ** and a regular journal file-handle. Note that a "regular journal-handle"
 1.44085 +  ** may be a wrapper capable of caching the first portion of the journal
 1.44086 +  ** file in memory to implement the atomic-write optimization (see 
 1.44087 +  ** source file journal.c).
 1.44088 +  */
 1.44089 +  if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
 1.44090 +    journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
 1.44091 +  }else{
 1.44092 +    journalFileSize = ROUND8(sqlite3MemJournalSize());
 1.44093 +  }
 1.44094 +
 1.44095 +  /* Set the output variable to NULL in case an error occurs. */
 1.44096 +  *ppPager = 0;
 1.44097 +
 1.44098 +#ifndef SQLITE_OMIT_MEMORYDB
 1.44099 +  if( flags & PAGER_MEMORY ){
 1.44100 +    memDb = 1;
 1.44101 +    if( zFilename && zFilename[0] ){
 1.44102 +      zPathname = sqlite3DbStrDup(0, zFilename);
 1.44103 +      if( zPathname==0  ) return SQLITE_NOMEM;
 1.44104 +      nPathname = sqlite3Strlen30(zPathname);
 1.44105 +      zFilename = 0;
 1.44106 +    }
 1.44107 +  }
 1.44108 +#endif
 1.44109 +
 1.44110 +  /* Compute and store the full pathname in an allocated buffer pointed
 1.44111 +  ** to by zPathname, length nPathname. Or, if this is a temporary file,
 1.44112 +  ** leave both nPathname and zPathname set to 0.
 1.44113 +  */
 1.44114 +  if( zFilename && zFilename[0] ){
 1.44115 +    const char *z;
 1.44116 +    nPathname = pVfs->mxPathname+1;
 1.44117 +    zPathname = sqlite3DbMallocRaw(0, nPathname*2);
 1.44118 +    if( zPathname==0 ){
 1.44119 +      return SQLITE_NOMEM;
 1.44120 +    }
 1.44121 +    zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
 1.44122 +    rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
 1.44123 +    nPathname = sqlite3Strlen30(zPathname);
 1.44124 +    z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
 1.44125 +    while( *z ){
 1.44126 +      z += sqlite3Strlen30(z)+1;
 1.44127 +      z += sqlite3Strlen30(z)+1;
 1.44128 +    }
 1.44129 +    nUri = (int)(&z[1] - zUri);
 1.44130 +    assert( nUri>=0 );
 1.44131 +    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
 1.44132 +      /* This branch is taken when the journal path required by
 1.44133 +      ** the database being opened will be more than pVfs->mxPathname
 1.44134 +      ** bytes in length. This means the database cannot be opened,
 1.44135 +      ** as it will not be possible to open the journal file or even
 1.44136 +      ** check for a hot-journal before reading.
 1.44137 +      */
 1.44138 +      rc = SQLITE_CANTOPEN_BKPT;
 1.44139 +    }
 1.44140 +    if( rc!=SQLITE_OK ){
 1.44141 +      sqlite3DbFree(0, zPathname);
 1.44142 +      return rc;
 1.44143 +    }
 1.44144 +  }
 1.44145 +
 1.44146 +  /* Allocate memory for the Pager structure, PCache object, the
 1.44147 +  ** three file descriptors, the database file name and the journal 
 1.44148 +  ** file name. The layout in memory is as follows:
 1.44149 +  **
 1.44150 +  **     Pager object                    (sizeof(Pager) bytes)
 1.44151 +  **     PCache object                   (sqlite3PcacheSize() bytes)
 1.44152 +  **     Database file handle            (pVfs->szOsFile bytes)
 1.44153 +  **     Sub-journal file handle         (journalFileSize bytes)
 1.44154 +  **     Main journal file handle        (journalFileSize bytes)
 1.44155 +  **     Database file name              (nPathname+1 bytes)
 1.44156 +  **     Journal file name               (nPathname+8+1 bytes)
 1.44157 +  */
 1.44158 +  pPtr = (u8 *)sqlite3MallocZero(
 1.44159 +    ROUND8(sizeof(*pPager)) +      /* Pager structure */
 1.44160 +    ROUND8(pcacheSize) +           /* PCache object */
 1.44161 +    ROUND8(pVfs->szOsFile) +       /* The main db file */
 1.44162 +    journalFileSize * 2 +          /* The two journal files */ 
 1.44163 +    nPathname + 1 + nUri +         /* zFilename */
 1.44164 +    nPathname + 8 + 2              /* zJournal */
 1.44165 +#ifndef SQLITE_OMIT_WAL
 1.44166 +    + nPathname + 4 + 2            /* zWal */
 1.44167 +#endif
 1.44168 +  );
 1.44169 +  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
 1.44170 +  if( !pPtr ){
 1.44171 +    sqlite3DbFree(0, zPathname);
 1.44172 +    return SQLITE_NOMEM;
 1.44173 +  }
 1.44174 +  pPager =              (Pager*)(pPtr);
 1.44175 +  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
 1.44176 +  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
 1.44177 +  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
 1.44178 +  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
 1.44179 +  pPager->zFilename =    (char*)(pPtr += journalFileSize);
 1.44180 +  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
 1.44181 +
 1.44182 +  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
 1.44183 +  if( zPathname ){
 1.44184 +    assert( nPathname>0 );
 1.44185 +    pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
 1.44186 +    memcpy(pPager->zFilename, zPathname, nPathname);
 1.44187 +    if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
 1.44188 +    memcpy(pPager->zJournal, zPathname, nPathname);
 1.44189 +    memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
 1.44190 +    sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
 1.44191 +#ifndef SQLITE_OMIT_WAL
 1.44192 +    pPager->zWal = &pPager->zJournal[nPathname+8+1];
 1.44193 +    memcpy(pPager->zWal, zPathname, nPathname);
 1.44194 +    memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
 1.44195 +    sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
 1.44196 +#endif
 1.44197 +    sqlite3DbFree(0, zPathname);
 1.44198 +  }
 1.44199 +  pPager->pVfs = pVfs;
 1.44200 +  pPager->vfsFlags = vfsFlags;
 1.44201 +
 1.44202 +  /* Open the pager file.
 1.44203 +  */
 1.44204 +  if( zFilename && zFilename[0] ){
 1.44205 +    int fout = 0;                    /* VFS flags returned by xOpen() */
 1.44206 +    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
 1.44207 +    assert( !memDb );
 1.44208 +    readOnly = (fout&SQLITE_OPEN_READONLY);
 1.44209 +
 1.44210 +    /* If the file was successfully opened for read/write access,
 1.44211 +    ** choose a default page size in case we have to create the
 1.44212 +    ** database file. The default page size is the maximum of:
 1.44213 +    **
 1.44214 +    **    + SQLITE_DEFAULT_PAGE_SIZE,
 1.44215 +    **    + The value returned by sqlite3OsSectorSize()
 1.44216 +    **    + The largest page size that can be written atomically.
 1.44217 +    */
 1.44218 +    if( rc==SQLITE_OK && !readOnly ){
 1.44219 +      setSectorSize(pPager);
 1.44220 +      assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
 1.44221 +      if( szPageDflt<pPager->sectorSize ){
 1.44222 +        if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
 1.44223 +          szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
 1.44224 +        }else{
 1.44225 +          szPageDflt = (u32)pPager->sectorSize;
 1.44226 +        }
 1.44227 +      }
 1.44228 +#ifdef SQLITE_ENABLE_ATOMIC_WRITE
 1.44229 +      {
 1.44230 +        int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
 1.44231 +        int ii;
 1.44232 +        assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
 1.44233 +        assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
 1.44234 +        assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
 1.44235 +        for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
 1.44236 +          if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
 1.44237 +            szPageDflt = ii;
 1.44238 +          }
 1.44239 +        }
 1.44240 +      }
 1.44241 +#endif
 1.44242 +    }
 1.44243 +  }else{
 1.44244 +    /* If a temporary file is requested, it is not opened immediately.
 1.44245 +    ** In this case we accept the default page size and delay actually
 1.44246 +    ** opening the file until the first call to OsWrite().
 1.44247 +    **
 1.44248 +    ** This branch is also run for an in-memory database. An in-memory
 1.44249 +    ** database is the same as a temp-file that is never written out to
 1.44250 +    ** disk and uses an in-memory rollback journal.
 1.44251 +    */ 
 1.44252 +    tempFile = 1;
 1.44253 +    pPager->eState = PAGER_READER;
 1.44254 +    pPager->eLock = EXCLUSIVE_LOCK;
 1.44255 +    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
 1.44256 +  }
 1.44257 +
 1.44258 +  /* The following call to PagerSetPagesize() serves to set the value of 
 1.44259 +  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
 1.44260 +  */
 1.44261 +  if( rc==SQLITE_OK ){
 1.44262 +    assert( pPager->memDb==0 );
 1.44263 +    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
 1.44264 +    testcase( rc!=SQLITE_OK );
 1.44265 +  }
 1.44266 +
 1.44267 +  /* If an error occurred in either of the blocks above, free the 
 1.44268 +  ** Pager structure and close the file.
 1.44269 +  */
 1.44270 +  if( rc!=SQLITE_OK ){
 1.44271 +    assert( !pPager->pTmpSpace );
 1.44272 +    sqlite3OsClose(pPager->fd);
 1.44273 +    sqlite3_free(pPager);
 1.44274 +    return rc;
 1.44275 +  }
 1.44276 +
 1.44277 +  /* Initialize the PCache object. */
 1.44278 +  assert( nExtra<1000 );
 1.44279 +  nExtra = ROUND8(nExtra);
 1.44280 +  sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
 1.44281 +                    !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
 1.44282 +
 1.44283 +  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
 1.44284 +  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
 1.44285 +
 1.44286 +  pPager->useJournal = (u8)useJournal;
 1.44287 +  /* pPager->stmtOpen = 0; */
 1.44288 +  /* pPager->stmtInUse = 0; */
 1.44289 +  /* pPager->nRef = 0; */
 1.44290 +  /* pPager->stmtSize = 0; */
 1.44291 +  /* pPager->stmtJSize = 0; */
 1.44292 +  /* pPager->nPage = 0; */
 1.44293 +  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
 1.44294 +  /* pPager->state = PAGER_UNLOCK; */
 1.44295 +#if 0
 1.44296 +  assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
 1.44297 +#endif
 1.44298 +  /* pPager->errMask = 0; */
 1.44299 +  pPager->tempFile = (u8)tempFile;
 1.44300 +  assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
 1.44301 +          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
 1.44302 +  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
 1.44303 +  pPager->exclusiveMode = (u8)tempFile; 
 1.44304 +  pPager->changeCountDone = pPager->tempFile;
 1.44305 +  pPager->memDb = (u8)memDb;
 1.44306 +  pPager->readOnly = (u8)readOnly;
 1.44307 +  assert( useJournal || pPager->tempFile );
 1.44308 +  pPager->noSync = pPager->tempFile;
 1.44309 +  if( pPager->noSync ){
 1.44310 +    assert( pPager->fullSync==0 );
 1.44311 +    assert( pPager->syncFlags==0 );
 1.44312 +    assert( pPager->walSyncFlags==0 );
 1.44313 +    assert( pPager->ckptSyncFlags==0 );
 1.44314 +  }else{
 1.44315 +    pPager->fullSync = 1;
 1.44316 +    pPager->syncFlags = SQLITE_SYNC_NORMAL;
 1.44317 +    pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
 1.44318 +    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
 1.44319 +  }
 1.44320 +  /* pPager->pFirst = 0; */
 1.44321 +  /* pPager->pFirstSynced = 0; */
 1.44322 +  /* pPager->pLast = 0; */
 1.44323 +  pPager->nExtra = (u16)nExtra;
 1.44324 +  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
 1.44325 +  assert( isOpen(pPager->fd) || tempFile );
 1.44326 +  setSectorSize(pPager);
 1.44327 +  if( !useJournal ){
 1.44328 +    pPager->journalMode = PAGER_JOURNALMODE_OFF;
 1.44329 +  }else if( memDb ){
 1.44330 +    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
 1.44331 +  }
 1.44332 +  /* pPager->xBusyHandler = 0; */
 1.44333 +  /* pPager->pBusyHandlerArg = 0; */
 1.44334 +  pPager->xReiniter = xReinit;
 1.44335 +  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
 1.44336 +  /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
 1.44337 +
 1.44338 +  *ppPager = pPager;
 1.44339 +  return SQLITE_OK;
 1.44340 +}
 1.44341 +
 1.44342 +
 1.44343 +/* Verify that the database file has not be deleted or renamed out from
 1.44344 +** under the pager.  Return SQLITE_OK if the database is still were it ought
 1.44345 +** to be on disk.  Return non-zero (SQLITE_READONLY_DBMOVED or some other error
 1.44346 +** code from sqlite3OsAccess()) if the database has gone missing.
 1.44347 +*/
 1.44348 +static int databaseIsUnmoved(Pager *pPager){
 1.44349 +  int bHasMoved = 0;
 1.44350 +  int rc;
 1.44351 +
 1.44352 +  if( pPager->tempFile ) return SQLITE_OK;
 1.44353 +  if( pPager->dbSize==0 ) return SQLITE_OK;
 1.44354 +  assert( pPager->zFilename && pPager->zFilename[0] );
 1.44355 +  rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
 1.44356 +  if( rc==SQLITE_NOTFOUND ){
 1.44357 +    /* If the HAS_MOVED file-control is unimplemented, assume that the file
 1.44358 +    ** has not been moved.  That is the historical behavior of SQLite: prior to
 1.44359 +    ** version 3.8.3, it never checked */
 1.44360 +    rc = SQLITE_OK;
 1.44361 +  }else if( rc==SQLITE_OK && bHasMoved ){
 1.44362 +    rc = SQLITE_READONLY_DBMOVED;
 1.44363 +  }
 1.44364 +  return rc;
 1.44365 +}
 1.44366 +
 1.44367 +
 1.44368 +/*
 1.44369 +** This function is called after transitioning from PAGER_UNLOCK to
 1.44370 +** PAGER_SHARED state. It tests if there is a hot journal present in
 1.44371 +** the file-system for the given pager. A hot journal is one that 
 1.44372 +** needs to be played back. According to this function, a hot-journal
 1.44373 +** file exists if the following criteria are met:
 1.44374 +**
 1.44375 +**   * The journal file exists in the file system, and
 1.44376 +**   * No process holds a RESERVED or greater lock on the database file, and
 1.44377 +**   * The database file itself is greater than 0 bytes in size, and
 1.44378 +**   * The first byte of the journal file exists and is not 0x00.
 1.44379 +**
 1.44380 +** If the current size of the database file is 0 but a journal file
 1.44381 +** exists, that is probably an old journal left over from a prior
 1.44382 +** database with the same name. In this case the journal file is
 1.44383 +** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
 1.44384 +** is returned.
 1.44385 +**
 1.44386 +** This routine does not check if there is a master journal filename
 1.44387 +** at the end of the file. If there is, and that master journal file
 1.44388 +** does not exist, then the journal file is not really hot. In this
 1.44389 +** case this routine will return a false-positive. The pager_playback()
 1.44390 +** routine will discover that the journal file is not really hot and 
 1.44391 +** will not roll it back. 
 1.44392 +**
 1.44393 +** If a hot-journal file is found to exist, *pExists is set to 1 and 
 1.44394 +** SQLITE_OK returned. If no hot-journal file is present, *pExists is
 1.44395 +** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
 1.44396 +** to determine whether or not a hot-journal file exists, the IO error
 1.44397 +** code is returned and the value of *pExists is undefined.
 1.44398 +*/
 1.44399 +static int hasHotJournal(Pager *pPager, int *pExists){
 1.44400 +  sqlite3_vfs * const pVfs = pPager->pVfs;
 1.44401 +  int rc = SQLITE_OK;           /* Return code */
 1.44402 +  int exists = 1;               /* True if a journal file is present */
 1.44403 +  int jrnlOpen = !!isOpen(pPager->jfd);
 1.44404 +
 1.44405 +  assert( pPager->useJournal );
 1.44406 +  assert( isOpen(pPager->fd) );
 1.44407 +  assert( pPager->eState==PAGER_OPEN );
 1.44408 +
 1.44409 +  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
 1.44410 +    SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
 1.44411 +  ));
 1.44412 +
 1.44413 +  *pExists = 0;
 1.44414 +  if( !jrnlOpen ){
 1.44415 +    rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
 1.44416 +  }
 1.44417 +  if( rc==SQLITE_OK && exists ){
 1.44418 +    int locked = 0;             /* True if some process holds a RESERVED lock */
 1.44419 +
 1.44420 +    /* Race condition here:  Another process might have been holding the
 1.44421 +    ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
 1.44422 +    ** call above, but then delete the journal and drop the lock before
 1.44423 +    ** we get to the following sqlite3OsCheckReservedLock() call.  If that
 1.44424 +    ** is the case, this routine might think there is a hot journal when
 1.44425 +    ** in fact there is none.  This results in a false-positive which will
 1.44426 +    ** be dealt with by the playback routine.  Ticket #3883.
 1.44427 +    */
 1.44428 +    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
 1.44429 +    if( rc==SQLITE_OK && !locked ){
 1.44430 +      Pgno nPage;                 /* Number of pages in database file */
 1.44431 +
 1.44432 +      rc = pagerPagecount(pPager, &nPage);
 1.44433 +      if( rc==SQLITE_OK ){
 1.44434 +        /* If the database is zero pages in size, that means that either (1) the
 1.44435 +        ** journal is a remnant from a prior database with the same name where
 1.44436 +        ** the database file but not the journal was deleted, or (2) the initial
 1.44437 +        ** transaction that populates a new database is being rolled back.
 1.44438 +        ** In either case, the journal file can be deleted.  However, take care
 1.44439 +        ** not to delete the journal file if it is already open due to
 1.44440 +        ** journal_mode=PERSIST.
 1.44441 +        */
 1.44442 +        if( nPage==0 && !jrnlOpen ){
 1.44443 +          sqlite3BeginBenignMalloc();
 1.44444 +          if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
 1.44445 +            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
 1.44446 +            if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
 1.44447 +          }
 1.44448 +          sqlite3EndBenignMalloc();
 1.44449 +        }else{
 1.44450 +          /* The journal file exists and no other connection has a reserved
 1.44451 +          ** or greater lock on the database file. Now check that there is
 1.44452 +          ** at least one non-zero bytes at the start of the journal file.
 1.44453 +          ** If there is, then we consider this journal to be hot. If not, 
 1.44454 +          ** it can be ignored.
 1.44455 +          */
 1.44456 +          if( !jrnlOpen ){
 1.44457 +            int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
 1.44458 +            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
 1.44459 +          }
 1.44460 +          if( rc==SQLITE_OK ){
 1.44461 +            u8 first = 0;
 1.44462 +            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
 1.44463 +            if( rc==SQLITE_IOERR_SHORT_READ ){
 1.44464 +              rc = SQLITE_OK;
 1.44465 +            }
 1.44466 +            if( !jrnlOpen ){
 1.44467 +              sqlite3OsClose(pPager->jfd);
 1.44468 +            }
 1.44469 +            *pExists = (first!=0);
 1.44470 +          }else if( rc==SQLITE_CANTOPEN ){
 1.44471 +            /* If we cannot open the rollback journal file in order to see if
 1.44472 +            ** its has a zero header, that might be due to an I/O error, or
 1.44473 +            ** it might be due to the race condition described above and in
 1.44474 +            ** ticket #3883.  Either way, assume that the journal is hot.
 1.44475 +            ** This might be a false positive.  But if it is, then the
 1.44476 +            ** automatic journal playback and recovery mechanism will deal
 1.44477 +            ** with it under an EXCLUSIVE lock where we do not need to
 1.44478 +            ** worry so much with race conditions.
 1.44479 +            */
 1.44480 +            *pExists = 1;
 1.44481 +            rc = SQLITE_OK;
 1.44482 +          }
 1.44483 +        }
 1.44484 +      }
 1.44485 +    }
 1.44486 +  }
 1.44487 +
 1.44488 +  return rc;
 1.44489 +}
 1.44490 +
 1.44491 +/*
 1.44492 +** This function is called to obtain a shared lock on the database file.
 1.44493 +** It is illegal to call sqlite3PagerAcquire() until after this function
 1.44494 +** has been successfully called. If a shared-lock is already held when
 1.44495 +** this function is called, it is a no-op.
 1.44496 +**
 1.44497 +** The following operations are also performed by this function.
 1.44498 +**
 1.44499 +**   1) If the pager is currently in PAGER_OPEN state (no lock held
 1.44500 +**      on the database file), then an attempt is made to obtain a
 1.44501 +**      SHARED lock on the database file. Immediately after obtaining
 1.44502 +**      the SHARED lock, the file-system is checked for a hot-journal,
 1.44503 +**      which is played back if present. Following any hot-journal 
 1.44504 +**      rollback, the contents of the cache are validated by checking
 1.44505 +**      the 'change-counter' field of the database file header and
 1.44506 +**      discarded if they are found to be invalid.
 1.44507 +**
 1.44508 +**   2) If the pager is running in exclusive-mode, and there are currently
 1.44509 +**      no outstanding references to any pages, and is in the error state,
 1.44510 +**      then an attempt is made to clear the error state by discarding
 1.44511 +**      the contents of the page cache and rolling back any open journal
 1.44512 +**      file.
 1.44513 +**
 1.44514 +** If everything is successful, SQLITE_OK is returned. If an IO error 
 1.44515 +** occurs while locking the database, checking for a hot-journal file or 
 1.44516 +** rolling back a journal file, the IO error code is returned.
 1.44517 +*/
 1.44518 +SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
 1.44519 +  int rc = SQLITE_OK;                /* Return code */
 1.44520 +
 1.44521 +  /* This routine is only called from b-tree and only when there are no
 1.44522 +  ** outstanding pages. This implies that the pager state should either
 1.44523 +  ** be OPEN or READER. READER is only possible if the pager is or was in 
 1.44524 +  ** exclusive access mode.
 1.44525 +  */
 1.44526 +  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
 1.44527 +  assert( assert_pager_state(pPager) );
 1.44528 +  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
 1.44529 +  if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
 1.44530 +
 1.44531 +  if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
 1.44532 +    int bHotJournal = 1;          /* True if there exists a hot journal-file */
 1.44533 +
 1.44534 +    assert( !MEMDB );
 1.44535 +
 1.44536 +    rc = pager_wait_on_lock(pPager, SHARED_LOCK);
 1.44537 +    if( rc!=SQLITE_OK ){
 1.44538 +      assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
 1.44539 +      goto failed;
 1.44540 +    }
 1.44541 +
 1.44542 +    /* If a journal file exists, and there is no RESERVED lock on the
 1.44543 +    ** database file, then it either needs to be played back or deleted.
 1.44544 +    */
 1.44545 +    if( pPager->eLock<=SHARED_LOCK ){
 1.44546 +      rc = hasHotJournal(pPager, &bHotJournal);
 1.44547 +    }
 1.44548 +    if( rc!=SQLITE_OK ){
 1.44549 +      goto failed;
 1.44550 +    }
 1.44551 +    if( bHotJournal ){
 1.44552 +      if( pPager->readOnly ){
 1.44553 +        rc = SQLITE_READONLY_ROLLBACK;
 1.44554 +        goto failed;
 1.44555 +      }
 1.44556 +
 1.44557 +      /* Get an EXCLUSIVE lock on the database file. At this point it is
 1.44558 +      ** important that a RESERVED lock is not obtained on the way to the
 1.44559 +      ** EXCLUSIVE lock. If it were, another process might open the
 1.44560 +      ** database file, detect the RESERVED lock, and conclude that the
 1.44561 +      ** database is safe to read while this process is still rolling the 
 1.44562 +      ** hot-journal back.
 1.44563 +      ** 
 1.44564 +      ** Because the intermediate RESERVED lock is not requested, any
 1.44565 +      ** other process attempting to access the database file will get to 
 1.44566 +      ** this point in the code and fail to obtain its own EXCLUSIVE lock 
 1.44567 +      ** on the database file.
 1.44568 +      **
 1.44569 +      ** Unless the pager is in locking_mode=exclusive mode, the lock is
 1.44570 +      ** downgraded to SHARED_LOCK before this function returns.
 1.44571 +      */
 1.44572 +      rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
 1.44573 +      if( rc!=SQLITE_OK ){
 1.44574 +        goto failed;
 1.44575 +      }
 1.44576 + 
 1.44577 +      /* If it is not already open and the file exists on disk, open the 
 1.44578 +      ** journal for read/write access. Write access is required because 
 1.44579 +      ** in exclusive-access mode the file descriptor will be kept open 
 1.44580 +      ** and possibly used for a transaction later on. Also, write-access 
 1.44581 +      ** is usually required to finalize the journal in journal_mode=persist 
 1.44582 +      ** mode (and also for journal_mode=truncate on some systems).
 1.44583 +      **
 1.44584 +      ** If the journal does not exist, it usually means that some 
 1.44585 +      ** other connection managed to get in and roll it back before 
 1.44586 +      ** this connection obtained the exclusive lock above. Or, it 
 1.44587 +      ** may mean that the pager was in the error-state when this
 1.44588 +      ** function was called and the journal file does not exist.
 1.44589 +      */
 1.44590 +      if( !isOpen(pPager->jfd) ){
 1.44591 +        sqlite3_vfs * const pVfs = pPager->pVfs;
 1.44592 +        int bExists;              /* True if journal file exists */
 1.44593 +        rc = sqlite3OsAccess(
 1.44594 +            pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
 1.44595 +        if( rc==SQLITE_OK && bExists ){
 1.44596 +          int fout = 0;
 1.44597 +          int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
 1.44598 +          assert( !pPager->tempFile );
 1.44599 +          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
 1.44600 +          assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
 1.44601 +          if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
 1.44602 +            rc = SQLITE_CANTOPEN_BKPT;
 1.44603 +            sqlite3OsClose(pPager->jfd);
 1.44604 +          }
 1.44605 +        }
 1.44606 +      }
 1.44607 + 
 1.44608 +      /* Playback and delete the journal.  Drop the database write
 1.44609 +      ** lock and reacquire the read lock. Purge the cache before
 1.44610 +      ** playing back the hot-journal so that we don't end up with
 1.44611 +      ** an inconsistent cache.  Sync the hot journal before playing
 1.44612 +      ** it back since the process that crashed and left the hot journal
 1.44613 +      ** probably did not sync it and we are required to always sync
 1.44614 +      ** the journal before playing it back.
 1.44615 +      */
 1.44616 +      if( isOpen(pPager->jfd) ){
 1.44617 +        assert( rc==SQLITE_OK );
 1.44618 +        rc = pagerSyncHotJournal(pPager);
 1.44619 +        if( rc==SQLITE_OK ){
 1.44620 +          rc = pager_playback(pPager, 1);
 1.44621 +          pPager->eState = PAGER_OPEN;
 1.44622 +        }
 1.44623 +      }else if( !pPager->exclusiveMode ){
 1.44624 +        pagerUnlockDb(pPager, SHARED_LOCK);
 1.44625 +      }
 1.44626 +
 1.44627 +      if( rc!=SQLITE_OK ){
 1.44628 +        /* This branch is taken if an error occurs while trying to open
 1.44629 +        ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
 1.44630 +        ** pager_unlock() routine will be called before returning to unlock
 1.44631 +        ** the file. If the unlock attempt fails, then Pager.eLock must be
 1.44632 +        ** set to UNKNOWN_LOCK (see the comment above the #define for 
 1.44633 +        ** UNKNOWN_LOCK above for an explanation). 
 1.44634 +        **
 1.44635 +        ** In order to get pager_unlock() to do this, set Pager.eState to
 1.44636 +        ** PAGER_ERROR now. This is not actually counted as a transition
 1.44637 +        ** to ERROR state in the state diagram at the top of this file,
 1.44638 +        ** since we know that the same call to pager_unlock() will very
 1.44639 +        ** shortly transition the pager object to the OPEN state. Calling
 1.44640 +        ** assert_pager_state() would fail now, as it should not be possible
 1.44641 +        ** to be in ERROR state when there are zero outstanding page 
 1.44642 +        ** references.
 1.44643 +        */
 1.44644 +        pager_error(pPager, rc);
 1.44645 +        goto failed;
 1.44646 +      }
 1.44647 +
 1.44648 +      assert( pPager->eState==PAGER_OPEN );
 1.44649 +      assert( (pPager->eLock==SHARED_LOCK)
 1.44650 +           || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
 1.44651 +      );
 1.44652 +    }
 1.44653 +
 1.44654 +    if( !pPager->tempFile && (
 1.44655 +        pPager->pBackup 
 1.44656 +     || sqlite3PcachePagecount(pPager->pPCache)>0 
 1.44657 +     || USEFETCH(pPager)
 1.44658 +    )){
 1.44659 +      /* The shared-lock has just been acquired on the database file
 1.44660 +      ** and there are already pages in the cache (from a previous
 1.44661 +      ** read or write transaction).  Check to see if the database
 1.44662 +      ** has been modified.  If the database has changed, flush the
 1.44663 +      ** cache.
 1.44664 +      **
 1.44665 +      ** Database changes is detected by looking at 15 bytes beginning
 1.44666 +      ** at offset 24 into the file.  The first 4 of these 16 bytes are
 1.44667 +      ** a 32-bit counter that is incremented with each change.  The
 1.44668 +      ** other bytes change randomly with each file change when
 1.44669 +      ** a codec is in use.
 1.44670 +      ** 
 1.44671 +      ** There is a vanishingly small chance that a change will not be 
 1.44672 +      ** detected.  The chance of an undetected change is so small that
 1.44673 +      ** it can be neglected.
 1.44674 +      */
 1.44675 +      Pgno nPage = 0;
 1.44676 +      char dbFileVers[sizeof(pPager->dbFileVers)];
 1.44677 +
 1.44678 +      rc = pagerPagecount(pPager, &nPage);
 1.44679 +      if( rc ) goto failed;
 1.44680 +
 1.44681 +      if( nPage>0 ){
 1.44682 +        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
 1.44683 +        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
 1.44684 +        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
 1.44685 +          goto failed;
 1.44686 +        }
 1.44687 +      }else{
 1.44688 +        memset(dbFileVers, 0, sizeof(dbFileVers));
 1.44689 +      }
 1.44690 +
 1.44691 +      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
 1.44692 +        pager_reset(pPager);
 1.44693 +
 1.44694 +        /* Unmap the database file. It is possible that external processes
 1.44695 +        ** may have truncated the database file and then extended it back
 1.44696 +        ** to its original size while this process was not holding a lock.
 1.44697 +        ** In this case there may exist a Pager.pMap mapping that appears
 1.44698 +        ** to be the right size but is not actually valid. Avoid this
 1.44699 +        ** possibility by unmapping the db here. */
 1.44700 +        if( USEFETCH(pPager) ){
 1.44701 +          sqlite3OsUnfetch(pPager->fd, 0, 0);
 1.44702 +        }
 1.44703 +      }
 1.44704 +    }
 1.44705 +
 1.44706 +    /* If there is a WAL file in the file-system, open this database in WAL
 1.44707 +    ** mode. Otherwise, the following function call is a no-op.
 1.44708 +    */
 1.44709 +    rc = pagerOpenWalIfPresent(pPager);
 1.44710 +#ifndef SQLITE_OMIT_WAL
 1.44711 +    assert( pPager->pWal==0 || rc==SQLITE_OK );
 1.44712 +#endif
 1.44713 +  }
 1.44714 +
 1.44715 +  if( pagerUseWal(pPager) ){
 1.44716 +    assert( rc==SQLITE_OK );
 1.44717 +    rc = pagerBeginReadTransaction(pPager);
 1.44718 +  }
 1.44719 +
 1.44720 +  if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
 1.44721 +    rc = pagerPagecount(pPager, &pPager->dbSize);
 1.44722 +  }
 1.44723 +
 1.44724 + failed:
 1.44725 +  if( rc!=SQLITE_OK ){
 1.44726 +    assert( !MEMDB );
 1.44727 +    pager_unlock(pPager);
 1.44728 +    assert( pPager->eState==PAGER_OPEN );
 1.44729 +  }else{
 1.44730 +    pPager->eState = PAGER_READER;
 1.44731 +  }
 1.44732 +  return rc;
 1.44733 +}
 1.44734 +
 1.44735 +/*
 1.44736 +** If the reference count has reached zero, rollback any active
 1.44737 +** transaction and unlock the pager.
 1.44738 +**
 1.44739 +** Except, in locking_mode=EXCLUSIVE when there is nothing to in
 1.44740 +** the rollback journal, the unlock is not performed and there is
 1.44741 +** nothing to rollback, so this routine is a no-op.
 1.44742 +*/ 
 1.44743 +static void pagerUnlockIfUnused(Pager *pPager){
 1.44744 +  if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
 1.44745 +    pagerUnlockAndRollback(pPager);
 1.44746 +  }
 1.44747 +}
 1.44748 +
 1.44749 +/*
 1.44750 +** Acquire a reference to page number pgno in pager pPager (a page
 1.44751 +** reference has type DbPage*). If the requested reference is 
 1.44752 +** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
 1.44753 +**
 1.44754 +** If the requested page is already in the cache, it is returned. 
 1.44755 +** Otherwise, a new page object is allocated and populated with data
 1.44756 +** read from the database file. In some cases, the pcache module may
 1.44757 +** choose not to allocate a new page object and may reuse an existing
 1.44758 +** object with no outstanding references.
 1.44759 +**
 1.44760 +** The extra data appended to a page is always initialized to zeros the 
 1.44761 +** first time a page is loaded into memory. If the page requested is 
 1.44762 +** already in the cache when this function is called, then the extra
 1.44763 +** data is left as it was when the page object was last used.
 1.44764 +**
 1.44765 +** If the database image is smaller than the requested page or if a 
 1.44766 +** non-zero value is passed as the noContent parameter and the 
 1.44767 +** requested page is not already stored in the cache, then no 
 1.44768 +** actual disk read occurs. In this case the memory image of the 
 1.44769 +** page is initialized to all zeros. 
 1.44770 +**
 1.44771 +** If noContent is true, it means that we do not care about the contents
 1.44772 +** of the page. This occurs in two scenarios:
 1.44773 +**
 1.44774 +**   a) When reading a free-list leaf page from the database, and
 1.44775 +**
 1.44776 +**   b) When a savepoint is being rolled back and we need to load
 1.44777 +**      a new page into the cache to be filled with the data read
 1.44778 +**      from the savepoint journal.
 1.44779 +**
 1.44780 +** If noContent is true, then the data returned is zeroed instead of
 1.44781 +** being read from the database. Additionally, the bits corresponding
 1.44782 +** to pgno in Pager.pInJournal (bitvec of pages already written to the
 1.44783 +** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
 1.44784 +** savepoints are set. This means if the page is made writable at any
 1.44785 +** point in the future, using a call to sqlite3PagerWrite(), its contents
 1.44786 +** will not be journaled. This saves IO.
 1.44787 +**
 1.44788 +** The acquisition might fail for several reasons.  In all cases,
 1.44789 +** an appropriate error code is returned and *ppPage is set to NULL.
 1.44790 +**
 1.44791 +** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
 1.44792 +** to find a page in the in-memory cache first.  If the page is not already
 1.44793 +** in memory, this routine goes to disk to read it in whereas Lookup()
 1.44794 +** just returns 0.  This routine acquires a read-lock the first time it
 1.44795 +** has to go to disk, and could also playback an old journal if necessary.
 1.44796 +** Since Lookup() never goes to disk, it never has to deal with locks
 1.44797 +** or journal files.
 1.44798 +*/
 1.44799 +SQLITE_PRIVATE int sqlite3PagerAcquire(
 1.44800 +  Pager *pPager,      /* The pager open on the database file */
 1.44801 +  Pgno pgno,          /* Page number to fetch */
 1.44802 +  DbPage **ppPage,    /* Write a pointer to the page here */
 1.44803 +  int flags           /* PAGER_GET_XXX flags */
 1.44804 +){
 1.44805 +  int rc = SQLITE_OK;
 1.44806 +  PgHdr *pPg = 0;
 1.44807 +  u32 iFrame = 0;                 /* Frame to read from WAL file */
 1.44808 +  const int noContent = (flags & PAGER_GET_NOCONTENT);
 1.44809 +
 1.44810 +  /* It is acceptable to use a read-only (mmap) page for any page except
 1.44811 +  ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
 1.44812 +  ** flag was specified by the caller. And so long as the db is not a 
 1.44813 +  ** temporary or in-memory database.  */
 1.44814 +  const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
 1.44815 +   && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
 1.44816 +#ifdef SQLITE_HAS_CODEC
 1.44817 +   && pPager->xCodec==0
 1.44818 +#endif
 1.44819 +  );
 1.44820 +
 1.44821 +  assert( pPager->eState>=PAGER_READER );
 1.44822 +  assert( assert_pager_state(pPager) );
 1.44823 +  assert( noContent==0 || bMmapOk==0 );
 1.44824 +
 1.44825 +  if( pgno==0 ){
 1.44826 +    return SQLITE_CORRUPT_BKPT;
 1.44827 +  }
 1.44828 +
 1.44829 +  /* If the pager is in the error state, return an error immediately. 
 1.44830 +  ** Otherwise, request the page from the PCache layer. */
 1.44831 +  if( pPager->errCode!=SQLITE_OK ){
 1.44832 +    rc = pPager->errCode;
 1.44833 +  }else{
 1.44834 +
 1.44835 +    if( bMmapOk && pagerUseWal(pPager) ){
 1.44836 +      rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
 1.44837 +      if( rc!=SQLITE_OK ) goto pager_acquire_err;
 1.44838 +    }
 1.44839 +
 1.44840 +    if( bMmapOk && iFrame==0 ){
 1.44841 +      void *pData = 0;
 1.44842 +
 1.44843 +      rc = sqlite3OsFetch(pPager->fd, 
 1.44844 +          (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
 1.44845 +      );
 1.44846 +
 1.44847 +      if( rc==SQLITE_OK && pData ){
 1.44848 +        if( pPager->eState>PAGER_READER ){
 1.44849 +          (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
 1.44850 +        }
 1.44851 +        if( pPg==0 ){
 1.44852 +          rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
 1.44853 +        }else{
 1.44854 +          sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
 1.44855 +        }
 1.44856 +        if( pPg ){
 1.44857 +          assert( rc==SQLITE_OK );
 1.44858 +          *ppPage = pPg;
 1.44859 +          return SQLITE_OK;
 1.44860 +        }
 1.44861 +      }
 1.44862 +      if( rc!=SQLITE_OK ){
 1.44863 +        goto pager_acquire_err;
 1.44864 +      }
 1.44865 +    }
 1.44866 +
 1.44867 +    rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
 1.44868 +  }
 1.44869 +
 1.44870 +  if( rc!=SQLITE_OK ){
 1.44871 +    /* Either the call to sqlite3PcacheFetch() returned an error or the
 1.44872 +    ** pager was already in the error-state when this function was called.
 1.44873 +    ** Set pPg to 0 and jump to the exception handler.  */
 1.44874 +    pPg = 0;
 1.44875 +    goto pager_acquire_err;
 1.44876 +  }
 1.44877 +  assert( (*ppPage)->pgno==pgno );
 1.44878 +  assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
 1.44879 +
 1.44880 +  if( (*ppPage)->pPager && !noContent ){
 1.44881 +    /* In this case the pcache already contains an initialized copy of
 1.44882 +    ** the page. Return without further ado.  */
 1.44883 +    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
 1.44884 +    pPager->aStat[PAGER_STAT_HIT]++;
 1.44885 +    return SQLITE_OK;
 1.44886 +
 1.44887 +  }else{
 1.44888 +    /* The pager cache has created a new page. Its content needs to 
 1.44889 +    ** be initialized.  */
 1.44890 +
 1.44891 +    pPg = *ppPage;
 1.44892 +    pPg->pPager = pPager;
 1.44893 +
 1.44894 +    /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
 1.44895 +    ** number greater than this, or the unused locking-page, is requested. */
 1.44896 +    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
 1.44897 +      rc = SQLITE_CORRUPT_BKPT;
 1.44898 +      goto pager_acquire_err;
 1.44899 +    }
 1.44900 +
 1.44901 +    if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
 1.44902 +      if( pgno>pPager->mxPgno ){
 1.44903 +        rc = SQLITE_FULL;
 1.44904 +        goto pager_acquire_err;
 1.44905 +      }
 1.44906 +      if( noContent ){
 1.44907 +        /* Failure to set the bits in the InJournal bit-vectors is benign.
 1.44908 +        ** It merely means that we might do some extra work to journal a 
 1.44909 +        ** page that does not need to be journaled.  Nevertheless, be sure 
 1.44910 +        ** to test the case where a malloc error occurs while trying to set 
 1.44911 +        ** a bit in a bit vector.
 1.44912 +        */
 1.44913 +        sqlite3BeginBenignMalloc();
 1.44914 +        if( pgno<=pPager->dbOrigSize ){
 1.44915 +          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
 1.44916 +          testcase( rc==SQLITE_NOMEM );
 1.44917 +        }
 1.44918 +        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
 1.44919 +        testcase( rc==SQLITE_NOMEM );
 1.44920 +        sqlite3EndBenignMalloc();
 1.44921 +      }
 1.44922 +      memset(pPg->pData, 0, pPager->pageSize);
 1.44923 +      IOTRACE(("ZERO %p %d\n", pPager, pgno));
 1.44924 +    }else{
 1.44925 +      if( pagerUseWal(pPager) && bMmapOk==0 ){
 1.44926 +        rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
 1.44927 +        if( rc!=SQLITE_OK ) goto pager_acquire_err;
 1.44928 +      }
 1.44929 +      assert( pPg->pPager==pPager );
 1.44930 +      pPager->aStat[PAGER_STAT_MISS]++;
 1.44931 +      rc = readDbPage(pPg, iFrame);
 1.44932 +      if( rc!=SQLITE_OK ){
 1.44933 +        goto pager_acquire_err;
 1.44934 +      }
 1.44935 +    }
 1.44936 +    pager_set_pagehash(pPg);
 1.44937 +  }
 1.44938 +
 1.44939 +  return SQLITE_OK;
 1.44940 +
 1.44941 +pager_acquire_err:
 1.44942 +  assert( rc!=SQLITE_OK );
 1.44943 +  if( pPg ){
 1.44944 +    sqlite3PcacheDrop(pPg);
 1.44945 +  }
 1.44946 +  pagerUnlockIfUnused(pPager);
 1.44947 +
 1.44948 +  *ppPage = 0;
 1.44949 +  return rc;
 1.44950 +}
 1.44951 +
 1.44952 +/*
 1.44953 +** Acquire a page if it is already in the in-memory cache.  Do
 1.44954 +** not read the page from disk.  Return a pointer to the page,
 1.44955 +** or 0 if the page is not in cache. 
 1.44956 +**
 1.44957 +** See also sqlite3PagerGet().  The difference between this routine
 1.44958 +** and sqlite3PagerGet() is that _get() will go to the disk and read
 1.44959 +** in the page if the page is not already in cache.  This routine
 1.44960 +** returns NULL if the page is not in cache or if a disk I/O error 
 1.44961 +** has ever happened.
 1.44962 +*/
 1.44963 +SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
 1.44964 +  PgHdr *pPg = 0;
 1.44965 +  assert( pPager!=0 );
 1.44966 +  assert( pgno!=0 );
 1.44967 +  assert( pPager->pPCache!=0 );
 1.44968 +  assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
 1.44969 +  sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
 1.44970 +  return pPg;
 1.44971 +}
 1.44972 +
 1.44973 +/*
 1.44974 +** Release a page reference.
 1.44975 +**
 1.44976 +** If the number of references to the page drop to zero, then the
 1.44977 +** page is added to the LRU list.  When all references to all pages
 1.44978 +** are released, a rollback occurs and the lock on the database is
 1.44979 +** removed.
 1.44980 +*/
 1.44981 +SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
 1.44982 +  Pager *pPager;
 1.44983 +  assert( pPg!=0 );
 1.44984 +  pPager = pPg->pPager;
 1.44985 +  if( pPg->flags & PGHDR_MMAP ){
 1.44986 +    pagerReleaseMapPage(pPg);
 1.44987 +  }else{
 1.44988 +    sqlite3PcacheRelease(pPg);
 1.44989 +  }
 1.44990 +  pagerUnlockIfUnused(pPager);
 1.44991 +}
 1.44992 +SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
 1.44993 +  if( pPg ) sqlite3PagerUnrefNotNull(pPg);
 1.44994 +}
 1.44995 +
 1.44996 +/*
 1.44997 +** This function is called at the start of every write transaction.
 1.44998 +** There must already be a RESERVED or EXCLUSIVE lock on the database 
 1.44999 +** file when this routine is called.
 1.45000 +**
 1.45001 +** Open the journal file for pager pPager and write a journal header
 1.45002 +** to the start of it. If there are active savepoints, open the sub-journal
 1.45003 +** as well. This function is only used when the journal file is being 
 1.45004 +** opened to write a rollback log for a transaction. It is not used 
 1.45005 +** when opening a hot journal file to roll it back.
 1.45006 +**
 1.45007 +** If the journal file is already open (as it may be in exclusive mode),
 1.45008 +** then this function just writes a journal header to the start of the
 1.45009 +** already open file. 
 1.45010 +**
 1.45011 +** Whether or not the journal file is opened by this function, the
 1.45012 +** Pager.pInJournal bitvec structure is allocated.
 1.45013 +**
 1.45014 +** Return SQLITE_OK if everything is successful. Otherwise, return 
 1.45015 +** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
 1.45016 +** an IO error code if opening or writing the journal file fails.
 1.45017 +*/
 1.45018 +static int pager_open_journal(Pager *pPager){
 1.45019 +  int rc = SQLITE_OK;                        /* Return code */
 1.45020 +  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
 1.45021 +
 1.45022 +  assert( pPager->eState==PAGER_WRITER_LOCKED );
 1.45023 +  assert( assert_pager_state(pPager) );
 1.45024 +  assert( pPager->pInJournal==0 );
 1.45025 +  
 1.45026 +  /* If already in the error state, this function is a no-op.  But on
 1.45027 +  ** the other hand, this routine is never called if we are already in
 1.45028 +  ** an error state. */
 1.45029 +  if( NEVER(pPager->errCode) ) return pPager->errCode;
 1.45030 +
 1.45031 +  if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
 1.45032 +    pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
 1.45033 +    if( pPager->pInJournal==0 ){
 1.45034 +      return SQLITE_NOMEM;
 1.45035 +    }
 1.45036 +  
 1.45037 +    /* Open the journal file if it is not already open. */
 1.45038 +    if( !isOpen(pPager->jfd) ){
 1.45039 +      if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
 1.45040 +        sqlite3MemJournalOpen(pPager->jfd);
 1.45041 +      }else{
 1.45042 +        const int flags =                   /* VFS flags to open journal file */
 1.45043 +          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
 1.45044 +          (pPager->tempFile ? 
 1.45045 +            (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
 1.45046 +            (SQLITE_OPEN_MAIN_JOURNAL)
 1.45047 +          );
 1.45048 +
 1.45049 +        /* Verify that the database still has the same name as it did when
 1.45050 +        ** it was originally opened. */
 1.45051 +        rc = databaseIsUnmoved(pPager);
 1.45052 +        if( rc==SQLITE_OK ){
 1.45053 +#ifdef SQLITE_ENABLE_ATOMIC_WRITE
 1.45054 +          rc = sqlite3JournalOpen(
 1.45055 +              pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
 1.45056 +          );
 1.45057 +#else
 1.45058 +          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
 1.45059 +#endif
 1.45060 +        }
 1.45061 +      }
 1.45062 +      assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
 1.45063 +    }
 1.45064 +  
 1.45065 +  
 1.45066 +    /* Write the first journal header to the journal file and open 
 1.45067 +    ** the sub-journal if necessary.
 1.45068 +    */
 1.45069 +    if( rc==SQLITE_OK ){
 1.45070 +      /* TODO: Check if all of these are really required. */
 1.45071 +      pPager->nRec = 0;
 1.45072 +      pPager->journalOff = 0;
 1.45073 +      pPager->setMaster = 0;
 1.45074 +      pPager->journalHdr = 0;
 1.45075 +      rc = writeJournalHdr(pPager);
 1.45076 +    }
 1.45077 +  }
 1.45078 +
 1.45079 +  if( rc!=SQLITE_OK ){
 1.45080 +    sqlite3BitvecDestroy(pPager->pInJournal);
 1.45081 +    pPager->pInJournal = 0;
 1.45082 +  }else{
 1.45083 +    assert( pPager->eState==PAGER_WRITER_LOCKED );
 1.45084 +    pPager->eState = PAGER_WRITER_CACHEMOD;
 1.45085 +  }
 1.45086 +
 1.45087 +  return rc;
 1.45088 +}
 1.45089 +
 1.45090 +/*
 1.45091 +** Begin a write-transaction on the specified pager object. If a 
 1.45092 +** write-transaction has already been opened, this function is a no-op.
 1.45093 +**
 1.45094 +** If the exFlag argument is false, then acquire at least a RESERVED
 1.45095 +** lock on the database file. If exFlag is true, then acquire at least
 1.45096 +** an EXCLUSIVE lock. If such a lock is already held, no locking 
 1.45097 +** functions need be called.
 1.45098 +**
 1.45099 +** If the subjInMemory argument is non-zero, then any sub-journal opened
 1.45100 +** within this transaction will be opened as an in-memory file. This
 1.45101 +** has no effect if the sub-journal is already opened (as it may be when
 1.45102 +** running in exclusive mode) or if the transaction does not require a
 1.45103 +** sub-journal. If the subjInMemory argument is zero, then any required
 1.45104 +** sub-journal is implemented in-memory if pPager is an in-memory database, 
 1.45105 +** or using a temporary file otherwise.
 1.45106 +*/
 1.45107 +SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
 1.45108 +  int rc = SQLITE_OK;
 1.45109 +
 1.45110 +  if( pPager->errCode ) return pPager->errCode;
 1.45111 +  assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
 1.45112 +  pPager->subjInMemory = (u8)subjInMemory;
 1.45113 +
 1.45114 +  if( ALWAYS(pPager->eState==PAGER_READER) ){
 1.45115 +    assert( pPager->pInJournal==0 );
 1.45116 +
 1.45117 +    if( pagerUseWal(pPager) ){
 1.45118 +      /* If the pager is configured to use locking_mode=exclusive, and an
 1.45119 +      ** exclusive lock on the database is not already held, obtain it now.
 1.45120 +      */
 1.45121 +      if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
 1.45122 +        rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
 1.45123 +        if( rc!=SQLITE_OK ){
 1.45124 +          return rc;
 1.45125 +        }
 1.45126 +        sqlite3WalExclusiveMode(pPager->pWal, 1);
 1.45127 +      }
 1.45128 +
 1.45129 +      /* Grab the write lock on the log file. If successful, upgrade to
 1.45130 +      ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
 1.45131 +      ** The busy-handler is not invoked if another connection already
 1.45132 +      ** holds the write-lock. If possible, the upper layer will call it.
 1.45133 +      */
 1.45134 +      rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
 1.45135 +    }else{
 1.45136 +      /* Obtain a RESERVED lock on the database file. If the exFlag parameter
 1.45137 +      ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
 1.45138 +      ** busy-handler callback can be used when upgrading to the EXCLUSIVE
 1.45139 +      ** lock, but not when obtaining the RESERVED lock.
 1.45140 +      */
 1.45141 +      rc = pagerLockDb(pPager, RESERVED_LOCK);
 1.45142 +      if( rc==SQLITE_OK && exFlag ){
 1.45143 +        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
 1.45144 +      }
 1.45145 +    }
 1.45146 +
 1.45147 +    if( rc==SQLITE_OK ){
 1.45148 +      /* Change to WRITER_LOCKED state.
 1.45149 +      **
 1.45150 +      ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
 1.45151 +      ** when it has an open transaction, but never to DBMOD or FINISHED.
 1.45152 +      ** This is because in those states the code to roll back savepoint 
 1.45153 +      ** transactions may copy data from the sub-journal into the database 
 1.45154 +      ** file as well as into the page cache. Which would be incorrect in 
 1.45155 +      ** WAL mode.
 1.45156 +      */
 1.45157 +      pPager->eState = PAGER_WRITER_LOCKED;
 1.45158 +      pPager->dbHintSize = pPager->dbSize;
 1.45159 +      pPager->dbFileSize = pPager->dbSize;
 1.45160 +      pPager->dbOrigSize = pPager->dbSize;
 1.45161 +      pPager->journalOff = 0;
 1.45162 +    }
 1.45163 +
 1.45164 +    assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
 1.45165 +    assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
 1.45166 +    assert( assert_pager_state(pPager) );
 1.45167 +  }
 1.45168 +
 1.45169 +  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
 1.45170 +  return rc;
 1.45171 +}
 1.45172 +
 1.45173 +/*
 1.45174 +** Mark a single data page as writeable. The page is written into the 
 1.45175 +** main journal or sub-journal as required. If the page is written into
 1.45176 +** one of the journals, the corresponding bit is set in the 
 1.45177 +** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
 1.45178 +** of any open savepoints as appropriate.
 1.45179 +*/
 1.45180 +static int pager_write(PgHdr *pPg){
 1.45181 +  Pager *pPager = pPg->pPager;
 1.45182 +  int rc = SQLITE_OK;
 1.45183 +  int inJournal;
 1.45184 +
 1.45185 +  /* This routine is not called unless a write-transaction has already 
 1.45186 +  ** been started. The journal file may or may not be open at this point.
 1.45187 +  ** It is never called in the ERROR state.
 1.45188 +  */
 1.45189 +  assert( pPager->eState==PAGER_WRITER_LOCKED
 1.45190 +       || pPager->eState==PAGER_WRITER_CACHEMOD
 1.45191 +       || pPager->eState==PAGER_WRITER_DBMOD
 1.45192 +  );
 1.45193 +  assert( assert_pager_state(pPager) );
 1.45194 +  assert( pPager->errCode==0 );
 1.45195 +  assert( pPager->readOnly==0 );
 1.45196 +
 1.45197 +  CHECK_PAGE(pPg);
 1.45198 +
 1.45199 +  /* The journal file needs to be opened. Higher level routines have already
 1.45200 +  ** obtained the necessary locks to begin the write-transaction, but the
 1.45201 +  ** rollback journal might not yet be open. Open it now if this is the case.
 1.45202 +  **
 1.45203 +  ** This is done before calling sqlite3PcacheMakeDirty() on the page. 
 1.45204 +  ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
 1.45205 +  ** an error might occur and the pager would end up in WRITER_LOCKED state
 1.45206 +  ** with pages marked as dirty in the cache.
 1.45207 +  */
 1.45208 +  if( pPager->eState==PAGER_WRITER_LOCKED ){
 1.45209 +    rc = pager_open_journal(pPager);
 1.45210 +    if( rc!=SQLITE_OK ) return rc;
 1.45211 +  }
 1.45212 +  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
 1.45213 +  assert( assert_pager_state(pPager) );
 1.45214 +
 1.45215 +  /* Mark the page as dirty.  If the page has already been written
 1.45216 +  ** to the journal then we can return right away.
 1.45217 +  */
 1.45218 +  sqlite3PcacheMakeDirty(pPg);
 1.45219 +  inJournal = pageInJournal(pPager, pPg);
 1.45220 +  if( inJournal && (pPager->nSavepoint==0 || !subjRequiresPage(pPg)) ){
 1.45221 +    assert( !pagerUseWal(pPager) );
 1.45222 +  }else{
 1.45223 +  
 1.45224 +    /* The transaction journal now exists and we have a RESERVED or an
 1.45225 +    ** EXCLUSIVE lock on the main database file.  Write the current page to
 1.45226 +    ** the transaction journal if it is not there already.
 1.45227 +    */
 1.45228 +    if( !inJournal && !pagerUseWal(pPager) ){
 1.45229 +      assert( pagerUseWal(pPager)==0 );
 1.45230 +      if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
 1.45231 +        u32 cksum;
 1.45232 +        char *pData2;
 1.45233 +        i64 iOff = pPager->journalOff;
 1.45234 +
 1.45235 +        /* We should never write to the journal file the page that
 1.45236 +        ** contains the database locks.  The following assert verifies
 1.45237 +        ** that we do not. */
 1.45238 +        assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
 1.45239 +
 1.45240 +        assert( pPager->journalHdr<=pPager->journalOff );
 1.45241 +        CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
 1.45242 +        cksum = pager_cksum(pPager, (u8*)pData2);
 1.45243 +
 1.45244 +        /* Even if an IO or diskfull error occurs while journalling the
 1.45245 +        ** page in the block above, set the need-sync flag for the page.
 1.45246 +        ** Otherwise, when the transaction is rolled back, the logic in
 1.45247 +        ** playback_one_page() will think that the page needs to be restored
 1.45248 +        ** in the database file. And if an IO error occurs while doing so,
 1.45249 +        ** then corruption may follow.
 1.45250 +        */
 1.45251 +        pPg->flags |= PGHDR_NEED_SYNC;
 1.45252 +
 1.45253 +        rc = write32bits(pPager->jfd, iOff, pPg->pgno);
 1.45254 +        if( rc!=SQLITE_OK ) return rc;
 1.45255 +        rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
 1.45256 +        if( rc!=SQLITE_OK ) return rc;
 1.45257 +        rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
 1.45258 +        if( rc!=SQLITE_OK ) return rc;
 1.45259 +
 1.45260 +        IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
 1.45261 +                 pPager->journalOff, pPager->pageSize));
 1.45262 +        PAGER_INCR(sqlite3_pager_writej_count);
 1.45263 +        PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
 1.45264 +             PAGERID(pPager), pPg->pgno, 
 1.45265 +             ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
 1.45266 +
 1.45267 +        pPager->journalOff += 8 + pPager->pageSize;
 1.45268 +        pPager->nRec++;
 1.45269 +        assert( pPager->pInJournal!=0 );
 1.45270 +        rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
 1.45271 +        testcase( rc==SQLITE_NOMEM );
 1.45272 +        assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
 1.45273 +        rc |= addToSavepointBitvecs(pPager, pPg->pgno);
 1.45274 +        if( rc!=SQLITE_OK ){
 1.45275 +          assert( rc==SQLITE_NOMEM );
 1.45276 +          return rc;
 1.45277 +        }
 1.45278 +      }else{
 1.45279 +        if( pPager->eState!=PAGER_WRITER_DBMOD ){
 1.45280 +          pPg->flags |= PGHDR_NEED_SYNC;
 1.45281 +        }
 1.45282 +        PAGERTRACE(("APPEND %d page %d needSync=%d\n",
 1.45283 +                PAGERID(pPager), pPg->pgno,
 1.45284 +               ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
 1.45285 +      }
 1.45286 +    }
 1.45287 +  
 1.45288 +    /* If the statement journal is open and the page is not in it,
 1.45289 +    ** then write the current page to the statement journal.  Note that
 1.45290 +    ** the statement journal format differs from the standard journal format
 1.45291 +    ** in that it omits the checksums and the header.
 1.45292 +    */
 1.45293 +    if( pPager->nSavepoint>0 && subjRequiresPage(pPg) ){
 1.45294 +      rc = subjournalPage(pPg);
 1.45295 +    }
 1.45296 +  }
 1.45297 +
 1.45298 +  /* Update the database size and return.
 1.45299 +  */
 1.45300 +  if( pPager->dbSize<pPg->pgno ){
 1.45301 +    pPager->dbSize = pPg->pgno;
 1.45302 +  }
 1.45303 +  return rc;
 1.45304 +}
 1.45305 +
 1.45306 +/*
 1.45307 +** Mark a data page as writeable. This routine must be called before 
 1.45308 +** making changes to a page. The caller must check the return value 
 1.45309 +** of this function and be careful not to change any page data unless 
 1.45310 +** this routine returns SQLITE_OK.
 1.45311 +**
 1.45312 +** The difference between this function and pager_write() is that this
 1.45313 +** function also deals with the special case where 2 or more pages
 1.45314 +** fit on a single disk sector. In this case all co-resident pages
 1.45315 +** must have been written to the journal file before returning.
 1.45316 +**
 1.45317 +** If an error occurs, SQLITE_NOMEM or an IO error code is returned
 1.45318 +** as appropriate. Otherwise, SQLITE_OK.
 1.45319 +*/
 1.45320 +SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
 1.45321 +  int rc = SQLITE_OK;
 1.45322 +
 1.45323 +  PgHdr *pPg = pDbPage;
 1.45324 +  Pager *pPager = pPg->pPager;
 1.45325 +
 1.45326 +  assert( (pPg->flags & PGHDR_MMAP)==0 );
 1.45327 +  assert( pPager->eState>=PAGER_WRITER_LOCKED );
 1.45328 +  assert( pPager->eState!=PAGER_ERROR );
 1.45329 +  assert( assert_pager_state(pPager) );
 1.45330 +
 1.45331 +  if( pPager->sectorSize > (u32)pPager->pageSize ){
 1.45332 +    Pgno nPageCount;          /* Total number of pages in database file */
 1.45333 +    Pgno pg1;                 /* First page of the sector pPg is located on. */
 1.45334 +    int nPage = 0;            /* Number of pages starting at pg1 to journal */
 1.45335 +    int ii;                   /* Loop counter */
 1.45336 +    int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
 1.45337 +    Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
 1.45338 +
 1.45339 +    /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
 1.45340 +    ** a journal header to be written between the pages journaled by
 1.45341 +    ** this function.
 1.45342 +    */
 1.45343 +    assert( !MEMDB );
 1.45344 +    assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
 1.45345 +    pPager->doNotSpill |= SPILLFLAG_NOSYNC;
 1.45346 +
 1.45347 +    /* This trick assumes that both the page-size and sector-size are
 1.45348 +    ** an integer power of 2. It sets variable pg1 to the identifier
 1.45349 +    ** of the first page of the sector pPg is located on.
 1.45350 +    */
 1.45351 +    pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
 1.45352 +
 1.45353 +    nPageCount = pPager->dbSize;
 1.45354 +    if( pPg->pgno>nPageCount ){
 1.45355 +      nPage = (pPg->pgno - pg1)+1;
 1.45356 +    }else if( (pg1+nPagePerSector-1)>nPageCount ){
 1.45357 +      nPage = nPageCount+1-pg1;
 1.45358 +    }else{
 1.45359 +      nPage = nPagePerSector;
 1.45360 +    }
 1.45361 +    assert(nPage>0);
 1.45362 +    assert(pg1<=pPg->pgno);
 1.45363 +    assert((pg1+nPage)>pPg->pgno);
 1.45364 +
 1.45365 +    for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
 1.45366 +      Pgno pg = pg1+ii;
 1.45367 +      PgHdr *pPage;
 1.45368 +      if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
 1.45369 +        if( pg!=PAGER_MJ_PGNO(pPager) ){
 1.45370 +          rc = sqlite3PagerGet(pPager, pg, &pPage);
 1.45371 +          if( rc==SQLITE_OK ){
 1.45372 +            rc = pager_write(pPage);
 1.45373 +            if( pPage->flags&PGHDR_NEED_SYNC ){
 1.45374 +              needSync = 1;
 1.45375 +            }
 1.45376 +            sqlite3PagerUnrefNotNull(pPage);
 1.45377 +          }
 1.45378 +        }
 1.45379 +      }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
 1.45380 +        if( pPage->flags&PGHDR_NEED_SYNC ){
 1.45381 +          needSync = 1;
 1.45382 +        }
 1.45383 +        sqlite3PagerUnrefNotNull(pPage);
 1.45384 +      }
 1.45385 +    }
 1.45386 +
 1.45387 +    /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
 1.45388 +    ** starting at pg1, then it needs to be set for all of them. Because
 1.45389 +    ** writing to any of these nPage pages may damage the others, the
 1.45390 +    ** journal file must contain sync()ed copies of all of them
 1.45391 +    ** before any of them can be written out to the database file.
 1.45392 +    */
 1.45393 +    if( rc==SQLITE_OK && needSync ){
 1.45394 +      assert( !MEMDB );
 1.45395 +      for(ii=0; ii<nPage; ii++){
 1.45396 +        PgHdr *pPage = pager_lookup(pPager, pg1+ii);
 1.45397 +        if( pPage ){
 1.45398 +          pPage->flags |= PGHDR_NEED_SYNC;
 1.45399 +          sqlite3PagerUnrefNotNull(pPage);
 1.45400 +        }
 1.45401 +      }
 1.45402 +    }
 1.45403 +
 1.45404 +    assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
 1.45405 +    pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
 1.45406 +  }else{
 1.45407 +    rc = pager_write(pDbPage);
 1.45408 +  }
 1.45409 +  return rc;
 1.45410 +}
 1.45411 +
 1.45412 +/*
 1.45413 +** Return TRUE if the page given in the argument was previously passed
 1.45414 +** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
 1.45415 +** to change the content of the page.
 1.45416 +*/
 1.45417 +#ifndef NDEBUG
 1.45418 +SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
 1.45419 +  return pPg->flags&PGHDR_DIRTY;
 1.45420 +}
 1.45421 +#endif
 1.45422 +
 1.45423 +/*
 1.45424 +** A call to this routine tells the pager that it is not necessary to
 1.45425 +** write the information on page pPg back to the disk, even though
 1.45426 +** that page might be marked as dirty.  This happens, for example, when
 1.45427 +** the page has been added as a leaf of the freelist and so its
 1.45428 +** content no longer matters.
 1.45429 +**
 1.45430 +** The overlying software layer calls this routine when all of the data
 1.45431 +** on the given page is unused. The pager marks the page as clean so
 1.45432 +** that it does not get written to disk.
 1.45433 +**
 1.45434 +** Tests show that this optimization can quadruple the speed of large 
 1.45435 +** DELETE operations.
 1.45436 +*/
 1.45437 +SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
 1.45438 +  Pager *pPager = pPg->pPager;
 1.45439 +  if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
 1.45440 +    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
 1.45441 +    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
 1.45442 +    pPg->flags |= PGHDR_DONT_WRITE;
 1.45443 +    pager_set_pagehash(pPg);
 1.45444 +  }
 1.45445 +}
 1.45446 +
 1.45447 +/*
 1.45448 +** This routine is called to increment the value of the database file 
 1.45449 +** change-counter, stored as a 4-byte big-endian integer starting at 
 1.45450 +** byte offset 24 of the pager file.  The secondary change counter at
 1.45451 +** 92 is also updated, as is the SQLite version number at offset 96.
 1.45452 +**
 1.45453 +** But this only happens if the pPager->changeCountDone flag is false.
 1.45454 +** To avoid excess churning of page 1, the update only happens once.
 1.45455 +** See also the pager_write_changecounter() routine that does an 
 1.45456 +** unconditional update of the change counters.
 1.45457 +**
 1.45458 +** If the isDirectMode flag is zero, then this is done by calling 
 1.45459 +** sqlite3PagerWrite() on page 1, then modifying the contents of the
 1.45460 +** page data. In this case the file will be updated when the current
 1.45461 +** transaction is committed.
 1.45462 +**
 1.45463 +** The isDirectMode flag may only be non-zero if the library was compiled
 1.45464 +** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
 1.45465 +** if isDirect is non-zero, then the database file is updated directly
 1.45466 +** by writing an updated version of page 1 using a call to the 
 1.45467 +** sqlite3OsWrite() function.
 1.45468 +*/
 1.45469 +static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
 1.45470 +  int rc = SQLITE_OK;
 1.45471 +
 1.45472 +  assert( pPager->eState==PAGER_WRITER_CACHEMOD
 1.45473 +       || pPager->eState==PAGER_WRITER_DBMOD
 1.45474 +  );
 1.45475 +  assert( assert_pager_state(pPager) );
 1.45476 +
 1.45477 +  /* Declare and initialize constant integer 'isDirect'. If the
 1.45478 +  ** atomic-write optimization is enabled in this build, then isDirect
 1.45479 +  ** is initialized to the value passed as the isDirectMode parameter
 1.45480 +  ** to this function. Otherwise, it is always set to zero.
 1.45481 +  **
 1.45482 +  ** The idea is that if the atomic-write optimization is not
 1.45483 +  ** enabled at compile time, the compiler can omit the tests of
 1.45484 +  ** 'isDirect' below, as well as the block enclosed in the
 1.45485 +  ** "if( isDirect )" condition.
 1.45486 +  */
 1.45487 +#ifndef SQLITE_ENABLE_ATOMIC_WRITE
 1.45488 +# define DIRECT_MODE 0
 1.45489 +  assert( isDirectMode==0 );
 1.45490 +  UNUSED_PARAMETER(isDirectMode);
 1.45491 +#else
 1.45492 +# define DIRECT_MODE isDirectMode
 1.45493 +#endif
 1.45494 +
 1.45495 +  if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
 1.45496 +    PgHdr *pPgHdr;                /* Reference to page 1 */
 1.45497 +
 1.45498 +    assert( !pPager->tempFile && isOpen(pPager->fd) );
 1.45499 +
 1.45500 +    /* Open page 1 of the file for writing. */
 1.45501 +    rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
 1.45502 +    assert( pPgHdr==0 || rc==SQLITE_OK );
 1.45503 +
 1.45504 +    /* If page one was fetched successfully, and this function is not
 1.45505 +    ** operating in direct-mode, make page 1 writable.  When not in 
 1.45506 +    ** direct mode, page 1 is always held in cache and hence the PagerGet()
 1.45507 +    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
 1.45508 +    */
 1.45509 +    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
 1.45510 +      rc = sqlite3PagerWrite(pPgHdr);
 1.45511 +    }
 1.45512 +
 1.45513 +    if( rc==SQLITE_OK ){
 1.45514 +      /* Actually do the update of the change counter */
 1.45515 +      pager_write_changecounter(pPgHdr);
 1.45516 +
 1.45517 +      /* If running in direct mode, write the contents of page 1 to the file. */
 1.45518 +      if( DIRECT_MODE ){
 1.45519 +        const void *zBuf;
 1.45520 +        assert( pPager->dbFileSize>0 );
 1.45521 +        CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
 1.45522 +        if( rc==SQLITE_OK ){
 1.45523 +          rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
 1.45524 +          pPager->aStat[PAGER_STAT_WRITE]++;
 1.45525 +        }
 1.45526 +        if( rc==SQLITE_OK ){
 1.45527 +          /* Update the pager's copy of the change-counter. Otherwise, the
 1.45528 +          ** next time a read transaction is opened the cache will be
 1.45529 +          ** flushed (as the change-counter values will not match).  */
 1.45530 +          const void *pCopy = (const void *)&((const char *)zBuf)[24];
 1.45531 +          memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
 1.45532 +          pPager->changeCountDone = 1;
 1.45533 +        }
 1.45534 +      }else{
 1.45535 +        pPager->changeCountDone = 1;
 1.45536 +      }
 1.45537 +    }
 1.45538 +
 1.45539 +    /* Release the page reference. */
 1.45540 +    sqlite3PagerUnref(pPgHdr);
 1.45541 +  }
 1.45542 +  return rc;
 1.45543 +}
 1.45544 +
 1.45545 +/*
 1.45546 +** Sync the database file to disk. This is a no-op for in-memory databases
 1.45547 +** or pages with the Pager.noSync flag set.
 1.45548 +**
 1.45549 +** If successful, or if called on a pager for which it is a no-op, this
 1.45550 +** function returns SQLITE_OK. Otherwise, an IO error code is returned.
 1.45551 +*/
 1.45552 +SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
 1.45553 +  int rc = SQLITE_OK;
 1.45554 +
 1.45555 +  if( isOpen(pPager->fd) ){
 1.45556 +    void *pArg = (void*)zMaster;
 1.45557 +    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
 1.45558 +    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
 1.45559 +  }
 1.45560 +  if( rc==SQLITE_OK && !pPager->noSync ){
 1.45561 +    assert( !MEMDB );
 1.45562 +    rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
 1.45563 +  }
 1.45564 +  return rc;
 1.45565 +}
 1.45566 +
 1.45567 +/*
 1.45568 +** This function may only be called while a write-transaction is active in
 1.45569 +** rollback. If the connection is in WAL mode, this call is a no-op. 
 1.45570 +** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
 1.45571 +** the database file, an attempt is made to obtain one.
 1.45572 +**
 1.45573 +** If the EXCLUSIVE lock is already held or the attempt to obtain it is
 1.45574 +** successful, or the connection is in WAL mode, SQLITE_OK is returned.
 1.45575 +** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is 
 1.45576 +** returned.
 1.45577 +*/
 1.45578 +SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
 1.45579 +  int rc = SQLITE_OK;
 1.45580 +  assert( pPager->eState==PAGER_WRITER_CACHEMOD 
 1.45581 +       || pPager->eState==PAGER_WRITER_DBMOD 
 1.45582 +       || pPager->eState==PAGER_WRITER_LOCKED 
 1.45583 +  );
 1.45584 +  assert( assert_pager_state(pPager) );
 1.45585 +  if( 0==pagerUseWal(pPager) ){
 1.45586 +    rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
 1.45587 +  }
 1.45588 +  return rc;
 1.45589 +}
 1.45590 +
 1.45591 +/*
 1.45592 +** Sync the database file for the pager pPager. zMaster points to the name
 1.45593 +** of a master journal file that should be written into the individual
 1.45594 +** journal file. zMaster may be NULL, which is interpreted as no master
 1.45595 +** journal (a single database transaction).
 1.45596 +**
 1.45597 +** This routine ensures that:
 1.45598 +**
 1.45599 +**   * The database file change-counter is updated,
 1.45600 +**   * the journal is synced (unless the atomic-write optimization is used),
 1.45601 +**   * all dirty pages are written to the database file, 
 1.45602 +**   * the database file is truncated (if required), and
 1.45603 +**   * the database file synced. 
 1.45604 +**
 1.45605 +** The only thing that remains to commit the transaction is to finalize 
 1.45606 +** (delete, truncate or zero the first part of) the journal file (or 
 1.45607 +** delete the master journal file if specified).
 1.45608 +**
 1.45609 +** Note that if zMaster==NULL, this does not overwrite a previous value
 1.45610 +** passed to an sqlite3PagerCommitPhaseOne() call.
 1.45611 +**
 1.45612 +** If the final parameter - noSync - is true, then the database file itself
 1.45613 +** is not synced. The caller must call sqlite3PagerSync() directly to
 1.45614 +** sync the database file before calling CommitPhaseTwo() to delete the
 1.45615 +** journal file in this case.
 1.45616 +*/
 1.45617 +SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
 1.45618 +  Pager *pPager,                  /* Pager object */
 1.45619 +  const char *zMaster,            /* If not NULL, the master journal name */
 1.45620 +  int noSync                      /* True to omit the xSync on the db file */
 1.45621 +){
 1.45622 +  int rc = SQLITE_OK;             /* Return code */
 1.45623 +
 1.45624 +  assert( pPager->eState==PAGER_WRITER_LOCKED
 1.45625 +       || pPager->eState==PAGER_WRITER_CACHEMOD
 1.45626 +       || pPager->eState==PAGER_WRITER_DBMOD
 1.45627 +       || pPager->eState==PAGER_ERROR
 1.45628 +  );
 1.45629 +  assert( assert_pager_state(pPager) );
 1.45630 +
 1.45631 +  /* If a prior error occurred, report that error again. */
 1.45632 +  if( NEVER(pPager->errCode) ) return pPager->errCode;
 1.45633 +
 1.45634 +  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
 1.45635 +      pPager->zFilename, zMaster, pPager->dbSize));
 1.45636 +
 1.45637 +  /* If no database changes have been made, return early. */
 1.45638 +  if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
 1.45639 +
 1.45640 +  if( MEMDB ){
 1.45641 +    /* If this is an in-memory db, or no pages have been written to, or this
 1.45642 +    ** function has already been called, it is mostly a no-op.  However, any
 1.45643 +    ** backup in progress needs to be restarted.
 1.45644 +    */
 1.45645 +    sqlite3BackupRestart(pPager->pBackup);
 1.45646 +  }else{
 1.45647 +    if( pagerUseWal(pPager) ){
 1.45648 +      PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
 1.45649 +      PgHdr *pPageOne = 0;
 1.45650 +      if( pList==0 ){
 1.45651 +        /* Must have at least one page for the WAL commit flag.
 1.45652 +        ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
 1.45653 +        rc = sqlite3PagerGet(pPager, 1, &pPageOne);
 1.45654 +        pList = pPageOne;
 1.45655 +        pList->pDirty = 0;
 1.45656 +      }
 1.45657 +      assert( rc==SQLITE_OK );
 1.45658 +      if( ALWAYS(pList) ){
 1.45659 +        rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
 1.45660 +      }
 1.45661 +      sqlite3PagerUnref(pPageOne);
 1.45662 +      if( rc==SQLITE_OK ){
 1.45663 +        sqlite3PcacheCleanAll(pPager->pPCache);
 1.45664 +      }
 1.45665 +    }else{
 1.45666 +      /* The following block updates the change-counter. Exactly how it
 1.45667 +      ** does this depends on whether or not the atomic-update optimization
 1.45668 +      ** was enabled at compile time, and if this transaction meets the 
 1.45669 +      ** runtime criteria to use the operation: 
 1.45670 +      **
 1.45671 +      **    * The file-system supports the atomic-write property for
 1.45672 +      **      blocks of size page-size, and 
 1.45673 +      **    * This commit is not part of a multi-file transaction, and
 1.45674 +      **    * Exactly one page has been modified and store in the journal file.
 1.45675 +      **
 1.45676 +      ** If the optimization was not enabled at compile time, then the
 1.45677 +      ** pager_incr_changecounter() function is called to update the change
 1.45678 +      ** counter in 'indirect-mode'. If the optimization is compiled in but
 1.45679 +      ** is not applicable to this transaction, call sqlite3JournalCreate()
 1.45680 +      ** to make sure the journal file has actually been created, then call
 1.45681 +      ** pager_incr_changecounter() to update the change-counter in indirect
 1.45682 +      ** mode. 
 1.45683 +      **
 1.45684 +      ** Otherwise, if the optimization is both enabled and applicable,
 1.45685 +      ** then call pager_incr_changecounter() to update the change-counter
 1.45686 +      ** in 'direct' mode. In this case the journal file will never be
 1.45687 +      ** created for this transaction.
 1.45688 +      */
 1.45689 +  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
 1.45690 +      PgHdr *pPg;
 1.45691 +      assert( isOpen(pPager->jfd) 
 1.45692 +           || pPager->journalMode==PAGER_JOURNALMODE_OFF 
 1.45693 +           || pPager->journalMode==PAGER_JOURNALMODE_WAL 
 1.45694 +      );
 1.45695 +      if( !zMaster && isOpen(pPager->jfd) 
 1.45696 +       && pPager->journalOff==jrnlBufferSize(pPager) 
 1.45697 +       && pPager->dbSize>=pPager->dbOrigSize
 1.45698 +       && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
 1.45699 +      ){
 1.45700 +        /* Update the db file change counter via the direct-write method. The 
 1.45701 +        ** following call will modify the in-memory representation of page 1 
 1.45702 +        ** to include the updated change counter and then write page 1 
 1.45703 +        ** directly to the database file. Because of the atomic-write 
 1.45704 +        ** property of the host file-system, this is safe.
 1.45705 +        */
 1.45706 +        rc = pager_incr_changecounter(pPager, 1);
 1.45707 +      }else{
 1.45708 +        rc = sqlite3JournalCreate(pPager->jfd);
 1.45709 +        if( rc==SQLITE_OK ){
 1.45710 +          rc = pager_incr_changecounter(pPager, 0);
 1.45711 +        }
 1.45712 +      }
 1.45713 +  #else
 1.45714 +      rc = pager_incr_changecounter(pPager, 0);
 1.45715 +  #endif
 1.45716 +      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
 1.45717 +  
 1.45718 +      /* Write the master journal name into the journal file. If a master 
 1.45719 +      ** journal file name has already been written to the journal file, 
 1.45720 +      ** or if zMaster is NULL (no master journal), then this call is a no-op.
 1.45721 +      */
 1.45722 +      rc = writeMasterJournal(pPager, zMaster);
 1.45723 +      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
 1.45724 +  
 1.45725 +      /* Sync the journal file and write all dirty pages to the database.
 1.45726 +      ** If the atomic-update optimization is being used, this sync will not 
 1.45727 +      ** create the journal file or perform any real IO.
 1.45728 +      **
 1.45729 +      ** Because the change-counter page was just modified, unless the
 1.45730 +      ** atomic-update optimization is used it is almost certain that the
 1.45731 +      ** journal requires a sync here. However, in locking_mode=exclusive
 1.45732 +      ** on a system under memory pressure it is just possible that this is 
 1.45733 +      ** not the case. In this case it is likely enough that the redundant
 1.45734 +      ** xSync() call will be changed to a no-op by the OS anyhow. 
 1.45735 +      */
 1.45736 +      rc = syncJournal(pPager, 0);
 1.45737 +      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
 1.45738 +  
 1.45739 +      rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
 1.45740 +      if( rc!=SQLITE_OK ){
 1.45741 +        assert( rc!=SQLITE_IOERR_BLOCKED );
 1.45742 +        goto commit_phase_one_exit;
 1.45743 +      }
 1.45744 +      sqlite3PcacheCleanAll(pPager->pPCache);
 1.45745 +
 1.45746 +      /* If the file on disk is smaller than the database image, use 
 1.45747 +      ** pager_truncate to grow the file here. This can happen if the database
 1.45748 +      ** image was extended as part of the current transaction and then the
 1.45749 +      ** last page in the db image moved to the free-list. In this case the
 1.45750 +      ** last page is never written out to disk, leaving the database file
 1.45751 +      ** undersized. Fix this now if it is the case.  */
 1.45752 +      if( pPager->dbSize>pPager->dbFileSize ){
 1.45753 +        Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
 1.45754 +        assert( pPager->eState==PAGER_WRITER_DBMOD );
 1.45755 +        rc = pager_truncate(pPager, nNew);
 1.45756 +        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
 1.45757 +      }
 1.45758 +  
 1.45759 +      /* Finally, sync the database file. */
 1.45760 +      if( !noSync ){
 1.45761 +        rc = sqlite3PagerSync(pPager, zMaster);
 1.45762 +      }
 1.45763 +      IOTRACE(("DBSYNC %p\n", pPager))
 1.45764 +    }
 1.45765 +  }
 1.45766 +
 1.45767 +commit_phase_one_exit:
 1.45768 +  if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
 1.45769 +    pPager->eState = PAGER_WRITER_FINISHED;
 1.45770 +  }
 1.45771 +  return rc;
 1.45772 +}
 1.45773 +
 1.45774 +
 1.45775 +/*
 1.45776 +** When this function is called, the database file has been completely
 1.45777 +** updated to reflect the changes made by the current transaction and
 1.45778 +** synced to disk. The journal file still exists in the file-system 
 1.45779 +** though, and if a failure occurs at this point it will eventually
 1.45780 +** be used as a hot-journal and the current transaction rolled back.
 1.45781 +**
 1.45782 +** This function finalizes the journal file, either by deleting, 
 1.45783 +** truncating or partially zeroing it, so that it cannot be used 
 1.45784 +** for hot-journal rollback. Once this is done the transaction is
 1.45785 +** irrevocably committed.
 1.45786 +**
 1.45787 +** If an error occurs, an IO error code is returned and the pager
 1.45788 +** moves into the error state. Otherwise, SQLITE_OK is returned.
 1.45789 +*/
 1.45790 +SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
 1.45791 +  int rc = SQLITE_OK;                  /* Return code */
 1.45792 +
 1.45793 +  /* This routine should not be called if a prior error has occurred.
 1.45794 +  ** But if (due to a coding error elsewhere in the system) it does get
 1.45795 +  ** called, just return the same error code without doing anything. */
 1.45796 +  if( NEVER(pPager->errCode) ) return pPager->errCode;
 1.45797 +
 1.45798 +  assert( pPager->eState==PAGER_WRITER_LOCKED
 1.45799 +       || pPager->eState==PAGER_WRITER_FINISHED
 1.45800 +       || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
 1.45801 +  );
 1.45802 +  assert( assert_pager_state(pPager) );
 1.45803 +
 1.45804 +  /* An optimization. If the database was not actually modified during
 1.45805 +  ** this transaction, the pager is running in exclusive-mode and is
 1.45806 +  ** using persistent journals, then this function is a no-op.
 1.45807 +  **
 1.45808 +  ** The start of the journal file currently contains a single journal 
 1.45809 +  ** header with the nRec field set to 0. If such a journal is used as
 1.45810 +  ** a hot-journal during hot-journal rollback, 0 changes will be made
 1.45811 +  ** to the database file. So there is no need to zero the journal 
 1.45812 +  ** header. Since the pager is in exclusive mode, there is no need
 1.45813 +  ** to drop any locks either.
 1.45814 +  */
 1.45815 +  if( pPager->eState==PAGER_WRITER_LOCKED 
 1.45816 +   && pPager->exclusiveMode 
 1.45817 +   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
 1.45818 +  ){
 1.45819 +    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
 1.45820 +    pPager->eState = PAGER_READER;
 1.45821 +    return SQLITE_OK;
 1.45822 +  }
 1.45823 +
 1.45824 +  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
 1.45825 +  rc = pager_end_transaction(pPager, pPager->setMaster, 1);
 1.45826 +  return pager_error(pPager, rc);
 1.45827 +}
 1.45828 +
 1.45829 +/*
 1.45830 +** If a write transaction is open, then all changes made within the 
 1.45831 +** transaction are reverted and the current write-transaction is closed.
 1.45832 +** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
 1.45833 +** state if an error occurs.
 1.45834 +**
 1.45835 +** If the pager is already in PAGER_ERROR state when this function is called,
 1.45836 +** it returns Pager.errCode immediately. No work is performed in this case.
 1.45837 +**
 1.45838 +** Otherwise, in rollback mode, this function performs two functions:
 1.45839 +**
 1.45840 +**   1) It rolls back the journal file, restoring all database file and 
 1.45841 +**      in-memory cache pages to the state they were in when the transaction
 1.45842 +**      was opened, and
 1.45843 +**
 1.45844 +**   2) It finalizes the journal file, so that it is not used for hot
 1.45845 +**      rollback at any point in the future.
 1.45846 +**
 1.45847 +** Finalization of the journal file (task 2) is only performed if the 
 1.45848 +** rollback is successful.
 1.45849 +**
 1.45850 +** In WAL mode, all cache-entries containing data modified within the
 1.45851 +** current transaction are either expelled from the cache or reverted to
 1.45852 +** their pre-transaction state by re-reading data from the database or
 1.45853 +** WAL files. The WAL transaction is then closed.
 1.45854 +*/
 1.45855 +SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
 1.45856 +  int rc = SQLITE_OK;                  /* Return code */
 1.45857 +  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
 1.45858 +
 1.45859 +  /* PagerRollback() is a no-op if called in READER or OPEN state. If
 1.45860 +  ** the pager is already in the ERROR state, the rollback is not 
 1.45861 +  ** attempted here. Instead, the error code is returned to the caller.
 1.45862 +  */
 1.45863 +  assert( assert_pager_state(pPager) );
 1.45864 +  if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
 1.45865 +  if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
 1.45866 +
 1.45867 +  if( pagerUseWal(pPager) ){
 1.45868 +    int rc2;
 1.45869 +    rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
 1.45870 +    rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
 1.45871 +    if( rc==SQLITE_OK ) rc = rc2;
 1.45872 +  }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
 1.45873 +    int eState = pPager->eState;
 1.45874 +    rc = pager_end_transaction(pPager, 0, 0);
 1.45875 +    if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
 1.45876 +      /* This can happen using journal_mode=off. Move the pager to the error 
 1.45877 +      ** state to indicate that the contents of the cache may not be trusted.
 1.45878 +      ** Any active readers will get SQLITE_ABORT.
 1.45879 +      */
 1.45880 +      pPager->errCode = SQLITE_ABORT;
 1.45881 +      pPager->eState = PAGER_ERROR;
 1.45882 +      return rc;
 1.45883 +    }
 1.45884 +  }else{
 1.45885 +    rc = pager_playback(pPager, 0);
 1.45886 +  }
 1.45887 +
 1.45888 +  assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
 1.45889 +  assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
 1.45890 +          || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR 
 1.45891 +          || rc==SQLITE_CANTOPEN
 1.45892 +  );
 1.45893 +
 1.45894 +  /* If an error occurs during a ROLLBACK, we can no longer trust the pager
 1.45895 +  ** cache. So call pager_error() on the way out to make any error persistent.
 1.45896 +  */
 1.45897 +  return pager_error(pPager, rc);
 1.45898 +}
 1.45899 +
 1.45900 +/*
 1.45901 +** Return TRUE if the database file is opened read-only.  Return FALSE
 1.45902 +** if the database is (in theory) writable.
 1.45903 +*/
 1.45904 +SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
 1.45905 +  return pPager->readOnly;
 1.45906 +}
 1.45907 +
 1.45908 +/*
 1.45909 +** Return the number of references to the pager.
 1.45910 +*/
 1.45911 +SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
 1.45912 +  return sqlite3PcacheRefCount(pPager->pPCache);
 1.45913 +}
 1.45914 +
 1.45915 +/*
 1.45916 +** Return the approximate number of bytes of memory currently
 1.45917 +** used by the pager and its associated cache.
 1.45918 +*/
 1.45919 +SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
 1.45920 +  int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
 1.45921 +                                     + 5*sizeof(void*);
 1.45922 +  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
 1.45923 +           + sqlite3MallocSize(pPager)
 1.45924 +           + pPager->pageSize;
 1.45925 +}
 1.45926 +
 1.45927 +/*
 1.45928 +** Return the number of references to the specified page.
 1.45929 +*/
 1.45930 +SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
 1.45931 +  return sqlite3PcachePageRefcount(pPage);
 1.45932 +}
 1.45933 +
 1.45934 +#ifdef SQLITE_TEST
 1.45935 +/*
 1.45936 +** This routine is used for testing and analysis only.
 1.45937 +*/
 1.45938 +SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
 1.45939 +  static int a[11];
 1.45940 +  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
 1.45941 +  a[1] = sqlite3PcachePagecount(pPager->pPCache);
 1.45942 +  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
 1.45943 +  a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
 1.45944 +  a[4] = pPager->eState;
 1.45945 +  a[5] = pPager->errCode;
 1.45946 +  a[6] = pPager->aStat[PAGER_STAT_HIT];
 1.45947 +  a[7] = pPager->aStat[PAGER_STAT_MISS];
 1.45948 +  a[8] = 0;  /* Used to be pPager->nOvfl */
 1.45949 +  a[9] = pPager->nRead;
 1.45950 +  a[10] = pPager->aStat[PAGER_STAT_WRITE];
 1.45951 +  return a;
 1.45952 +}
 1.45953 +#endif
 1.45954 +
 1.45955 +/*
 1.45956 +** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
 1.45957 +** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
 1.45958 +** current cache hit or miss count, according to the value of eStat. If the 
 1.45959 +** reset parameter is non-zero, the cache hit or miss count is zeroed before 
 1.45960 +** returning.
 1.45961 +*/
 1.45962 +SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
 1.45963 +
 1.45964 +  assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
 1.45965 +       || eStat==SQLITE_DBSTATUS_CACHE_MISS
 1.45966 +       || eStat==SQLITE_DBSTATUS_CACHE_WRITE
 1.45967 +  );
 1.45968 +
 1.45969 +  assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
 1.45970 +  assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
 1.45971 +  assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
 1.45972 +
 1.45973 +  *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
 1.45974 +  if( reset ){
 1.45975 +    pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
 1.45976 +  }
 1.45977 +}
 1.45978 +
 1.45979 +/*
 1.45980 +** Return true if this is an in-memory pager.
 1.45981 +*/
 1.45982 +SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
 1.45983 +  return MEMDB;
 1.45984 +}
 1.45985 +
 1.45986 +/*
 1.45987 +** Check that there are at least nSavepoint savepoints open. If there are
 1.45988 +** currently less than nSavepoints open, then open one or more savepoints
 1.45989 +** to make up the difference. If the number of savepoints is already
 1.45990 +** equal to nSavepoint, then this function is a no-op.
 1.45991 +**
 1.45992 +** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
 1.45993 +** occurs while opening the sub-journal file, then an IO error code is
 1.45994 +** returned. Otherwise, SQLITE_OK.
 1.45995 +*/
 1.45996 +SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
 1.45997 +  int rc = SQLITE_OK;                       /* Return code */
 1.45998 +  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
 1.45999 +
 1.46000 +  assert( pPager->eState>=PAGER_WRITER_LOCKED );
 1.46001 +  assert( assert_pager_state(pPager) );
 1.46002 +
 1.46003 +  if( nSavepoint>nCurrent && pPager->useJournal ){
 1.46004 +    int ii;                                 /* Iterator variable */
 1.46005 +    PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
 1.46006 +
 1.46007 +    /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
 1.46008 +    ** if the allocation fails. Otherwise, zero the new portion in case a 
 1.46009 +    ** malloc failure occurs while populating it in the for(...) loop below.
 1.46010 +    */
 1.46011 +    aNew = (PagerSavepoint *)sqlite3Realloc(
 1.46012 +        pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
 1.46013 +    );
 1.46014 +    if( !aNew ){
 1.46015 +      return SQLITE_NOMEM;
 1.46016 +    }
 1.46017 +    memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
 1.46018 +    pPager->aSavepoint = aNew;
 1.46019 +
 1.46020 +    /* Populate the PagerSavepoint structures just allocated. */
 1.46021 +    for(ii=nCurrent; ii<nSavepoint; ii++){
 1.46022 +      aNew[ii].nOrig = pPager->dbSize;
 1.46023 +      if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
 1.46024 +        aNew[ii].iOffset = pPager->journalOff;
 1.46025 +      }else{
 1.46026 +        aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
 1.46027 +      }
 1.46028 +      aNew[ii].iSubRec = pPager->nSubRec;
 1.46029 +      aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
 1.46030 +      if( !aNew[ii].pInSavepoint ){
 1.46031 +        return SQLITE_NOMEM;
 1.46032 +      }
 1.46033 +      if( pagerUseWal(pPager) ){
 1.46034 +        sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
 1.46035 +      }
 1.46036 +      pPager->nSavepoint = ii+1;
 1.46037 +    }
 1.46038 +    assert( pPager->nSavepoint==nSavepoint );
 1.46039 +    assertTruncateConstraint(pPager);
 1.46040 +  }
 1.46041 +
 1.46042 +  return rc;
 1.46043 +}
 1.46044 +
 1.46045 +/*
 1.46046 +** This function is called to rollback or release (commit) a savepoint.
 1.46047 +** The savepoint to release or rollback need not be the most recently 
 1.46048 +** created savepoint.
 1.46049 +**
 1.46050 +** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
 1.46051 +** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
 1.46052 +** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
 1.46053 +** that have occurred since the specified savepoint was created.
 1.46054 +**
 1.46055 +** The savepoint to rollback or release is identified by parameter 
 1.46056 +** iSavepoint. A value of 0 means to operate on the outermost savepoint
 1.46057 +** (the first created). A value of (Pager.nSavepoint-1) means operate
 1.46058 +** on the most recently created savepoint. If iSavepoint is greater than
 1.46059 +** (Pager.nSavepoint-1), then this function is a no-op.
 1.46060 +**
 1.46061 +** If a negative value is passed to this function, then the current
 1.46062 +** transaction is rolled back. This is different to calling 
 1.46063 +** sqlite3PagerRollback() because this function does not terminate
 1.46064 +** the transaction or unlock the database, it just restores the 
 1.46065 +** contents of the database to its original state. 
 1.46066 +**
 1.46067 +** In any case, all savepoints with an index greater than iSavepoint 
 1.46068 +** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
 1.46069 +** then savepoint iSavepoint is also destroyed.
 1.46070 +**
 1.46071 +** This function may return SQLITE_NOMEM if a memory allocation fails,
 1.46072 +** or an IO error code if an IO error occurs while rolling back a 
 1.46073 +** savepoint. If no errors occur, SQLITE_OK is returned.
 1.46074 +*/ 
 1.46075 +SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
 1.46076 +  int rc = pPager->errCode;       /* Return code */
 1.46077 +
 1.46078 +  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
 1.46079 +  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
 1.46080 +
 1.46081 +  if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
 1.46082 +    int ii;            /* Iterator variable */
 1.46083 +    int nNew;          /* Number of remaining savepoints after this op. */
 1.46084 +
 1.46085 +    /* Figure out how many savepoints will still be active after this
 1.46086 +    ** operation. Store this value in nNew. Then free resources associated 
 1.46087 +    ** with any savepoints that are destroyed by this operation.
 1.46088 +    */
 1.46089 +    nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
 1.46090 +    for(ii=nNew; ii<pPager->nSavepoint; ii++){
 1.46091 +      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
 1.46092 +    }
 1.46093 +    pPager->nSavepoint = nNew;
 1.46094 +
 1.46095 +    /* If this is a release of the outermost savepoint, truncate 
 1.46096 +    ** the sub-journal to zero bytes in size. */
 1.46097 +    if( op==SAVEPOINT_RELEASE ){
 1.46098 +      if( nNew==0 && isOpen(pPager->sjfd) ){
 1.46099 +        /* Only truncate if it is an in-memory sub-journal. */
 1.46100 +        if( sqlite3IsMemJournal(pPager->sjfd) ){
 1.46101 +          rc = sqlite3OsTruncate(pPager->sjfd, 0);
 1.46102 +          assert( rc==SQLITE_OK );
 1.46103 +        }
 1.46104 +        pPager->nSubRec = 0;
 1.46105 +      }
 1.46106 +    }
 1.46107 +    /* Else this is a rollback operation, playback the specified savepoint.
 1.46108 +    ** If this is a temp-file, it is possible that the journal file has
 1.46109 +    ** not yet been opened. In this case there have been no changes to
 1.46110 +    ** the database file, so the playback operation can be skipped.
 1.46111 +    */
 1.46112 +    else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
 1.46113 +      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
 1.46114 +      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
 1.46115 +      assert(rc!=SQLITE_DONE);
 1.46116 +    }
 1.46117 +  }
 1.46118 +
 1.46119 +  return rc;
 1.46120 +}
 1.46121 +
 1.46122 +/*
 1.46123 +** Return the full pathname of the database file.
 1.46124 +**
 1.46125 +** Except, if the pager is in-memory only, then return an empty string if
 1.46126 +** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
 1.46127 +** used to report the filename to the user, for compatibility with legacy
 1.46128 +** behavior.  But when the Btree needs to know the filename for matching to
 1.46129 +** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
 1.46130 +** participate in shared-cache.
 1.46131 +*/
 1.46132 +SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
 1.46133 +  return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
 1.46134 +}
 1.46135 +
 1.46136 +/*
 1.46137 +** Return the VFS structure for the pager.
 1.46138 +*/
 1.46139 +SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
 1.46140 +  return pPager->pVfs;
 1.46141 +}
 1.46142 +
 1.46143 +/*
 1.46144 +** Return the file handle for the database file associated
 1.46145 +** with the pager.  This might return NULL if the file has
 1.46146 +** not yet been opened.
 1.46147 +*/
 1.46148 +SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
 1.46149 +  return pPager->fd;
 1.46150 +}
 1.46151 +
 1.46152 +/*
 1.46153 +** Return the full pathname of the journal file.
 1.46154 +*/
 1.46155 +SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
 1.46156 +  return pPager->zJournal;
 1.46157 +}
 1.46158 +
 1.46159 +/*
 1.46160 +** Return true if fsync() calls are disabled for this pager.  Return FALSE
 1.46161 +** if fsync()s are executed normally.
 1.46162 +*/
 1.46163 +SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
 1.46164 +  return pPager->noSync;
 1.46165 +}
 1.46166 +
 1.46167 +#ifdef SQLITE_HAS_CODEC
 1.46168 +/*
 1.46169 +** Set or retrieve the codec for this pager
 1.46170 +*/
 1.46171 +SQLITE_PRIVATE void sqlite3PagerSetCodec(
 1.46172 +  Pager *pPager,
 1.46173 +  void *(*xCodec)(void*,void*,Pgno,int),
 1.46174 +  void (*xCodecSizeChng)(void*,int,int),
 1.46175 +  void (*xCodecFree)(void*),
 1.46176 +  void *pCodec
 1.46177 +){
 1.46178 +  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
 1.46179 +  pPager->xCodec = pPager->memDb ? 0 : xCodec;
 1.46180 +  pPager->xCodecSizeChng = xCodecSizeChng;
 1.46181 +  pPager->xCodecFree = xCodecFree;
 1.46182 +  pPager->pCodec = pCodec;
 1.46183 +  pagerReportSize(pPager);
 1.46184 +}
 1.46185 +SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
 1.46186 +  return pPager->pCodec;
 1.46187 +}
 1.46188 +
 1.46189 +/*
 1.46190 +** This function is called by the wal module when writing page content
 1.46191 +** into the log file.
 1.46192 +**
 1.46193 +** This function returns a pointer to a buffer containing the encrypted
 1.46194 +** page content. If a malloc fails, this function may return NULL.
 1.46195 +*/
 1.46196 +SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
 1.46197 +  void *aData = 0;
 1.46198 +  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
 1.46199 +  return aData;
 1.46200 +}
 1.46201 +
 1.46202 +/*
 1.46203 +** Return the current pager state
 1.46204 +*/
 1.46205 +SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
 1.46206 +  return pPager->eState;
 1.46207 +}
 1.46208 +#endif /* SQLITE_HAS_CODEC */
 1.46209 +
 1.46210 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.46211 +/*
 1.46212 +** Move the page pPg to location pgno in the file.
 1.46213 +**
 1.46214 +** There must be no references to the page previously located at
 1.46215 +** pgno (which we call pPgOld) though that page is allowed to be
 1.46216 +** in cache.  If the page previously located at pgno is not already
 1.46217 +** in the rollback journal, it is not put there by by this routine.
 1.46218 +**
 1.46219 +** References to the page pPg remain valid. Updating any
 1.46220 +** meta-data associated with pPg (i.e. data stored in the nExtra bytes
 1.46221 +** allocated along with the page) is the responsibility of the caller.
 1.46222 +**
 1.46223 +** A transaction must be active when this routine is called. It used to be
 1.46224 +** required that a statement transaction was not active, but this restriction
 1.46225 +** has been removed (CREATE INDEX needs to move a page when a statement
 1.46226 +** transaction is active).
 1.46227 +**
 1.46228 +** If the fourth argument, isCommit, is non-zero, then this page is being
 1.46229 +** moved as part of a database reorganization just before the transaction 
 1.46230 +** is being committed. In this case, it is guaranteed that the database page 
 1.46231 +** pPg refers to will not be written to again within this transaction.
 1.46232 +**
 1.46233 +** This function may return SQLITE_NOMEM or an IO error code if an error
 1.46234 +** occurs. Otherwise, it returns SQLITE_OK.
 1.46235 +*/
 1.46236 +SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
 1.46237 +  PgHdr *pPgOld;               /* The page being overwritten. */
 1.46238 +  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
 1.46239 +  int rc;                      /* Return code */
 1.46240 +  Pgno origPgno;               /* The original page number */
 1.46241 +
 1.46242 +  assert( pPg->nRef>0 );
 1.46243 +  assert( pPager->eState==PAGER_WRITER_CACHEMOD
 1.46244 +       || pPager->eState==PAGER_WRITER_DBMOD
 1.46245 +  );
 1.46246 +  assert( assert_pager_state(pPager) );
 1.46247 +
 1.46248 +  /* In order to be able to rollback, an in-memory database must journal
 1.46249 +  ** the page we are moving from.
 1.46250 +  */
 1.46251 +  if( MEMDB ){
 1.46252 +    rc = sqlite3PagerWrite(pPg);
 1.46253 +    if( rc ) return rc;
 1.46254 +  }
 1.46255 +
 1.46256 +  /* If the page being moved is dirty and has not been saved by the latest
 1.46257 +  ** savepoint, then save the current contents of the page into the 
 1.46258 +  ** sub-journal now. This is required to handle the following scenario:
 1.46259 +  **
 1.46260 +  **   BEGIN;
 1.46261 +  **     <journal page X, then modify it in memory>
 1.46262 +  **     SAVEPOINT one;
 1.46263 +  **       <Move page X to location Y>
 1.46264 +  **     ROLLBACK TO one;
 1.46265 +  **
 1.46266 +  ** If page X were not written to the sub-journal here, it would not
 1.46267 +  ** be possible to restore its contents when the "ROLLBACK TO one"
 1.46268 +  ** statement were is processed.
 1.46269 +  **
 1.46270 +  ** subjournalPage() may need to allocate space to store pPg->pgno into
 1.46271 +  ** one or more savepoint bitvecs. This is the reason this function
 1.46272 +  ** may return SQLITE_NOMEM.
 1.46273 +  */
 1.46274 +  if( pPg->flags&PGHDR_DIRTY
 1.46275 +   && subjRequiresPage(pPg)
 1.46276 +   && SQLITE_OK!=(rc = subjournalPage(pPg))
 1.46277 +  ){
 1.46278 +    return rc;
 1.46279 +  }
 1.46280 +
 1.46281 +  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
 1.46282 +      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
 1.46283 +  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
 1.46284 +
 1.46285 +  /* If the journal needs to be sync()ed before page pPg->pgno can
 1.46286 +  ** be written to, store pPg->pgno in local variable needSyncPgno.
 1.46287 +  **
 1.46288 +  ** If the isCommit flag is set, there is no need to remember that
 1.46289 +  ** the journal needs to be sync()ed before database page pPg->pgno 
 1.46290 +  ** can be written to. The caller has already promised not to write to it.
 1.46291 +  */
 1.46292 +  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
 1.46293 +    needSyncPgno = pPg->pgno;
 1.46294 +    assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
 1.46295 +            pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
 1.46296 +    assert( pPg->flags&PGHDR_DIRTY );
 1.46297 +  }
 1.46298 +
 1.46299 +  /* If the cache contains a page with page-number pgno, remove it
 1.46300 +  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for 
 1.46301 +  ** page pgno before the 'move' operation, it needs to be retained 
 1.46302 +  ** for the page moved there.
 1.46303 +  */
 1.46304 +  pPg->flags &= ~PGHDR_NEED_SYNC;
 1.46305 +  pPgOld = pager_lookup(pPager, pgno);
 1.46306 +  assert( !pPgOld || pPgOld->nRef==1 );
 1.46307 +  if( pPgOld ){
 1.46308 +    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
 1.46309 +    if( MEMDB ){
 1.46310 +      /* Do not discard pages from an in-memory database since we might
 1.46311 +      ** need to rollback later.  Just move the page out of the way. */
 1.46312 +      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
 1.46313 +    }else{
 1.46314 +      sqlite3PcacheDrop(pPgOld);
 1.46315 +    }
 1.46316 +  }
 1.46317 +
 1.46318 +  origPgno = pPg->pgno;
 1.46319 +  sqlite3PcacheMove(pPg, pgno);
 1.46320 +  sqlite3PcacheMakeDirty(pPg);
 1.46321 +
 1.46322 +  /* For an in-memory database, make sure the original page continues
 1.46323 +  ** to exist, in case the transaction needs to roll back.  Use pPgOld
 1.46324 +  ** as the original page since it has already been allocated.
 1.46325 +  */
 1.46326 +  if( MEMDB ){
 1.46327 +    assert( pPgOld );
 1.46328 +    sqlite3PcacheMove(pPgOld, origPgno);
 1.46329 +    sqlite3PagerUnrefNotNull(pPgOld);
 1.46330 +  }
 1.46331 +
 1.46332 +  if( needSyncPgno ){
 1.46333 +    /* If needSyncPgno is non-zero, then the journal file needs to be 
 1.46334 +    ** sync()ed before any data is written to database file page needSyncPgno.
 1.46335 +    ** Currently, no such page exists in the page-cache and the 
 1.46336 +    ** "is journaled" bitvec flag has been set. This needs to be remedied by
 1.46337 +    ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
 1.46338 +    ** flag.
 1.46339 +    **
 1.46340 +    ** If the attempt to load the page into the page-cache fails, (due
 1.46341 +    ** to a malloc() or IO failure), clear the bit in the pInJournal[]
 1.46342 +    ** array. Otherwise, if the page is loaded and written again in
 1.46343 +    ** this transaction, it may be written to the database file before
 1.46344 +    ** it is synced into the journal file. This way, it may end up in
 1.46345 +    ** the journal file twice, but that is not a problem.
 1.46346 +    */
 1.46347 +    PgHdr *pPgHdr;
 1.46348 +    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
 1.46349 +    if( rc!=SQLITE_OK ){
 1.46350 +      if( needSyncPgno<=pPager->dbOrigSize ){
 1.46351 +        assert( pPager->pTmpSpace!=0 );
 1.46352 +        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
 1.46353 +      }
 1.46354 +      return rc;
 1.46355 +    }
 1.46356 +    pPgHdr->flags |= PGHDR_NEED_SYNC;
 1.46357 +    sqlite3PcacheMakeDirty(pPgHdr);
 1.46358 +    sqlite3PagerUnrefNotNull(pPgHdr);
 1.46359 +  }
 1.46360 +
 1.46361 +  return SQLITE_OK;
 1.46362 +}
 1.46363 +#endif
 1.46364 +
 1.46365 +/*
 1.46366 +** Return a pointer to the data for the specified page.
 1.46367 +*/
 1.46368 +SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
 1.46369 +  assert( pPg->nRef>0 || pPg->pPager->memDb );
 1.46370 +  return pPg->pData;
 1.46371 +}
 1.46372 +
 1.46373 +/*
 1.46374 +** Return a pointer to the Pager.nExtra bytes of "extra" space 
 1.46375 +** allocated along with the specified page.
 1.46376 +*/
 1.46377 +SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
 1.46378 +  return pPg->pExtra;
 1.46379 +}
 1.46380 +
 1.46381 +/*
 1.46382 +** Get/set the locking-mode for this pager. Parameter eMode must be one
 1.46383 +** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
 1.46384 +** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
 1.46385 +** the locking-mode is set to the value specified.
 1.46386 +**
 1.46387 +** The returned value is either PAGER_LOCKINGMODE_NORMAL or
 1.46388 +** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
 1.46389 +** locking-mode.
 1.46390 +*/
 1.46391 +SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
 1.46392 +  assert( eMode==PAGER_LOCKINGMODE_QUERY
 1.46393 +            || eMode==PAGER_LOCKINGMODE_NORMAL
 1.46394 +            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
 1.46395 +  assert( PAGER_LOCKINGMODE_QUERY<0 );
 1.46396 +  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
 1.46397 +  assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
 1.46398 +  if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
 1.46399 +    pPager->exclusiveMode = (u8)eMode;
 1.46400 +  }
 1.46401 +  return (int)pPager->exclusiveMode;
 1.46402 +}
 1.46403 +
 1.46404 +/*
 1.46405 +** Set the journal-mode for this pager. Parameter eMode must be one of:
 1.46406 +**
 1.46407 +**    PAGER_JOURNALMODE_DELETE
 1.46408 +**    PAGER_JOURNALMODE_TRUNCATE
 1.46409 +**    PAGER_JOURNALMODE_PERSIST
 1.46410 +**    PAGER_JOURNALMODE_OFF
 1.46411 +**    PAGER_JOURNALMODE_MEMORY
 1.46412 +**    PAGER_JOURNALMODE_WAL
 1.46413 +**
 1.46414 +** The journalmode is set to the value specified if the change is allowed.
 1.46415 +** The change may be disallowed for the following reasons:
 1.46416 +**
 1.46417 +**   *  An in-memory database can only have its journal_mode set to _OFF
 1.46418 +**      or _MEMORY.
 1.46419 +**
 1.46420 +**   *  Temporary databases cannot have _WAL journalmode.
 1.46421 +**
 1.46422 +** The returned indicate the current (possibly updated) journal-mode.
 1.46423 +*/
 1.46424 +SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
 1.46425 +  u8 eOld = pPager->journalMode;    /* Prior journalmode */
 1.46426 +
 1.46427 +#ifdef SQLITE_DEBUG
 1.46428 +  /* The print_pager_state() routine is intended to be used by the debugger
 1.46429 +  ** only.  We invoke it once here to suppress a compiler warning. */
 1.46430 +  print_pager_state(pPager);
 1.46431 +#endif
 1.46432 +
 1.46433 +
 1.46434 +  /* The eMode parameter is always valid */
 1.46435 +  assert(      eMode==PAGER_JOURNALMODE_DELETE
 1.46436 +            || eMode==PAGER_JOURNALMODE_TRUNCATE
 1.46437 +            || eMode==PAGER_JOURNALMODE_PERSIST
 1.46438 +            || eMode==PAGER_JOURNALMODE_OFF 
 1.46439 +            || eMode==PAGER_JOURNALMODE_WAL 
 1.46440 +            || eMode==PAGER_JOURNALMODE_MEMORY );
 1.46441 +
 1.46442 +  /* This routine is only called from the OP_JournalMode opcode, and
 1.46443 +  ** the logic there will never allow a temporary file to be changed
 1.46444 +  ** to WAL mode.
 1.46445 +  */
 1.46446 +  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
 1.46447 +
 1.46448 +  /* Do allow the journalmode of an in-memory database to be set to
 1.46449 +  ** anything other than MEMORY or OFF
 1.46450 +  */
 1.46451 +  if( MEMDB ){
 1.46452 +    assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
 1.46453 +    if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
 1.46454 +      eMode = eOld;
 1.46455 +    }
 1.46456 +  }
 1.46457 +
 1.46458 +  if( eMode!=eOld ){
 1.46459 +
 1.46460 +    /* Change the journal mode. */
 1.46461 +    assert( pPager->eState!=PAGER_ERROR );
 1.46462 +    pPager->journalMode = (u8)eMode;
 1.46463 +
 1.46464 +    /* When transistioning from TRUNCATE or PERSIST to any other journal
 1.46465 +    ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
 1.46466 +    ** delete the journal file.
 1.46467 +    */
 1.46468 +    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
 1.46469 +    assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
 1.46470 +    assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
 1.46471 +    assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
 1.46472 +    assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
 1.46473 +    assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
 1.46474 +
 1.46475 +    assert( isOpen(pPager->fd) || pPager->exclusiveMode );
 1.46476 +    if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
 1.46477 +
 1.46478 +      /* In this case we would like to delete the journal file. If it is
 1.46479 +      ** not possible, then that is not a problem. Deleting the journal file
 1.46480 +      ** here is an optimization only.
 1.46481 +      **
 1.46482 +      ** Before deleting the journal file, obtain a RESERVED lock on the
 1.46483 +      ** database file. This ensures that the journal file is not deleted
 1.46484 +      ** while it is in use by some other client.
 1.46485 +      */
 1.46486 +      sqlite3OsClose(pPager->jfd);
 1.46487 +      if( pPager->eLock>=RESERVED_LOCK ){
 1.46488 +        sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
 1.46489 +      }else{
 1.46490 +        int rc = SQLITE_OK;
 1.46491 +        int state = pPager->eState;
 1.46492 +        assert( state==PAGER_OPEN || state==PAGER_READER );
 1.46493 +        if( state==PAGER_OPEN ){
 1.46494 +          rc = sqlite3PagerSharedLock(pPager);
 1.46495 +        }
 1.46496 +        if( pPager->eState==PAGER_READER ){
 1.46497 +          assert( rc==SQLITE_OK );
 1.46498 +          rc = pagerLockDb(pPager, RESERVED_LOCK);
 1.46499 +        }
 1.46500 +        if( rc==SQLITE_OK ){
 1.46501 +          sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
 1.46502 +        }
 1.46503 +        if( rc==SQLITE_OK && state==PAGER_READER ){
 1.46504 +          pagerUnlockDb(pPager, SHARED_LOCK);
 1.46505 +        }else if( state==PAGER_OPEN ){
 1.46506 +          pager_unlock(pPager);
 1.46507 +        }
 1.46508 +        assert( state==pPager->eState );
 1.46509 +      }
 1.46510 +    }
 1.46511 +  }
 1.46512 +
 1.46513 +  /* Return the new journal mode */
 1.46514 +  return (int)pPager->journalMode;
 1.46515 +}
 1.46516 +
 1.46517 +/*
 1.46518 +** Return the current journal mode.
 1.46519 +*/
 1.46520 +SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
 1.46521 +  return (int)pPager->journalMode;
 1.46522 +}
 1.46523 +
 1.46524 +/*
 1.46525 +** Return TRUE if the pager is in a state where it is OK to change the
 1.46526 +** journalmode.  Journalmode changes can only happen when the database
 1.46527 +** is unmodified.
 1.46528 +*/
 1.46529 +SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
 1.46530 +  assert( assert_pager_state(pPager) );
 1.46531 +  if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
 1.46532 +  if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
 1.46533 +  return 1;
 1.46534 +}
 1.46535 +
 1.46536 +/*
 1.46537 +** Get/set the size-limit used for persistent journal files.
 1.46538 +**
 1.46539 +** Setting the size limit to -1 means no limit is enforced.
 1.46540 +** An attempt to set a limit smaller than -1 is a no-op.
 1.46541 +*/
 1.46542 +SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
 1.46543 +  if( iLimit>=-1 ){
 1.46544 +    pPager->journalSizeLimit = iLimit;
 1.46545 +    sqlite3WalLimit(pPager->pWal, iLimit);
 1.46546 +  }
 1.46547 +  return pPager->journalSizeLimit;
 1.46548 +}
 1.46549 +
 1.46550 +/*
 1.46551 +** Return a pointer to the pPager->pBackup variable. The backup module
 1.46552 +** in backup.c maintains the content of this variable. This module
 1.46553 +** uses it opaquely as an argument to sqlite3BackupRestart() and
 1.46554 +** sqlite3BackupUpdate() only.
 1.46555 +*/
 1.46556 +SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
 1.46557 +  return &pPager->pBackup;
 1.46558 +}
 1.46559 +
 1.46560 +#ifndef SQLITE_OMIT_VACUUM
 1.46561 +/*
 1.46562 +** Unless this is an in-memory or temporary database, clear the pager cache.
 1.46563 +*/
 1.46564 +SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
 1.46565 +  if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
 1.46566 +}
 1.46567 +#endif
 1.46568 +
 1.46569 +#ifndef SQLITE_OMIT_WAL
 1.46570 +/*
 1.46571 +** This function is called when the user invokes "PRAGMA wal_checkpoint",
 1.46572 +** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
 1.46573 +** or wal_blocking_checkpoint() API functions.
 1.46574 +**
 1.46575 +** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
 1.46576 +*/
 1.46577 +SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
 1.46578 +  int rc = SQLITE_OK;
 1.46579 +  if( pPager->pWal ){
 1.46580 +    rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
 1.46581 +        pPager->xBusyHandler, pPager->pBusyHandlerArg,
 1.46582 +        pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
 1.46583 +        pnLog, pnCkpt
 1.46584 +    );
 1.46585 +  }
 1.46586 +  return rc;
 1.46587 +}
 1.46588 +
 1.46589 +SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
 1.46590 +  return sqlite3WalCallback(pPager->pWal);
 1.46591 +}
 1.46592 +
 1.46593 +/*
 1.46594 +** Return true if the underlying VFS for the given pager supports the
 1.46595 +** primitives necessary for write-ahead logging.
 1.46596 +*/
 1.46597 +SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
 1.46598 +  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
 1.46599 +  return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
 1.46600 +}
 1.46601 +
 1.46602 +/*
 1.46603 +** Attempt to take an exclusive lock on the database file. If a PENDING lock
 1.46604 +** is obtained instead, immediately release it.
 1.46605 +*/
 1.46606 +static int pagerExclusiveLock(Pager *pPager){
 1.46607 +  int rc;                         /* Return code */
 1.46608 +
 1.46609 +  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
 1.46610 +  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
 1.46611 +  if( rc!=SQLITE_OK ){
 1.46612 +    /* If the attempt to grab the exclusive lock failed, release the 
 1.46613 +    ** pending lock that may have been obtained instead.  */
 1.46614 +    pagerUnlockDb(pPager, SHARED_LOCK);
 1.46615 +  }
 1.46616 +
 1.46617 +  return rc;
 1.46618 +}
 1.46619 +
 1.46620 +/*
 1.46621 +** Call sqlite3WalOpen() to open the WAL handle. If the pager is in 
 1.46622 +** exclusive-locking mode when this function is called, take an EXCLUSIVE
 1.46623 +** lock on the database file and use heap-memory to store the wal-index
 1.46624 +** in. Otherwise, use the normal shared-memory.
 1.46625 +*/
 1.46626 +static int pagerOpenWal(Pager *pPager){
 1.46627 +  int rc = SQLITE_OK;
 1.46628 +
 1.46629 +  assert( pPager->pWal==0 && pPager->tempFile==0 );
 1.46630 +  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
 1.46631 +
 1.46632 +  /* If the pager is already in exclusive-mode, the WAL module will use 
 1.46633 +  ** heap-memory for the wal-index instead of the VFS shared-memory 
 1.46634 +  ** implementation. Take the exclusive lock now, before opening the WAL
 1.46635 +  ** file, to make sure this is safe.
 1.46636 +  */
 1.46637 +  if( pPager->exclusiveMode ){
 1.46638 +    rc = pagerExclusiveLock(pPager);
 1.46639 +  }
 1.46640 +
 1.46641 +  /* Open the connection to the log file. If this operation fails, 
 1.46642 +  ** (e.g. due to malloc() failure), return an error code.
 1.46643 +  */
 1.46644 +  if( rc==SQLITE_OK ){
 1.46645 +    rc = sqlite3WalOpen(pPager->pVfs,
 1.46646 +        pPager->fd, pPager->zWal, pPager->exclusiveMode,
 1.46647 +        pPager->journalSizeLimit, &pPager->pWal
 1.46648 +    );
 1.46649 +  }
 1.46650 +  pagerFixMaplimit(pPager);
 1.46651 +
 1.46652 +  return rc;
 1.46653 +}
 1.46654 +
 1.46655 +
 1.46656 +/*
 1.46657 +** The caller must be holding a SHARED lock on the database file to call
 1.46658 +** this function.
 1.46659 +**
 1.46660 +** If the pager passed as the first argument is open on a real database
 1.46661 +** file (not a temp file or an in-memory database), and the WAL file
 1.46662 +** is not already open, make an attempt to open it now. If successful,
 1.46663 +** return SQLITE_OK. If an error occurs or the VFS used by the pager does 
 1.46664 +** not support the xShmXXX() methods, return an error code. *pbOpen is
 1.46665 +** not modified in either case.
 1.46666 +**
 1.46667 +** If the pager is open on a temp-file (or in-memory database), or if
 1.46668 +** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
 1.46669 +** without doing anything.
 1.46670 +*/
 1.46671 +SQLITE_PRIVATE int sqlite3PagerOpenWal(
 1.46672 +  Pager *pPager,                  /* Pager object */
 1.46673 +  int *pbOpen                     /* OUT: Set to true if call is a no-op */
 1.46674 +){
 1.46675 +  int rc = SQLITE_OK;             /* Return code */
 1.46676 +
 1.46677 +  assert( assert_pager_state(pPager) );
 1.46678 +  assert( pPager->eState==PAGER_OPEN   || pbOpen );
 1.46679 +  assert( pPager->eState==PAGER_READER || !pbOpen );
 1.46680 +  assert( pbOpen==0 || *pbOpen==0 );
 1.46681 +  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
 1.46682 +
 1.46683 +  if( !pPager->tempFile && !pPager->pWal ){
 1.46684 +    if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
 1.46685 +
 1.46686 +    /* Close any rollback journal previously open */
 1.46687 +    sqlite3OsClose(pPager->jfd);
 1.46688 +
 1.46689 +    rc = pagerOpenWal(pPager);
 1.46690 +    if( rc==SQLITE_OK ){
 1.46691 +      pPager->journalMode = PAGER_JOURNALMODE_WAL;
 1.46692 +      pPager->eState = PAGER_OPEN;
 1.46693 +    }
 1.46694 +  }else{
 1.46695 +    *pbOpen = 1;
 1.46696 +  }
 1.46697 +
 1.46698 +  return rc;
 1.46699 +}
 1.46700 +
 1.46701 +/*
 1.46702 +** This function is called to close the connection to the log file prior
 1.46703 +** to switching from WAL to rollback mode.
 1.46704 +**
 1.46705 +** Before closing the log file, this function attempts to take an 
 1.46706 +** EXCLUSIVE lock on the database file. If this cannot be obtained, an
 1.46707 +** error (SQLITE_BUSY) is returned and the log connection is not closed.
 1.46708 +** If successful, the EXCLUSIVE lock is not released before returning.
 1.46709 +*/
 1.46710 +SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
 1.46711 +  int rc = SQLITE_OK;
 1.46712 +
 1.46713 +  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
 1.46714 +
 1.46715 +  /* If the log file is not already open, but does exist in the file-system,
 1.46716 +  ** it may need to be checkpointed before the connection can switch to
 1.46717 +  ** rollback mode. Open it now so this can happen.
 1.46718 +  */
 1.46719 +  if( !pPager->pWal ){
 1.46720 +    int logexists = 0;
 1.46721 +    rc = pagerLockDb(pPager, SHARED_LOCK);
 1.46722 +    if( rc==SQLITE_OK ){
 1.46723 +      rc = sqlite3OsAccess(
 1.46724 +          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
 1.46725 +      );
 1.46726 +    }
 1.46727 +    if( rc==SQLITE_OK && logexists ){
 1.46728 +      rc = pagerOpenWal(pPager);
 1.46729 +    }
 1.46730 +  }
 1.46731 +    
 1.46732 +  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
 1.46733 +  ** the database file, the log and log-summary files will be deleted.
 1.46734 +  */
 1.46735 +  if( rc==SQLITE_OK && pPager->pWal ){
 1.46736 +    rc = pagerExclusiveLock(pPager);
 1.46737 +    if( rc==SQLITE_OK ){
 1.46738 +      rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
 1.46739 +                           pPager->pageSize, (u8*)pPager->pTmpSpace);
 1.46740 +      pPager->pWal = 0;
 1.46741 +      pagerFixMaplimit(pPager);
 1.46742 +    }
 1.46743 +  }
 1.46744 +  return rc;
 1.46745 +}
 1.46746 +
 1.46747 +#endif /* !SQLITE_OMIT_WAL */
 1.46748 +
 1.46749 +#ifdef SQLITE_ENABLE_ZIPVFS
 1.46750 +/*
 1.46751 +** A read-lock must be held on the pager when this function is called. If
 1.46752 +** the pager is in WAL mode and the WAL file currently contains one or more
 1.46753 +** frames, return the size in bytes of the page images stored within the
 1.46754 +** WAL frames. Otherwise, if this is not a WAL database or the WAL file
 1.46755 +** is empty, return 0.
 1.46756 +*/
 1.46757 +SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
 1.46758 +  assert( pPager->eState==PAGER_READER );
 1.46759 +  return sqlite3WalFramesize(pPager->pWal);
 1.46760 +}
 1.46761 +#endif
 1.46762 +
 1.46763 +#endif /* SQLITE_OMIT_DISKIO */
 1.46764 +
 1.46765 +/************** End of pager.c ***********************************************/
 1.46766 +/************** Begin file wal.c *********************************************/
 1.46767 +/*
 1.46768 +** 2010 February 1
 1.46769 +**
 1.46770 +** The author disclaims copyright to this source code.  In place of
 1.46771 +** a legal notice, here is a blessing:
 1.46772 +**
 1.46773 +**    May you do good and not evil.
 1.46774 +**    May you find forgiveness for yourself and forgive others.
 1.46775 +**    May you share freely, never taking more than you give.
 1.46776 +**
 1.46777 +*************************************************************************
 1.46778 +**
 1.46779 +** This file contains the implementation of a write-ahead log (WAL) used in 
 1.46780 +** "journal_mode=WAL" mode.
 1.46781 +**
 1.46782 +** WRITE-AHEAD LOG (WAL) FILE FORMAT
 1.46783 +**
 1.46784 +** A WAL file consists of a header followed by zero or more "frames".
 1.46785 +** Each frame records the revised content of a single page from the
 1.46786 +** database file.  All changes to the database are recorded by writing
 1.46787 +** frames into the WAL.  Transactions commit when a frame is written that
 1.46788 +** contains a commit marker.  A single WAL can and usually does record 
 1.46789 +** multiple transactions.  Periodically, the content of the WAL is
 1.46790 +** transferred back into the database file in an operation called a
 1.46791 +** "checkpoint".
 1.46792 +**
 1.46793 +** A single WAL file can be used multiple times.  In other words, the
 1.46794 +** WAL can fill up with frames and then be checkpointed and then new
 1.46795 +** frames can overwrite the old ones.  A WAL always grows from beginning
 1.46796 +** toward the end.  Checksums and counters attached to each frame are
 1.46797 +** used to determine which frames within the WAL are valid and which
 1.46798 +** are leftovers from prior checkpoints.
 1.46799 +**
 1.46800 +** The WAL header is 32 bytes in size and consists of the following eight
 1.46801 +** big-endian 32-bit unsigned integer values:
 1.46802 +**
 1.46803 +**     0: Magic number.  0x377f0682 or 0x377f0683
 1.46804 +**     4: File format version.  Currently 3007000
 1.46805 +**     8: Database page size.  Example: 1024
 1.46806 +**    12: Checkpoint sequence number
 1.46807 +**    16: Salt-1, random integer incremented with each checkpoint
 1.46808 +**    20: Salt-2, a different random integer changing with each ckpt
 1.46809 +**    24: Checksum-1 (first part of checksum for first 24 bytes of header).
 1.46810 +**    28: Checksum-2 (second part of checksum for first 24 bytes of header).
 1.46811 +**
 1.46812 +** Immediately following the wal-header are zero or more frames. Each
 1.46813 +** frame consists of a 24-byte frame-header followed by a <page-size> bytes
 1.46814 +** of page data. The frame-header is six big-endian 32-bit unsigned 
 1.46815 +** integer values, as follows:
 1.46816 +**
 1.46817 +**     0: Page number.
 1.46818 +**     4: For commit records, the size of the database image in pages 
 1.46819 +**        after the commit. For all other records, zero.
 1.46820 +**     8: Salt-1 (copied from the header)
 1.46821 +**    12: Salt-2 (copied from the header)
 1.46822 +**    16: Checksum-1.
 1.46823 +**    20: Checksum-2.
 1.46824 +**
 1.46825 +** A frame is considered valid if and only if the following conditions are
 1.46826 +** true:
 1.46827 +**
 1.46828 +**    (1) The salt-1 and salt-2 values in the frame-header match
 1.46829 +**        salt values in the wal-header
 1.46830 +**
 1.46831 +**    (2) The checksum values in the final 8 bytes of the frame-header
 1.46832 +**        exactly match the checksum computed consecutively on the
 1.46833 +**        WAL header and the first 8 bytes and the content of all frames
 1.46834 +**        up to and including the current frame.
 1.46835 +**
 1.46836 +** The checksum is computed using 32-bit big-endian integers if the
 1.46837 +** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
 1.46838 +** is computed using little-endian if the magic number is 0x377f0682.
 1.46839 +** The checksum values are always stored in the frame header in a
 1.46840 +** big-endian format regardless of which byte order is used to compute
 1.46841 +** the checksum.  The checksum is computed by interpreting the input as
 1.46842 +** an even number of unsigned 32-bit integers: x[0] through x[N].  The
 1.46843 +** algorithm used for the checksum is as follows:
 1.46844 +** 
 1.46845 +**   for i from 0 to n-1 step 2:
 1.46846 +**     s0 += x[i] + s1;
 1.46847 +**     s1 += x[i+1] + s0;
 1.46848 +**   endfor
 1.46849 +**
 1.46850 +** Note that s0 and s1 are both weighted checksums using fibonacci weights
 1.46851 +** in reverse order (the largest fibonacci weight occurs on the first element
 1.46852 +** of the sequence being summed.)  The s1 value spans all 32-bit 
 1.46853 +** terms of the sequence whereas s0 omits the final term.
 1.46854 +**
 1.46855 +** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
 1.46856 +** WAL is transferred into the database, then the database is VFS.xSync-ed.
 1.46857 +** The VFS.xSync operations serve as write barriers - all writes launched
 1.46858 +** before the xSync must complete before any write that launches after the
 1.46859 +** xSync begins.
 1.46860 +**
 1.46861 +** After each checkpoint, the salt-1 value is incremented and the salt-2
 1.46862 +** value is randomized.  This prevents old and new frames in the WAL from
 1.46863 +** being considered valid at the same time and being checkpointing together
 1.46864 +** following a crash.
 1.46865 +**
 1.46866 +** READER ALGORITHM
 1.46867 +**
 1.46868 +** To read a page from the database (call it page number P), a reader
 1.46869 +** first checks the WAL to see if it contains page P.  If so, then the
 1.46870 +** last valid instance of page P that is a followed by a commit frame
 1.46871 +** or is a commit frame itself becomes the value read.  If the WAL
 1.46872 +** contains no copies of page P that are valid and which are a commit
 1.46873 +** frame or are followed by a commit frame, then page P is read from
 1.46874 +** the database file.
 1.46875 +**
 1.46876 +** To start a read transaction, the reader records the index of the last
 1.46877 +** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
 1.46878 +** for all subsequent read operations.  New transactions can be appended
 1.46879 +** to the WAL, but as long as the reader uses its original mxFrame value
 1.46880 +** and ignores the newly appended content, it will see a consistent snapshot
 1.46881 +** of the database from a single point in time.  This technique allows
 1.46882 +** multiple concurrent readers to view different versions of the database
 1.46883 +** content simultaneously.
 1.46884 +**
 1.46885 +** The reader algorithm in the previous paragraphs works correctly, but 
 1.46886 +** because frames for page P can appear anywhere within the WAL, the
 1.46887 +** reader has to scan the entire WAL looking for page P frames.  If the
 1.46888 +** WAL is large (multiple megabytes is typical) that scan can be slow,
 1.46889 +** and read performance suffers.  To overcome this problem, a separate
 1.46890 +** data structure called the wal-index is maintained to expedite the
 1.46891 +** search for frames of a particular page.
 1.46892 +** 
 1.46893 +** WAL-INDEX FORMAT
 1.46894 +**
 1.46895 +** Conceptually, the wal-index is shared memory, though VFS implementations
 1.46896 +** might choose to implement the wal-index using a mmapped file.  Because
 1.46897 +** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
 1.46898 +** on a network filesystem.  All users of the database must be able to
 1.46899 +** share memory.
 1.46900 +**
 1.46901 +** The wal-index is transient.  After a crash, the wal-index can (and should
 1.46902 +** be) reconstructed from the original WAL file.  In fact, the VFS is required
 1.46903 +** to either truncate or zero the header of the wal-index when the last
 1.46904 +** connection to it closes.  Because the wal-index is transient, it can
 1.46905 +** use an architecture-specific format; it does not have to be cross-platform.
 1.46906 +** Hence, unlike the database and WAL file formats which store all values
 1.46907 +** as big endian, the wal-index can store multi-byte values in the native
 1.46908 +** byte order of the host computer.
 1.46909 +**
 1.46910 +** The purpose of the wal-index is to answer this question quickly:  Given
 1.46911 +** a page number P and a maximum frame index M, return the index of the 
 1.46912 +** last frame in the wal before frame M for page P in the WAL, or return
 1.46913 +** NULL if there are no frames for page P in the WAL prior to M.
 1.46914 +**
 1.46915 +** The wal-index consists of a header region, followed by an one or
 1.46916 +** more index blocks.  
 1.46917 +**
 1.46918 +** The wal-index header contains the total number of frames within the WAL
 1.46919 +** in the mxFrame field.
 1.46920 +**
 1.46921 +** Each index block except for the first contains information on 
 1.46922 +** HASHTABLE_NPAGE frames. The first index block contains information on
 1.46923 +** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
 1.46924 +** HASHTABLE_NPAGE are selected so that together the wal-index header and
 1.46925 +** first index block are the same size as all other index blocks in the
 1.46926 +** wal-index.
 1.46927 +**
 1.46928 +** Each index block contains two sections, a page-mapping that contains the
 1.46929 +** database page number associated with each wal frame, and a hash-table 
 1.46930 +** that allows readers to query an index block for a specific page number.
 1.46931 +** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
 1.46932 +** for the first index block) 32-bit page numbers. The first entry in the 
 1.46933 +** first index-block contains the database page number corresponding to the
 1.46934 +** first frame in the WAL file. The first entry in the second index block
 1.46935 +** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
 1.46936 +** the log, and so on.
 1.46937 +**
 1.46938 +** The last index block in a wal-index usually contains less than the full
 1.46939 +** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
 1.46940 +** depending on the contents of the WAL file. This does not change the
 1.46941 +** allocated size of the page-mapping array - the page-mapping array merely
 1.46942 +** contains unused entries.
 1.46943 +**
 1.46944 +** Even without using the hash table, the last frame for page P
 1.46945 +** can be found by scanning the page-mapping sections of each index block
 1.46946 +** starting with the last index block and moving toward the first, and
 1.46947 +** within each index block, starting at the end and moving toward the
 1.46948 +** beginning.  The first entry that equals P corresponds to the frame
 1.46949 +** holding the content for that page.
 1.46950 +**
 1.46951 +** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
 1.46952 +** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
 1.46953 +** hash table for each page number in the mapping section, so the hash 
 1.46954 +** table is never more than half full.  The expected number of collisions 
 1.46955 +** prior to finding a match is 1.  Each entry of the hash table is an
 1.46956 +** 1-based index of an entry in the mapping section of the same
 1.46957 +** index block.   Let K be the 1-based index of the largest entry in
 1.46958 +** the mapping section.  (For index blocks other than the last, K will
 1.46959 +** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
 1.46960 +** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
 1.46961 +** contain a value of 0.
 1.46962 +**
 1.46963 +** To look for page P in the hash table, first compute a hash iKey on
 1.46964 +** P as follows:
 1.46965 +**
 1.46966 +**      iKey = (P * 383) % HASHTABLE_NSLOT
 1.46967 +**
 1.46968 +** Then start scanning entries of the hash table, starting with iKey
 1.46969 +** (wrapping around to the beginning when the end of the hash table is
 1.46970 +** reached) until an unused hash slot is found. Let the first unused slot
 1.46971 +** be at index iUnused.  (iUnused might be less than iKey if there was
 1.46972 +** wrap-around.) Because the hash table is never more than half full,
 1.46973 +** the search is guaranteed to eventually hit an unused entry.  Let 
 1.46974 +** iMax be the value between iKey and iUnused, closest to iUnused,
 1.46975 +** where aHash[iMax]==P.  If there is no iMax entry (if there exists
 1.46976 +** no hash slot such that aHash[i]==p) then page P is not in the
 1.46977 +** current index block.  Otherwise the iMax-th mapping entry of the
 1.46978 +** current index block corresponds to the last entry that references 
 1.46979 +** page P.
 1.46980 +**
 1.46981 +** A hash search begins with the last index block and moves toward the
 1.46982 +** first index block, looking for entries corresponding to page P.  On
 1.46983 +** average, only two or three slots in each index block need to be
 1.46984 +** examined in order to either find the last entry for page P, or to
 1.46985 +** establish that no such entry exists in the block.  Each index block
 1.46986 +** holds over 4000 entries.  So two or three index blocks are sufficient
 1.46987 +** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
 1.46988 +** comparisons (on average) suffice to either locate a frame in the
 1.46989 +** WAL or to establish that the frame does not exist in the WAL.  This
 1.46990 +** is much faster than scanning the entire 10MB WAL.
 1.46991 +**
 1.46992 +** Note that entries are added in order of increasing K.  Hence, one
 1.46993 +** reader might be using some value K0 and a second reader that started
 1.46994 +** at a later time (after additional transactions were added to the WAL
 1.46995 +** and to the wal-index) might be using a different value K1, where K1>K0.
 1.46996 +** Both readers can use the same hash table and mapping section to get
 1.46997 +** the correct result.  There may be entries in the hash table with
 1.46998 +** K>K0 but to the first reader, those entries will appear to be unused
 1.46999 +** slots in the hash table and so the first reader will get an answer as
 1.47000 +** if no values greater than K0 had ever been inserted into the hash table
 1.47001 +** in the first place - which is what reader one wants.  Meanwhile, the
 1.47002 +** second reader using K1 will see additional values that were inserted
 1.47003 +** later, which is exactly what reader two wants.  
 1.47004 +**
 1.47005 +** When a rollback occurs, the value of K is decreased. Hash table entries
 1.47006 +** that correspond to frames greater than the new K value are removed
 1.47007 +** from the hash table at this point.
 1.47008 +*/
 1.47009 +#ifndef SQLITE_OMIT_WAL
 1.47010 +
 1.47011 +
 1.47012 +/*
 1.47013 +** Trace output macros
 1.47014 +*/
 1.47015 +#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
 1.47016 +SQLITE_PRIVATE int sqlite3WalTrace = 0;
 1.47017 +# define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
 1.47018 +#else
 1.47019 +# define WALTRACE(X)
 1.47020 +#endif
 1.47021 +
 1.47022 +/*
 1.47023 +** The maximum (and only) versions of the wal and wal-index formats
 1.47024 +** that may be interpreted by this version of SQLite.
 1.47025 +**
 1.47026 +** If a client begins recovering a WAL file and finds that (a) the checksum
 1.47027 +** values in the wal-header are correct and (b) the version field is not
 1.47028 +** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
 1.47029 +**
 1.47030 +** Similarly, if a client successfully reads a wal-index header (i.e. the 
 1.47031 +** checksum test is successful) and finds that the version field is not
 1.47032 +** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
 1.47033 +** returns SQLITE_CANTOPEN.
 1.47034 +*/
 1.47035 +#define WAL_MAX_VERSION      3007000
 1.47036 +#define WALINDEX_MAX_VERSION 3007000
 1.47037 +
 1.47038 +/*
 1.47039 +** Indices of various locking bytes.   WAL_NREADER is the number
 1.47040 +** of available reader locks and should be at least 3.
 1.47041 +*/
 1.47042 +#define WAL_WRITE_LOCK         0
 1.47043 +#define WAL_ALL_BUT_WRITE      1
 1.47044 +#define WAL_CKPT_LOCK          1
 1.47045 +#define WAL_RECOVER_LOCK       2
 1.47046 +#define WAL_READ_LOCK(I)       (3+(I))
 1.47047 +#define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
 1.47048 +
 1.47049 +
 1.47050 +/* Object declarations */
 1.47051 +typedef struct WalIndexHdr WalIndexHdr;
 1.47052 +typedef struct WalIterator WalIterator;
 1.47053 +typedef struct WalCkptInfo WalCkptInfo;
 1.47054 +
 1.47055 +
 1.47056 +/*
 1.47057 +** The following object holds a copy of the wal-index header content.
 1.47058 +**
 1.47059 +** The actual header in the wal-index consists of two copies of this
 1.47060 +** object.
 1.47061 +**
 1.47062 +** The szPage value can be any power of 2 between 512 and 32768, inclusive.
 1.47063 +** Or it can be 1 to represent a 65536-byte page.  The latter case was
 1.47064 +** added in 3.7.1 when support for 64K pages was added.  
 1.47065 +*/
 1.47066 +struct WalIndexHdr {
 1.47067 +  u32 iVersion;                   /* Wal-index version */
 1.47068 +  u32 unused;                     /* Unused (padding) field */
 1.47069 +  u32 iChange;                    /* Counter incremented each transaction */
 1.47070 +  u8 isInit;                      /* 1 when initialized */
 1.47071 +  u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
 1.47072 +  u16 szPage;                     /* Database page size in bytes. 1==64K */
 1.47073 +  u32 mxFrame;                    /* Index of last valid frame in the WAL */
 1.47074 +  u32 nPage;                      /* Size of database in pages */
 1.47075 +  u32 aFrameCksum[2];             /* Checksum of last frame in log */
 1.47076 +  u32 aSalt[2];                   /* Two salt values copied from WAL header */
 1.47077 +  u32 aCksum[2];                  /* Checksum over all prior fields */
 1.47078 +};
 1.47079 +
 1.47080 +/*
 1.47081 +** A copy of the following object occurs in the wal-index immediately
 1.47082 +** following the second copy of the WalIndexHdr.  This object stores
 1.47083 +** information used by checkpoint.
 1.47084 +**
 1.47085 +** nBackfill is the number of frames in the WAL that have been written
 1.47086 +** back into the database. (We call the act of moving content from WAL to
 1.47087 +** database "backfilling".)  The nBackfill number is never greater than
 1.47088 +** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
 1.47089 +** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
 1.47090 +** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
 1.47091 +** mxFrame back to zero when the WAL is reset.
 1.47092 +**
 1.47093 +** There is one entry in aReadMark[] for each reader lock.  If a reader
 1.47094 +** holds read-lock K, then the value in aReadMark[K] is no greater than
 1.47095 +** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
 1.47096 +** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
 1.47097 +** a special case; its value is never used and it exists as a place-holder
 1.47098 +** to avoid having to offset aReadMark[] indexs by one.  Readers holding
 1.47099 +** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
 1.47100 +** directly from the database.
 1.47101 +**
 1.47102 +** The value of aReadMark[K] may only be changed by a thread that
 1.47103 +** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
 1.47104 +** aReadMark[K] cannot changed while there is a reader is using that mark
 1.47105 +** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
 1.47106 +**
 1.47107 +** The checkpointer may only transfer frames from WAL to database where
 1.47108 +** the frame numbers are less than or equal to every aReadMark[] that is
 1.47109 +** in use (that is, every aReadMark[j] for which there is a corresponding
 1.47110 +** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
 1.47111 +** largest value and will increase an unused aReadMark[] to mxFrame if there
 1.47112 +** is not already an aReadMark[] equal to mxFrame.  The exception to the
 1.47113 +** previous sentence is when nBackfill equals mxFrame (meaning that everything
 1.47114 +** in the WAL has been backfilled into the database) then new readers
 1.47115 +** will choose aReadMark[0] which has value 0 and hence such reader will
 1.47116 +** get all their all content directly from the database file and ignore 
 1.47117 +** the WAL.
 1.47118 +**
 1.47119 +** Writers normally append new frames to the end of the WAL.  However,
 1.47120 +** if nBackfill equals mxFrame (meaning that all WAL content has been
 1.47121 +** written back into the database) and if no readers are using the WAL
 1.47122 +** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
 1.47123 +** the writer will first "reset" the WAL back to the beginning and start
 1.47124 +** writing new content beginning at frame 1.
 1.47125 +**
 1.47126 +** We assume that 32-bit loads are atomic and so no locks are needed in
 1.47127 +** order to read from any aReadMark[] entries.
 1.47128 +*/
 1.47129 +struct WalCkptInfo {
 1.47130 +  u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
 1.47131 +  u32 aReadMark[WAL_NREADER];     /* Reader marks */
 1.47132 +};
 1.47133 +#define READMARK_NOT_USED  0xffffffff
 1.47134 +
 1.47135 +
 1.47136 +/* A block of WALINDEX_LOCK_RESERVED bytes beginning at
 1.47137 +** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
 1.47138 +** only support mandatory file-locks, we do not read or write data
 1.47139 +** from the region of the file on which locks are applied.
 1.47140 +*/
 1.47141 +#define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
 1.47142 +#define WALINDEX_LOCK_RESERVED 16
 1.47143 +#define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
 1.47144 +
 1.47145 +/* Size of header before each frame in wal */
 1.47146 +#define WAL_FRAME_HDRSIZE 24
 1.47147 +
 1.47148 +/* Size of write ahead log header, including checksum. */
 1.47149 +/* #define WAL_HDRSIZE 24 */
 1.47150 +#define WAL_HDRSIZE 32
 1.47151 +
 1.47152 +/* WAL magic value. Either this value, or the same value with the least
 1.47153 +** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
 1.47154 +** big-endian format in the first 4 bytes of a WAL file.
 1.47155 +**
 1.47156 +** If the LSB is set, then the checksums for each frame within the WAL
 1.47157 +** file are calculated by treating all data as an array of 32-bit 
 1.47158 +** big-endian words. Otherwise, they are calculated by interpreting 
 1.47159 +** all data as 32-bit little-endian words.
 1.47160 +*/
 1.47161 +#define WAL_MAGIC 0x377f0682
 1.47162 +
 1.47163 +/*
 1.47164 +** Return the offset of frame iFrame in the write-ahead log file, 
 1.47165 +** assuming a database page size of szPage bytes. The offset returned
 1.47166 +** is to the start of the write-ahead log frame-header.
 1.47167 +*/
 1.47168 +#define walFrameOffset(iFrame, szPage) (                               \
 1.47169 +  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
 1.47170 +)
 1.47171 +
 1.47172 +/*
 1.47173 +** An open write-ahead log file is represented by an instance of the
 1.47174 +** following object.
 1.47175 +*/
 1.47176 +struct Wal {
 1.47177 +  sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
 1.47178 +  sqlite3_file *pDbFd;       /* File handle for the database file */
 1.47179 +  sqlite3_file *pWalFd;      /* File handle for WAL file */
 1.47180 +  u32 iCallback;             /* Value to pass to log callback (or 0) */
 1.47181 +  i64 mxWalSize;             /* Truncate WAL to this size upon reset */
 1.47182 +  int nWiData;               /* Size of array apWiData */
 1.47183 +  int szFirstBlock;          /* Size of first block written to WAL file */
 1.47184 +  volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
 1.47185 +  u32 szPage;                /* Database page size */
 1.47186 +  i16 readLock;              /* Which read lock is being held.  -1 for none */
 1.47187 +  u8 syncFlags;              /* Flags to use to sync header writes */
 1.47188 +  u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
 1.47189 +  u8 writeLock;              /* True if in a write transaction */
 1.47190 +  u8 ckptLock;               /* True if holding a checkpoint lock */
 1.47191 +  u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
 1.47192 +  u8 truncateOnCommit;       /* True to truncate WAL file on commit */
 1.47193 +  u8 syncHeader;             /* Fsync the WAL header if true */
 1.47194 +  u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
 1.47195 +  WalIndexHdr hdr;           /* Wal-index header for current transaction */
 1.47196 +  const char *zWalName;      /* Name of WAL file */
 1.47197 +  u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
 1.47198 +#ifdef SQLITE_DEBUG
 1.47199 +  u8 lockError;              /* True if a locking error has occurred */
 1.47200 +#endif
 1.47201 +};
 1.47202 +
 1.47203 +/*
 1.47204 +** Candidate values for Wal.exclusiveMode.
 1.47205 +*/
 1.47206 +#define WAL_NORMAL_MODE     0
 1.47207 +#define WAL_EXCLUSIVE_MODE  1     
 1.47208 +#define WAL_HEAPMEMORY_MODE 2
 1.47209 +
 1.47210 +/*
 1.47211 +** Possible values for WAL.readOnly
 1.47212 +*/
 1.47213 +#define WAL_RDWR        0    /* Normal read/write connection */
 1.47214 +#define WAL_RDONLY      1    /* The WAL file is readonly */
 1.47215 +#define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
 1.47216 +
 1.47217 +/*
 1.47218 +** Each page of the wal-index mapping contains a hash-table made up of
 1.47219 +** an array of HASHTABLE_NSLOT elements of the following type.
 1.47220 +*/
 1.47221 +typedef u16 ht_slot;
 1.47222 +
 1.47223 +/*
 1.47224 +** This structure is used to implement an iterator that loops through
 1.47225 +** all frames in the WAL in database page order. Where two or more frames
 1.47226 +** correspond to the same database page, the iterator visits only the 
 1.47227 +** frame most recently written to the WAL (in other words, the frame with
 1.47228 +** the largest index).
 1.47229 +**
 1.47230 +** The internals of this structure are only accessed by:
 1.47231 +**
 1.47232 +**   walIteratorInit() - Create a new iterator,
 1.47233 +**   walIteratorNext() - Step an iterator,
 1.47234 +**   walIteratorFree() - Free an iterator.
 1.47235 +**
 1.47236 +** This functionality is used by the checkpoint code (see walCheckpoint()).
 1.47237 +*/
 1.47238 +struct WalIterator {
 1.47239 +  int iPrior;                     /* Last result returned from the iterator */
 1.47240 +  int nSegment;                   /* Number of entries in aSegment[] */
 1.47241 +  struct WalSegment {
 1.47242 +    int iNext;                    /* Next slot in aIndex[] not yet returned */
 1.47243 +    ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
 1.47244 +    u32 *aPgno;                   /* Array of page numbers. */
 1.47245 +    int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
 1.47246 +    int iZero;                    /* Frame number associated with aPgno[0] */
 1.47247 +  } aSegment[1];                  /* One for every 32KB page in the wal-index */
 1.47248 +};
 1.47249 +
 1.47250 +/*
 1.47251 +** Define the parameters of the hash tables in the wal-index file. There
 1.47252 +** is a hash-table following every HASHTABLE_NPAGE page numbers in the
 1.47253 +** wal-index.
 1.47254 +**
 1.47255 +** Changing any of these constants will alter the wal-index format and
 1.47256 +** create incompatibilities.
 1.47257 +*/
 1.47258 +#define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
 1.47259 +#define HASHTABLE_HASH_1     383                  /* Should be prime */
 1.47260 +#define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
 1.47261 +
 1.47262 +/* 
 1.47263 +** The block of page numbers associated with the first hash-table in a
 1.47264 +** wal-index is smaller than usual. This is so that there is a complete
 1.47265 +** hash-table on each aligned 32KB page of the wal-index.
 1.47266 +*/
 1.47267 +#define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
 1.47268 +
 1.47269 +/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
 1.47270 +#define WALINDEX_PGSZ   (                                         \
 1.47271 +    sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
 1.47272 +)
 1.47273 +
 1.47274 +/*
 1.47275 +** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
 1.47276 +** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
 1.47277 +** numbered from zero.
 1.47278 +**
 1.47279 +** If this call is successful, *ppPage is set to point to the wal-index
 1.47280 +** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
 1.47281 +** then an SQLite error code is returned and *ppPage is set to 0.
 1.47282 +*/
 1.47283 +static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
 1.47284 +  int rc = SQLITE_OK;
 1.47285 +
 1.47286 +  /* Enlarge the pWal->apWiData[] array if required */
 1.47287 +  if( pWal->nWiData<=iPage ){
 1.47288 +    int nByte = sizeof(u32*)*(iPage+1);
 1.47289 +    volatile u32 **apNew;
 1.47290 +    apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
 1.47291 +    if( !apNew ){
 1.47292 +      *ppPage = 0;
 1.47293 +      return SQLITE_NOMEM;
 1.47294 +    }
 1.47295 +    memset((void*)&apNew[pWal->nWiData], 0,
 1.47296 +           sizeof(u32*)*(iPage+1-pWal->nWiData));
 1.47297 +    pWal->apWiData = apNew;
 1.47298 +    pWal->nWiData = iPage+1;
 1.47299 +  }
 1.47300 +
 1.47301 +  /* Request a pointer to the required page from the VFS */
 1.47302 +  if( pWal->apWiData[iPage]==0 ){
 1.47303 +    if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
 1.47304 +      pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
 1.47305 +      if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
 1.47306 +    }else{
 1.47307 +      rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
 1.47308 +          pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
 1.47309 +      );
 1.47310 +      if( rc==SQLITE_READONLY ){
 1.47311 +        pWal->readOnly |= WAL_SHM_RDONLY;
 1.47312 +        rc = SQLITE_OK;
 1.47313 +      }
 1.47314 +    }
 1.47315 +  }
 1.47316 +
 1.47317 +  *ppPage = pWal->apWiData[iPage];
 1.47318 +  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
 1.47319 +  return rc;
 1.47320 +}
 1.47321 +
 1.47322 +/*
 1.47323 +** Return a pointer to the WalCkptInfo structure in the wal-index.
 1.47324 +*/
 1.47325 +static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
 1.47326 +  assert( pWal->nWiData>0 && pWal->apWiData[0] );
 1.47327 +  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
 1.47328 +}
 1.47329 +
 1.47330 +/*
 1.47331 +** Return a pointer to the WalIndexHdr structure in the wal-index.
 1.47332 +*/
 1.47333 +static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
 1.47334 +  assert( pWal->nWiData>0 && pWal->apWiData[0] );
 1.47335 +  return (volatile WalIndexHdr*)pWal->apWiData[0];
 1.47336 +}
 1.47337 +
 1.47338 +/*
 1.47339 +** The argument to this macro must be of type u32. On a little-endian
 1.47340 +** architecture, it returns the u32 value that results from interpreting
 1.47341 +** the 4 bytes as a big-endian value. On a big-endian architecture, it
 1.47342 +** returns the value that would be produced by intepreting the 4 bytes
 1.47343 +** of the input value as a little-endian integer.
 1.47344 +*/
 1.47345 +#define BYTESWAP32(x) ( \
 1.47346 +    (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
 1.47347 +  + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
 1.47348 +)
 1.47349 +
 1.47350 +/*
 1.47351 +** Generate or extend an 8 byte checksum based on the data in 
 1.47352 +** array aByte[] and the initial values of aIn[0] and aIn[1] (or
 1.47353 +** initial values of 0 and 0 if aIn==NULL).
 1.47354 +**
 1.47355 +** The checksum is written back into aOut[] before returning.
 1.47356 +**
 1.47357 +** nByte must be a positive multiple of 8.
 1.47358 +*/
 1.47359 +static void walChecksumBytes(
 1.47360 +  int nativeCksum, /* True for native byte-order, false for non-native */
 1.47361 +  u8 *a,           /* Content to be checksummed */
 1.47362 +  int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
 1.47363 +  const u32 *aIn,  /* Initial checksum value input */
 1.47364 +  u32 *aOut        /* OUT: Final checksum value output */
 1.47365 +){
 1.47366 +  u32 s1, s2;
 1.47367 +  u32 *aData = (u32 *)a;
 1.47368 +  u32 *aEnd = (u32 *)&a[nByte];
 1.47369 +
 1.47370 +  if( aIn ){
 1.47371 +    s1 = aIn[0];
 1.47372 +    s2 = aIn[1];
 1.47373 +  }else{
 1.47374 +    s1 = s2 = 0;
 1.47375 +  }
 1.47376 +
 1.47377 +  assert( nByte>=8 );
 1.47378 +  assert( (nByte&0x00000007)==0 );
 1.47379 +
 1.47380 +  if( nativeCksum ){
 1.47381 +    do {
 1.47382 +      s1 += *aData++ + s2;
 1.47383 +      s2 += *aData++ + s1;
 1.47384 +    }while( aData<aEnd );
 1.47385 +  }else{
 1.47386 +    do {
 1.47387 +      s1 += BYTESWAP32(aData[0]) + s2;
 1.47388 +      s2 += BYTESWAP32(aData[1]) + s1;
 1.47389 +      aData += 2;
 1.47390 +    }while( aData<aEnd );
 1.47391 +  }
 1.47392 +
 1.47393 +  aOut[0] = s1;
 1.47394 +  aOut[1] = s2;
 1.47395 +}
 1.47396 +
 1.47397 +static void walShmBarrier(Wal *pWal){
 1.47398 +  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
 1.47399 +    sqlite3OsShmBarrier(pWal->pDbFd);
 1.47400 +  }
 1.47401 +}
 1.47402 +
 1.47403 +/*
 1.47404 +** Write the header information in pWal->hdr into the wal-index.
 1.47405 +**
 1.47406 +** The checksum on pWal->hdr is updated before it is written.
 1.47407 +*/
 1.47408 +static void walIndexWriteHdr(Wal *pWal){
 1.47409 +  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
 1.47410 +  const int nCksum = offsetof(WalIndexHdr, aCksum);
 1.47411 +
 1.47412 +  assert( pWal->writeLock );
 1.47413 +  pWal->hdr.isInit = 1;
 1.47414 +  pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
 1.47415 +  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
 1.47416 +  memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
 1.47417 +  walShmBarrier(pWal);
 1.47418 +  memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
 1.47419 +}
 1.47420 +
 1.47421 +/*
 1.47422 +** This function encodes a single frame header and writes it to a buffer
 1.47423 +** supplied by the caller. A frame-header is made up of a series of 
 1.47424 +** 4-byte big-endian integers, as follows:
 1.47425 +**
 1.47426 +**     0: Page number.
 1.47427 +**     4: For commit records, the size of the database image in pages 
 1.47428 +**        after the commit. For all other records, zero.
 1.47429 +**     8: Salt-1 (copied from the wal-header)
 1.47430 +**    12: Salt-2 (copied from the wal-header)
 1.47431 +**    16: Checksum-1.
 1.47432 +**    20: Checksum-2.
 1.47433 +*/
 1.47434 +static void walEncodeFrame(
 1.47435 +  Wal *pWal,                      /* The write-ahead log */
 1.47436 +  u32 iPage,                      /* Database page number for frame */
 1.47437 +  u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
 1.47438 +  u8 *aData,                      /* Pointer to page data */
 1.47439 +  u8 *aFrame                      /* OUT: Write encoded frame here */
 1.47440 +){
 1.47441 +  int nativeCksum;                /* True for native byte-order checksums */
 1.47442 +  u32 *aCksum = pWal->hdr.aFrameCksum;
 1.47443 +  assert( WAL_FRAME_HDRSIZE==24 );
 1.47444 +  sqlite3Put4byte(&aFrame[0], iPage);
 1.47445 +  sqlite3Put4byte(&aFrame[4], nTruncate);
 1.47446 +  memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
 1.47447 +
 1.47448 +  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
 1.47449 +  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
 1.47450 +  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
 1.47451 +
 1.47452 +  sqlite3Put4byte(&aFrame[16], aCksum[0]);
 1.47453 +  sqlite3Put4byte(&aFrame[20], aCksum[1]);
 1.47454 +}
 1.47455 +
 1.47456 +/*
 1.47457 +** Check to see if the frame with header in aFrame[] and content
 1.47458 +** in aData[] is valid.  If it is a valid frame, fill *piPage and
 1.47459 +** *pnTruncate and return true.  Return if the frame is not valid.
 1.47460 +*/
 1.47461 +static int walDecodeFrame(
 1.47462 +  Wal *pWal,                      /* The write-ahead log */
 1.47463 +  u32 *piPage,                    /* OUT: Database page number for frame */
 1.47464 +  u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
 1.47465 +  u8 *aData,                      /* Pointer to page data (for checksum) */
 1.47466 +  u8 *aFrame                      /* Frame data */
 1.47467 +){
 1.47468 +  int nativeCksum;                /* True for native byte-order checksums */
 1.47469 +  u32 *aCksum = pWal->hdr.aFrameCksum;
 1.47470 +  u32 pgno;                       /* Page number of the frame */
 1.47471 +  assert( WAL_FRAME_HDRSIZE==24 );
 1.47472 +
 1.47473 +  /* A frame is only valid if the salt values in the frame-header
 1.47474 +  ** match the salt values in the wal-header. 
 1.47475 +  */
 1.47476 +  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
 1.47477 +    return 0;
 1.47478 +  }
 1.47479 +
 1.47480 +  /* A frame is only valid if the page number is creater than zero.
 1.47481 +  */
 1.47482 +  pgno = sqlite3Get4byte(&aFrame[0]);
 1.47483 +  if( pgno==0 ){
 1.47484 +    return 0;
 1.47485 +  }
 1.47486 +
 1.47487 +  /* A frame is only valid if a checksum of the WAL header,
 1.47488 +  ** all prior frams, the first 16 bytes of this frame-header, 
 1.47489 +  ** and the frame-data matches the checksum in the last 8 
 1.47490 +  ** bytes of this frame-header.
 1.47491 +  */
 1.47492 +  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
 1.47493 +  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
 1.47494 +  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
 1.47495 +  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
 1.47496 +   || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) 
 1.47497 +  ){
 1.47498 +    /* Checksum failed. */
 1.47499 +    return 0;
 1.47500 +  }
 1.47501 +
 1.47502 +  /* If we reach this point, the frame is valid.  Return the page number
 1.47503 +  ** and the new database size.
 1.47504 +  */
 1.47505 +  *piPage = pgno;
 1.47506 +  *pnTruncate = sqlite3Get4byte(&aFrame[4]);
 1.47507 +  return 1;
 1.47508 +}
 1.47509 +
 1.47510 +
 1.47511 +#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
 1.47512 +/*
 1.47513 +** Names of locks.  This routine is used to provide debugging output and is not
 1.47514 +** a part of an ordinary build.
 1.47515 +*/
 1.47516 +static const char *walLockName(int lockIdx){
 1.47517 +  if( lockIdx==WAL_WRITE_LOCK ){
 1.47518 +    return "WRITE-LOCK";
 1.47519 +  }else if( lockIdx==WAL_CKPT_LOCK ){
 1.47520 +    return "CKPT-LOCK";
 1.47521 +  }else if( lockIdx==WAL_RECOVER_LOCK ){
 1.47522 +    return "RECOVER-LOCK";
 1.47523 +  }else{
 1.47524 +    static char zName[15];
 1.47525 +    sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
 1.47526 +                     lockIdx-WAL_READ_LOCK(0));
 1.47527 +    return zName;
 1.47528 +  }
 1.47529 +}
 1.47530 +#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
 1.47531 +    
 1.47532 +
 1.47533 +/*
 1.47534 +** Set or release locks on the WAL.  Locks are either shared or exclusive.
 1.47535 +** A lock cannot be moved directly between shared and exclusive - it must go
 1.47536 +** through the unlocked state first.
 1.47537 +**
 1.47538 +** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
 1.47539 +*/
 1.47540 +static int walLockShared(Wal *pWal, int lockIdx){
 1.47541 +  int rc;
 1.47542 +  if( pWal->exclusiveMode ) return SQLITE_OK;
 1.47543 +  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
 1.47544 +                        SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
 1.47545 +  WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
 1.47546 +            walLockName(lockIdx), rc ? "failed" : "ok"));
 1.47547 +  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
 1.47548 +  return rc;
 1.47549 +}
 1.47550 +static void walUnlockShared(Wal *pWal, int lockIdx){
 1.47551 +  if( pWal->exclusiveMode ) return;
 1.47552 +  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
 1.47553 +                         SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
 1.47554 +  WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
 1.47555 +}
 1.47556 +static int walLockExclusive(Wal *pWal, int lockIdx, int n){
 1.47557 +  int rc;
 1.47558 +  if( pWal->exclusiveMode ) return SQLITE_OK;
 1.47559 +  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
 1.47560 +                        SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
 1.47561 +  WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
 1.47562 +            walLockName(lockIdx), n, rc ? "failed" : "ok"));
 1.47563 +  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
 1.47564 +  return rc;
 1.47565 +}
 1.47566 +static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
 1.47567 +  if( pWal->exclusiveMode ) return;
 1.47568 +  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
 1.47569 +                         SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
 1.47570 +  WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
 1.47571 +             walLockName(lockIdx), n));
 1.47572 +}
 1.47573 +
 1.47574 +/*
 1.47575 +** Compute a hash on a page number.  The resulting hash value must land
 1.47576 +** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
 1.47577 +** the hash to the next value in the event of a collision.
 1.47578 +*/
 1.47579 +static int walHash(u32 iPage){
 1.47580 +  assert( iPage>0 );
 1.47581 +  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
 1.47582 +  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
 1.47583 +}
 1.47584 +static int walNextHash(int iPriorHash){
 1.47585 +  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
 1.47586 +}
 1.47587 +
 1.47588 +/* 
 1.47589 +** Return pointers to the hash table and page number array stored on
 1.47590 +** page iHash of the wal-index. The wal-index is broken into 32KB pages
 1.47591 +** numbered starting from 0.
 1.47592 +**
 1.47593 +** Set output variable *paHash to point to the start of the hash table
 1.47594 +** in the wal-index file. Set *piZero to one less than the frame 
 1.47595 +** number of the first frame indexed by this hash table. If a
 1.47596 +** slot in the hash table is set to N, it refers to frame number 
 1.47597 +** (*piZero+N) in the log.
 1.47598 +**
 1.47599 +** Finally, set *paPgno so that *paPgno[1] is the page number of the
 1.47600 +** first frame indexed by the hash table, frame (*piZero+1).
 1.47601 +*/
 1.47602 +static int walHashGet(
 1.47603 +  Wal *pWal,                      /* WAL handle */
 1.47604 +  int iHash,                      /* Find the iHash'th table */
 1.47605 +  volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
 1.47606 +  volatile u32 **paPgno,          /* OUT: Pointer to page number array */
 1.47607 +  u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
 1.47608 +){
 1.47609 +  int rc;                         /* Return code */
 1.47610 +  volatile u32 *aPgno;
 1.47611 +
 1.47612 +  rc = walIndexPage(pWal, iHash, &aPgno);
 1.47613 +  assert( rc==SQLITE_OK || iHash>0 );
 1.47614 +
 1.47615 +  if( rc==SQLITE_OK ){
 1.47616 +    u32 iZero;
 1.47617 +    volatile ht_slot *aHash;
 1.47618 +
 1.47619 +    aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
 1.47620 +    if( iHash==0 ){
 1.47621 +      aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
 1.47622 +      iZero = 0;
 1.47623 +    }else{
 1.47624 +      iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
 1.47625 +    }
 1.47626 +  
 1.47627 +    *paPgno = &aPgno[-1];
 1.47628 +    *paHash = aHash;
 1.47629 +    *piZero = iZero;
 1.47630 +  }
 1.47631 +  return rc;
 1.47632 +}
 1.47633 +
 1.47634 +/*
 1.47635 +** Return the number of the wal-index page that contains the hash-table
 1.47636 +** and page-number array that contain entries corresponding to WAL frame
 1.47637 +** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
 1.47638 +** are numbered starting from 0.
 1.47639 +*/
 1.47640 +static int walFramePage(u32 iFrame){
 1.47641 +  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
 1.47642 +  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
 1.47643 +       && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
 1.47644 +       && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
 1.47645 +       && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
 1.47646 +       && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
 1.47647 +  );
 1.47648 +  return iHash;
 1.47649 +}
 1.47650 +
 1.47651 +/*
 1.47652 +** Return the page number associated with frame iFrame in this WAL.
 1.47653 +*/
 1.47654 +static u32 walFramePgno(Wal *pWal, u32 iFrame){
 1.47655 +  int iHash = walFramePage(iFrame);
 1.47656 +  if( iHash==0 ){
 1.47657 +    return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
 1.47658 +  }
 1.47659 +  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
 1.47660 +}
 1.47661 +
 1.47662 +/*
 1.47663 +** Remove entries from the hash table that point to WAL slots greater
 1.47664 +** than pWal->hdr.mxFrame.
 1.47665 +**
 1.47666 +** This function is called whenever pWal->hdr.mxFrame is decreased due
 1.47667 +** to a rollback or savepoint.
 1.47668 +**
 1.47669 +** At most only the hash table containing pWal->hdr.mxFrame needs to be
 1.47670 +** updated.  Any later hash tables will be automatically cleared when
 1.47671 +** pWal->hdr.mxFrame advances to the point where those hash tables are
 1.47672 +** actually needed.
 1.47673 +*/
 1.47674 +static void walCleanupHash(Wal *pWal){
 1.47675 +  volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
 1.47676 +  volatile u32 *aPgno = 0;        /* Page number array for hash table */
 1.47677 +  u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
 1.47678 +  int iLimit = 0;                 /* Zero values greater than this */
 1.47679 +  int nByte;                      /* Number of bytes to zero in aPgno[] */
 1.47680 +  int i;                          /* Used to iterate through aHash[] */
 1.47681 +
 1.47682 +  assert( pWal->writeLock );
 1.47683 +  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
 1.47684 +  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
 1.47685 +  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
 1.47686 +
 1.47687 +  if( pWal->hdr.mxFrame==0 ) return;
 1.47688 +
 1.47689 +  /* Obtain pointers to the hash-table and page-number array containing 
 1.47690 +  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
 1.47691 +  ** that the page said hash-table and array reside on is already mapped.
 1.47692 +  */
 1.47693 +  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
 1.47694 +  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
 1.47695 +  walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
 1.47696 +
 1.47697 +  /* Zero all hash-table entries that correspond to frame numbers greater
 1.47698 +  ** than pWal->hdr.mxFrame.
 1.47699 +  */
 1.47700 +  iLimit = pWal->hdr.mxFrame - iZero;
 1.47701 +  assert( iLimit>0 );
 1.47702 +  for(i=0; i<HASHTABLE_NSLOT; i++){
 1.47703 +    if( aHash[i]>iLimit ){
 1.47704 +      aHash[i] = 0;
 1.47705 +    }
 1.47706 +  }
 1.47707 +  
 1.47708 +  /* Zero the entries in the aPgno array that correspond to frames with
 1.47709 +  ** frame numbers greater than pWal->hdr.mxFrame. 
 1.47710 +  */
 1.47711 +  nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
 1.47712 +  memset((void *)&aPgno[iLimit+1], 0, nByte);
 1.47713 +
 1.47714 +#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
 1.47715 +  /* Verify that the every entry in the mapping region is still reachable
 1.47716 +  ** via the hash table even after the cleanup.
 1.47717 +  */
 1.47718 +  if( iLimit ){
 1.47719 +    int i;           /* Loop counter */
 1.47720 +    int iKey;        /* Hash key */
 1.47721 +    for(i=1; i<=iLimit; i++){
 1.47722 +      for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
 1.47723 +        if( aHash[iKey]==i ) break;
 1.47724 +      }
 1.47725 +      assert( aHash[iKey]==i );
 1.47726 +    }
 1.47727 +  }
 1.47728 +#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
 1.47729 +}
 1.47730 +
 1.47731 +
 1.47732 +/*
 1.47733 +** Set an entry in the wal-index that will map database page number
 1.47734 +** pPage into WAL frame iFrame.
 1.47735 +*/
 1.47736 +static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
 1.47737 +  int rc;                         /* Return code */
 1.47738 +  u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
 1.47739 +  volatile u32 *aPgno = 0;        /* Page number array */
 1.47740 +  volatile ht_slot *aHash = 0;    /* Hash table */
 1.47741 +
 1.47742 +  rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
 1.47743 +
 1.47744 +  /* Assuming the wal-index file was successfully mapped, populate the
 1.47745 +  ** page number array and hash table entry.
 1.47746 +  */
 1.47747 +  if( rc==SQLITE_OK ){
 1.47748 +    int iKey;                     /* Hash table key */
 1.47749 +    int idx;                      /* Value to write to hash-table slot */
 1.47750 +    int nCollide;                 /* Number of hash collisions */
 1.47751 +
 1.47752 +    idx = iFrame - iZero;
 1.47753 +    assert( idx <= HASHTABLE_NSLOT/2 + 1 );
 1.47754 +    
 1.47755 +    /* If this is the first entry to be added to this hash-table, zero the
 1.47756 +    ** entire hash table and aPgno[] array before proceding. 
 1.47757 +    */
 1.47758 +    if( idx==1 ){
 1.47759 +      int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
 1.47760 +      memset((void*)&aPgno[1], 0, nByte);
 1.47761 +    }
 1.47762 +
 1.47763 +    /* If the entry in aPgno[] is already set, then the previous writer
 1.47764 +    ** must have exited unexpectedly in the middle of a transaction (after
 1.47765 +    ** writing one or more dirty pages to the WAL to free up memory). 
 1.47766 +    ** Remove the remnants of that writers uncommitted transaction from 
 1.47767 +    ** the hash-table before writing any new entries.
 1.47768 +    */
 1.47769 +    if( aPgno[idx] ){
 1.47770 +      walCleanupHash(pWal);
 1.47771 +      assert( !aPgno[idx] );
 1.47772 +    }
 1.47773 +
 1.47774 +    /* Write the aPgno[] array entry and the hash-table slot. */
 1.47775 +    nCollide = idx;
 1.47776 +    for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
 1.47777 +      if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
 1.47778 +    }
 1.47779 +    aPgno[idx] = iPage;
 1.47780 +    aHash[iKey] = (ht_slot)idx;
 1.47781 +
 1.47782 +#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
 1.47783 +    /* Verify that the number of entries in the hash table exactly equals
 1.47784 +    ** the number of entries in the mapping region.
 1.47785 +    */
 1.47786 +    {
 1.47787 +      int i;           /* Loop counter */
 1.47788 +      int nEntry = 0;  /* Number of entries in the hash table */
 1.47789 +      for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
 1.47790 +      assert( nEntry==idx );
 1.47791 +    }
 1.47792 +
 1.47793 +    /* Verify that the every entry in the mapping region is reachable
 1.47794 +    ** via the hash table.  This turns out to be a really, really expensive
 1.47795 +    ** thing to check, so only do this occasionally - not on every
 1.47796 +    ** iteration.
 1.47797 +    */
 1.47798 +    if( (idx&0x3ff)==0 ){
 1.47799 +      int i;           /* Loop counter */
 1.47800 +      for(i=1; i<=idx; i++){
 1.47801 +        for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
 1.47802 +          if( aHash[iKey]==i ) break;
 1.47803 +        }
 1.47804 +        assert( aHash[iKey]==i );
 1.47805 +      }
 1.47806 +    }
 1.47807 +#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
 1.47808 +  }
 1.47809 +
 1.47810 +
 1.47811 +  return rc;
 1.47812 +}
 1.47813 +
 1.47814 +
 1.47815 +/*
 1.47816 +** Recover the wal-index by reading the write-ahead log file. 
 1.47817 +**
 1.47818 +** This routine first tries to establish an exclusive lock on the
 1.47819 +** wal-index to prevent other threads/processes from doing anything
 1.47820 +** with the WAL or wal-index while recovery is running.  The
 1.47821 +** WAL_RECOVER_LOCK is also held so that other threads will know
 1.47822 +** that this thread is running recovery.  If unable to establish
 1.47823 +** the necessary locks, this routine returns SQLITE_BUSY.
 1.47824 +*/
 1.47825 +static int walIndexRecover(Wal *pWal){
 1.47826 +  int rc;                         /* Return Code */
 1.47827 +  i64 nSize;                      /* Size of log file */
 1.47828 +  u32 aFrameCksum[2] = {0, 0};
 1.47829 +  int iLock;                      /* Lock offset to lock for checkpoint */
 1.47830 +  int nLock;                      /* Number of locks to hold */
 1.47831 +
 1.47832 +  /* Obtain an exclusive lock on all byte in the locking range not already
 1.47833 +  ** locked by the caller. The caller is guaranteed to have locked the
 1.47834 +  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
 1.47835 +  ** If successful, the same bytes that are locked here are unlocked before
 1.47836 +  ** this function returns.
 1.47837 +  */
 1.47838 +  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
 1.47839 +  assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
 1.47840 +  assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
 1.47841 +  assert( pWal->writeLock );
 1.47842 +  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
 1.47843 +  nLock = SQLITE_SHM_NLOCK - iLock;
 1.47844 +  rc = walLockExclusive(pWal, iLock, nLock);
 1.47845 +  if( rc ){
 1.47846 +    return rc;
 1.47847 +  }
 1.47848 +  WALTRACE(("WAL%p: recovery begin...\n", pWal));
 1.47849 +
 1.47850 +  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
 1.47851 +
 1.47852 +  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
 1.47853 +  if( rc!=SQLITE_OK ){
 1.47854 +    goto recovery_error;
 1.47855 +  }
 1.47856 +
 1.47857 +  if( nSize>WAL_HDRSIZE ){
 1.47858 +    u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
 1.47859 +    u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
 1.47860 +    int szFrame;                  /* Number of bytes in buffer aFrame[] */
 1.47861 +    u8 *aData;                    /* Pointer to data part of aFrame buffer */
 1.47862 +    int iFrame;                   /* Index of last frame read */
 1.47863 +    i64 iOffset;                  /* Next offset to read from log file */
 1.47864 +    int szPage;                   /* Page size according to the log */
 1.47865 +    u32 magic;                    /* Magic value read from WAL header */
 1.47866 +    u32 version;                  /* Magic value read from WAL header */
 1.47867 +    int isValid;                  /* True if this frame is valid */
 1.47868 +
 1.47869 +    /* Read in the WAL header. */
 1.47870 +    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
 1.47871 +    if( rc!=SQLITE_OK ){
 1.47872 +      goto recovery_error;
 1.47873 +    }
 1.47874 +
 1.47875 +    /* If the database page size is not a power of two, or is greater than
 1.47876 +    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
 1.47877 +    ** data. Similarly, if the 'magic' value is invalid, ignore the whole
 1.47878 +    ** WAL file.
 1.47879 +    */
 1.47880 +    magic = sqlite3Get4byte(&aBuf[0]);
 1.47881 +    szPage = sqlite3Get4byte(&aBuf[8]);
 1.47882 +    if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
 1.47883 +     || szPage&(szPage-1) 
 1.47884 +     || szPage>SQLITE_MAX_PAGE_SIZE 
 1.47885 +     || szPage<512 
 1.47886 +    ){
 1.47887 +      goto finished;
 1.47888 +    }
 1.47889 +    pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
 1.47890 +    pWal->szPage = szPage;
 1.47891 +    pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
 1.47892 +    memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
 1.47893 +
 1.47894 +    /* Verify that the WAL header checksum is correct */
 1.47895 +    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
 1.47896 +        aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
 1.47897 +    );
 1.47898 +    if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
 1.47899 +     || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
 1.47900 +    ){
 1.47901 +      goto finished;
 1.47902 +    }
 1.47903 +
 1.47904 +    /* Verify that the version number on the WAL format is one that
 1.47905 +    ** are able to understand */
 1.47906 +    version = sqlite3Get4byte(&aBuf[4]);
 1.47907 +    if( version!=WAL_MAX_VERSION ){
 1.47908 +      rc = SQLITE_CANTOPEN_BKPT;
 1.47909 +      goto finished;
 1.47910 +    }
 1.47911 +
 1.47912 +    /* Malloc a buffer to read frames into. */
 1.47913 +    szFrame = szPage + WAL_FRAME_HDRSIZE;
 1.47914 +    aFrame = (u8 *)sqlite3_malloc(szFrame);
 1.47915 +    if( !aFrame ){
 1.47916 +      rc = SQLITE_NOMEM;
 1.47917 +      goto recovery_error;
 1.47918 +    }
 1.47919 +    aData = &aFrame[WAL_FRAME_HDRSIZE];
 1.47920 +
 1.47921 +    /* Read all frames from the log file. */
 1.47922 +    iFrame = 0;
 1.47923 +    for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
 1.47924 +      u32 pgno;                   /* Database page number for frame */
 1.47925 +      u32 nTruncate;              /* dbsize field from frame header */
 1.47926 +
 1.47927 +      /* Read and decode the next log frame. */
 1.47928 +      iFrame++;
 1.47929 +      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
 1.47930 +      if( rc!=SQLITE_OK ) break;
 1.47931 +      isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
 1.47932 +      if( !isValid ) break;
 1.47933 +      rc = walIndexAppend(pWal, iFrame, pgno);
 1.47934 +      if( rc!=SQLITE_OK ) break;
 1.47935 +
 1.47936 +      /* If nTruncate is non-zero, this is a commit record. */
 1.47937 +      if( nTruncate ){
 1.47938 +        pWal->hdr.mxFrame = iFrame;
 1.47939 +        pWal->hdr.nPage = nTruncate;
 1.47940 +        pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
 1.47941 +        testcase( szPage<=32768 );
 1.47942 +        testcase( szPage>=65536 );
 1.47943 +        aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
 1.47944 +        aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
 1.47945 +      }
 1.47946 +    }
 1.47947 +
 1.47948 +    sqlite3_free(aFrame);
 1.47949 +  }
 1.47950 +
 1.47951 +finished:
 1.47952 +  if( rc==SQLITE_OK ){
 1.47953 +    volatile WalCkptInfo *pInfo;
 1.47954 +    int i;
 1.47955 +    pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
 1.47956 +    pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
 1.47957 +    walIndexWriteHdr(pWal);
 1.47958 +
 1.47959 +    /* Reset the checkpoint-header. This is safe because this thread is 
 1.47960 +    ** currently holding locks that exclude all other readers, writers and
 1.47961 +    ** checkpointers.
 1.47962 +    */
 1.47963 +    pInfo = walCkptInfo(pWal);
 1.47964 +    pInfo->nBackfill = 0;
 1.47965 +    pInfo->aReadMark[0] = 0;
 1.47966 +    for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
 1.47967 +    if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
 1.47968 +
 1.47969 +    /* If more than one frame was recovered from the log file, report an
 1.47970 +    ** event via sqlite3_log(). This is to help with identifying performance
 1.47971 +    ** problems caused by applications routinely shutting down without
 1.47972 +    ** checkpointing the log file.
 1.47973 +    */
 1.47974 +    if( pWal->hdr.nPage ){
 1.47975 +      sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
 1.47976 +          "recovered %d frames from WAL file %s",
 1.47977 +          pWal->hdr.mxFrame, pWal->zWalName
 1.47978 +      );
 1.47979 +    }
 1.47980 +  }
 1.47981 +
 1.47982 +recovery_error:
 1.47983 +  WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
 1.47984 +  walUnlockExclusive(pWal, iLock, nLock);
 1.47985 +  return rc;
 1.47986 +}
 1.47987 +
 1.47988 +/*
 1.47989 +** Close an open wal-index.
 1.47990 +*/
 1.47991 +static void walIndexClose(Wal *pWal, int isDelete){
 1.47992 +  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
 1.47993 +    int i;
 1.47994 +    for(i=0; i<pWal->nWiData; i++){
 1.47995 +      sqlite3_free((void *)pWal->apWiData[i]);
 1.47996 +      pWal->apWiData[i] = 0;
 1.47997 +    }
 1.47998 +  }else{
 1.47999 +    sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
 1.48000 +  }
 1.48001 +}
 1.48002 +
 1.48003 +/* 
 1.48004 +** Open a connection to the WAL file zWalName. The database file must 
 1.48005 +** already be opened on connection pDbFd. The buffer that zWalName points
 1.48006 +** to must remain valid for the lifetime of the returned Wal* handle.
 1.48007 +**
 1.48008 +** A SHARED lock should be held on the database file when this function
 1.48009 +** is called. The purpose of this SHARED lock is to prevent any other
 1.48010 +** client from unlinking the WAL or wal-index file. If another process
 1.48011 +** were to do this just after this client opened one of these files, the
 1.48012 +** system would be badly broken.
 1.48013 +**
 1.48014 +** If the log file is successfully opened, SQLITE_OK is returned and 
 1.48015 +** *ppWal is set to point to a new WAL handle. If an error occurs,
 1.48016 +** an SQLite error code is returned and *ppWal is left unmodified.
 1.48017 +*/
 1.48018 +SQLITE_PRIVATE int sqlite3WalOpen(
 1.48019 +  sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
 1.48020 +  sqlite3_file *pDbFd,            /* The open database file */
 1.48021 +  const char *zWalName,           /* Name of the WAL file */
 1.48022 +  int bNoShm,                     /* True to run in heap-memory mode */
 1.48023 +  i64 mxWalSize,                  /* Truncate WAL to this size on reset */
 1.48024 +  Wal **ppWal                     /* OUT: Allocated Wal handle */
 1.48025 +){
 1.48026 +  int rc;                         /* Return Code */
 1.48027 +  Wal *pRet;                      /* Object to allocate and return */
 1.48028 +  int flags;                      /* Flags passed to OsOpen() */
 1.48029 +
 1.48030 +  assert( zWalName && zWalName[0] );
 1.48031 +  assert( pDbFd );
 1.48032 +
 1.48033 +  /* In the amalgamation, the os_unix.c and os_win.c source files come before
 1.48034 +  ** this source file.  Verify that the #defines of the locking byte offsets
 1.48035 +  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
 1.48036 +  */
 1.48037 +#ifdef WIN_SHM_BASE
 1.48038 +  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
 1.48039 +#endif
 1.48040 +#ifdef UNIX_SHM_BASE
 1.48041 +  assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
 1.48042 +#endif
 1.48043 +
 1.48044 +
 1.48045 +  /* Allocate an instance of struct Wal to return. */
 1.48046 +  *ppWal = 0;
 1.48047 +  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
 1.48048 +  if( !pRet ){
 1.48049 +    return SQLITE_NOMEM;
 1.48050 +  }
 1.48051 +
 1.48052 +  pRet->pVfs = pVfs;
 1.48053 +  pRet->pWalFd = (sqlite3_file *)&pRet[1];
 1.48054 +  pRet->pDbFd = pDbFd;
 1.48055 +  pRet->readLock = -1;
 1.48056 +  pRet->mxWalSize = mxWalSize;
 1.48057 +  pRet->zWalName = zWalName;
 1.48058 +  pRet->syncHeader = 1;
 1.48059 +  pRet->padToSectorBoundary = 1;
 1.48060 +  pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
 1.48061 +
 1.48062 +  /* Open file handle on the write-ahead log file. */
 1.48063 +  flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
 1.48064 +  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
 1.48065 +  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
 1.48066 +    pRet->readOnly = WAL_RDONLY;
 1.48067 +  }
 1.48068 +
 1.48069 +  if( rc!=SQLITE_OK ){
 1.48070 +    walIndexClose(pRet, 0);
 1.48071 +    sqlite3OsClose(pRet->pWalFd);
 1.48072 +    sqlite3_free(pRet);
 1.48073 +  }else{
 1.48074 +    int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
 1.48075 +    if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
 1.48076 +    if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
 1.48077 +      pRet->padToSectorBoundary = 0;
 1.48078 +    }
 1.48079 +    *ppWal = pRet;
 1.48080 +    WALTRACE(("WAL%d: opened\n", pRet));
 1.48081 +  }
 1.48082 +  return rc;
 1.48083 +}
 1.48084 +
 1.48085 +/*
 1.48086 +** Change the size to which the WAL file is trucated on each reset.
 1.48087 +*/
 1.48088 +SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
 1.48089 +  if( pWal ) pWal->mxWalSize = iLimit;
 1.48090 +}
 1.48091 +
 1.48092 +/*
 1.48093 +** Find the smallest page number out of all pages held in the WAL that
 1.48094 +** has not been returned by any prior invocation of this method on the
 1.48095 +** same WalIterator object.   Write into *piFrame the frame index where
 1.48096 +** that page was last written into the WAL.  Write into *piPage the page
 1.48097 +** number.
 1.48098 +**
 1.48099 +** Return 0 on success.  If there are no pages in the WAL with a page
 1.48100 +** number larger than *piPage, then return 1.
 1.48101 +*/
 1.48102 +static int walIteratorNext(
 1.48103 +  WalIterator *p,               /* Iterator */
 1.48104 +  u32 *piPage,                  /* OUT: The page number of the next page */
 1.48105 +  u32 *piFrame                  /* OUT: Wal frame index of next page */
 1.48106 +){
 1.48107 +  u32 iMin;                     /* Result pgno must be greater than iMin */
 1.48108 +  u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
 1.48109 +  int i;                        /* For looping through segments */
 1.48110 +
 1.48111 +  iMin = p->iPrior;
 1.48112 +  assert( iMin<0xffffffff );
 1.48113 +  for(i=p->nSegment-1; i>=0; i--){
 1.48114 +    struct WalSegment *pSegment = &p->aSegment[i];
 1.48115 +    while( pSegment->iNext<pSegment->nEntry ){
 1.48116 +      u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
 1.48117 +      if( iPg>iMin ){
 1.48118 +        if( iPg<iRet ){
 1.48119 +          iRet = iPg;
 1.48120 +          *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
 1.48121 +        }
 1.48122 +        break;
 1.48123 +      }
 1.48124 +      pSegment->iNext++;
 1.48125 +    }
 1.48126 +  }
 1.48127 +
 1.48128 +  *piPage = p->iPrior = iRet;
 1.48129 +  return (iRet==0xFFFFFFFF);
 1.48130 +}
 1.48131 +
 1.48132 +/*
 1.48133 +** This function merges two sorted lists into a single sorted list.
 1.48134 +**
 1.48135 +** aLeft[] and aRight[] are arrays of indices.  The sort key is
 1.48136 +** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
 1.48137 +** is guaranteed for all J<K:
 1.48138 +**
 1.48139 +**        aContent[aLeft[J]] < aContent[aLeft[K]]
 1.48140 +**        aContent[aRight[J]] < aContent[aRight[K]]
 1.48141 +**
 1.48142 +** This routine overwrites aRight[] with a new (probably longer) sequence
 1.48143 +** of indices such that the aRight[] contains every index that appears in
 1.48144 +** either aLeft[] or the old aRight[] and such that the second condition
 1.48145 +** above is still met.
 1.48146 +**
 1.48147 +** The aContent[aLeft[X]] values will be unique for all X.  And the
 1.48148 +** aContent[aRight[X]] values will be unique too.  But there might be
 1.48149 +** one or more combinations of X and Y such that
 1.48150 +**
 1.48151 +**      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
 1.48152 +**
 1.48153 +** When that happens, omit the aLeft[X] and use the aRight[Y] index.
 1.48154 +*/
 1.48155 +static void walMerge(
 1.48156 +  const u32 *aContent,            /* Pages in wal - keys for the sort */
 1.48157 +  ht_slot *aLeft,                 /* IN: Left hand input list */
 1.48158 +  int nLeft,                      /* IN: Elements in array *paLeft */
 1.48159 +  ht_slot **paRight,              /* IN/OUT: Right hand input list */
 1.48160 +  int *pnRight,                   /* IN/OUT: Elements in *paRight */
 1.48161 +  ht_slot *aTmp                   /* Temporary buffer */
 1.48162 +){
 1.48163 +  int iLeft = 0;                  /* Current index in aLeft */
 1.48164 +  int iRight = 0;                 /* Current index in aRight */
 1.48165 +  int iOut = 0;                   /* Current index in output buffer */
 1.48166 +  int nRight = *pnRight;
 1.48167 +  ht_slot *aRight = *paRight;
 1.48168 +
 1.48169 +  assert( nLeft>0 && nRight>0 );
 1.48170 +  while( iRight<nRight || iLeft<nLeft ){
 1.48171 +    ht_slot logpage;
 1.48172 +    Pgno dbpage;
 1.48173 +
 1.48174 +    if( (iLeft<nLeft) 
 1.48175 +     && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
 1.48176 +    ){
 1.48177 +      logpage = aLeft[iLeft++];
 1.48178 +    }else{
 1.48179 +      logpage = aRight[iRight++];
 1.48180 +    }
 1.48181 +    dbpage = aContent[logpage];
 1.48182 +
 1.48183 +    aTmp[iOut++] = logpage;
 1.48184 +    if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
 1.48185 +
 1.48186 +    assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
 1.48187 +    assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
 1.48188 +  }
 1.48189 +
 1.48190 +  *paRight = aLeft;
 1.48191 +  *pnRight = iOut;
 1.48192 +  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
 1.48193 +}
 1.48194 +
 1.48195 +/*
 1.48196 +** Sort the elements in list aList using aContent[] as the sort key.
 1.48197 +** Remove elements with duplicate keys, preferring to keep the
 1.48198 +** larger aList[] values.
 1.48199 +**
 1.48200 +** The aList[] entries are indices into aContent[].  The values in
 1.48201 +** aList[] are to be sorted so that for all J<K:
 1.48202 +**
 1.48203 +**      aContent[aList[J]] < aContent[aList[K]]
 1.48204 +**
 1.48205 +** For any X and Y such that
 1.48206 +**
 1.48207 +**      aContent[aList[X]] == aContent[aList[Y]]
 1.48208 +**
 1.48209 +** Keep the larger of the two values aList[X] and aList[Y] and discard
 1.48210 +** the smaller.
 1.48211 +*/
 1.48212 +static void walMergesort(
 1.48213 +  const u32 *aContent,            /* Pages in wal */
 1.48214 +  ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
 1.48215 +  ht_slot *aList,                 /* IN/OUT: List to sort */
 1.48216 +  int *pnList                     /* IN/OUT: Number of elements in aList[] */
 1.48217 +){
 1.48218 +  struct Sublist {
 1.48219 +    int nList;                    /* Number of elements in aList */
 1.48220 +    ht_slot *aList;               /* Pointer to sub-list content */
 1.48221 +  };
 1.48222 +
 1.48223 +  const int nList = *pnList;      /* Size of input list */
 1.48224 +  int nMerge = 0;                 /* Number of elements in list aMerge */
 1.48225 +  ht_slot *aMerge = 0;            /* List to be merged */
 1.48226 +  int iList;                      /* Index into input list */
 1.48227 +  int iSub = 0;                   /* Index into aSub array */
 1.48228 +  struct Sublist aSub[13];        /* Array of sub-lists */
 1.48229 +
 1.48230 +  memset(aSub, 0, sizeof(aSub));
 1.48231 +  assert( nList<=HASHTABLE_NPAGE && nList>0 );
 1.48232 +  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
 1.48233 +
 1.48234 +  for(iList=0; iList<nList; iList++){
 1.48235 +    nMerge = 1;
 1.48236 +    aMerge = &aList[iList];
 1.48237 +    for(iSub=0; iList & (1<<iSub); iSub++){
 1.48238 +      struct Sublist *p = &aSub[iSub];
 1.48239 +      assert( p->aList && p->nList<=(1<<iSub) );
 1.48240 +      assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
 1.48241 +      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
 1.48242 +    }
 1.48243 +    aSub[iSub].aList = aMerge;
 1.48244 +    aSub[iSub].nList = nMerge;
 1.48245 +  }
 1.48246 +
 1.48247 +  for(iSub++; iSub<ArraySize(aSub); iSub++){
 1.48248 +    if( nList & (1<<iSub) ){
 1.48249 +      struct Sublist *p = &aSub[iSub];
 1.48250 +      assert( p->nList<=(1<<iSub) );
 1.48251 +      assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
 1.48252 +      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
 1.48253 +    }
 1.48254 +  }
 1.48255 +  assert( aMerge==aList );
 1.48256 +  *pnList = nMerge;
 1.48257 +
 1.48258 +#ifdef SQLITE_DEBUG
 1.48259 +  {
 1.48260 +    int i;
 1.48261 +    for(i=1; i<*pnList; i++){
 1.48262 +      assert( aContent[aList[i]] > aContent[aList[i-1]] );
 1.48263 +    }
 1.48264 +  }
 1.48265 +#endif
 1.48266 +}
 1.48267 +
 1.48268 +/* 
 1.48269 +** Free an iterator allocated by walIteratorInit().
 1.48270 +*/
 1.48271 +static void walIteratorFree(WalIterator *p){
 1.48272 +  sqlite3ScratchFree(p);
 1.48273 +}
 1.48274 +
 1.48275 +/*
 1.48276 +** Construct a WalInterator object that can be used to loop over all 
 1.48277 +** pages in the WAL in ascending order. The caller must hold the checkpoint
 1.48278 +** lock.
 1.48279 +**
 1.48280 +** On success, make *pp point to the newly allocated WalInterator object
 1.48281 +** return SQLITE_OK. Otherwise, return an error code. If this routine
 1.48282 +** returns an error, the value of *pp is undefined.
 1.48283 +**
 1.48284 +** The calling routine should invoke walIteratorFree() to destroy the
 1.48285 +** WalIterator object when it has finished with it.
 1.48286 +*/
 1.48287 +static int walIteratorInit(Wal *pWal, WalIterator **pp){
 1.48288 +  WalIterator *p;                 /* Return value */
 1.48289 +  int nSegment;                   /* Number of segments to merge */
 1.48290 +  u32 iLast;                      /* Last frame in log */
 1.48291 +  int nByte;                      /* Number of bytes to allocate */
 1.48292 +  int i;                          /* Iterator variable */
 1.48293 +  ht_slot *aTmp;                  /* Temp space used by merge-sort */
 1.48294 +  int rc = SQLITE_OK;             /* Return Code */
 1.48295 +
 1.48296 +  /* This routine only runs while holding the checkpoint lock. And
 1.48297 +  ** it only runs if there is actually content in the log (mxFrame>0).
 1.48298 +  */
 1.48299 +  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
 1.48300 +  iLast = pWal->hdr.mxFrame;
 1.48301 +
 1.48302 +  /* Allocate space for the WalIterator object. */
 1.48303 +  nSegment = walFramePage(iLast) + 1;
 1.48304 +  nByte = sizeof(WalIterator) 
 1.48305 +        + (nSegment-1)*sizeof(struct WalSegment)
 1.48306 +        + iLast*sizeof(ht_slot);
 1.48307 +  p = (WalIterator *)sqlite3ScratchMalloc(nByte);
 1.48308 +  if( !p ){
 1.48309 +    return SQLITE_NOMEM;
 1.48310 +  }
 1.48311 +  memset(p, 0, nByte);
 1.48312 +  p->nSegment = nSegment;
 1.48313 +
 1.48314 +  /* Allocate temporary space used by the merge-sort routine. This block
 1.48315 +  ** of memory will be freed before this function returns.
 1.48316 +  */
 1.48317 +  aTmp = (ht_slot *)sqlite3ScratchMalloc(
 1.48318 +      sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
 1.48319 +  );
 1.48320 +  if( !aTmp ){
 1.48321 +    rc = SQLITE_NOMEM;
 1.48322 +  }
 1.48323 +
 1.48324 +  for(i=0; rc==SQLITE_OK && i<nSegment; i++){
 1.48325 +    volatile ht_slot *aHash;
 1.48326 +    u32 iZero;
 1.48327 +    volatile u32 *aPgno;
 1.48328 +
 1.48329 +    rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
 1.48330 +    if( rc==SQLITE_OK ){
 1.48331 +      int j;                      /* Counter variable */
 1.48332 +      int nEntry;                 /* Number of entries in this segment */
 1.48333 +      ht_slot *aIndex;            /* Sorted index for this segment */
 1.48334 +
 1.48335 +      aPgno++;
 1.48336 +      if( (i+1)==nSegment ){
 1.48337 +        nEntry = (int)(iLast - iZero);
 1.48338 +      }else{
 1.48339 +        nEntry = (int)((u32*)aHash - (u32*)aPgno);
 1.48340 +      }
 1.48341 +      aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
 1.48342 +      iZero++;
 1.48343 +  
 1.48344 +      for(j=0; j<nEntry; j++){
 1.48345 +        aIndex[j] = (ht_slot)j;
 1.48346 +      }
 1.48347 +      walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
 1.48348 +      p->aSegment[i].iZero = iZero;
 1.48349 +      p->aSegment[i].nEntry = nEntry;
 1.48350 +      p->aSegment[i].aIndex = aIndex;
 1.48351 +      p->aSegment[i].aPgno = (u32 *)aPgno;
 1.48352 +    }
 1.48353 +  }
 1.48354 +  sqlite3ScratchFree(aTmp);
 1.48355 +
 1.48356 +  if( rc!=SQLITE_OK ){
 1.48357 +    walIteratorFree(p);
 1.48358 +  }
 1.48359 +  *pp = p;
 1.48360 +  return rc;
 1.48361 +}
 1.48362 +
 1.48363 +/*
 1.48364 +** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
 1.48365 +** n. If the attempt fails and parameter xBusy is not NULL, then it is a
 1.48366 +** busy-handler function. Invoke it and retry the lock until either the
 1.48367 +** lock is successfully obtained or the busy-handler returns 0.
 1.48368 +*/
 1.48369 +static int walBusyLock(
 1.48370 +  Wal *pWal,                      /* WAL connection */
 1.48371 +  int (*xBusy)(void*),            /* Function to call when busy */
 1.48372 +  void *pBusyArg,                 /* Context argument for xBusyHandler */
 1.48373 +  int lockIdx,                    /* Offset of first byte to lock */
 1.48374 +  int n                           /* Number of bytes to lock */
 1.48375 +){
 1.48376 +  int rc;
 1.48377 +  do {
 1.48378 +    rc = walLockExclusive(pWal, lockIdx, n);
 1.48379 +  }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
 1.48380 +  return rc;
 1.48381 +}
 1.48382 +
 1.48383 +/*
 1.48384 +** The cache of the wal-index header must be valid to call this function.
 1.48385 +** Return the page-size in bytes used by the database.
 1.48386 +*/
 1.48387 +static int walPagesize(Wal *pWal){
 1.48388 +  return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
 1.48389 +}
 1.48390 +
 1.48391 +/*
 1.48392 +** Copy as much content as we can from the WAL back into the database file
 1.48393 +** in response to an sqlite3_wal_checkpoint() request or the equivalent.
 1.48394 +**
 1.48395 +** The amount of information copies from WAL to database might be limited
 1.48396 +** by active readers.  This routine will never overwrite a database page
 1.48397 +** that a concurrent reader might be using.
 1.48398 +**
 1.48399 +** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
 1.48400 +** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
 1.48401 +** checkpoints are always run by a background thread or background 
 1.48402 +** process, foreground threads will never block on a lengthy fsync call.
 1.48403 +**
 1.48404 +** Fsync is called on the WAL before writing content out of the WAL and
 1.48405 +** into the database.  This ensures that if the new content is persistent
 1.48406 +** in the WAL and can be recovered following a power-loss or hard reset.
 1.48407 +**
 1.48408 +** Fsync is also called on the database file if (and only if) the entire
 1.48409 +** WAL content is copied into the database file.  This second fsync makes
 1.48410 +** it safe to delete the WAL since the new content will persist in the
 1.48411 +** database file.
 1.48412 +**
 1.48413 +** This routine uses and updates the nBackfill field of the wal-index header.
 1.48414 +** This is the only routine tha will increase the value of nBackfill.  
 1.48415 +** (A WAL reset or recovery will revert nBackfill to zero, but not increase
 1.48416 +** its value.)
 1.48417 +**
 1.48418 +** The caller must be holding sufficient locks to ensure that no other
 1.48419 +** checkpoint is running (in any other thread or process) at the same
 1.48420 +** time.
 1.48421 +*/
 1.48422 +static int walCheckpoint(
 1.48423 +  Wal *pWal,                      /* Wal connection */
 1.48424 +  int eMode,                      /* One of PASSIVE, FULL or RESTART */
 1.48425 +  int (*xBusyCall)(void*),        /* Function to call when busy */
 1.48426 +  void *pBusyArg,                 /* Context argument for xBusyHandler */
 1.48427 +  int sync_flags,                 /* Flags for OsSync() (or 0) */
 1.48428 +  u8 *zBuf                        /* Temporary buffer to use */
 1.48429 +){
 1.48430 +  int rc;                         /* Return code */
 1.48431 +  int szPage;                     /* Database page-size */
 1.48432 +  WalIterator *pIter = 0;         /* Wal iterator context */
 1.48433 +  u32 iDbpage = 0;                /* Next database page to write */
 1.48434 +  u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
 1.48435 +  u32 mxSafeFrame;                /* Max frame that can be backfilled */
 1.48436 +  u32 mxPage;                     /* Max database page to write */
 1.48437 +  int i;                          /* Loop counter */
 1.48438 +  volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
 1.48439 +  int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
 1.48440 +
 1.48441 +  szPage = walPagesize(pWal);
 1.48442 +  testcase( szPage<=32768 );
 1.48443 +  testcase( szPage>=65536 );
 1.48444 +  pInfo = walCkptInfo(pWal);
 1.48445 +  if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
 1.48446 +
 1.48447 +  /* Allocate the iterator */
 1.48448 +  rc = walIteratorInit(pWal, &pIter);
 1.48449 +  if( rc!=SQLITE_OK ){
 1.48450 +    return rc;
 1.48451 +  }
 1.48452 +  assert( pIter );
 1.48453 +
 1.48454 +  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
 1.48455 +
 1.48456 +  /* Compute in mxSafeFrame the index of the last frame of the WAL that is
 1.48457 +  ** safe to write into the database.  Frames beyond mxSafeFrame might
 1.48458 +  ** overwrite database pages that are in use by active readers and thus
 1.48459 +  ** cannot be backfilled from the WAL.
 1.48460 +  */
 1.48461 +  mxSafeFrame = pWal->hdr.mxFrame;
 1.48462 +  mxPage = pWal->hdr.nPage;
 1.48463 +  for(i=1; i<WAL_NREADER; i++){
 1.48464 +    u32 y = pInfo->aReadMark[i];
 1.48465 +    if( mxSafeFrame>y ){
 1.48466 +      assert( y<=pWal->hdr.mxFrame );
 1.48467 +      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
 1.48468 +      if( rc==SQLITE_OK ){
 1.48469 +        pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
 1.48470 +        walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
 1.48471 +      }else if( rc==SQLITE_BUSY ){
 1.48472 +        mxSafeFrame = y;
 1.48473 +        xBusy = 0;
 1.48474 +      }else{
 1.48475 +        goto walcheckpoint_out;
 1.48476 +      }
 1.48477 +    }
 1.48478 +  }
 1.48479 +
 1.48480 +  if( pInfo->nBackfill<mxSafeFrame
 1.48481 +   && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
 1.48482 +  ){
 1.48483 +    i64 nSize;                    /* Current size of database file */
 1.48484 +    u32 nBackfill = pInfo->nBackfill;
 1.48485 +
 1.48486 +    /* Sync the WAL to disk */
 1.48487 +    if( sync_flags ){
 1.48488 +      rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
 1.48489 +    }
 1.48490 +
 1.48491 +    /* If the database may grow as a result of this checkpoint, hint
 1.48492 +    ** about the eventual size of the db file to the VFS layer.
 1.48493 +    */
 1.48494 +    if( rc==SQLITE_OK ){
 1.48495 +      i64 nReq = ((i64)mxPage * szPage);
 1.48496 +      rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
 1.48497 +      if( rc==SQLITE_OK && nSize<nReq ){
 1.48498 +        sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
 1.48499 +      }
 1.48500 +    }
 1.48501 +
 1.48502 +
 1.48503 +    /* Iterate through the contents of the WAL, copying data to the db file. */
 1.48504 +    while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
 1.48505 +      i64 iOffset;
 1.48506 +      assert( walFramePgno(pWal, iFrame)==iDbpage );
 1.48507 +      if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
 1.48508 +      iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
 1.48509 +      /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
 1.48510 +      rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
 1.48511 +      if( rc!=SQLITE_OK ) break;
 1.48512 +      iOffset = (iDbpage-1)*(i64)szPage;
 1.48513 +      testcase( IS_BIG_INT(iOffset) );
 1.48514 +      rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
 1.48515 +      if( rc!=SQLITE_OK ) break;
 1.48516 +    }
 1.48517 +
 1.48518 +    /* If work was actually accomplished... */
 1.48519 +    if( rc==SQLITE_OK ){
 1.48520 +      if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
 1.48521 +        i64 szDb = pWal->hdr.nPage*(i64)szPage;
 1.48522 +        testcase( IS_BIG_INT(szDb) );
 1.48523 +        rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
 1.48524 +        if( rc==SQLITE_OK && sync_flags ){
 1.48525 +          rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
 1.48526 +        }
 1.48527 +      }
 1.48528 +      if( rc==SQLITE_OK ){
 1.48529 +        pInfo->nBackfill = mxSafeFrame;
 1.48530 +      }
 1.48531 +    }
 1.48532 +
 1.48533 +    /* Release the reader lock held while backfilling */
 1.48534 +    walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
 1.48535 +  }
 1.48536 +
 1.48537 +  if( rc==SQLITE_BUSY ){
 1.48538 +    /* Reset the return code so as not to report a checkpoint failure
 1.48539 +    ** just because there are active readers.  */
 1.48540 +    rc = SQLITE_OK;
 1.48541 +  }
 1.48542 +
 1.48543 +  /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
 1.48544 +  ** file has been copied into the database file, then block until all
 1.48545 +  ** readers have finished using the wal file. This ensures that the next
 1.48546 +  ** process to write to the database restarts the wal file.
 1.48547 +  */
 1.48548 +  if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
 1.48549 +    assert( pWal->writeLock );
 1.48550 +    if( pInfo->nBackfill<pWal->hdr.mxFrame ){
 1.48551 +      rc = SQLITE_BUSY;
 1.48552 +    }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
 1.48553 +      assert( mxSafeFrame==pWal->hdr.mxFrame );
 1.48554 +      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
 1.48555 +      if( rc==SQLITE_OK ){
 1.48556 +        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
 1.48557 +      }
 1.48558 +    }
 1.48559 +  }
 1.48560 +
 1.48561 + walcheckpoint_out:
 1.48562 +  walIteratorFree(pIter);
 1.48563 +  return rc;
 1.48564 +}
 1.48565 +
 1.48566 +/*
 1.48567 +** If the WAL file is currently larger than nMax bytes in size, truncate
 1.48568 +** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
 1.48569 +*/
 1.48570 +static void walLimitSize(Wal *pWal, i64 nMax){
 1.48571 +  i64 sz;
 1.48572 +  int rx;
 1.48573 +  sqlite3BeginBenignMalloc();
 1.48574 +  rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
 1.48575 +  if( rx==SQLITE_OK && (sz > nMax ) ){
 1.48576 +    rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
 1.48577 +  }
 1.48578 +  sqlite3EndBenignMalloc();
 1.48579 +  if( rx ){
 1.48580 +    sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
 1.48581 +  }
 1.48582 +}
 1.48583 +
 1.48584 +/*
 1.48585 +** Close a connection to a log file.
 1.48586 +*/
 1.48587 +SQLITE_PRIVATE int sqlite3WalClose(
 1.48588 +  Wal *pWal,                      /* Wal to close */
 1.48589 +  int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
 1.48590 +  int nBuf,
 1.48591 +  u8 *zBuf                        /* Buffer of at least nBuf bytes */
 1.48592 +){
 1.48593 +  int rc = SQLITE_OK;
 1.48594 +  if( pWal ){
 1.48595 +    int isDelete = 0;             /* True to unlink wal and wal-index files */
 1.48596 +
 1.48597 +    /* If an EXCLUSIVE lock can be obtained on the database file (using the
 1.48598 +    ** ordinary, rollback-mode locking methods, this guarantees that the
 1.48599 +    ** connection associated with this log file is the only connection to
 1.48600 +    ** the database. In this case checkpoint the database and unlink both
 1.48601 +    ** the wal and wal-index files.
 1.48602 +    **
 1.48603 +    ** The EXCLUSIVE lock is not released before returning.
 1.48604 +    */
 1.48605 +    rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
 1.48606 +    if( rc==SQLITE_OK ){
 1.48607 +      if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
 1.48608 +        pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
 1.48609 +      }
 1.48610 +      rc = sqlite3WalCheckpoint(
 1.48611 +          pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
 1.48612 +      );
 1.48613 +      if( rc==SQLITE_OK ){
 1.48614 +        int bPersist = -1;
 1.48615 +        sqlite3OsFileControlHint(
 1.48616 +            pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
 1.48617 +        );
 1.48618 +        if( bPersist!=1 ){
 1.48619 +          /* Try to delete the WAL file if the checkpoint completed and
 1.48620 +          ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
 1.48621 +          ** mode (!bPersist) */
 1.48622 +          isDelete = 1;
 1.48623 +        }else if( pWal->mxWalSize>=0 ){
 1.48624 +          /* Try to truncate the WAL file to zero bytes if the checkpoint
 1.48625 +          ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
 1.48626 +          ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
 1.48627 +          ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
 1.48628 +          ** to zero bytes as truncating to the journal_size_limit might
 1.48629 +          ** leave a corrupt WAL file on disk. */
 1.48630 +          walLimitSize(pWal, 0);
 1.48631 +        }
 1.48632 +      }
 1.48633 +    }
 1.48634 +
 1.48635 +    walIndexClose(pWal, isDelete);
 1.48636 +    sqlite3OsClose(pWal->pWalFd);
 1.48637 +    if( isDelete ){
 1.48638 +      sqlite3BeginBenignMalloc();
 1.48639 +      sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
 1.48640 +      sqlite3EndBenignMalloc();
 1.48641 +    }
 1.48642 +    WALTRACE(("WAL%p: closed\n", pWal));
 1.48643 +    sqlite3_free((void *)pWal->apWiData);
 1.48644 +    sqlite3_free(pWal);
 1.48645 +  }
 1.48646 +  return rc;
 1.48647 +}
 1.48648 +
 1.48649 +/*
 1.48650 +** Try to read the wal-index header.  Return 0 on success and 1 if
 1.48651 +** there is a problem.
 1.48652 +**
 1.48653 +** The wal-index is in shared memory.  Another thread or process might
 1.48654 +** be writing the header at the same time this procedure is trying to
 1.48655 +** read it, which might result in inconsistency.  A dirty read is detected
 1.48656 +** by verifying that both copies of the header are the same and also by
 1.48657 +** a checksum on the header.
 1.48658 +**
 1.48659 +** If and only if the read is consistent and the header is different from
 1.48660 +** pWal->hdr, then pWal->hdr is updated to the content of the new header
 1.48661 +** and *pChanged is set to 1.
 1.48662 +**
 1.48663 +** If the checksum cannot be verified return non-zero. If the header
 1.48664 +** is read successfully and the checksum verified, return zero.
 1.48665 +*/
 1.48666 +static int walIndexTryHdr(Wal *pWal, int *pChanged){
 1.48667 +  u32 aCksum[2];                  /* Checksum on the header content */
 1.48668 +  WalIndexHdr h1, h2;             /* Two copies of the header content */
 1.48669 +  WalIndexHdr volatile *aHdr;     /* Header in shared memory */
 1.48670 +
 1.48671 +  /* The first page of the wal-index must be mapped at this point. */
 1.48672 +  assert( pWal->nWiData>0 && pWal->apWiData[0] );
 1.48673 +
 1.48674 +  /* Read the header. This might happen concurrently with a write to the
 1.48675 +  ** same area of shared memory on a different CPU in a SMP,
 1.48676 +  ** meaning it is possible that an inconsistent snapshot is read
 1.48677 +  ** from the file. If this happens, return non-zero.
 1.48678 +  **
 1.48679 +  ** There are two copies of the header at the beginning of the wal-index.
 1.48680 +  ** When reading, read [0] first then [1].  Writes are in the reverse order.
 1.48681 +  ** Memory barriers are used to prevent the compiler or the hardware from
 1.48682 +  ** reordering the reads and writes.
 1.48683 +  */
 1.48684 +  aHdr = walIndexHdr(pWal);
 1.48685 +  memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
 1.48686 +  walShmBarrier(pWal);
 1.48687 +  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
 1.48688 +
 1.48689 +  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
 1.48690 +    return 1;   /* Dirty read */
 1.48691 +  }  
 1.48692 +  if( h1.isInit==0 ){
 1.48693 +    return 1;   /* Malformed header - probably all zeros */
 1.48694 +  }
 1.48695 +  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
 1.48696 +  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
 1.48697 +    return 1;   /* Checksum does not match */
 1.48698 +  }
 1.48699 +
 1.48700 +  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
 1.48701 +    *pChanged = 1;
 1.48702 +    memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
 1.48703 +    pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
 1.48704 +    testcase( pWal->szPage<=32768 );
 1.48705 +    testcase( pWal->szPage>=65536 );
 1.48706 +  }
 1.48707 +
 1.48708 +  /* The header was successfully read. Return zero. */
 1.48709 +  return 0;
 1.48710 +}
 1.48711 +
 1.48712 +/*
 1.48713 +** Read the wal-index header from the wal-index and into pWal->hdr.
 1.48714 +** If the wal-header appears to be corrupt, try to reconstruct the
 1.48715 +** wal-index from the WAL before returning.
 1.48716 +**
 1.48717 +** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
 1.48718 +** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
 1.48719 +** to 0.
 1.48720 +**
 1.48721 +** If the wal-index header is successfully read, return SQLITE_OK. 
 1.48722 +** Otherwise an SQLite error code.
 1.48723 +*/
 1.48724 +static int walIndexReadHdr(Wal *pWal, int *pChanged){
 1.48725 +  int rc;                         /* Return code */
 1.48726 +  int badHdr;                     /* True if a header read failed */
 1.48727 +  volatile u32 *page0;            /* Chunk of wal-index containing header */
 1.48728 +
 1.48729 +  /* Ensure that page 0 of the wal-index (the page that contains the 
 1.48730 +  ** wal-index header) is mapped. Return early if an error occurs here.
 1.48731 +  */
 1.48732 +  assert( pChanged );
 1.48733 +  rc = walIndexPage(pWal, 0, &page0);
 1.48734 +  if( rc!=SQLITE_OK ){
 1.48735 +    return rc;
 1.48736 +  };
 1.48737 +  assert( page0 || pWal->writeLock==0 );
 1.48738 +
 1.48739 +  /* If the first page of the wal-index has been mapped, try to read the
 1.48740 +  ** wal-index header immediately, without holding any lock. This usually
 1.48741 +  ** works, but may fail if the wal-index header is corrupt or currently 
 1.48742 +  ** being modified by another thread or process.
 1.48743 +  */
 1.48744 +  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
 1.48745 +
 1.48746 +  /* If the first attempt failed, it might have been due to a race
 1.48747 +  ** with a writer.  So get a WRITE lock and try again.
 1.48748 +  */
 1.48749 +  assert( badHdr==0 || pWal->writeLock==0 );
 1.48750 +  if( badHdr ){
 1.48751 +    if( pWal->readOnly & WAL_SHM_RDONLY ){
 1.48752 +      if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
 1.48753 +        walUnlockShared(pWal, WAL_WRITE_LOCK);
 1.48754 +        rc = SQLITE_READONLY_RECOVERY;
 1.48755 +      }
 1.48756 +    }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
 1.48757 +      pWal->writeLock = 1;
 1.48758 +      if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
 1.48759 +        badHdr = walIndexTryHdr(pWal, pChanged);
 1.48760 +        if( badHdr ){
 1.48761 +          /* If the wal-index header is still malformed even while holding
 1.48762 +          ** a WRITE lock, it can only mean that the header is corrupted and
 1.48763 +          ** needs to be reconstructed.  So run recovery to do exactly that.
 1.48764 +          */
 1.48765 +          rc = walIndexRecover(pWal);
 1.48766 +          *pChanged = 1;
 1.48767 +        }
 1.48768 +      }
 1.48769 +      pWal->writeLock = 0;
 1.48770 +      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
 1.48771 +    }
 1.48772 +  }
 1.48773 +
 1.48774 +  /* If the header is read successfully, check the version number to make
 1.48775 +  ** sure the wal-index was not constructed with some future format that
 1.48776 +  ** this version of SQLite cannot understand.
 1.48777 +  */
 1.48778 +  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
 1.48779 +    rc = SQLITE_CANTOPEN_BKPT;
 1.48780 +  }
 1.48781 +
 1.48782 +  return rc;
 1.48783 +}
 1.48784 +
 1.48785 +/*
 1.48786 +** This is the value that walTryBeginRead returns when it needs to
 1.48787 +** be retried.
 1.48788 +*/
 1.48789 +#define WAL_RETRY  (-1)
 1.48790 +
 1.48791 +/*
 1.48792 +** Attempt to start a read transaction.  This might fail due to a race or
 1.48793 +** other transient condition.  When that happens, it returns WAL_RETRY to
 1.48794 +** indicate to the caller that it is safe to retry immediately.
 1.48795 +**
 1.48796 +** On success return SQLITE_OK.  On a permanent failure (such an
 1.48797 +** I/O error or an SQLITE_BUSY because another process is running
 1.48798 +** recovery) return a positive error code.
 1.48799 +**
 1.48800 +** The useWal parameter is true to force the use of the WAL and disable
 1.48801 +** the case where the WAL is bypassed because it has been completely
 1.48802 +** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
 1.48803 +** to make a copy of the wal-index header into pWal->hdr.  If the 
 1.48804 +** wal-index header has changed, *pChanged is set to 1 (as an indication 
 1.48805 +** to the caller that the local paget cache is obsolete and needs to be 
 1.48806 +** flushed.)  When useWal==1, the wal-index header is assumed to already
 1.48807 +** be loaded and the pChanged parameter is unused.
 1.48808 +**
 1.48809 +** The caller must set the cnt parameter to the number of prior calls to
 1.48810 +** this routine during the current read attempt that returned WAL_RETRY.
 1.48811 +** This routine will start taking more aggressive measures to clear the
 1.48812 +** race conditions after multiple WAL_RETRY returns, and after an excessive
 1.48813 +** number of errors will ultimately return SQLITE_PROTOCOL.  The
 1.48814 +** SQLITE_PROTOCOL return indicates that some other process has gone rogue
 1.48815 +** and is not honoring the locking protocol.  There is a vanishingly small
 1.48816 +** chance that SQLITE_PROTOCOL could be returned because of a run of really
 1.48817 +** bad luck when there is lots of contention for the wal-index, but that
 1.48818 +** possibility is so small that it can be safely neglected, we believe.
 1.48819 +**
 1.48820 +** On success, this routine obtains a read lock on 
 1.48821 +** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
 1.48822 +** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
 1.48823 +** that means the Wal does not hold any read lock.  The reader must not
 1.48824 +** access any database page that is modified by a WAL frame up to and
 1.48825 +** including frame number aReadMark[pWal->readLock].  The reader will
 1.48826 +** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
 1.48827 +** Or if pWal->readLock==0, then the reader will ignore the WAL
 1.48828 +** completely and get all content directly from the database file.
 1.48829 +** If the useWal parameter is 1 then the WAL will never be ignored and
 1.48830 +** this routine will always set pWal->readLock>0 on success.
 1.48831 +** When the read transaction is completed, the caller must release the
 1.48832 +** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
 1.48833 +**
 1.48834 +** This routine uses the nBackfill and aReadMark[] fields of the header
 1.48835 +** to select a particular WAL_READ_LOCK() that strives to let the
 1.48836 +** checkpoint process do as much work as possible.  This routine might
 1.48837 +** update values of the aReadMark[] array in the header, but if it does
 1.48838 +** so it takes care to hold an exclusive lock on the corresponding
 1.48839 +** WAL_READ_LOCK() while changing values.
 1.48840 +*/
 1.48841 +static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
 1.48842 +  volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
 1.48843 +  u32 mxReadMark;                 /* Largest aReadMark[] value */
 1.48844 +  int mxI;                        /* Index of largest aReadMark[] value */
 1.48845 +  int i;                          /* Loop counter */
 1.48846 +  int rc = SQLITE_OK;             /* Return code  */
 1.48847 +
 1.48848 +  assert( pWal->readLock<0 );     /* Not currently locked */
 1.48849 +
 1.48850 +  /* Take steps to avoid spinning forever if there is a protocol error.
 1.48851 +  **
 1.48852 +  ** Circumstances that cause a RETRY should only last for the briefest
 1.48853 +  ** instances of time.  No I/O or other system calls are done while the
 1.48854 +  ** locks are held, so the locks should not be held for very long. But 
 1.48855 +  ** if we are unlucky, another process that is holding a lock might get
 1.48856 +  ** paged out or take a page-fault that is time-consuming to resolve, 
 1.48857 +  ** during the few nanoseconds that it is holding the lock.  In that case,
 1.48858 +  ** it might take longer than normal for the lock to free.
 1.48859 +  **
 1.48860 +  ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
 1.48861 +  ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
 1.48862 +  ** is more of a scheduler yield than an actual delay.  But on the 10th
 1.48863 +  ** an subsequent retries, the delays start becoming longer and longer, 
 1.48864 +  ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
 1.48865 +  ** The total delay time before giving up is less than 1 second.
 1.48866 +  */
 1.48867 +  if( cnt>5 ){
 1.48868 +    int nDelay = 1;                      /* Pause time in microseconds */
 1.48869 +    if( cnt>100 ){
 1.48870 +      VVA_ONLY( pWal->lockError = 1; )
 1.48871 +      return SQLITE_PROTOCOL;
 1.48872 +    }
 1.48873 +    if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
 1.48874 +    sqlite3OsSleep(pWal->pVfs, nDelay);
 1.48875 +  }
 1.48876 +
 1.48877 +  if( !useWal ){
 1.48878 +    rc = walIndexReadHdr(pWal, pChanged);
 1.48879 +    if( rc==SQLITE_BUSY ){
 1.48880 +      /* If there is not a recovery running in another thread or process
 1.48881 +      ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
 1.48882 +      ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
 1.48883 +      ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
 1.48884 +      ** would be technically correct.  But the race is benign since with
 1.48885 +      ** WAL_RETRY this routine will be called again and will probably be
 1.48886 +      ** right on the second iteration.
 1.48887 +      */
 1.48888 +      if( pWal->apWiData[0]==0 ){
 1.48889 +        /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
 1.48890 +        ** We assume this is a transient condition, so return WAL_RETRY. The
 1.48891 +        ** xShmMap() implementation used by the default unix and win32 VFS 
 1.48892 +        ** modules may return SQLITE_BUSY due to a race condition in the 
 1.48893 +        ** code that determines whether or not the shared-memory region 
 1.48894 +        ** must be zeroed before the requested page is returned.
 1.48895 +        */
 1.48896 +        rc = WAL_RETRY;
 1.48897 +      }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
 1.48898 +        walUnlockShared(pWal, WAL_RECOVER_LOCK);
 1.48899 +        rc = WAL_RETRY;
 1.48900 +      }else if( rc==SQLITE_BUSY ){
 1.48901 +        rc = SQLITE_BUSY_RECOVERY;
 1.48902 +      }
 1.48903 +    }
 1.48904 +    if( rc!=SQLITE_OK ){
 1.48905 +      return rc;
 1.48906 +    }
 1.48907 +  }
 1.48908 +
 1.48909 +  pInfo = walCkptInfo(pWal);
 1.48910 +  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
 1.48911 +    /* The WAL has been completely backfilled (or it is empty).
 1.48912 +    ** and can be safely ignored.
 1.48913 +    */
 1.48914 +    rc = walLockShared(pWal, WAL_READ_LOCK(0));
 1.48915 +    walShmBarrier(pWal);
 1.48916 +    if( rc==SQLITE_OK ){
 1.48917 +      if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
 1.48918 +        /* It is not safe to allow the reader to continue here if frames
 1.48919 +        ** may have been appended to the log before READ_LOCK(0) was obtained.
 1.48920 +        ** When holding READ_LOCK(0), the reader ignores the entire log file,
 1.48921 +        ** which implies that the database file contains a trustworthy
 1.48922 +        ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
 1.48923 +        ** happening, this is usually correct.
 1.48924 +        **
 1.48925 +        ** However, if frames have been appended to the log (or if the log 
 1.48926 +        ** is wrapped and written for that matter) before the READ_LOCK(0)
 1.48927 +        ** is obtained, that is not necessarily true. A checkpointer may
 1.48928 +        ** have started to backfill the appended frames but crashed before
 1.48929 +        ** it finished. Leaving a corrupt image in the database file.
 1.48930 +        */
 1.48931 +        walUnlockShared(pWal, WAL_READ_LOCK(0));
 1.48932 +        return WAL_RETRY;
 1.48933 +      }
 1.48934 +      pWal->readLock = 0;
 1.48935 +      return SQLITE_OK;
 1.48936 +    }else if( rc!=SQLITE_BUSY ){
 1.48937 +      return rc;
 1.48938 +    }
 1.48939 +  }
 1.48940 +
 1.48941 +  /* If we get this far, it means that the reader will want to use
 1.48942 +  ** the WAL to get at content from recent commits.  The job now is
 1.48943 +  ** to select one of the aReadMark[] entries that is closest to
 1.48944 +  ** but not exceeding pWal->hdr.mxFrame and lock that entry.
 1.48945 +  */
 1.48946 +  mxReadMark = 0;
 1.48947 +  mxI = 0;
 1.48948 +  for(i=1; i<WAL_NREADER; i++){
 1.48949 +    u32 thisMark = pInfo->aReadMark[i];
 1.48950 +    if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
 1.48951 +      assert( thisMark!=READMARK_NOT_USED );
 1.48952 +      mxReadMark = thisMark;
 1.48953 +      mxI = i;
 1.48954 +    }
 1.48955 +  }
 1.48956 +  /* There was once an "if" here. The extra "{" is to preserve indentation. */
 1.48957 +  {
 1.48958 +    if( (pWal->readOnly & WAL_SHM_RDONLY)==0
 1.48959 +     && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
 1.48960 +    ){
 1.48961 +      for(i=1; i<WAL_NREADER; i++){
 1.48962 +        rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
 1.48963 +        if( rc==SQLITE_OK ){
 1.48964 +          mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
 1.48965 +          mxI = i;
 1.48966 +          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
 1.48967 +          break;
 1.48968 +        }else if( rc!=SQLITE_BUSY ){
 1.48969 +          return rc;
 1.48970 +        }
 1.48971 +      }
 1.48972 +    }
 1.48973 +    if( mxI==0 ){
 1.48974 +      assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
 1.48975 +      return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
 1.48976 +    }
 1.48977 +
 1.48978 +    rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
 1.48979 +    if( rc ){
 1.48980 +      return rc==SQLITE_BUSY ? WAL_RETRY : rc;
 1.48981 +    }
 1.48982 +    /* Now that the read-lock has been obtained, check that neither the
 1.48983 +    ** value in the aReadMark[] array or the contents of the wal-index
 1.48984 +    ** header have changed.
 1.48985 +    **
 1.48986 +    ** It is necessary to check that the wal-index header did not change
 1.48987 +    ** between the time it was read and when the shared-lock was obtained
 1.48988 +    ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
 1.48989 +    ** that the log file may have been wrapped by a writer, or that frames
 1.48990 +    ** that occur later in the log than pWal->hdr.mxFrame may have been
 1.48991 +    ** copied into the database by a checkpointer. If either of these things
 1.48992 +    ** happened, then reading the database with the current value of
 1.48993 +    ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
 1.48994 +    ** instead.
 1.48995 +    **
 1.48996 +    ** This does not guarantee that the copy of the wal-index header is up to
 1.48997 +    ** date before proceeding. That would not be possible without somehow
 1.48998 +    ** blocking writers. It only guarantees that a dangerous checkpoint or 
 1.48999 +    ** log-wrap (either of which would require an exclusive lock on
 1.49000 +    ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
 1.49001 +    */
 1.49002 +    walShmBarrier(pWal);
 1.49003 +    if( pInfo->aReadMark[mxI]!=mxReadMark
 1.49004 +     || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
 1.49005 +    ){
 1.49006 +      walUnlockShared(pWal, WAL_READ_LOCK(mxI));
 1.49007 +      return WAL_RETRY;
 1.49008 +    }else{
 1.49009 +      assert( mxReadMark<=pWal->hdr.mxFrame );
 1.49010 +      pWal->readLock = (i16)mxI;
 1.49011 +    }
 1.49012 +  }
 1.49013 +  return rc;
 1.49014 +}
 1.49015 +
 1.49016 +/*
 1.49017 +** Begin a read transaction on the database.
 1.49018 +**
 1.49019 +** This routine used to be called sqlite3OpenSnapshot() and with good reason:
 1.49020 +** it takes a snapshot of the state of the WAL and wal-index for the current
 1.49021 +** instant in time.  The current thread will continue to use this snapshot.
 1.49022 +** Other threads might append new content to the WAL and wal-index but
 1.49023 +** that extra content is ignored by the current thread.
 1.49024 +**
 1.49025 +** If the database contents have changes since the previous read
 1.49026 +** transaction, then *pChanged is set to 1 before returning.  The
 1.49027 +** Pager layer will use this to know that is cache is stale and
 1.49028 +** needs to be flushed.
 1.49029 +*/
 1.49030 +SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
 1.49031 +  int rc;                         /* Return code */
 1.49032 +  int cnt = 0;                    /* Number of TryBeginRead attempts */
 1.49033 +
 1.49034 +  do{
 1.49035 +    rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
 1.49036 +  }while( rc==WAL_RETRY );
 1.49037 +  testcase( (rc&0xff)==SQLITE_BUSY );
 1.49038 +  testcase( (rc&0xff)==SQLITE_IOERR );
 1.49039 +  testcase( rc==SQLITE_PROTOCOL );
 1.49040 +  testcase( rc==SQLITE_OK );
 1.49041 +  return rc;
 1.49042 +}
 1.49043 +
 1.49044 +/*
 1.49045 +** Finish with a read transaction.  All this does is release the
 1.49046 +** read-lock.
 1.49047 +*/
 1.49048 +SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
 1.49049 +  sqlite3WalEndWriteTransaction(pWal);
 1.49050 +  if( pWal->readLock>=0 ){
 1.49051 +    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
 1.49052 +    pWal->readLock = -1;
 1.49053 +  }
 1.49054 +}
 1.49055 +
 1.49056 +/*
 1.49057 +** Search the wal file for page pgno. If found, set *piRead to the frame that
 1.49058 +** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
 1.49059 +** to zero.
 1.49060 +**
 1.49061 +** Return SQLITE_OK if successful, or an error code if an error occurs. If an
 1.49062 +** error does occur, the final value of *piRead is undefined.
 1.49063 +*/
 1.49064 +SQLITE_PRIVATE int sqlite3WalFindFrame(
 1.49065 +  Wal *pWal,                      /* WAL handle */
 1.49066 +  Pgno pgno,                      /* Database page number to read data for */
 1.49067 +  u32 *piRead                     /* OUT: Frame number (or zero) */
 1.49068 +){
 1.49069 +  u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
 1.49070 +  u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
 1.49071 +  int iHash;                      /* Used to loop through N hash tables */
 1.49072 +
 1.49073 +  /* This routine is only be called from within a read transaction. */
 1.49074 +  assert( pWal->readLock>=0 || pWal->lockError );
 1.49075 +
 1.49076 +  /* If the "last page" field of the wal-index header snapshot is 0, then
 1.49077 +  ** no data will be read from the wal under any circumstances. Return early
 1.49078 +  ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
 1.49079 +  ** then the WAL is ignored by the reader so return early, as if the 
 1.49080 +  ** WAL were empty.
 1.49081 +  */
 1.49082 +  if( iLast==0 || pWal->readLock==0 ){
 1.49083 +    *piRead = 0;
 1.49084 +    return SQLITE_OK;
 1.49085 +  }
 1.49086 +
 1.49087 +  /* Search the hash table or tables for an entry matching page number
 1.49088 +  ** pgno. Each iteration of the following for() loop searches one
 1.49089 +  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
 1.49090 +  **
 1.49091 +  ** This code might run concurrently to the code in walIndexAppend()
 1.49092 +  ** that adds entries to the wal-index (and possibly to this hash 
 1.49093 +  ** table). This means the value just read from the hash 
 1.49094 +  ** slot (aHash[iKey]) may have been added before or after the 
 1.49095 +  ** current read transaction was opened. Values added after the
 1.49096 +  ** read transaction was opened may have been written incorrectly -
 1.49097 +  ** i.e. these slots may contain garbage data. However, we assume
 1.49098 +  ** that any slots written before the current read transaction was
 1.49099 +  ** opened remain unmodified.
 1.49100 +  **
 1.49101 +  ** For the reasons above, the if(...) condition featured in the inner
 1.49102 +  ** loop of the following block is more stringent that would be required 
 1.49103 +  ** if we had exclusive access to the hash-table:
 1.49104 +  **
 1.49105 +  **   (aPgno[iFrame]==pgno): 
 1.49106 +  **     This condition filters out normal hash-table collisions.
 1.49107 +  **
 1.49108 +  **   (iFrame<=iLast): 
 1.49109 +  **     This condition filters out entries that were added to the hash
 1.49110 +  **     table after the current read-transaction had started.
 1.49111 +  */
 1.49112 +  for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
 1.49113 +    volatile ht_slot *aHash;      /* Pointer to hash table */
 1.49114 +    volatile u32 *aPgno;          /* Pointer to array of page numbers */
 1.49115 +    u32 iZero;                    /* Frame number corresponding to aPgno[0] */
 1.49116 +    int iKey;                     /* Hash slot index */
 1.49117 +    int nCollide;                 /* Number of hash collisions remaining */
 1.49118 +    int rc;                       /* Error code */
 1.49119 +
 1.49120 +    rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
 1.49121 +    if( rc!=SQLITE_OK ){
 1.49122 +      return rc;
 1.49123 +    }
 1.49124 +    nCollide = HASHTABLE_NSLOT;
 1.49125 +    for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
 1.49126 +      u32 iFrame = aHash[iKey] + iZero;
 1.49127 +      if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
 1.49128 +        /* assert( iFrame>iRead ); -- not true if there is corruption */
 1.49129 +        iRead = iFrame;
 1.49130 +      }
 1.49131 +      if( (nCollide--)==0 ){
 1.49132 +        return SQLITE_CORRUPT_BKPT;
 1.49133 +      }
 1.49134 +    }
 1.49135 +  }
 1.49136 +
 1.49137 +#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
 1.49138 +  /* If expensive assert() statements are available, do a linear search
 1.49139 +  ** of the wal-index file content. Make sure the results agree with the
 1.49140 +  ** result obtained using the hash indexes above.  */
 1.49141 +  {
 1.49142 +    u32 iRead2 = 0;
 1.49143 +    u32 iTest;
 1.49144 +    for(iTest=iLast; iTest>0; iTest--){
 1.49145 +      if( walFramePgno(pWal, iTest)==pgno ){
 1.49146 +        iRead2 = iTest;
 1.49147 +        break;
 1.49148 +      }
 1.49149 +    }
 1.49150 +    assert( iRead==iRead2 );
 1.49151 +  }
 1.49152 +#endif
 1.49153 +
 1.49154 +  *piRead = iRead;
 1.49155 +  return SQLITE_OK;
 1.49156 +}
 1.49157 +
 1.49158 +/*
 1.49159 +** Read the contents of frame iRead from the wal file into buffer pOut
 1.49160 +** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
 1.49161 +** error code otherwise.
 1.49162 +*/
 1.49163 +SQLITE_PRIVATE int sqlite3WalReadFrame(
 1.49164 +  Wal *pWal,                      /* WAL handle */
 1.49165 +  u32 iRead,                      /* Frame to read */
 1.49166 +  int nOut,                       /* Size of buffer pOut in bytes */
 1.49167 +  u8 *pOut                        /* Buffer to write page data to */
 1.49168 +){
 1.49169 +  int sz;
 1.49170 +  i64 iOffset;
 1.49171 +  sz = pWal->hdr.szPage;
 1.49172 +  sz = (sz&0xfe00) + ((sz&0x0001)<<16);
 1.49173 +  testcase( sz<=32768 );
 1.49174 +  testcase( sz>=65536 );
 1.49175 +  iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
 1.49176 +  /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
 1.49177 +  return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
 1.49178 +}
 1.49179 +
 1.49180 +/* 
 1.49181 +** Return the size of the database in pages (or zero, if unknown).
 1.49182 +*/
 1.49183 +SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
 1.49184 +  if( pWal && ALWAYS(pWal->readLock>=0) ){
 1.49185 +    return pWal->hdr.nPage;
 1.49186 +  }
 1.49187 +  return 0;
 1.49188 +}
 1.49189 +
 1.49190 +
 1.49191 +/* 
 1.49192 +** This function starts a write transaction on the WAL.
 1.49193 +**
 1.49194 +** A read transaction must have already been started by a prior call
 1.49195 +** to sqlite3WalBeginReadTransaction().
 1.49196 +**
 1.49197 +** If another thread or process has written into the database since
 1.49198 +** the read transaction was started, then it is not possible for this
 1.49199 +** thread to write as doing so would cause a fork.  So this routine
 1.49200 +** returns SQLITE_BUSY in that case and no write transaction is started.
 1.49201 +**
 1.49202 +** There can only be a single writer active at a time.
 1.49203 +*/
 1.49204 +SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
 1.49205 +  int rc;
 1.49206 +
 1.49207 +  /* Cannot start a write transaction without first holding a read
 1.49208 +  ** transaction. */
 1.49209 +  assert( pWal->readLock>=0 );
 1.49210 +
 1.49211 +  if( pWal->readOnly ){
 1.49212 +    return SQLITE_READONLY;
 1.49213 +  }
 1.49214 +
 1.49215 +  /* Only one writer allowed at a time.  Get the write lock.  Return
 1.49216 +  ** SQLITE_BUSY if unable.
 1.49217 +  */
 1.49218 +  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
 1.49219 +  if( rc ){
 1.49220 +    return rc;
 1.49221 +  }
 1.49222 +  pWal->writeLock = 1;
 1.49223 +
 1.49224 +  /* If another connection has written to the database file since the
 1.49225 +  ** time the read transaction on this connection was started, then
 1.49226 +  ** the write is disallowed.
 1.49227 +  */
 1.49228 +  if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
 1.49229 +    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
 1.49230 +    pWal->writeLock = 0;
 1.49231 +    rc = SQLITE_BUSY_SNAPSHOT;
 1.49232 +  }
 1.49233 +
 1.49234 +  return rc;
 1.49235 +}
 1.49236 +
 1.49237 +/*
 1.49238 +** End a write transaction.  The commit has already been done.  This
 1.49239 +** routine merely releases the lock.
 1.49240 +*/
 1.49241 +SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
 1.49242 +  if( pWal->writeLock ){
 1.49243 +    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
 1.49244 +    pWal->writeLock = 0;
 1.49245 +    pWal->truncateOnCommit = 0;
 1.49246 +  }
 1.49247 +  return SQLITE_OK;
 1.49248 +}
 1.49249 +
 1.49250 +/*
 1.49251 +** If any data has been written (but not committed) to the log file, this
 1.49252 +** function moves the write-pointer back to the start of the transaction.
 1.49253 +**
 1.49254 +** Additionally, the callback function is invoked for each frame written
 1.49255 +** to the WAL since the start of the transaction. If the callback returns
 1.49256 +** other than SQLITE_OK, it is not invoked again and the error code is
 1.49257 +** returned to the caller.
 1.49258 +**
 1.49259 +** Otherwise, if the callback function does not return an error, this
 1.49260 +** function returns SQLITE_OK.
 1.49261 +*/
 1.49262 +SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
 1.49263 +  int rc = SQLITE_OK;
 1.49264 +  if( ALWAYS(pWal->writeLock) ){
 1.49265 +    Pgno iMax = pWal->hdr.mxFrame;
 1.49266 +    Pgno iFrame;
 1.49267 +  
 1.49268 +    /* Restore the clients cache of the wal-index header to the state it
 1.49269 +    ** was in before the client began writing to the database. 
 1.49270 +    */
 1.49271 +    memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
 1.49272 +
 1.49273 +    for(iFrame=pWal->hdr.mxFrame+1; 
 1.49274 +        ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
 1.49275 +        iFrame++
 1.49276 +    ){
 1.49277 +      /* This call cannot fail. Unless the page for which the page number
 1.49278 +      ** is passed as the second argument is (a) in the cache and 
 1.49279 +      ** (b) has an outstanding reference, then xUndo is either a no-op
 1.49280 +      ** (if (a) is false) or simply expels the page from the cache (if (b)
 1.49281 +      ** is false).
 1.49282 +      **
 1.49283 +      ** If the upper layer is doing a rollback, it is guaranteed that there
 1.49284 +      ** are no outstanding references to any page other than page 1. And
 1.49285 +      ** page 1 is never written to the log until the transaction is
 1.49286 +      ** committed. As a result, the call to xUndo may not fail.
 1.49287 +      */
 1.49288 +      assert( walFramePgno(pWal, iFrame)!=1 );
 1.49289 +      rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
 1.49290 +    }
 1.49291 +    if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
 1.49292 +  }
 1.49293 +  assert( rc==SQLITE_OK );
 1.49294 +  return rc;
 1.49295 +}
 1.49296 +
 1.49297 +/* 
 1.49298 +** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
 1.49299 +** values. This function populates the array with values required to 
 1.49300 +** "rollback" the write position of the WAL handle back to the current 
 1.49301 +** point in the event of a savepoint rollback (via WalSavepointUndo()).
 1.49302 +*/
 1.49303 +SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
 1.49304 +  assert( pWal->writeLock );
 1.49305 +  aWalData[0] = pWal->hdr.mxFrame;
 1.49306 +  aWalData[1] = pWal->hdr.aFrameCksum[0];
 1.49307 +  aWalData[2] = pWal->hdr.aFrameCksum[1];
 1.49308 +  aWalData[3] = pWal->nCkpt;
 1.49309 +}
 1.49310 +
 1.49311 +/* 
 1.49312 +** Move the write position of the WAL back to the point identified by
 1.49313 +** the values in the aWalData[] array. aWalData must point to an array
 1.49314 +** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
 1.49315 +** by a call to WalSavepoint().
 1.49316 +*/
 1.49317 +SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
 1.49318 +  int rc = SQLITE_OK;
 1.49319 +
 1.49320 +  assert( pWal->writeLock );
 1.49321 +  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
 1.49322 +
 1.49323 +  if( aWalData[3]!=pWal->nCkpt ){
 1.49324 +    /* This savepoint was opened immediately after the write-transaction
 1.49325 +    ** was started. Right after that, the writer decided to wrap around
 1.49326 +    ** to the start of the log. Update the savepoint values to match.
 1.49327 +    */
 1.49328 +    aWalData[0] = 0;
 1.49329 +    aWalData[3] = pWal->nCkpt;
 1.49330 +  }
 1.49331 +
 1.49332 +  if( aWalData[0]<pWal->hdr.mxFrame ){
 1.49333 +    pWal->hdr.mxFrame = aWalData[0];
 1.49334 +    pWal->hdr.aFrameCksum[0] = aWalData[1];
 1.49335 +    pWal->hdr.aFrameCksum[1] = aWalData[2];
 1.49336 +    walCleanupHash(pWal);
 1.49337 +  }
 1.49338 +
 1.49339 +  return rc;
 1.49340 +}
 1.49341 +
 1.49342 +
 1.49343 +/*
 1.49344 +** This function is called just before writing a set of frames to the log
 1.49345 +** file (see sqlite3WalFrames()). It checks to see if, instead of appending
 1.49346 +** to the current log file, it is possible to overwrite the start of the
 1.49347 +** existing log file with the new frames (i.e. "reset" the log). If so,
 1.49348 +** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
 1.49349 +** unchanged.
 1.49350 +**
 1.49351 +** SQLITE_OK is returned if no error is encountered (regardless of whether
 1.49352 +** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
 1.49353 +** if an error occurs.
 1.49354 +*/
 1.49355 +static int walRestartLog(Wal *pWal){
 1.49356 +  int rc = SQLITE_OK;
 1.49357 +  int cnt;
 1.49358 +
 1.49359 +  if( pWal->readLock==0 ){
 1.49360 +    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
 1.49361 +    assert( pInfo->nBackfill==pWal->hdr.mxFrame );
 1.49362 +    if( pInfo->nBackfill>0 ){
 1.49363 +      u32 salt1;
 1.49364 +      sqlite3_randomness(4, &salt1);
 1.49365 +      rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
 1.49366 +      if( rc==SQLITE_OK ){
 1.49367 +        /* If all readers are using WAL_READ_LOCK(0) (in other words if no
 1.49368 +        ** readers are currently using the WAL), then the transactions
 1.49369 +        ** frames will overwrite the start of the existing log. Update the
 1.49370 +        ** wal-index header to reflect this.
 1.49371 +        **
 1.49372 +        ** In theory it would be Ok to update the cache of the header only
 1.49373 +        ** at this point. But updating the actual wal-index header is also
 1.49374 +        ** safe and means there is no special case for sqlite3WalUndo()
 1.49375 +        ** to handle if this transaction is rolled back.
 1.49376 +        */
 1.49377 +        int i;                    /* Loop counter */
 1.49378 +        u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
 1.49379 +
 1.49380 +        pWal->nCkpt++;
 1.49381 +        pWal->hdr.mxFrame = 0;
 1.49382 +        sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
 1.49383 +        aSalt[1] = salt1;
 1.49384 +        walIndexWriteHdr(pWal);
 1.49385 +        pInfo->nBackfill = 0;
 1.49386 +        pInfo->aReadMark[1] = 0;
 1.49387 +        for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
 1.49388 +        assert( pInfo->aReadMark[0]==0 );
 1.49389 +        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
 1.49390 +      }else if( rc!=SQLITE_BUSY ){
 1.49391 +        return rc;
 1.49392 +      }
 1.49393 +    }
 1.49394 +    walUnlockShared(pWal, WAL_READ_LOCK(0));
 1.49395 +    pWal->readLock = -1;
 1.49396 +    cnt = 0;
 1.49397 +    do{
 1.49398 +      int notUsed;
 1.49399 +      rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
 1.49400 +    }while( rc==WAL_RETRY );
 1.49401 +    assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
 1.49402 +    testcase( (rc&0xff)==SQLITE_IOERR );
 1.49403 +    testcase( rc==SQLITE_PROTOCOL );
 1.49404 +    testcase( rc==SQLITE_OK );
 1.49405 +  }
 1.49406 +  return rc;
 1.49407 +}
 1.49408 +
 1.49409 +/*
 1.49410 +** Information about the current state of the WAL file and where
 1.49411 +** the next fsync should occur - passed from sqlite3WalFrames() into
 1.49412 +** walWriteToLog().
 1.49413 +*/
 1.49414 +typedef struct WalWriter {
 1.49415 +  Wal *pWal;                   /* The complete WAL information */
 1.49416 +  sqlite3_file *pFd;           /* The WAL file to which we write */
 1.49417 +  sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
 1.49418 +  int syncFlags;               /* Flags for the fsync */
 1.49419 +  int szPage;                  /* Size of one page */
 1.49420 +} WalWriter;
 1.49421 +
 1.49422 +/*
 1.49423 +** Write iAmt bytes of content into the WAL file beginning at iOffset.
 1.49424 +** Do a sync when crossing the p->iSyncPoint boundary.
 1.49425 +**
 1.49426 +** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
 1.49427 +** first write the part before iSyncPoint, then sync, then write the
 1.49428 +** rest.
 1.49429 +*/
 1.49430 +static int walWriteToLog(
 1.49431 +  WalWriter *p,              /* WAL to write to */
 1.49432 +  void *pContent,            /* Content to be written */
 1.49433 +  int iAmt,                  /* Number of bytes to write */
 1.49434 +  sqlite3_int64 iOffset      /* Start writing at this offset */
 1.49435 +){
 1.49436 +  int rc;
 1.49437 +  if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
 1.49438 +    int iFirstAmt = (int)(p->iSyncPoint - iOffset);
 1.49439 +    rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
 1.49440 +    if( rc ) return rc;
 1.49441 +    iOffset += iFirstAmt;
 1.49442 +    iAmt -= iFirstAmt;
 1.49443 +    pContent = (void*)(iFirstAmt + (char*)pContent);
 1.49444 +    assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
 1.49445 +    rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
 1.49446 +    if( iAmt==0 || rc ) return rc;
 1.49447 +  }
 1.49448 +  rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
 1.49449 +  return rc;
 1.49450 +}
 1.49451 +
 1.49452 +/*
 1.49453 +** Write out a single frame of the WAL
 1.49454 +*/
 1.49455 +static int walWriteOneFrame(
 1.49456 +  WalWriter *p,               /* Where to write the frame */
 1.49457 +  PgHdr *pPage,               /* The page of the frame to be written */
 1.49458 +  int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
 1.49459 +  sqlite3_int64 iOffset       /* Byte offset at which to write */
 1.49460 +){
 1.49461 +  int rc;                         /* Result code from subfunctions */
 1.49462 +  void *pData;                    /* Data actually written */
 1.49463 +  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
 1.49464 +#if defined(SQLITE_HAS_CODEC)
 1.49465 +  if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
 1.49466 +#else
 1.49467 +  pData = pPage->pData;
 1.49468 +#endif
 1.49469 +  walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
 1.49470 +  rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
 1.49471 +  if( rc ) return rc;
 1.49472 +  /* Write the page data */
 1.49473 +  rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
 1.49474 +  return rc;
 1.49475 +}
 1.49476 +
 1.49477 +/* 
 1.49478 +** Write a set of frames to the log. The caller must hold the write-lock
 1.49479 +** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
 1.49480 +*/
 1.49481 +SQLITE_PRIVATE int sqlite3WalFrames(
 1.49482 +  Wal *pWal,                      /* Wal handle to write to */
 1.49483 +  int szPage,                     /* Database page-size in bytes */
 1.49484 +  PgHdr *pList,                   /* List of dirty pages to write */
 1.49485 +  Pgno nTruncate,                 /* Database size after this commit */
 1.49486 +  int isCommit,                   /* True if this is a commit */
 1.49487 +  int sync_flags                  /* Flags to pass to OsSync() (or 0) */
 1.49488 +){
 1.49489 +  int rc;                         /* Used to catch return codes */
 1.49490 +  u32 iFrame;                     /* Next frame address */
 1.49491 +  PgHdr *p;                       /* Iterator to run through pList with. */
 1.49492 +  PgHdr *pLast = 0;               /* Last frame in list */
 1.49493 +  int nExtra = 0;                 /* Number of extra copies of last page */
 1.49494 +  int szFrame;                    /* The size of a single frame */
 1.49495 +  i64 iOffset;                    /* Next byte to write in WAL file */
 1.49496 +  WalWriter w;                    /* The writer */
 1.49497 +
 1.49498 +  assert( pList );
 1.49499 +  assert( pWal->writeLock );
 1.49500 +
 1.49501 +  /* If this frame set completes a transaction, then nTruncate>0.  If
 1.49502 +  ** nTruncate==0 then this frame set does not complete the transaction. */
 1.49503 +  assert( (isCommit!=0)==(nTruncate!=0) );
 1.49504 +
 1.49505 +#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
 1.49506 +  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
 1.49507 +    WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
 1.49508 +              pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
 1.49509 +  }
 1.49510 +#endif
 1.49511 +
 1.49512 +  /* See if it is possible to write these frames into the start of the
 1.49513 +  ** log file, instead of appending to it at pWal->hdr.mxFrame.
 1.49514 +  */
 1.49515 +  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
 1.49516 +    return rc;
 1.49517 +  }
 1.49518 +
 1.49519 +  /* If this is the first frame written into the log, write the WAL
 1.49520 +  ** header to the start of the WAL file. See comments at the top of
 1.49521 +  ** this source file for a description of the WAL header format.
 1.49522 +  */
 1.49523 +  iFrame = pWal->hdr.mxFrame;
 1.49524 +  if( iFrame==0 ){
 1.49525 +    u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
 1.49526 +    u32 aCksum[2];                /* Checksum for wal-header */
 1.49527 +
 1.49528 +    sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
 1.49529 +    sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
 1.49530 +    sqlite3Put4byte(&aWalHdr[8], szPage);
 1.49531 +    sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
 1.49532 +    if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
 1.49533 +    memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
 1.49534 +    walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
 1.49535 +    sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
 1.49536 +    sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
 1.49537 +    
 1.49538 +    pWal->szPage = szPage;
 1.49539 +    pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
 1.49540 +    pWal->hdr.aFrameCksum[0] = aCksum[0];
 1.49541 +    pWal->hdr.aFrameCksum[1] = aCksum[1];
 1.49542 +    pWal->truncateOnCommit = 1;
 1.49543 +
 1.49544 +    rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
 1.49545 +    WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
 1.49546 +    if( rc!=SQLITE_OK ){
 1.49547 +      return rc;
 1.49548 +    }
 1.49549 +
 1.49550 +    /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
 1.49551 +    ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
 1.49552 +    ** an out-of-order write following a WAL restart could result in
 1.49553 +    ** database corruption.  See the ticket:
 1.49554 +    **
 1.49555 +    **     http://localhost:591/sqlite/info/ff5be73dee
 1.49556 +    */
 1.49557 +    if( pWal->syncHeader && sync_flags ){
 1.49558 +      rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
 1.49559 +      if( rc ) return rc;
 1.49560 +    }
 1.49561 +  }
 1.49562 +  assert( (int)pWal->szPage==szPage );
 1.49563 +
 1.49564 +  /* Setup information needed to write frames into the WAL */
 1.49565 +  w.pWal = pWal;
 1.49566 +  w.pFd = pWal->pWalFd;
 1.49567 +  w.iSyncPoint = 0;
 1.49568 +  w.syncFlags = sync_flags;
 1.49569 +  w.szPage = szPage;
 1.49570 +  iOffset = walFrameOffset(iFrame+1, szPage);
 1.49571 +  szFrame = szPage + WAL_FRAME_HDRSIZE;
 1.49572 +
 1.49573 +  /* Write all frames into the log file exactly once */
 1.49574 +  for(p=pList; p; p=p->pDirty){
 1.49575 +    int nDbSize;   /* 0 normally.  Positive == commit flag */
 1.49576 +    iFrame++;
 1.49577 +    assert( iOffset==walFrameOffset(iFrame, szPage) );
 1.49578 +    nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
 1.49579 +    rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
 1.49580 +    if( rc ) return rc;
 1.49581 +    pLast = p;
 1.49582 +    iOffset += szFrame;
 1.49583 +  }
 1.49584 +
 1.49585 +  /* If this is the end of a transaction, then we might need to pad
 1.49586 +  ** the transaction and/or sync the WAL file.
 1.49587 +  **
 1.49588 +  ** Padding and syncing only occur if this set of frames complete a
 1.49589 +  ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
 1.49590 +  ** or synchonous==OFF, then no padding or syncing are needed.
 1.49591 +  **
 1.49592 +  ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
 1.49593 +  ** needed and only the sync is done.  If padding is needed, then the
 1.49594 +  ** final frame is repeated (with its commit mark) until the next sector
 1.49595 +  ** boundary is crossed.  Only the part of the WAL prior to the last
 1.49596 +  ** sector boundary is synced; the part of the last frame that extends
 1.49597 +  ** past the sector boundary is written after the sync.
 1.49598 +  */
 1.49599 +  if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
 1.49600 +    if( pWal->padToSectorBoundary ){
 1.49601 +      int sectorSize = sqlite3SectorSize(pWal->pWalFd);
 1.49602 +      w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
 1.49603 +      while( iOffset<w.iSyncPoint ){
 1.49604 +        rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
 1.49605 +        if( rc ) return rc;
 1.49606 +        iOffset += szFrame;
 1.49607 +        nExtra++;
 1.49608 +      }
 1.49609 +    }else{
 1.49610 +      rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
 1.49611 +    }
 1.49612 +  }
 1.49613 +
 1.49614 +  /* If this frame set completes the first transaction in the WAL and
 1.49615 +  ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
 1.49616 +  ** journal size limit, if possible.
 1.49617 +  */
 1.49618 +  if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
 1.49619 +    i64 sz = pWal->mxWalSize;
 1.49620 +    if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
 1.49621 +      sz = walFrameOffset(iFrame+nExtra+1, szPage);
 1.49622 +    }
 1.49623 +    walLimitSize(pWal, sz);
 1.49624 +    pWal->truncateOnCommit = 0;
 1.49625 +  }
 1.49626 +
 1.49627 +  /* Append data to the wal-index. It is not necessary to lock the 
 1.49628 +  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
 1.49629 +  ** guarantees that there are no other writers, and no data that may
 1.49630 +  ** be in use by existing readers is being overwritten.
 1.49631 +  */
 1.49632 +  iFrame = pWal->hdr.mxFrame;
 1.49633 +  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
 1.49634 +    iFrame++;
 1.49635 +    rc = walIndexAppend(pWal, iFrame, p->pgno);
 1.49636 +  }
 1.49637 +  while( rc==SQLITE_OK && nExtra>0 ){
 1.49638 +    iFrame++;
 1.49639 +    nExtra--;
 1.49640 +    rc = walIndexAppend(pWal, iFrame, pLast->pgno);
 1.49641 +  }
 1.49642 +
 1.49643 +  if( rc==SQLITE_OK ){
 1.49644 +    /* Update the private copy of the header. */
 1.49645 +    pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
 1.49646 +    testcase( szPage<=32768 );
 1.49647 +    testcase( szPage>=65536 );
 1.49648 +    pWal->hdr.mxFrame = iFrame;
 1.49649 +    if( isCommit ){
 1.49650 +      pWal->hdr.iChange++;
 1.49651 +      pWal->hdr.nPage = nTruncate;
 1.49652 +    }
 1.49653 +    /* If this is a commit, update the wal-index header too. */
 1.49654 +    if( isCommit ){
 1.49655 +      walIndexWriteHdr(pWal);
 1.49656 +      pWal->iCallback = iFrame;
 1.49657 +    }
 1.49658 +  }
 1.49659 +
 1.49660 +  WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
 1.49661 +  return rc;
 1.49662 +}
 1.49663 +
 1.49664 +/* 
 1.49665 +** This routine is called to implement sqlite3_wal_checkpoint() and
 1.49666 +** related interfaces.
 1.49667 +**
 1.49668 +** Obtain a CHECKPOINT lock and then backfill as much information as
 1.49669 +** we can from WAL into the database.
 1.49670 +**
 1.49671 +** If parameter xBusy is not NULL, it is a pointer to a busy-handler
 1.49672 +** callback. In this case this function runs a blocking checkpoint.
 1.49673 +*/
 1.49674 +SQLITE_PRIVATE int sqlite3WalCheckpoint(
 1.49675 +  Wal *pWal,                      /* Wal connection */
 1.49676 +  int eMode,                      /* PASSIVE, FULL or RESTART */
 1.49677 +  int (*xBusy)(void*),            /* Function to call when busy */
 1.49678 +  void *pBusyArg,                 /* Context argument for xBusyHandler */
 1.49679 +  int sync_flags,                 /* Flags to sync db file with (or 0) */
 1.49680 +  int nBuf,                       /* Size of temporary buffer */
 1.49681 +  u8 *zBuf,                       /* Temporary buffer to use */
 1.49682 +  int *pnLog,                     /* OUT: Number of frames in WAL */
 1.49683 +  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
 1.49684 +){
 1.49685 +  int rc;                         /* Return code */
 1.49686 +  int isChanged = 0;              /* True if a new wal-index header is loaded */
 1.49687 +  int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
 1.49688 +
 1.49689 +  assert( pWal->ckptLock==0 );
 1.49690 +  assert( pWal->writeLock==0 );
 1.49691 +
 1.49692 +  if( pWal->readOnly ) return SQLITE_READONLY;
 1.49693 +  WALTRACE(("WAL%p: checkpoint begins\n", pWal));
 1.49694 +  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
 1.49695 +  if( rc ){
 1.49696 +    /* Usually this is SQLITE_BUSY meaning that another thread or process
 1.49697 +    ** is already running a checkpoint, or maybe a recovery.  But it might
 1.49698 +    ** also be SQLITE_IOERR. */
 1.49699 +    return rc;
 1.49700 +  }
 1.49701 +  pWal->ckptLock = 1;
 1.49702 +
 1.49703 +  /* If this is a blocking-checkpoint, then obtain the write-lock as well
 1.49704 +  ** to prevent any writers from running while the checkpoint is underway.
 1.49705 +  ** This has to be done before the call to walIndexReadHdr() below.
 1.49706 +  **
 1.49707 +  ** If the writer lock cannot be obtained, then a passive checkpoint is
 1.49708 +  ** run instead. Since the checkpointer is not holding the writer lock,
 1.49709 +  ** there is no point in blocking waiting for any readers. Assuming no 
 1.49710 +  ** other error occurs, this function will return SQLITE_BUSY to the caller.
 1.49711 +  */
 1.49712 +  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
 1.49713 +    rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
 1.49714 +    if( rc==SQLITE_OK ){
 1.49715 +      pWal->writeLock = 1;
 1.49716 +    }else if( rc==SQLITE_BUSY ){
 1.49717 +      eMode2 = SQLITE_CHECKPOINT_PASSIVE;
 1.49718 +      rc = SQLITE_OK;
 1.49719 +    }
 1.49720 +  }
 1.49721 +
 1.49722 +  /* Read the wal-index header. */
 1.49723 +  if( rc==SQLITE_OK ){
 1.49724 +    rc = walIndexReadHdr(pWal, &isChanged);
 1.49725 +    if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
 1.49726 +      sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
 1.49727 +    }
 1.49728 +  }
 1.49729 +
 1.49730 +  /* Copy data from the log to the database file. */
 1.49731 +  if( rc==SQLITE_OK ){
 1.49732 +    if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
 1.49733 +      rc = SQLITE_CORRUPT_BKPT;
 1.49734 +    }else{
 1.49735 +      rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
 1.49736 +    }
 1.49737 +
 1.49738 +    /* If no error occurred, set the output variables. */
 1.49739 +    if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
 1.49740 +      if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
 1.49741 +      if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
 1.49742 +    }
 1.49743 +  }
 1.49744 +
 1.49745 +  if( isChanged ){
 1.49746 +    /* If a new wal-index header was loaded before the checkpoint was 
 1.49747 +    ** performed, then the pager-cache associated with pWal is now
 1.49748 +    ** out of date. So zero the cached wal-index header to ensure that
 1.49749 +    ** next time the pager opens a snapshot on this database it knows that
 1.49750 +    ** the cache needs to be reset.
 1.49751 +    */
 1.49752 +    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
 1.49753 +  }
 1.49754 +
 1.49755 +  /* Release the locks. */
 1.49756 +  sqlite3WalEndWriteTransaction(pWal);
 1.49757 +  walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
 1.49758 +  pWal->ckptLock = 0;
 1.49759 +  WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
 1.49760 +  return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
 1.49761 +}
 1.49762 +
 1.49763 +/* Return the value to pass to a sqlite3_wal_hook callback, the
 1.49764 +** number of frames in the WAL at the point of the last commit since
 1.49765 +** sqlite3WalCallback() was called.  If no commits have occurred since
 1.49766 +** the last call, then return 0.
 1.49767 +*/
 1.49768 +SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
 1.49769 +  u32 ret = 0;
 1.49770 +  if( pWal ){
 1.49771 +    ret = pWal->iCallback;
 1.49772 +    pWal->iCallback = 0;
 1.49773 +  }
 1.49774 +  return (int)ret;
 1.49775 +}
 1.49776 +
 1.49777 +/*
 1.49778 +** This function is called to change the WAL subsystem into or out
 1.49779 +** of locking_mode=EXCLUSIVE.
 1.49780 +**
 1.49781 +** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
 1.49782 +** into locking_mode=NORMAL.  This means that we must acquire a lock
 1.49783 +** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
 1.49784 +** or if the acquisition of the lock fails, then return 0.  If the
 1.49785 +** transition out of exclusive-mode is successful, return 1.  This
 1.49786 +** operation must occur while the pager is still holding the exclusive
 1.49787 +** lock on the main database file.
 1.49788 +**
 1.49789 +** If op is one, then change from locking_mode=NORMAL into 
 1.49790 +** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
 1.49791 +** be released.  Return 1 if the transition is made and 0 if the
 1.49792 +** WAL is already in exclusive-locking mode - meaning that this
 1.49793 +** routine is a no-op.  The pager must already hold the exclusive lock
 1.49794 +** on the main database file before invoking this operation.
 1.49795 +**
 1.49796 +** If op is negative, then do a dry-run of the op==1 case but do
 1.49797 +** not actually change anything. The pager uses this to see if it
 1.49798 +** should acquire the database exclusive lock prior to invoking
 1.49799 +** the op==1 case.
 1.49800 +*/
 1.49801 +SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
 1.49802 +  int rc;
 1.49803 +  assert( pWal->writeLock==0 );
 1.49804 +  assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
 1.49805 +
 1.49806 +  /* pWal->readLock is usually set, but might be -1 if there was a 
 1.49807 +  ** prior error while attempting to acquire are read-lock. This cannot 
 1.49808 +  ** happen if the connection is actually in exclusive mode (as no xShmLock
 1.49809 +  ** locks are taken in this case). Nor should the pager attempt to
 1.49810 +  ** upgrade to exclusive-mode following such an error.
 1.49811 +  */
 1.49812 +  assert( pWal->readLock>=0 || pWal->lockError );
 1.49813 +  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
 1.49814 +
 1.49815 +  if( op==0 ){
 1.49816 +    if( pWal->exclusiveMode ){
 1.49817 +      pWal->exclusiveMode = 0;
 1.49818 +      if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
 1.49819 +        pWal->exclusiveMode = 1;
 1.49820 +      }
 1.49821 +      rc = pWal->exclusiveMode==0;
 1.49822 +    }else{
 1.49823 +      /* Already in locking_mode=NORMAL */
 1.49824 +      rc = 0;
 1.49825 +    }
 1.49826 +  }else if( op>0 ){
 1.49827 +    assert( pWal->exclusiveMode==0 );
 1.49828 +    assert( pWal->readLock>=0 );
 1.49829 +    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
 1.49830 +    pWal->exclusiveMode = 1;
 1.49831 +    rc = 1;
 1.49832 +  }else{
 1.49833 +    rc = pWal->exclusiveMode==0;
 1.49834 +  }
 1.49835 +  return rc;
 1.49836 +}
 1.49837 +
 1.49838 +/* 
 1.49839 +** Return true if the argument is non-NULL and the WAL module is using
 1.49840 +** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
 1.49841 +** WAL module is using shared-memory, return false. 
 1.49842 +*/
 1.49843 +SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
 1.49844 +  return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
 1.49845 +}
 1.49846 +
 1.49847 +#ifdef SQLITE_ENABLE_ZIPVFS
 1.49848 +/*
 1.49849 +** If the argument is not NULL, it points to a Wal object that holds a
 1.49850 +** read-lock. This function returns the database page-size if it is known,
 1.49851 +** or zero if it is not (or if pWal is NULL).
 1.49852 +*/
 1.49853 +SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
 1.49854 +  assert( pWal==0 || pWal->readLock>=0 );
 1.49855 +  return (pWal ? pWal->szPage : 0);
 1.49856 +}
 1.49857 +#endif
 1.49858 +
 1.49859 +#endif /* #ifndef SQLITE_OMIT_WAL */
 1.49860 +
 1.49861 +/************** End of wal.c *************************************************/
 1.49862 +/************** Begin file btmutex.c *****************************************/
 1.49863 +/*
 1.49864 +** 2007 August 27
 1.49865 +**
 1.49866 +** The author disclaims copyright to this source code.  In place of
 1.49867 +** a legal notice, here is a blessing:
 1.49868 +**
 1.49869 +**    May you do good and not evil.
 1.49870 +**    May you find forgiveness for yourself and forgive others.
 1.49871 +**    May you share freely, never taking more than you give.
 1.49872 +**
 1.49873 +*************************************************************************
 1.49874 +**
 1.49875 +** This file contains code used to implement mutexes on Btree objects.
 1.49876 +** This code really belongs in btree.c.  But btree.c is getting too
 1.49877 +** big and we want to break it down some.  This packaged seemed like
 1.49878 +** a good breakout.
 1.49879 +*/
 1.49880 +/************** Include btreeInt.h in the middle of btmutex.c ****************/
 1.49881 +/************** Begin file btreeInt.h ****************************************/
 1.49882 +/*
 1.49883 +** 2004 April 6
 1.49884 +**
 1.49885 +** The author disclaims copyright to this source code.  In place of
 1.49886 +** a legal notice, here is a blessing:
 1.49887 +**
 1.49888 +**    May you do good and not evil.
 1.49889 +**    May you find forgiveness for yourself and forgive others.
 1.49890 +**    May you share freely, never taking more than you give.
 1.49891 +**
 1.49892 +*************************************************************************
 1.49893 +** This file implements a external (disk-based) database using BTrees.
 1.49894 +** For a detailed discussion of BTrees, refer to
 1.49895 +**
 1.49896 +**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
 1.49897 +**     "Sorting And Searching", pages 473-480. Addison-Wesley
 1.49898 +**     Publishing Company, Reading, Massachusetts.
 1.49899 +**
 1.49900 +** The basic idea is that each page of the file contains N database
 1.49901 +** entries and N+1 pointers to subpages.
 1.49902 +**
 1.49903 +**   ----------------------------------------------------------------
 1.49904 +**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
 1.49905 +**   ----------------------------------------------------------------
 1.49906 +**
 1.49907 +** All of the keys on the page that Ptr(0) points to have values less
 1.49908 +** than Key(0).  All of the keys on page Ptr(1) and its subpages have
 1.49909 +** values greater than Key(0) and less than Key(1).  All of the keys
 1.49910 +** on Ptr(N) and its subpages have values greater than Key(N-1).  And
 1.49911 +** so forth.
 1.49912 +**
 1.49913 +** Finding a particular key requires reading O(log(M)) pages from the 
 1.49914 +** disk where M is the number of entries in the tree.
 1.49915 +**
 1.49916 +** In this implementation, a single file can hold one or more separate 
 1.49917 +** BTrees.  Each BTree is identified by the index of its root page.  The
 1.49918 +** key and data for any entry are combined to form the "payload".  A
 1.49919 +** fixed amount of payload can be carried directly on the database
 1.49920 +** page.  If the payload is larger than the preset amount then surplus
 1.49921 +** bytes are stored on overflow pages.  The payload for an entry
 1.49922 +** and the preceding pointer are combined to form a "Cell".  Each 
 1.49923 +** page has a small header which contains the Ptr(N) pointer and other
 1.49924 +** information such as the size of key and data.
 1.49925 +**
 1.49926 +** FORMAT DETAILS
 1.49927 +**
 1.49928 +** The file is divided into pages.  The first page is called page 1,
 1.49929 +** the second is page 2, and so forth.  A page number of zero indicates
 1.49930 +** "no such page".  The page size can be any power of 2 between 512 and 65536.
 1.49931 +** Each page can be either a btree page, a freelist page, an overflow
 1.49932 +** page, or a pointer-map page.
 1.49933 +**
 1.49934 +** The first page is always a btree page.  The first 100 bytes of the first
 1.49935 +** page contain a special header (the "file header") that describes the file.
 1.49936 +** The format of the file header is as follows:
 1.49937 +**
 1.49938 +**   OFFSET   SIZE    DESCRIPTION
 1.49939 +**      0      16     Header string: "SQLite format 3\000"
 1.49940 +**     16       2     Page size in bytes.  (1 means 65536)
 1.49941 +**     18       1     File format write version
 1.49942 +**     19       1     File format read version
 1.49943 +**     20       1     Bytes of unused space at the end of each page
 1.49944 +**     21       1     Max embedded payload fraction (must be 64)
 1.49945 +**     22       1     Min embedded payload fraction (must be 32)
 1.49946 +**     23       1     Min leaf payload fraction (must be 32)
 1.49947 +**     24       4     File change counter
 1.49948 +**     28       4     Reserved for future use
 1.49949 +**     32       4     First freelist page
 1.49950 +**     36       4     Number of freelist pages in the file
 1.49951 +**     40      60     15 4-byte meta values passed to higher layers
 1.49952 +**
 1.49953 +**     40       4     Schema cookie
 1.49954 +**     44       4     File format of schema layer
 1.49955 +**     48       4     Size of page cache
 1.49956 +**     52       4     Largest root-page (auto/incr_vacuum)
 1.49957 +**     56       4     1=UTF-8 2=UTF16le 3=UTF16be
 1.49958 +**     60       4     User version
 1.49959 +**     64       4     Incremental vacuum mode
 1.49960 +**     68       4     Application-ID
 1.49961 +**     72      20     unused
 1.49962 +**     92       4     The version-valid-for number
 1.49963 +**     96       4     SQLITE_VERSION_NUMBER
 1.49964 +**
 1.49965 +** All of the integer values are big-endian (most significant byte first).
 1.49966 +**
 1.49967 +** The file change counter is incremented when the database is changed
 1.49968 +** This counter allows other processes to know when the file has changed
 1.49969 +** and thus when they need to flush their cache.
 1.49970 +**
 1.49971 +** The max embedded payload fraction is the amount of the total usable
 1.49972 +** space in a page that can be consumed by a single cell for standard
 1.49973 +** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
 1.49974 +** is to limit the maximum cell size so that at least 4 cells will fit
 1.49975 +** on one page.  Thus the default max embedded payload fraction is 64.
 1.49976 +**
 1.49977 +** If the payload for a cell is larger than the max payload, then extra
 1.49978 +** payload is spilled to overflow pages.  Once an overflow page is allocated,
 1.49979 +** as many bytes as possible are moved into the overflow pages without letting
 1.49980 +** the cell size drop below the min embedded payload fraction.
 1.49981 +**
 1.49982 +** The min leaf payload fraction is like the min embedded payload fraction
 1.49983 +** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
 1.49984 +** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
 1.49985 +** not specified in the header.
 1.49986 +**
 1.49987 +** Each btree pages is divided into three sections:  The header, the
 1.49988 +** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
 1.49989 +** file header that occurs before the page header.
 1.49990 +**
 1.49991 +**      |----------------|
 1.49992 +**      | file header    |   100 bytes.  Page 1 only.
 1.49993 +**      |----------------|
 1.49994 +**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
 1.49995 +**      |----------------|
 1.49996 +**      | cell pointer   |   |  2 bytes per cell.  Sorted order.
 1.49997 +**      | array          |   |  Grows downward
 1.49998 +**      |                |   v
 1.49999 +**      |----------------|
 1.50000 +**      | unallocated    |
 1.50001 +**      | space          |
 1.50002 +**      |----------------|   ^  Grows upwards
 1.50003 +**      | cell content   |   |  Arbitrary order interspersed with freeblocks.
 1.50004 +**      | area           |   |  and free space fragments.
 1.50005 +**      |----------------|
 1.50006 +**
 1.50007 +** The page headers looks like this:
 1.50008 +**
 1.50009 +**   OFFSET   SIZE     DESCRIPTION
 1.50010 +**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
 1.50011 +**      1       2      byte offset to the first freeblock
 1.50012 +**      3       2      number of cells on this page
 1.50013 +**      5       2      first byte of the cell content area
 1.50014 +**      7       1      number of fragmented free bytes
 1.50015 +**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
 1.50016 +**
 1.50017 +** The flags define the format of this btree page.  The leaf flag means that
 1.50018 +** this page has no children.  The zerodata flag means that this page carries
 1.50019 +** only keys and no data.  The intkey flag means that the key is a integer
 1.50020 +** which is stored in the key size entry of the cell header rather than in
 1.50021 +** the payload area.
 1.50022 +**
 1.50023 +** The cell pointer array begins on the first byte after the page header.
 1.50024 +** The cell pointer array contains zero or more 2-byte numbers which are
 1.50025 +** offsets from the beginning of the page to the cell content in the cell
 1.50026 +** content area.  The cell pointers occur in sorted order.  The system strives
 1.50027 +** to keep free space after the last cell pointer so that new cells can
 1.50028 +** be easily added without having to defragment the page.
 1.50029 +**
 1.50030 +** Cell content is stored at the very end of the page and grows toward the
 1.50031 +** beginning of the page.
 1.50032 +**
 1.50033 +** Unused space within the cell content area is collected into a linked list of
 1.50034 +** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
 1.50035 +** to the first freeblock is given in the header.  Freeblocks occur in
 1.50036 +** increasing order.  Because a freeblock must be at least 4 bytes in size,
 1.50037 +** any group of 3 or fewer unused bytes in the cell content area cannot
 1.50038 +** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
 1.50039 +** a fragment.  The total number of bytes in all fragments is recorded.
 1.50040 +** in the page header at offset 7.
 1.50041 +**
 1.50042 +**    SIZE    DESCRIPTION
 1.50043 +**      2     Byte offset of the next freeblock
 1.50044 +**      2     Bytes in this freeblock
 1.50045 +**
 1.50046 +** Cells are of variable length.  Cells are stored in the cell content area at
 1.50047 +** the end of the page.  Pointers to the cells are in the cell pointer array
 1.50048 +** that immediately follows the page header.  Cells is not necessarily
 1.50049 +** contiguous or in order, but cell pointers are contiguous and in order.
 1.50050 +**
 1.50051 +** Cell content makes use of variable length integers.  A variable
 1.50052 +** length integer is 1 to 9 bytes where the lower 7 bits of each 
 1.50053 +** byte are used.  The integer consists of all bytes that have bit 8 set and
 1.50054 +** the first byte with bit 8 clear.  The most significant byte of the integer
 1.50055 +** appears first.  A variable-length integer may not be more than 9 bytes long.
 1.50056 +** As a special case, all 8 bytes of the 9th byte are used as data.  This
 1.50057 +** allows a 64-bit integer to be encoded in 9 bytes.
 1.50058 +**
 1.50059 +**    0x00                      becomes  0x00000000
 1.50060 +**    0x7f                      becomes  0x0000007f
 1.50061 +**    0x81 0x00                 becomes  0x00000080
 1.50062 +**    0x82 0x00                 becomes  0x00000100
 1.50063 +**    0x80 0x7f                 becomes  0x0000007f
 1.50064 +**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
 1.50065 +**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
 1.50066 +**
 1.50067 +** Variable length integers are used for rowids and to hold the number of
 1.50068 +** bytes of key and data in a btree cell.
 1.50069 +**
 1.50070 +** The content of a cell looks like this:
 1.50071 +**
 1.50072 +**    SIZE    DESCRIPTION
 1.50073 +**      4     Page number of the left child. Omitted if leaf flag is set.
 1.50074 +**     var    Number of bytes of data. Omitted if the zerodata flag is set.
 1.50075 +**     var    Number of bytes of key. Or the key itself if intkey flag is set.
 1.50076 +**      *     Payload
 1.50077 +**      4     First page of the overflow chain.  Omitted if no overflow
 1.50078 +**
 1.50079 +** Overflow pages form a linked list.  Each page except the last is completely
 1.50080 +** filled with data (pagesize - 4 bytes).  The last page can have as little
 1.50081 +** as 1 byte of data.
 1.50082 +**
 1.50083 +**    SIZE    DESCRIPTION
 1.50084 +**      4     Page number of next overflow page
 1.50085 +**      *     Data
 1.50086 +**
 1.50087 +** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
 1.50088 +** file header points to the first in a linked list of trunk page.  Each trunk
 1.50089 +** page points to multiple leaf pages.  The content of a leaf page is
 1.50090 +** unspecified.  A trunk page looks like this:
 1.50091 +**
 1.50092 +**    SIZE    DESCRIPTION
 1.50093 +**      4     Page number of next trunk page
 1.50094 +**      4     Number of leaf pointers on this page
 1.50095 +**      *     zero or more pages numbers of leaves
 1.50096 +*/
 1.50097 +
 1.50098 +
 1.50099 +/* The following value is the maximum cell size assuming a maximum page
 1.50100 +** size give above.
 1.50101 +*/
 1.50102 +#define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
 1.50103 +
 1.50104 +/* The maximum number of cells on a single page of the database.  This
 1.50105 +** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
 1.50106 +** plus 2 bytes for the index to the cell in the page header).  Such
 1.50107 +** small cells will be rare, but they are possible.
 1.50108 +*/
 1.50109 +#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
 1.50110 +
 1.50111 +/* Forward declarations */
 1.50112 +typedef struct MemPage MemPage;
 1.50113 +typedef struct BtLock BtLock;
 1.50114 +
 1.50115 +/*
 1.50116 +** This is a magic string that appears at the beginning of every
 1.50117 +** SQLite database in order to identify the file as a real database.
 1.50118 +**
 1.50119 +** You can change this value at compile-time by specifying a
 1.50120 +** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
 1.50121 +** header must be exactly 16 bytes including the zero-terminator so
 1.50122 +** the string itself should be 15 characters long.  If you change
 1.50123 +** the header, then your custom library will not be able to read 
 1.50124 +** databases generated by the standard tools and the standard tools
 1.50125 +** will not be able to read databases created by your custom library.
 1.50126 +*/
 1.50127 +#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
 1.50128 +#  define SQLITE_FILE_HEADER "SQLite format 3"
 1.50129 +#endif
 1.50130 +
 1.50131 +/*
 1.50132 +** Page type flags.  An ORed combination of these flags appear as the
 1.50133 +** first byte of on-disk image of every BTree page.
 1.50134 +*/
 1.50135 +#define PTF_INTKEY    0x01
 1.50136 +#define PTF_ZERODATA  0x02
 1.50137 +#define PTF_LEAFDATA  0x04
 1.50138 +#define PTF_LEAF      0x08
 1.50139 +
 1.50140 +/*
 1.50141 +** As each page of the file is loaded into memory, an instance of the following
 1.50142 +** structure is appended and initialized to zero.  This structure stores
 1.50143 +** information about the page that is decoded from the raw file page.
 1.50144 +**
 1.50145 +** The pParent field points back to the parent page.  This allows us to
 1.50146 +** walk up the BTree from any leaf to the root.  Care must be taken to
 1.50147 +** unref() the parent page pointer when this page is no longer referenced.
 1.50148 +** The pageDestructor() routine handles that chore.
 1.50149 +**
 1.50150 +** Access to all fields of this structure is controlled by the mutex
 1.50151 +** stored in MemPage.pBt->mutex.
 1.50152 +*/
 1.50153 +struct MemPage {
 1.50154 +  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
 1.50155 +  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
 1.50156 +  u8 intKey;           /* True if intkey flag is set */
 1.50157 +  u8 leaf;             /* True if leaf flag is set */
 1.50158 +  u8 hasData;          /* True if this page stores data */
 1.50159 +  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
 1.50160 +  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
 1.50161 +  u8 max1bytePayload;  /* min(maxLocal,127) */
 1.50162 +  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
 1.50163 +  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
 1.50164 +  u16 cellOffset;      /* Index in aData of first cell pointer */
 1.50165 +  u16 nFree;           /* Number of free bytes on the page */
 1.50166 +  u16 nCell;           /* Number of cells on this page, local and ovfl */
 1.50167 +  u16 maskPage;        /* Mask for page offset */
 1.50168 +  u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
 1.50169 +                       ** non-overflow cell */
 1.50170 +  u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
 1.50171 +  BtShared *pBt;       /* Pointer to BtShared that this page is part of */
 1.50172 +  u8 *aData;           /* Pointer to disk image of the page data */
 1.50173 +  u8 *aDataEnd;        /* One byte past the end of usable data */
 1.50174 +  u8 *aCellIdx;        /* The cell index area */
 1.50175 +  DbPage *pDbPage;     /* Pager page handle */
 1.50176 +  Pgno pgno;           /* Page number for this page */
 1.50177 +};
 1.50178 +
 1.50179 +/*
 1.50180 +** The in-memory image of a disk page has the auxiliary information appended
 1.50181 +** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
 1.50182 +** that extra information.
 1.50183 +*/
 1.50184 +#define EXTRA_SIZE sizeof(MemPage)
 1.50185 +
 1.50186 +/*
 1.50187 +** A linked list of the following structures is stored at BtShared.pLock.
 1.50188 +** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
 1.50189 +** is opened on the table with root page BtShared.iTable. Locks are removed
 1.50190 +** from this list when a transaction is committed or rolled back, or when
 1.50191 +** a btree handle is closed.
 1.50192 +*/
 1.50193 +struct BtLock {
 1.50194 +  Btree *pBtree;        /* Btree handle holding this lock */
 1.50195 +  Pgno iTable;          /* Root page of table */
 1.50196 +  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
 1.50197 +  BtLock *pNext;        /* Next in BtShared.pLock list */
 1.50198 +};
 1.50199 +
 1.50200 +/* Candidate values for BtLock.eLock */
 1.50201 +#define READ_LOCK     1
 1.50202 +#define WRITE_LOCK    2
 1.50203 +
 1.50204 +/* A Btree handle
 1.50205 +**
 1.50206 +** A database connection contains a pointer to an instance of
 1.50207 +** this object for every database file that it has open.  This structure
 1.50208 +** is opaque to the database connection.  The database connection cannot
 1.50209 +** see the internals of this structure and only deals with pointers to
 1.50210 +** this structure.
 1.50211 +**
 1.50212 +** For some database files, the same underlying database cache might be 
 1.50213 +** shared between multiple connections.  In that case, each connection
 1.50214 +** has it own instance of this object.  But each instance of this object
 1.50215 +** points to the same BtShared object.  The database cache and the
 1.50216 +** schema associated with the database file are all contained within
 1.50217 +** the BtShared object.
 1.50218 +**
 1.50219 +** All fields in this structure are accessed under sqlite3.mutex.
 1.50220 +** The pBt pointer itself may not be changed while there exists cursors 
 1.50221 +** in the referenced BtShared that point back to this Btree since those
 1.50222 +** cursors have to go through this Btree to find their BtShared and
 1.50223 +** they often do so without holding sqlite3.mutex.
 1.50224 +*/
 1.50225 +struct Btree {
 1.50226 +  sqlite3 *db;       /* The database connection holding this btree */
 1.50227 +  BtShared *pBt;     /* Sharable content of this btree */
 1.50228 +  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
 1.50229 +  u8 sharable;       /* True if we can share pBt with another db */
 1.50230 +  u8 locked;         /* True if db currently has pBt locked */
 1.50231 +  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
 1.50232 +  int nBackup;       /* Number of backup operations reading this btree */
 1.50233 +  Btree *pNext;      /* List of other sharable Btrees from the same db */
 1.50234 +  Btree *pPrev;      /* Back pointer of the same list */
 1.50235 +#ifndef SQLITE_OMIT_SHARED_CACHE
 1.50236 +  BtLock lock;       /* Object used to lock page 1 */
 1.50237 +#endif
 1.50238 +};
 1.50239 +
 1.50240 +/*
 1.50241 +** Btree.inTrans may take one of the following values.
 1.50242 +**
 1.50243 +** If the shared-data extension is enabled, there may be multiple users
 1.50244 +** of the Btree structure. At most one of these may open a write transaction,
 1.50245 +** but any number may have active read transactions.
 1.50246 +*/
 1.50247 +#define TRANS_NONE  0
 1.50248 +#define TRANS_READ  1
 1.50249 +#define TRANS_WRITE 2
 1.50250 +
 1.50251 +/*
 1.50252 +** An instance of this object represents a single database file.
 1.50253 +** 
 1.50254 +** A single database file can be in use at the same time by two
 1.50255 +** or more database connections.  When two or more connections are
 1.50256 +** sharing the same database file, each connection has it own
 1.50257 +** private Btree object for the file and each of those Btrees points
 1.50258 +** to this one BtShared object.  BtShared.nRef is the number of
 1.50259 +** connections currently sharing this database file.
 1.50260 +**
 1.50261 +** Fields in this structure are accessed under the BtShared.mutex
 1.50262 +** mutex, except for nRef and pNext which are accessed under the
 1.50263 +** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
 1.50264 +** may not be modified once it is initially set as long as nRef>0.
 1.50265 +** The pSchema field may be set once under BtShared.mutex and
 1.50266 +** thereafter is unchanged as long as nRef>0.
 1.50267 +**
 1.50268 +** isPending:
 1.50269 +**
 1.50270 +**   If a BtShared client fails to obtain a write-lock on a database
 1.50271 +**   table (because there exists one or more read-locks on the table),
 1.50272 +**   the shared-cache enters 'pending-lock' state and isPending is
 1.50273 +**   set to true.
 1.50274 +**
 1.50275 +**   The shared-cache leaves the 'pending lock' state when either of
 1.50276 +**   the following occur:
 1.50277 +**
 1.50278 +**     1) The current writer (BtShared.pWriter) concludes its transaction, OR
 1.50279 +**     2) The number of locks held by other connections drops to zero.
 1.50280 +**
 1.50281 +**   while in the 'pending-lock' state, no connection may start a new
 1.50282 +**   transaction.
 1.50283 +**
 1.50284 +**   This feature is included to help prevent writer-starvation.
 1.50285 +*/
 1.50286 +struct BtShared {
 1.50287 +  Pager *pPager;        /* The page cache */
 1.50288 +  sqlite3 *db;          /* Database connection currently using this Btree */
 1.50289 +  BtCursor *pCursor;    /* A list of all open cursors */
 1.50290 +  MemPage *pPage1;      /* First page of the database */
 1.50291 +  u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
 1.50292 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.50293 +  u8 autoVacuum;        /* True if auto-vacuum is enabled */
 1.50294 +  u8 incrVacuum;        /* True if incr-vacuum is enabled */
 1.50295 +  u8 bDoTruncate;       /* True to truncate db on commit */
 1.50296 +#endif
 1.50297 +  u8 inTransaction;     /* Transaction state */
 1.50298 +  u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
 1.50299 +  u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
 1.50300 +  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
 1.50301 +  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
 1.50302 +  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
 1.50303 +  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
 1.50304 +  u32 pageSize;         /* Total number of bytes on a page */
 1.50305 +  u32 usableSize;       /* Number of usable bytes on each page */
 1.50306 +  int nTransaction;     /* Number of open transactions (read + write) */
 1.50307 +  u32 nPage;            /* Number of pages in the database */
 1.50308 +  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
 1.50309 +  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
 1.50310 +  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
 1.50311 +  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
 1.50312 +#ifndef SQLITE_OMIT_SHARED_CACHE
 1.50313 +  int nRef;             /* Number of references to this structure */
 1.50314 +  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
 1.50315 +  BtLock *pLock;        /* List of locks held on this shared-btree struct */
 1.50316 +  Btree *pWriter;       /* Btree with currently open write transaction */
 1.50317 +#endif
 1.50318 +  u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
 1.50319 +};
 1.50320 +
 1.50321 +/*
 1.50322 +** Allowed values for BtShared.btsFlags
 1.50323 +*/
 1.50324 +#define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
 1.50325 +#define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
 1.50326 +#define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
 1.50327 +#define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
 1.50328 +#define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
 1.50329 +#define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
 1.50330 +#define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
 1.50331 +
 1.50332 +/*
 1.50333 +** An instance of the following structure is used to hold information
 1.50334 +** about a cell.  The parseCellPtr() function fills in this structure
 1.50335 +** based on information extract from the raw disk page.
 1.50336 +*/
 1.50337 +typedef struct CellInfo CellInfo;
 1.50338 +struct CellInfo {
 1.50339 +  i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
 1.50340 +  u8 *pCell;     /* Pointer to the start of cell content */
 1.50341 +  u32 nData;     /* Number of bytes of data */
 1.50342 +  u32 nPayload;  /* Total amount of payload */
 1.50343 +  u16 nHeader;   /* Size of the cell content header in bytes */
 1.50344 +  u16 nLocal;    /* Amount of payload held locally */
 1.50345 +  u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
 1.50346 +  u16 nSize;     /* Size of the cell content on the main b-tree page */
 1.50347 +};
 1.50348 +
 1.50349 +/*
 1.50350 +** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
 1.50351 +** this will be declared corrupt. This value is calculated based on a
 1.50352 +** maximum database size of 2^31 pages a minimum fanout of 2 for a
 1.50353 +** root-node and 3 for all other internal nodes.
 1.50354 +**
 1.50355 +** If a tree that appears to be taller than this is encountered, it is
 1.50356 +** assumed that the database is corrupt.
 1.50357 +*/
 1.50358 +#define BTCURSOR_MAX_DEPTH 20
 1.50359 +
 1.50360 +/*
 1.50361 +** A cursor is a pointer to a particular entry within a particular
 1.50362 +** b-tree within a database file.
 1.50363 +**
 1.50364 +** The entry is identified by its MemPage and the index in
 1.50365 +** MemPage.aCell[] of the entry.
 1.50366 +**
 1.50367 +** A single database file can be shared by two more database connections,
 1.50368 +** but cursors cannot be shared.  Each cursor is associated with a
 1.50369 +** particular database connection identified BtCursor.pBtree.db.
 1.50370 +**
 1.50371 +** Fields in this structure are accessed under the BtShared.mutex
 1.50372 +** found at self->pBt->mutex. 
 1.50373 +*/
 1.50374 +struct BtCursor {
 1.50375 +  Btree *pBtree;            /* The Btree to which this cursor belongs */
 1.50376 +  BtShared *pBt;            /* The BtShared this cursor points to */
 1.50377 +  BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
 1.50378 +  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
 1.50379 +#ifndef SQLITE_OMIT_INCRBLOB
 1.50380 +  Pgno *aOverflow;          /* Cache of overflow page locations */
 1.50381 +#endif
 1.50382 +  Pgno pgnoRoot;            /* The root page of this tree */
 1.50383 +  CellInfo info;            /* A parse of the cell we are pointing at */
 1.50384 +  i64 nKey;        /* Size of pKey, or last integer key */
 1.50385 +  void *pKey;      /* Saved key that was cursor's last known position */
 1.50386 +  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
 1.50387 +  u8 wrFlag;                /* True if writable */
 1.50388 +  u8 atLast;                /* Cursor pointing to the last entry */
 1.50389 +  u8 validNKey;             /* True if info.nKey is valid */
 1.50390 +  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
 1.50391 +#ifndef SQLITE_OMIT_INCRBLOB
 1.50392 +  u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
 1.50393 +#endif
 1.50394 +  u8 hints;                             /* As configured by CursorSetHints() */
 1.50395 +  i16 iPage;                            /* Index of current page in apPage */
 1.50396 +  u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
 1.50397 +  MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
 1.50398 +};
 1.50399 +
 1.50400 +/*
 1.50401 +** Potential values for BtCursor.eState.
 1.50402 +**
 1.50403 +** CURSOR_INVALID:
 1.50404 +**   Cursor does not point to a valid entry. This can happen (for example) 
 1.50405 +**   because the table is empty or because BtreeCursorFirst() has not been
 1.50406 +**   called.
 1.50407 +**
 1.50408 +** CURSOR_VALID:
 1.50409 +**   Cursor points to a valid entry. getPayload() etc. may be called.
 1.50410 +**
 1.50411 +** CURSOR_SKIPNEXT:
 1.50412 +**   Cursor is valid except that the Cursor.skipNext field is non-zero
 1.50413 +**   indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
 1.50414 +**   operation should be a no-op.
 1.50415 +**
 1.50416 +** CURSOR_REQUIRESEEK:
 1.50417 +**   The table that this cursor was opened on still exists, but has been 
 1.50418 +**   modified since the cursor was last used. The cursor position is saved
 1.50419 +**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
 1.50420 +**   this state, restoreCursorPosition() can be called to attempt to
 1.50421 +**   seek the cursor to the saved position.
 1.50422 +**
 1.50423 +** CURSOR_FAULT:
 1.50424 +**   A unrecoverable error (an I/O error or a malloc failure) has occurred
 1.50425 +**   on a different connection that shares the BtShared cache with this
 1.50426 +**   cursor.  The error has left the cache in an inconsistent state.
 1.50427 +**   Do nothing else with this cursor.  Any attempt to use the cursor
 1.50428 +**   should return the error code stored in BtCursor.skip
 1.50429 +*/
 1.50430 +#define CURSOR_INVALID           0
 1.50431 +#define CURSOR_VALID             1
 1.50432 +#define CURSOR_SKIPNEXT          2
 1.50433 +#define CURSOR_REQUIRESEEK       3
 1.50434 +#define CURSOR_FAULT             4
 1.50435 +
 1.50436 +/* 
 1.50437 +** The database page the PENDING_BYTE occupies. This page is never used.
 1.50438 +*/
 1.50439 +# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
 1.50440 +
 1.50441 +/*
 1.50442 +** These macros define the location of the pointer-map entry for a 
 1.50443 +** database page. The first argument to each is the number of usable
 1.50444 +** bytes on each page of the database (often 1024). The second is the
 1.50445 +** page number to look up in the pointer map.
 1.50446 +**
 1.50447 +** PTRMAP_PAGENO returns the database page number of the pointer-map
 1.50448 +** page that stores the required pointer. PTRMAP_PTROFFSET returns
 1.50449 +** the offset of the requested map entry.
 1.50450 +**
 1.50451 +** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
 1.50452 +** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
 1.50453 +** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
 1.50454 +** this test.
 1.50455 +*/
 1.50456 +#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
 1.50457 +#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
 1.50458 +#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
 1.50459 +
 1.50460 +/*
 1.50461 +** The pointer map is a lookup table that identifies the parent page for
 1.50462 +** each child page in the database file.  The parent page is the page that
 1.50463 +** contains a pointer to the child.  Every page in the database contains
 1.50464 +** 0 or 1 parent pages.  (In this context 'database page' refers
 1.50465 +** to any page that is not part of the pointer map itself.)  Each pointer map
 1.50466 +** entry consists of a single byte 'type' and a 4 byte parent page number.
 1.50467 +** The PTRMAP_XXX identifiers below are the valid types.
 1.50468 +**
 1.50469 +** The purpose of the pointer map is to facility moving pages from one
 1.50470 +** position in the file to another as part of autovacuum.  When a page
 1.50471 +** is moved, the pointer in its parent must be updated to point to the
 1.50472 +** new location.  The pointer map is used to locate the parent page quickly.
 1.50473 +**
 1.50474 +** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
 1.50475 +**                  used in this case.
 1.50476 +**
 1.50477 +** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
 1.50478 +**                  is not used in this case.
 1.50479 +**
 1.50480 +** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
 1.50481 +**                   overflow pages. The page number identifies the page that
 1.50482 +**                   contains the cell with a pointer to this overflow page.
 1.50483 +**
 1.50484 +** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
 1.50485 +**                   overflow pages. The page-number identifies the previous
 1.50486 +**                   page in the overflow page list.
 1.50487 +**
 1.50488 +** PTRMAP_BTREE: The database page is a non-root btree page. The page number
 1.50489 +**               identifies the parent page in the btree.
 1.50490 +*/
 1.50491 +#define PTRMAP_ROOTPAGE 1
 1.50492 +#define PTRMAP_FREEPAGE 2
 1.50493 +#define PTRMAP_OVERFLOW1 3
 1.50494 +#define PTRMAP_OVERFLOW2 4
 1.50495 +#define PTRMAP_BTREE 5
 1.50496 +
 1.50497 +/* A bunch of assert() statements to check the transaction state variables
 1.50498 +** of handle p (type Btree*) are internally consistent.
 1.50499 +*/
 1.50500 +#define btreeIntegrity(p) \
 1.50501 +  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
 1.50502 +  assert( p->pBt->inTransaction>=p->inTrans ); 
 1.50503 +
 1.50504 +
 1.50505 +/*
 1.50506 +** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
 1.50507 +** if the database supports auto-vacuum or not. Because it is used
 1.50508 +** within an expression that is an argument to another macro 
 1.50509 +** (sqliteMallocRaw), it is not possible to use conditional compilation.
 1.50510 +** So, this macro is defined instead.
 1.50511 +*/
 1.50512 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.50513 +#define ISAUTOVACUUM (pBt->autoVacuum)
 1.50514 +#else
 1.50515 +#define ISAUTOVACUUM 0
 1.50516 +#endif
 1.50517 +
 1.50518 +
 1.50519 +/*
 1.50520 +** This structure is passed around through all the sanity checking routines
 1.50521 +** in order to keep track of some global state information.
 1.50522 +**
 1.50523 +** The aRef[] array is allocated so that there is 1 bit for each page in
 1.50524 +** the database. As the integrity-check proceeds, for each page used in
 1.50525 +** the database the corresponding bit is set. This allows integrity-check to 
 1.50526 +** detect pages that are used twice and orphaned pages (both of which 
 1.50527 +** indicate corruption).
 1.50528 +*/
 1.50529 +typedef struct IntegrityCk IntegrityCk;
 1.50530 +struct IntegrityCk {
 1.50531 +  BtShared *pBt;    /* The tree being checked out */
 1.50532 +  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
 1.50533 +  u8 *aPgRef;       /* 1 bit per page in the db (see above) */
 1.50534 +  Pgno nPage;       /* Number of pages in the database */
 1.50535 +  int mxErr;        /* Stop accumulating errors when this reaches zero */
 1.50536 +  int nErr;         /* Number of messages written to zErrMsg so far */
 1.50537 +  int mallocFailed; /* A memory allocation error has occurred */
 1.50538 +  StrAccum errMsg;  /* Accumulate the error message text here */
 1.50539 +};
 1.50540 +
 1.50541 +/*
 1.50542 +** Routines to read or write a two- and four-byte big-endian integer values.
 1.50543 +*/
 1.50544 +#define get2byte(x)   ((x)[0]<<8 | (x)[1])
 1.50545 +#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
 1.50546 +#define get4byte sqlite3Get4byte
 1.50547 +#define put4byte sqlite3Put4byte
 1.50548 +
 1.50549 +/************** End of btreeInt.h ********************************************/
 1.50550 +/************** Continuing where we left off in btmutex.c ********************/
 1.50551 +#ifndef SQLITE_OMIT_SHARED_CACHE
 1.50552 +#if SQLITE_THREADSAFE
 1.50553 +
 1.50554 +/*
 1.50555 +** Obtain the BtShared mutex associated with B-Tree handle p. Also,
 1.50556 +** set BtShared.db to the database handle associated with p and the
 1.50557 +** p->locked boolean to true.
 1.50558 +*/
 1.50559 +static void lockBtreeMutex(Btree *p){
 1.50560 +  assert( p->locked==0 );
 1.50561 +  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
 1.50562 +  assert( sqlite3_mutex_held(p->db->mutex) );
 1.50563 +
 1.50564 +  sqlite3_mutex_enter(p->pBt->mutex);
 1.50565 +  p->pBt->db = p->db;
 1.50566 +  p->locked = 1;
 1.50567 +}
 1.50568 +
 1.50569 +/*
 1.50570 +** Release the BtShared mutex associated with B-Tree handle p and
 1.50571 +** clear the p->locked boolean.
 1.50572 +*/
 1.50573 +static void unlockBtreeMutex(Btree *p){
 1.50574 +  BtShared *pBt = p->pBt;
 1.50575 +  assert( p->locked==1 );
 1.50576 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.50577 +  assert( sqlite3_mutex_held(p->db->mutex) );
 1.50578 +  assert( p->db==pBt->db );
 1.50579 +
 1.50580 +  sqlite3_mutex_leave(pBt->mutex);
 1.50581 +  p->locked = 0;
 1.50582 +}
 1.50583 +
 1.50584 +/*
 1.50585 +** Enter a mutex on the given BTree object.
 1.50586 +**
 1.50587 +** If the object is not sharable, then no mutex is ever required
 1.50588 +** and this routine is a no-op.  The underlying mutex is non-recursive.
 1.50589 +** But we keep a reference count in Btree.wantToLock so the behavior
 1.50590 +** of this interface is recursive.
 1.50591 +**
 1.50592 +** To avoid deadlocks, multiple Btrees are locked in the same order
 1.50593 +** by all database connections.  The p->pNext is a list of other
 1.50594 +** Btrees belonging to the same database connection as the p Btree
 1.50595 +** which need to be locked after p.  If we cannot get a lock on
 1.50596 +** p, then first unlock all of the others on p->pNext, then wait
 1.50597 +** for the lock to become available on p, then relock all of the
 1.50598 +** subsequent Btrees that desire a lock.
 1.50599 +*/
 1.50600 +SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
 1.50601 +  Btree *pLater;
 1.50602 +
 1.50603 +  /* Some basic sanity checking on the Btree.  The list of Btrees
 1.50604 +  ** connected by pNext and pPrev should be in sorted order by
 1.50605 +  ** Btree.pBt value. All elements of the list should belong to
 1.50606 +  ** the same connection. Only shared Btrees are on the list. */
 1.50607 +  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
 1.50608 +  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
 1.50609 +  assert( p->pNext==0 || p->pNext->db==p->db );
 1.50610 +  assert( p->pPrev==0 || p->pPrev->db==p->db );
 1.50611 +  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
 1.50612 +
 1.50613 +  /* Check for locking consistency */
 1.50614 +  assert( !p->locked || p->wantToLock>0 );
 1.50615 +  assert( p->sharable || p->wantToLock==0 );
 1.50616 +
 1.50617 +  /* We should already hold a lock on the database connection */
 1.50618 +  assert( sqlite3_mutex_held(p->db->mutex) );
 1.50619 +
 1.50620 +  /* Unless the database is sharable and unlocked, then BtShared.db
 1.50621 +  ** should already be set correctly. */
 1.50622 +  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
 1.50623 +
 1.50624 +  if( !p->sharable ) return;
 1.50625 +  p->wantToLock++;
 1.50626 +  if( p->locked ) return;
 1.50627 +
 1.50628 +  /* In most cases, we should be able to acquire the lock we
 1.50629 +  ** want without having to go throught the ascending lock
 1.50630 +  ** procedure that follows.  Just be sure not to block.
 1.50631 +  */
 1.50632 +  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
 1.50633 +    p->pBt->db = p->db;
 1.50634 +    p->locked = 1;
 1.50635 +    return;
 1.50636 +  }
 1.50637 +
 1.50638 +  /* To avoid deadlock, first release all locks with a larger
 1.50639 +  ** BtShared address.  Then acquire our lock.  Then reacquire
 1.50640 +  ** the other BtShared locks that we used to hold in ascending
 1.50641 +  ** order.
 1.50642 +  */
 1.50643 +  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
 1.50644 +    assert( pLater->sharable );
 1.50645 +    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
 1.50646 +    assert( !pLater->locked || pLater->wantToLock>0 );
 1.50647 +    if( pLater->locked ){
 1.50648 +      unlockBtreeMutex(pLater);
 1.50649 +    }
 1.50650 +  }
 1.50651 +  lockBtreeMutex(p);
 1.50652 +  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
 1.50653 +    if( pLater->wantToLock ){
 1.50654 +      lockBtreeMutex(pLater);
 1.50655 +    }
 1.50656 +  }
 1.50657 +}
 1.50658 +
 1.50659 +/*
 1.50660 +** Exit the recursive mutex on a Btree.
 1.50661 +*/
 1.50662 +SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
 1.50663 +  if( p->sharable ){
 1.50664 +    assert( p->wantToLock>0 );
 1.50665 +    p->wantToLock--;
 1.50666 +    if( p->wantToLock==0 ){
 1.50667 +      unlockBtreeMutex(p);
 1.50668 +    }
 1.50669 +  }
 1.50670 +}
 1.50671 +
 1.50672 +#ifndef NDEBUG
 1.50673 +/*
 1.50674 +** Return true if the BtShared mutex is held on the btree, or if the
 1.50675 +** B-Tree is not marked as sharable.
 1.50676 +**
 1.50677 +** This routine is used only from within assert() statements.
 1.50678 +*/
 1.50679 +SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
 1.50680 +  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
 1.50681 +  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
 1.50682 +  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
 1.50683 +  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
 1.50684 +
 1.50685 +  return (p->sharable==0 || p->locked);
 1.50686 +}
 1.50687 +#endif
 1.50688 +
 1.50689 +
 1.50690 +#ifndef SQLITE_OMIT_INCRBLOB
 1.50691 +/*
 1.50692 +** Enter and leave a mutex on a Btree given a cursor owned by that
 1.50693 +** Btree.  These entry points are used by incremental I/O and can be
 1.50694 +** omitted if that module is not used.
 1.50695 +*/
 1.50696 +SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
 1.50697 +  sqlite3BtreeEnter(pCur->pBtree);
 1.50698 +}
 1.50699 +SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
 1.50700 +  sqlite3BtreeLeave(pCur->pBtree);
 1.50701 +}
 1.50702 +#endif /* SQLITE_OMIT_INCRBLOB */
 1.50703 +
 1.50704 +
 1.50705 +/*
 1.50706 +** Enter the mutex on every Btree associated with a database
 1.50707 +** connection.  This is needed (for example) prior to parsing
 1.50708 +** a statement since we will be comparing table and column names
 1.50709 +** against all schemas and we do not want those schemas being
 1.50710 +** reset out from under us.
 1.50711 +**
 1.50712 +** There is a corresponding leave-all procedures.
 1.50713 +**
 1.50714 +** Enter the mutexes in accending order by BtShared pointer address
 1.50715 +** to avoid the possibility of deadlock when two threads with
 1.50716 +** two or more btrees in common both try to lock all their btrees
 1.50717 +** at the same instant.
 1.50718 +*/
 1.50719 +SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
 1.50720 +  int i;
 1.50721 +  Btree *p;
 1.50722 +  assert( sqlite3_mutex_held(db->mutex) );
 1.50723 +  for(i=0; i<db->nDb; i++){
 1.50724 +    p = db->aDb[i].pBt;
 1.50725 +    if( p ) sqlite3BtreeEnter(p);
 1.50726 +  }
 1.50727 +}
 1.50728 +SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
 1.50729 +  int i;
 1.50730 +  Btree *p;
 1.50731 +  assert( sqlite3_mutex_held(db->mutex) );
 1.50732 +  for(i=0; i<db->nDb; i++){
 1.50733 +    p = db->aDb[i].pBt;
 1.50734 +    if( p ) sqlite3BtreeLeave(p);
 1.50735 +  }
 1.50736 +}
 1.50737 +
 1.50738 +/*
 1.50739 +** Return true if a particular Btree requires a lock.  Return FALSE if
 1.50740 +** no lock is ever required since it is not sharable.
 1.50741 +*/
 1.50742 +SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
 1.50743 +  return p->sharable;
 1.50744 +}
 1.50745 +
 1.50746 +#ifndef NDEBUG
 1.50747 +/*
 1.50748 +** Return true if the current thread holds the database connection
 1.50749 +** mutex and all required BtShared mutexes.
 1.50750 +**
 1.50751 +** This routine is used inside assert() statements only.
 1.50752 +*/
 1.50753 +SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
 1.50754 +  int i;
 1.50755 +  if( !sqlite3_mutex_held(db->mutex) ){
 1.50756 +    return 0;
 1.50757 +  }
 1.50758 +  for(i=0; i<db->nDb; i++){
 1.50759 +    Btree *p;
 1.50760 +    p = db->aDb[i].pBt;
 1.50761 +    if( p && p->sharable &&
 1.50762 +         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
 1.50763 +      return 0;
 1.50764 +    }
 1.50765 +  }
 1.50766 +  return 1;
 1.50767 +}
 1.50768 +#endif /* NDEBUG */
 1.50769 +
 1.50770 +#ifndef NDEBUG
 1.50771 +/*
 1.50772 +** Return true if the correct mutexes are held for accessing the
 1.50773 +** db->aDb[iDb].pSchema structure.  The mutexes required for schema
 1.50774 +** access are:
 1.50775 +**
 1.50776 +**   (1) The mutex on db
 1.50777 +**   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
 1.50778 +**
 1.50779 +** If pSchema is not NULL, then iDb is computed from pSchema and
 1.50780 +** db using sqlite3SchemaToIndex().
 1.50781 +*/
 1.50782 +SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
 1.50783 +  Btree *p;
 1.50784 +  assert( db!=0 );
 1.50785 +  if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
 1.50786 +  assert( iDb>=0 && iDb<db->nDb );
 1.50787 +  if( !sqlite3_mutex_held(db->mutex) ) return 0;
 1.50788 +  if( iDb==1 ) return 1;
 1.50789 +  p = db->aDb[iDb].pBt;
 1.50790 +  assert( p!=0 );
 1.50791 +  return p->sharable==0 || p->locked==1;
 1.50792 +}
 1.50793 +#endif /* NDEBUG */
 1.50794 +
 1.50795 +#else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
 1.50796 +/*
 1.50797 +** The following are special cases for mutex enter routines for use
 1.50798 +** in single threaded applications that use shared cache.  Except for
 1.50799 +** these two routines, all mutex operations are no-ops in that case and
 1.50800 +** are null #defines in btree.h.
 1.50801 +**
 1.50802 +** If shared cache is disabled, then all btree mutex routines, including
 1.50803 +** the ones below, are no-ops and are null #defines in btree.h.
 1.50804 +*/
 1.50805 +
 1.50806 +SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
 1.50807 +  p->pBt->db = p->db;
 1.50808 +}
 1.50809 +SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
 1.50810 +  int i;
 1.50811 +  for(i=0; i<db->nDb; i++){
 1.50812 +    Btree *p = db->aDb[i].pBt;
 1.50813 +    if( p ){
 1.50814 +      p->pBt->db = p->db;
 1.50815 +    }
 1.50816 +  }
 1.50817 +}
 1.50818 +#endif /* if SQLITE_THREADSAFE */
 1.50819 +#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
 1.50820 +
 1.50821 +/************** End of btmutex.c *********************************************/
 1.50822 +/************** Begin file btree.c *******************************************/
 1.50823 +/*
 1.50824 +** 2004 April 6
 1.50825 +**
 1.50826 +** The author disclaims copyright to this source code.  In place of
 1.50827 +** a legal notice, here is a blessing:
 1.50828 +**
 1.50829 +**    May you do good and not evil.
 1.50830 +**    May you find forgiveness for yourself and forgive others.
 1.50831 +**    May you share freely, never taking more than you give.
 1.50832 +**
 1.50833 +*************************************************************************
 1.50834 +** This file implements a external (disk-based) database using BTrees.
 1.50835 +** See the header comment on "btreeInt.h" for additional information.
 1.50836 +** Including a description of file format and an overview of operation.
 1.50837 +*/
 1.50838 +
 1.50839 +/*
 1.50840 +** The header string that appears at the beginning of every
 1.50841 +** SQLite database.
 1.50842 +*/
 1.50843 +static const char zMagicHeader[] = SQLITE_FILE_HEADER;
 1.50844 +
 1.50845 +/*
 1.50846 +** Set this global variable to 1 to enable tracing using the TRACE
 1.50847 +** macro.
 1.50848 +*/
 1.50849 +#if 0
 1.50850 +int sqlite3BtreeTrace=1;  /* True to enable tracing */
 1.50851 +# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
 1.50852 +#else
 1.50853 +# define TRACE(X)
 1.50854 +#endif
 1.50855 +
 1.50856 +/*
 1.50857 +** Extract a 2-byte big-endian integer from an array of unsigned bytes.
 1.50858 +** But if the value is zero, make it 65536.
 1.50859 +**
 1.50860 +** This routine is used to extract the "offset to cell content area" value
 1.50861 +** from the header of a btree page.  If the page size is 65536 and the page
 1.50862 +** is empty, the offset should be 65536, but the 2-byte value stores zero.
 1.50863 +** This routine makes the necessary adjustment to 65536.
 1.50864 +*/
 1.50865 +#define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
 1.50866 +
 1.50867 +/*
 1.50868 +** Values passed as the 5th argument to allocateBtreePage()
 1.50869 +*/
 1.50870 +#define BTALLOC_ANY   0           /* Allocate any page */
 1.50871 +#define BTALLOC_EXACT 1           /* Allocate exact page if possible */
 1.50872 +#define BTALLOC_LE    2           /* Allocate any page <= the parameter */
 1.50873 +
 1.50874 +/*
 1.50875 +** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not 
 1.50876 +** defined, or 0 if it is. For example:
 1.50877 +**
 1.50878 +**   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
 1.50879 +*/
 1.50880 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.50881 +#define IfNotOmitAV(expr) (expr)
 1.50882 +#else
 1.50883 +#define IfNotOmitAV(expr) 0
 1.50884 +#endif
 1.50885 +
 1.50886 +#ifndef SQLITE_OMIT_SHARED_CACHE
 1.50887 +/*
 1.50888 +** A list of BtShared objects that are eligible for participation
 1.50889 +** in shared cache.  This variable has file scope during normal builds,
 1.50890 +** but the test harness needs to access it so we make it global for 
 1.50891 +** test builds.
 1.50892 +**
 1.50893 +** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
 1.50894 +*/
 1.50895 +#ifdef SQLITE_TEST
 1.50896 +SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
 1.50897 +#else
 1.50898 +static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
 1.50899 +#endif
 1.50900 +#endif /* SQLITE_OMIT_SHARED_CACHE */
 1.50901 +
 1.50902 +#ifndef SQLITE_OMIT_SHARED_CACHE
 1.50903 +/*
 1.50904 +** Enable or disable the shared pager and schema features.
 1.50905 +**
 1.50906 +** This routine has no effect on existing database connections.
 1.50907 +** The shared cache setting effects only future calls to
 1.50908 +** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
 1.50909 +*/
 1.50910 +SQLITE_API int sqlite3_enable_shared_cache(int enable){
 1.50911 +  sqlite3GlobalConfig.sharedCacheEnabled = enable;
 1.50912 +  return SQLITE_OK;
 1.50913 +}
 1.50914 +#endif
 1.50915 +
 1.50916 +
 1.50917 +
 1.50918 +#ifdef SQLITE_OMIT_SHARED_CACHE
 1.50919 +  /*
 1.50920 +  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
 1.50921 +  ** and clearAllSharedCacheTableLocks()
 1.50922 +  ** manipulate entries in the BtShared.pLock linked list used to store
 1.50923 +  ** shared-cache table level locks. If the library is compiled with the
 1.50924 +  ** shared-cache feature disabled, then there is only ever one user
 1.50925 +  ** of each BtShared structure and so this locking is not necessary. 
 1.50926 +  ** So define the lock related functions as no-ops.
 1.50927 +  */
 1.50928 +  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
 1.50929 +  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
 1.50930 +  #define clearAllSharedCacheTableLocks(a)
 1.50931 +  #define downgradeAllSharedCacheTableLocks(a)
 1.50932 +  #define hasSharedCacheTableLock(a,b,c,d) 1
 1.50933 +  #define hasReadConflicts(a, b) 0
 1.50934 +#endif
 1.50935 +
 1.50936 +#ifndef SQLITE_OMIT_SHARED_CACHE
 1.50937 +
 1.50938 +#ifdef SQLITE_DEBUG
 1.50939 +/*
 1.50940 +**** This function is only used as part of an assert() statement. ***
 1.50941 +**
 1.50942 +** Check to see if pBtree holds the required locks to read or write to the 
 1.50943 +** table with root page iRoot.   Return 1 if it does and 0 if not.
 1.50944 +**
 1.50945 +** For example, when writing to a table with root-page iRoot via 
 1.50946 +** Btree connection pBtree:
 1.50947 +**
 1.50948 +**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
 1.50949 +**
 1.50950 +** When writing to an index that resides in a sharable database, the 
 1.50951 +** caller should have first obtained a lock specifying the root page of
 1.50952 +** the corresponding table. This makes things a bit more complicated,
 1.50953 +** as this module treats each table as a separate structure. To determine
 1.50954 +** the table corresponding to the index being written, this
 1.50955 +** function has to search through the database schema.
 1.50956 +**
 1.50957 +** Instead of a lock on the table/index rooted at page iRoot, the caller may
 1.50958 +** hold a write-lock on the schema table (root page 1). This is also
 1.50959 +** acceptable.
 1.50960 +*/
 1.50961 +static int hasSharedCacheTableLock(
 1.50962 +  Btree *pBtree,         /* Handle that must hold lock */
 1.50963 +  Pgno iRoot,            /* Root page of b-tree */
 1.50964 +  int isIndex,           /* True if iRoot is the root of an index b-tree */
 1.50965 +  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
 1.50966 +){
 1.50967 +  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
 1.50968 +  Pgno iTab = 0;
 1.50969 +  BtLock *pLock;
 1.50970 +
 1.50971 +  /* If this database is not shareable, or if the client is reading
 1.50972 +  ** and has the read-uncommitted flag set, then no lock is required. 
 1.50973 +  ** Return true immediately.
 1.50974 +  */
 1.50975 +  if( (pBtree->sharable==0)
 1.50976 +   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
 1.50977 +  ){
 1.50978 +    return 1;
 1.50979 +  }
 1.50980 +
 1.50981 +  /* If the client is reading  or writing an index and the schema is
 1.50982 +  ** not loaded, then it is too difficult to actually check to see if
 1.50983 +  ** the correct locks are held.  So do not bother - just return true.
 1.50984 +  ** This case does not come up very often anyhow.
 1.50985 +  */
 1.50986 +  if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
 1.50987 +    return 1;
 1.50988 +  }
 1.50989 +
 1.50990 +  /* Figure out the root-page that the lock should be held on. For table
 1.50991 +  ** b-trees, this is just the root page of the b-tree being read or
 1.50992 +  ** written. For index b-trees, it is the root page of the associated
 1.50993 +  ** table.  */
 1.50994 +  if( isIndex ){
 1.50995 +    HashElem *p;
 1.50996 +    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
 1.50997 +      Index *pIdx = (Index *)sqliteHashData(p);
 1.50998 +      if( pIdx->tnum==(int)iRoot ){
 1.50999 +        iTab = pIdx->pTable->tnum;
 1.51000 +      }
 1.51001 +    }
 1.51002 +  }else{
 1.51003 +    iTab = iRoot;
 1.51004 +  }
 1.51005 +
 1.51006 +  /* Search for the required lock. Either a write-lock on root-page iTab, a 
 1.51007 +  ** write-lock on the schema table, or (if the client is reading) a
 1.51008 +  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
 1.51009 +  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
 1.51010 +    if( pLock->pBtree==pBtree 
 1.51011 +     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
 1.51012 +     && pLock->eLock>=eLockType 
 1.51013 +    ){
 1.51014 +      return 1;
 1.51015 +    }
 1.51016 +  }
 1.51017 +
 1.51018 +  /* Failed to find the required lock. */
 1.51019 +  return 0;
 1.51020 +}
 1.51021 +#endif /* SQLITE_DEBUG */
 1.51022 +
 1.51023 +#ifdef SQLITE_DEBUG
 1.51024 +/*
 1.51025 +**** This function may be used as part of assert() statements only. ****
 1.51026 +**
 1.51027 +** Return true if it would be illegal for pBtree to write into the
 1.51028 +** table or index rooted at iRoot because other shared connections are
 1.51029 +** simultaneously reading that same table or index.
 1.51030 +**
 1.51031 +** It is illegal for pBtree to write if some other Btree object that
 1.51032 +** shares the same BtShared object is currently reading or writing
 1.51033 +** the iRoot table.  Except, if the other Btree object has the
 1.51034 +** read-uncommitted flag set, then it is OK for the other object to
 1.51035 +** have a read cursor.
 1.51036 +**
 1.51037 +** For example, before writing to any part of the table or index
 1.51038 +** rooted at page iRoot, one should call:
 1.51039 +**
 1.51040 +**    assert( !hasReadConflicts(pBtree, iRoot) );
 1.51041 +*/
 1.51042 +static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
 1.51043 +  BtCursor *p;
 1.51044 +  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
 1.51045 +    if( p->pgnoRoot==iRoot 
 1.51046 +     && p->pBtree!=pBtree
 1.51047 +     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
 1.51048 +    ){
 1.51049 +      return 1;
 1.51050 +    }
 1.51051 +  }
 1.51052 +  return 0;
 1.51053 +}
 1.51054 +#endif    /* #ifdef SQLITE_DEBUG */
 1.51055 +
 1.51056 +/*
 1.51057 +** Query to see if Btree handle p may obtain a lock of type eLock 
 1.51058 +** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
 1.51059 +** SQLITE_OK if the lock may be obtained (by calling
 1.51060 +** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
 1.51061 +*/
 1.51062 +static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
 1.51063 +  BtShared *pBt = p->pBt;
 1.51064 +  BtLock *pIter;
 1.51065 +
 1.51066 +  assert( sqlite3BtreeHoldsMutex(p) );
 1.51067 +  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
 1.51068 +  assert( p->db!=0 );
 1.51069 +  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
 1.51070 +  
 1.51071 +  /* If requesting a write-lock, then the Btree must have an open write
 1.51072 +  ** transaction on this file. And, obviously, for this to be so there 
 1.51073 +  ** must be an open write transaction on the file itself.
 1.51074 +  */
 1.51075 +  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
 1.51076 +  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
 1.51077 +  
 1.51078 +  /* This routine is a no-op if the shared-cache is not enabled */
 1.51079 +  if( !p->sharable ){
 1.51080 +    return SQLITE_OK;
 1.51081 +  }
 1.51082 +
 1.51083 +  /* If some other connection is holding an exclusive lock, the
 1.51084 +  ** requested lock may not be obtained.
 1.51085 +  */
 1.51086 +  if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
 1.51087 +    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
 1.51088 +    return SQLITE_LOCKED_SHAREDCACHE;
 1.51089 +  }
 1.51090 +
 1.51091 +  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
 1.51092 +    /* The condition (pIter->eLock!=eLock) in the following if(...) 
 1.51093 +    ** statement is a simplification of:
 1.51094 +    **
 1.51095 +    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
 1.51096 +    **
 1.51097 +    ** since we know that if eLock==WRITE_LOCK, then no other connection
 1.51098 +    ** may hold a WRITE_LOCK on any table in this file (since there can
 1.51099 +    ** only be a single writer).
 1.51100 +    */
 1.51101 +    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
 1.51102 +    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
 1.51103 +    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
 1.51104 +      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
 1.51105 +      if( eLock==WRITE_LOCK ){
 1.51106 +        assert( p==pBt->pWriter );
 1.51107 +        pBt->btsFlags |= BTS_PENDING;
 1.51108 +      }
 1.51109 +      return SQLITE_LOCKED_SHAREDCACHE;
 1.51110 +    }
 1.51111 +  }
 1.51112 +  return SQLITE_OK;
 1.51113 +}
 1.51114 +#endif /* !SQLITE_OMIT_SHARED_CACHE */
 1.51115 +
 1.51116 +#ifndef SQLITE_OMIT_SHARED_CACHE
 1.51117 +/*
 1.51118 +** Add a lock on the table with root-page iTable to the shared-btree used
 1.51119 +** by Btree handle p. Parameter eLock must be either READ_LOCK or 
 1.51120 +** WRITE_LOCK.
 1.51121 +**
 1.51122 +** This function assumes the following:
 1.51123 +**
 1.51124 +**   (a) The specified Btree object p is connected to a sharable
 1.51125 +**       database (one with the BtShared.sharable flag set), and
 1.51126 +**
 1.51127 +**   (b) No other Btree objects hold a lock that conflicts
 1.51128 +**       with the requested lock (i.e. querySharedCacheTableLock() has
 1.51129 +**       already been called and returned SQLITE_OK).
 1.51130 +**
 1.51131 +** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
 1.51132 +** is returned if a malloc attempt fails.
 1.51133 +*/
 1.51134 +static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
 1.51135 +  BtShared *pBt = p->pBt;
 1.51136 +  BtLock *pLock = 0;
 1.51137 +  BtLock *pIter;
 1.51138 +
 1.51139 +  assert( sqlite3BtreeHoldsMutex(p) );
 1.51140 +  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
 1.51141 +  assert( p->db!=0 );
 1.51142 +
 1.51143 +  /* A connection with the read-uncommitted flag set will never try to
 1.51144 +  ** obtain a read-lock using this function. The only read-lock obtained
 1.51145 +  ** by a connection in read-uncommitted mode is on the sqlite_master 
 1.51146 +  ** table, and that lock is obtained in BtreeBeginTrans().  */
 1.51147 +  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
 1.51148 +
 1.51149 +  /* This function should only be called on a sharable b-tree after it 
 1.51150 +  ** has been determined that no other b-tree holds a conflicting lock.  */
 1.51151 +  assert( p->sharable );
 1.51152 +  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
 1.51153 +
 1.51154 +  /* First search the list for an existing lock on this table. */
 1.51155 +  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
 1.51156 +    if( pIter->iTable==iTable && pIter->pBtree==p ){
 1.51157 +      pLock = pIter;
 1.51158 +      break;
 1.51159 +    }
 1.51160 +  }
 1.51161 +
 1.51162 +  /* If the above search did not find a BtLock struct associating Btree p
 1.51163 +  ** with table iTable, allocate one and link it into the list.
 1.51164 +  */
 1.51165 +  if( !pLock ){
 1.51166 +    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
 1.51167 +    if( !pLock ){
 1.51168 +      return SQLITE_NOMEM;
 1.51169 +    }
 1.51170 +    pLock->iTable = iTable;
 1.51171 +    pLock->pBtree = p;
 1.51172 +    pLock->pNext = pBt->pLock;
 1.51173 +    pBt->pLock = pLock;
 1.51174 +  }
 1.51175 +
 1.51176 +  /* Set the BtLock.eLock variable to the maximum of the current lock
 1.51177 +  ** and the requested lock. This means if a write-lock was already held
 1.51178 +  ** and a read-lock requested, we don't incorrectly downgrade the lock.
 1.51179 +  */
 1.51180 +  assert( WRITE_LOCK>READ_LOCK );
 1.51181 +  if( eLock>pLock->eLock ){
 1.51182 +    pLock->eLock = eLock;
 1.51183 +  }
 1.51184 +
 1.51185 +  return SQLITE_OK;
 1.51186 +}
 1.51187 +#endif /* !SQLITE_OMIT_SHARED_CACHE */
 1.51188 +
 1.51189 +#ifndef SQLITE_OMIT_SHARED_CACHE
 1.51190 +/*
 1.51191 +** Release all the table locks (locks obtained via calls to
 1.51192 +** the setSharedCacheTableLock() procedure) held by Btree object p.
 1.51193 +**
 1.51194 +** This function assumes that Btree p has an open read or write 
 1.51195 +** transaction. If it does not, then the BTS_PENDING flag
 1.51196 +** may be incorrectly cleared.
 1.51197 +*/
 1.51198 +static void clearAllSharedCacheTableLocks(Btree *p){
 1.51199 +  BtShared *pBt = p->pBt;
 1.51200 +  BtLock **ppIter = &pBt->pLock;
 1.51201 +
 1.51202 +  assert( sqlite3BtreeHoldsMutex(p) );
 1.51203 +  assert( p->sharable || 0==*ppIter );
 1.51204 +  assert( p->inTrans>0 );
 1.51205 +
 1.51206 +  while( *ppIter ){
 1.51207 +    BtLock *pLock = *ppIter;
 1.51208 +    assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
 1.51209 +    assert( pLock->pBtree->inTrans>=pLock->eLock );
 1.51210 +    if( pLock->pBtree==p ){
 1.51211 +      *ppIter = pLock->pNext;
 1.51212 +      assert( pLock->iTable!=1 || pLock==&p->lock );
 1.51213 +      if( pLock->iTable!=1 ){
 1.51214 +        sqlite3_free(pLock);
 1.51215 +      }
 1.51216 +    }else{
 1.51217 +      ppIter = &pLock->pNext;
 1.51218 +    }
 1.51219 +  }
 1.51220 +
 1.51221 +  assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
 1.51222 +  if( pBt->pWriter==p ){
 1.51223 +    pBt->pWriter = 0;
 1.51224 +    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
 1.51225 +  }else if( pBt->nTransaction==2 ){
 1.51226 +    /* This function is called when Btree p is concluding its 
 1.51227 +    ** transaction. If there currently exists a writer, and p is not
 1.51228 +    ** that writer, then the number of locks held by connections other
 1.51229 +    ** than the writer must be about to drop to zero. In this case
 1.51230 +    ** set the BTS_PENDING flag to 0.
 1.51231 +    **
 1.51232 +    ** If there is not currently a writer, then BTS_PENDING must
 1.51233 +    ** be zero already. So this next line is harmless in that case.
 1.51234 +    */
 1.51235 +    pBt->btsFlags &= ~BTS_PENDING;
 1.51236 +  }
 1.51237 +}
 1.51238 +
 1.51239 +/*
 1.51240 +** This function changes all write-locks held by Btree p into read-locks.
 1.51241 +*/
 1.51242 +static void downgradeAllSharedCacheTableLocks(Btree *p){
 1.51243 +  BtShared *pBt = p->pBt;
 1.51244 +  if( pBt->pWriter==p ){
 1.51245 +    BtLock *pLock;
 1.51246 +    pBt->pWriter = 0;
 1.51247 +    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
 1.51248 +    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
 1.51249 +      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
 1.51250 +      pLock->eLock = READ_LOCK;
 1.51251 +    }
 1.51252 +  }
 1.51253 +}
 1.51254 +
 1.51255 +#endif /* SQLITE_OMIT_SHARED_CACHE */
 1.51256 +
 1.51257 +static void releasePage(MemPage *pPage);  /* Forward reference */
 1.51258 +
 1.51259 +/*
 1.51260 +***** This routine is used inside of assert() only ****
 1.51261 +**
 1.51262 +** Verify that the cursor holds the mutex on its BtShared
 1.51263 +*/
 1.51264 +#ifdef SQLITE_DEBUG
 1.51265 +static int cursorHoldsMutex(BtCursor *p){
 1.51266 +  return sqlite3_mutex_held(p->pBt->mutex);
 1.51267 +}
 1.51268 +#endif
 1.51269 +
 1.51270 +
 1.51271 +#ifndef SQLITE_OMIT_INCRBLOB
 1.51272 +/*
 1.51273 +** Invalidate the overflow page-list cache for cursor pCur, if any.
 1.51274 +*/
 1.51275 +static void invalidateOverflowCache(BtCursor *pCur){
 1.51276 +  assert( cursorHoldsMutex(pCur) );
 1.51277 +  sqlite3_free(pCur->aOverflow);
 1.51278 +  pCur->aOverflow = 0;
 1.51279 +}
 1.51280 +
 1.51281 +/*
 1.51282 +** Invalidate the overflow page-list cache for all cursors opened
 1.51283 +** on the shared btree structure pBt.
 1.51284 +*/
 1.51285 +static void invalidateAllOverflowCache(BtShared *pBt){
 1.51286 +  BtCursor *p;
 1.51287 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.51288 +  for(p=pBt->pCursor; p; p=p->pNext){
 1.51289 +    invalidateOverflowCache(p);
 1.51290 +  }
 1.51291 +}
 1.51292 +
 1.51293 +/*
 1.51294 +** This function is called before modifying the contents of a table
 1.51295 +** to invalidate any incrblob cursors that are open on the
 1.51296 +** row or one of the rows being modified.
 1.51297 +**
 1.51298 +** If argument isClearTable is true, then the entire contents of the
 1.51299 +** table is about to be deleted. In this case invalidate all incrblob
 1.51300 +** cursors open on any row within the table with root-page pgnoRoot.
 1.51301 +**
 1.51302 +** Otherwise, if argument isClearTable is false, then the row with
 1.51303 +** rowid iRow is being replaced or deleted. In this case invalidate
 1.51304 +** only those incrblob cursors open on that specific row.
 1.51305 +*/
 1.51306 +static void invalidateIncrblobCursors(
 1.51307 +  Btree *pBtree,          /* The database file to check */
 1.51308 +  i64 iRow,               /* The rowid that might be changing */
 1.51309 +  int isClearTable        /* True if all rows are being deleted */
 1.51310 +){
 1.51311 +  BtCursor *p;
 1.51312 +  BtShared *pBt = pBtree->pBt;
 1.51313 +  assert( sqlite3BtreeHoldsMutex(pBtree) );
 1.51314 +  for(p=pBt->pCursor; p; p=p->pNext){
 1.51315 +    if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
 1.51316 +      p->eState = CURSOR_INVALID;
 1.51317 +    }
 1.51318 +  }
 1.51319 +}
 1.51320 +
 1.51321 +#else
 1.51322 +  /* Stub functions when INCRBLOB is omitted */
 1.51323 +  #define invalidateOverflowCache(x)
 1.51324 +  #define invalidateAllOverflowCache(x)
 1.51325 +  #define invalidateIncrblobCursors(x,y,z)
 1.51326 +#endif /* SQLITE_OMIT_INCRBLOB */
 1.51327 +
 1.51328 +/*
 1.51329 +** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
 1.51330 +** when a page that previously contained data becomes a free-list leaf 
 1.51331 +** page.
 1.51332 +**
 1.51333 +** The BtShared.pHasContent bitvec exists to work around an obscure
 1.51334 +** bug caused by the interaction of two useful IO optimizations surrounding
 1.51335 +** free-list leaf pages:
 1.51336 +**
 1.51337 +**   1) When all data is deleted from a page and the page becomes
 1.51338 +**      a free-list leaf page, the page is not written to the database
 1.51339 +**      (as free-list leaf pages contain no meaningful data). Sometimes
 1.51340 +**      such a page is not even journalled (as it will not be modified,
 1.51341 +**      why bother journalling it?).
 1.51342 +**
 1.51343 +**   2) When a free-list leaf page is reused, its content is not read
 1.51344 +**      from the database or written to the journal file (why should it
 1.51345 +**      be, if it is not at all meaningful?).
 1.51346 +**
 1.51347 +** By themselves, these optimizations work fine and provide a handy
 1.51348 +** performance boost to bulk delete or insert operations. However, if
 1.51349 +** a page is moved to the free-list and then reused within the same
 1.51350 +** transaction, a problem comes up. If the page is not journalled when
 1.51351 +** it is moved to the free-list and it is also not journalled when it
 1.51352 +** is extracted from the free-list and reused, then the original data
 1.51353 +** may be lost. In the event of a rollback, it may not be possible
 1.51354 +** to restore the database to its original configuration.
 1.51355 +**
 1.51356 +** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
 1.51357 +** moved to become a free-list leaf page, the corresponding bit is
 1.51358 +** set in the bitvec. Whenever a leaf page is extracted from the free-list,
 1.51359 +** optimization 2 above is omitted if the corresponding bit is already
 1.51360 +** set in BtShared.pHasContent. The contents of the bitvec are cleared
 1.51361 +** at the end of every transaction.
 1.51362 +*/
 1.51363 +static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
 1.51364 +  int rc = SQLITE_OK;
 1.51365 +  if( !pBt->pHasContent ){
 1.51366 +    assert( pgno<=pBt->nPage );
 1.51367 +    pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
 1.51368 +    if( !pBt->pHasContent ){
 1.51369 +      rc = SQLITE_NOMEM;
 1.51370 +    }
 1.51371 +  }
 1.51372 +  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
 1.51373 +    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
 1.51374 +  }
 1.51375 +  return rc;
 1.51376 +}
 1.51377 +
 1.51378 +/*
 1.51379 +** Query the BtShared.pHasContent vector.
 1.51380 +**
 1.51381 +** This function is called when a free-list leaf page is removed from the
 1.51382 +** free-list for reuse. It returns false if it is safe to retrieve the
 1.51383 +** page from the pager layer with the 'no-content' flag set. True otherwise.
 1.51384 +*/
 1.51385 +static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
 1.51386 +  Bitvec *p = pBt->pHasContent;
 1.51387 +  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
 1.51388 +}
 1.51389 +
 1.51390 +/*
 1.51391 +** Clear (destroy) the BtShared.pHasContent bitvec. This should be
 1.51392 +** invoked at the conclusion of each write-transaction.
 1.51393 +*/
 1.51394 +static void btreeClearHasContent(BtShared *pBt){
 1.51395 +  sqlite3BitvecDestroy(pBt->pHasContent);
 1.51396 +  pBt->pHasContent = 0;
 1.51397 +}
 1.51398 +
 1.51399 +/*
 1.51400 +** Release all of the apPage[] pages for a cursor.
 1.51401 +*/
 1.51402 +static void btreeReleaseAllCursorPages(BtCursor *pCur){
 1.51403 +  int i;
 1.51404 +  for(i=0; i<=pCur->iPage; i++){
 1.51405 +    releasePage(pCur->apPage[i]);
 1.51406 +    pCur->apPage[i] = 0;
 1.51407 +  }
 1.51408 +  pCur->iPage = -1;
 1.51409 +}
 1.51410 +
 1.51411 +
 1.51412 +/*
 1.51413 +** Save the current cursor position in the variables BtCursor.nKey 
 1.51414 +** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
 1.51415 +**
 1.51416 +** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
 1.51417 +** prior to calling this routine.  
 1.51418 +*/
 1.51419 +static int saveCursorPosition(BtCursor *pCur){
 1.51420 +  int rc;
 1.51421 +
 1.51422 +  assert( CURSOR_VALID==pCur->eState );
 1.51423 +  assert( 0==pCur->pKey );
 1.51424 +  assert( cursorHoldsMutex(pCur) );
 1.51425 +
 1.51426 +  rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
 1.51427 +  assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
 1.51428 +
 1.51429 +  /* If this is an intKey table, then the above call to BtreeKeySize()
 1.51430 +  ** stores the integer key in pCur->nKey. In this case this value is
 1.51431 +  ** all that is required. Otherwise, if pCur is not open on an intKey
 1.51432 +  ** table, then malloc space for and store the pCur->nKey bytes of key 
 1.51433 +  ** data.
 1.51434 +  */
 1.51435 +  if( 0==pCur->apPage[0]->intKey ){
 1.51436 +    void *pKey = sqlite3Malloc( (int)pCur->nKey );
 1.51437 +    if( pKey ){
 1.51438 +      rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
 1.51439 +      if( rc==SQLITE_OK ){
 1.51440 +        pCur->pKey = pKey;
 1.51441 +      }else{
 1.51442 +        sqlite3_free(pKey);
 1.51443 +      }
 1.51444 +    }else{
 1.51445 +      rc = SQLITE_NOMEM;
 1.51446 +    }
 1.51447 +  }
 1.51448 +  assert( !pCur->apPage[0]->intKey || !pCur->pKey );
 1.51449 +
 1.51450 +  if( rc==SQLITE_OK ){
 1.51451 +    btreeReleaseAllCursorPages(pCur);
 1.51452 +    pCur->eState = CURSOR_REQUIRESEEK;
 1.51453 +  }
 1.51454 +
 1.51455 +  invalidateOverflowCache(pCur);
 1.51456 +  return rc;
 1.51457 +}
 1.51458 +
 1.51459 +/*
 1.51460 +** Save the positions of all cursors (except pExcept) that are open on
 1.51461 +** the table  with root-page iRoot. Usually, this is called just before cursor
 1.51462 +** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
 1.51463 +*/
 1.51464 +static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
 1.51465 +  BtCursor *p;
 1.51466 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.51467 +  assert( pExcept==0 || pExcept->pBt==pBt );
 1.51468 +  for(p=pBt->pCursor; p; p=p->pNext){
 1.51469 +    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
 1.51470 +      if( p->eState==CURSOR_VALID ){
 1.51471 +        int rc = saveCursorPosition(p);
 1.51472 +        if( SQLITE_OK!=rc ){
 1.51473 +          return rc;
 1.51474 +        }
 1.51475 +      }else{
 1.51476 +        testcase( p->iPage>0 );
 1.51477 +        btreeReleaseAllCursorPages(p);
 1.51478 +      }
 1.51479 +    }
 1.51480 +  }
 1.51481 +  return SQLITE_OK;
 1.51482 +}
 1.51483 +
 1.51484 +/*
 1.51485 +** Clear the current cursor position.
 1.51486 +*/
 1.51487 +SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
 1.51488 +  assert( cursorHoldsMutex(pCur) );
 1.51489 +  sqlite3_free(pCur->pKey);
 1.51490 +  pCur->pKey = 0;
 1.51491 +  pCur->eState = CURSOR_INVALID;
 1.51492 +}
 1.51493 +
 1.51494 +/*
 1.51495 +** In this version of BtreeMoveto, pKey is a packed index record
 1.51496 +** such as is generated by the OP_MakeRecord opcode.  Unpack the
 1.51497 +** record and then call BtreeMovetoUnpacked() to do the work.
 1.51498 +*/
 1.51499 +static int btreeMoveto(
 1.51500 +  BtCursor *pCur,     /* Cursor open on the btree to be searched */
 1.51501 +  const void *pKey,   /* Packed key if the btree is an index */
 1.51502 +  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
 1.51503 +  int bias,           /* Bias search to the high end */
 1.51504 +  int *pRes           /* Write search results here */
 1.51505 +){
 1.51506 +  int rc;                    /* Status code */
 1.51507 +  UnpackedRecord *pIdxKey;   /* Unpacked index key */
 1.51508 +  char aSpace[200];          /* Temp space for pIdxKey - to avoid a malloc */
 1.51509 +  char *pFree = 0;
 1.51510 +
 1.51511 +  if( pKey ){
 1.51512 +    assert( nKey==(i64)(int)nKey );
 1.51513 +    pIdxKey = sqlite3VdbeAllocUnpackedRecord(
 1.51514 +        pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
 1.51515 +    );
 1.51516 +    if( pIdxKey==0 ) return SQLITE_NOMEM;
 1.51517 +    sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
 1.51518 +    if( pIdxKey->nField==0 ){
 1.51519 +      sqlite3DbFree(pCur->pKeyInfo->db, pFree);
 1.51520 +      return SQLITE_CORRUPT_BKPT;
 1.51521 +    }
 1.51522 +  }else{
 1.51523 +    pIdxKey = 0;
 1.51524 +  }
 1.51525 +  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
 1.51526 +  if( pFree ){
 1.51527 +    sqlite3DbFree(pCur->pKeyInfo->db, pFree);
 1.51528 +  }
 1.51529 +  return rc;
 1.51530 +}
 1.51531 +
 1.51532 +/*
 1.51533 +** Restore the cursor to the position it was in (or as close to as possible)
 1.51534 +** when saveCursorPosition() was called. Note that this call deletes the 
 1.51535 +** saved position info stored by saveCursorPosition(), so there can be
 1.51536 +** at most one effective restoreCursorPosition() call after each 
 1.51537 +** saveCursorPosition().
 1.51538 +*/
 1.51539 +static int btreeRestoreCursorPosition(BtCursor *pCur){
 1.51540 +  int rc;
 1.51541 +  assert( cursorHoldsMutex(pCur) );
 1.51542 +  assert( pCur->eState>=CURSOR_REQUIRESEEK );
 1.51543 +  if( pCur->eState==CURSOR_FAULT ){
 1.51544 +    return pCur->skipNext;
 1.51545 +  }
 1.51546 +  pCur->eState = CURSOR_INVALID;
 1.51547 +  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
 1.51548 +  if( rc==SQLITE_OK ){
 1.51549 +    sqlite3_free(pCur->pKey);
 1.51550 +    pCur->pKey = 0;
 1.51551 +    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
 1.51552 +    if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
 1.51553 +      pCur->eState = CURSOR_SKIPNEXT;
 1.51554 +    }
 1.51555 +  }
 1.51556 +  return rc;
 1.51557 +}
 1.51558 +
 1.51559 +#define restoreCursorPosition(p) \
 1.51560 +  (p->eState>=CURSOR_REQUIRESEEK ? \
 1.51561 +         btreeRestoreCursorPosition(p) : \
 1.51562 +         SQLITE_OK)
 1.51563 +
 1.51564 +/*
 1.51565 +** Determine whether or not a cursor has moved from the position it
 1.51566 +** was last placed at.  Cursors can move when the row they are pointing
 1.51567 +** at is deleted out from under them.
 1.51568 +**
 1.51569 +** This routine returns an error code if something goes wrong.  The
 1.51570 +** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
 1.51571 +*/
 1.51572 +SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
 1.51573 +  int rc;
 1.51574 +
 1.51575 +  rc = restoreCursorPosition(pCur);
 1.51576 +  if( rc ){
 1.51577 +    *pHasMoved = 1;
 1.51578 +    return rc;
 1.51579 +  }
 1.51580 +  if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){
 1.51581 +    *pHasMoved = 1;
 1.51582 +  }else{
 1.51583 +    *pHasMoved = 0;
 1.51584 +  }
 1.51585 +  return SQLITE_OK;
 1.51586 +}
 1.51587 +
 1.51588 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.51589 +/*
 1.51590 +** Given a page number of a regular database page, return the page
 1.51591 +** number for the pointer-map page that contains the entry for the
 1.51592 +** input page number.
 1.51593 +**
 1.51594 +** Return 0 (not a valid page) for pgno==1 since there is
 1.51595 +** no pointer map associated with page 1.  The integrity_check logic
 1.51596 +** requires that ptrmapPageno(*,1)!=1.
 1.51597 +*/
 1.51598 +static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
 1.51599 +  int nPagesPerMapPage;
 1.51600 +  Pgno iPtrMap, ret;
 1.51601 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.51602 +  if( pgno<2 ) return 0;
 1.51603 +  nPagesPerMapPage = (pBt->usableSize/5)+1;
 1.51604 +  iPtrMap = (pgno-2)/nPagesPerMapPage;
 1.51605 +  ret = (iPtrMap*nPagesPerMapPage) + 2; 
 1.51606 +  if( ret==PENDING_BYTE_PAGE(pBt) ){
 1.51607 +    ret++;
 1.51608 +  }
 1.51609 +  return ret;
 1.51610 +}
 1.51611 +
 1.51612 +/*
 1.51613 +** Write an entry into the pointer map.
 1.51614 +**
 1.51615 +** This routine updates the pointer map entry for page number 'key'
 1.51616 +** so that it maps to type 'eType' and parent page number 'pgno'.
 1.51617 +**
 1.51618 +** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
 1.51619 +** a no-op.  If an error occurs, the appropriate error code is written
 1.51620 +** into *pRC.
 1.51621 +*/
 1.51622 +static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
 1.51623 +  DbPage *pDbPage;  /* The pointer map page */
 1.51624 +  u8 *pPtrmap;      /* The pointer map data */
 1.51625 +  Pgno iPtrmap;     /* The pointer map page number */
 1.51626 +  int offset;       /* Offset in pointer map page */
 1.51627 +  int rc;           /* Return code from subfunctions */
 1.51628 +
 1.51629 +  if( *pRC ) return;
 1.51630 +
 1.51631 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.51632 +  /* The master-journal page number must never be used as a pointer map page */
 1.51633 +  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
 1.51634 +
 1.51635 +  assert( pBt->autoVacuum );
 1.51636 +  if( key==0 ){
 1.51637 +    *pRC = SQLITE_CORRUPT_BKPT;
 1.51638 +    return;
 1.51639 +  }
 1.51640 +  iPtrmap = PTRMAP_PAGENO(pBt, key);
 1.51641 +  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
 1.51642 +  if( rc!=SQLITE_OK ){
 1.51643 +    *pRC = rc;
 1.51644 +    return;
 1.51645 +  }
 1.51646 +  offset = PTRMAP_PTROFFSET(iPtrmap, key);
 1.51647 +  if( offset<0 ){
 1.51648 +    *pRC = SQLITE_CORRUPT_BKPT;
 1.51649 +    goto ptrmap_exit;
 1.51650 +  }
 1.51651 +  assert( offset <= (int)pBt->usableSize-5 );
 1.51652 +  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
 1.51653 +
 1.51654 +  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
 1.51655 +    TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
 1.51656 +    *pRC= rc = sqlite3PagerWrite(pDbPage);
 1.51657 +    if( rc==SQLITE_OK ){
 1.51658 +      pPtrmap[offset] = eType;
 1.51659 +      put4byte(&pPtrmap[offset+1], parent);
 1.51660 +    }
 1.51661 +  }
 1.51662 +
 1.51663 +ptrmap_exit:
 1.51664 +  sqlite3PagerUnref(pDbPage);
 1.51665 +}
 1.51666 +
 1.51667 +/*
 1.51668 +** Read an entry from the pointer map.
 1.51669 +**
 1.51670 +** This routine retrieves the pointer map entry for page 'key', writing
 1.51671 +** the type and parent page number to *pEType and *pPgno respectively.
 1.51672 +** An error code is returned if something goes wrong, otherwise SQLITE_OK.
 1.51673 +*/
 1.51674 +static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
 1.51675 +  DbPage *pDbPage;   /* The pointer map page */
 1.51676 +  int iPtrmap;       /* Pointer map page index */
 1.51677 +  u8 *pPtrmap;       /* Pointer map page data */
 1.51678 +  int offset;        /* Offset of entry in pointer map */
 1.51679 +  int rc;
 1.51680 +
 1.51681 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.51682 +
 1.51683 +  iPtrmap = PTRMAP_PAGENO(pBt, key);
 1.51684 +  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
 1.51685 +  if( rc!=0 ){
 1.51686 +    return rc;
 1.51687 +  }
 1.51688 +  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
 1.51689 +
 1.51690 +  offset = PTRMAP_PTROFFSET(iPtrmap, key);
 1.51691 +  if( offset<0 ){
 1.51692 +    sqlite3PagerUnref(pDbPage);
 1.51693 +    return SQLITE_CORRUPT_BKPT;
 1.51694 +  }
 1.51695 +  assert( offset <= (int)pBt->usableSize-5 );
 1.51696 +  assert( pEType!=0 );
 1.51697 +  *pEType = pPtrmap[offset];
 1.51698 +  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
 1.51699 +
 1.51700 +  sqlite3PagerUnref(pDbPage);
 1.51701 +  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
 1.51702 +  return SQLITE_OK;
 1.51703 +}
 1.51704 +
 1.51705 +#else /* if defined SQLITE_OMIT_AUTOVACUUM */
 1.51706 +  #define ptrmapPut(w,x,y,z,rc)
 1.51707 +  #define ptrmapGet(w,x,y,z) SQLITE_OK
 1.51708 +  #define ptrmapPutOvflPtr(x, y, rc)
 1.51709 +#endif
 1.51710 +
 1.51711 +/*
 1.51712 +** Given a btree page and a cell index (0 means the first cell on
 1.51713 +** the page, 1 means the second cell, and so forth) return a pointer
 1.51714 +** to the cell content.
 1.51715 +**
 1.51716 +** This routine works only for pages that do not contain overflow cells.
 1.51717 +*/
 1.51718 +#define findCell(P,I) \
 1.51719 +  ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
 1.51720 +#define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
 1.51721 +
 1.51722 +
 1.51723 +/*
 1.51724 +** This a more complex version of findCell() that works for
 1.51725 +** pages that do contain overflow cells.
 1.51726 +*/
 1.51727 +static u8 *findOverflowCell(MemPage *pPage, int iCell){
 1.51728 +  int i;
 1.51729 +  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 1.51730 +  for(i=pPage->nOverflow-1; i>=0; i--){
 1.51731 +    int k;
 1.51732 +    k = pPage->aiOvfl[i];
 1.51733 +    if( k<=iCell ){
 1.51734 +      if( k==iCell ){
 1.51735 +        return pPage->apOvfl[i];
 1.51736 +      }
 1.51737 +      iCell--;
 1.51738 +    }
 1.51739 +  }
 1.51740 +  return findCell(pPage, iCell);
 1.51741 +}
 1.51742 +
 1.51743 +/*
 1.51744 +** Parse a cell content block and fill in the CellInfo structure.  There
 1.51745 +** are two versions of this function.  btreeParseCell() takes a 
 1.51746 +** cell index as the second argument and btreeParseCellPtr() 
 1.51747 +** takes a pointer to the body of the cell as its second argument.
 1.51748 +**
 1.51749 +** Within this file, the parseCell() macro can be called instead of
 1.51750 +** btreeParseCellPtr(). Using some compilers, this will be faster.
 1.51751 +*/
 1.51752 +static void btreeParseCellPtr(
 1.51753 +  MemPage *pPage,         /* Page containing the cell */
 1.51754 +  u8 *pCell,              /* Pointer to the cell text. */
 1.51755 +  CellInfo *pInfo         /* Fill in this structure */
 1.51756 +){
 1.51757 +  u16 n;                  /* Number bytes in cell content header */
 1.51758 +  u32 nPayload;           /* Number of bytes of cell payload */
 1.51759 +
 1.51760 +  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 1.51761 +
 1.51762 +  pInfo->pCell = pCell;
 1.51763 +  assert( pPage->leaf==0 || pPage->leaf==1 );
 1.51764 +  n = pPage->childPtrSize;
 1.51765 +  assert( n==4-4*pPage->leaf );
 1.51766 +  if( pPage->intKey ){
 1.51767 +    if( pPage->hasData ){
 1.51768 +      assert( n==0 );
 1.51769 +      n = getVarint32(pCell, nPayload);
 1.51770 +    }else{
 1.51771 +      nPayload = 0;
 1.51772 +    }
 1.51773 +    n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
 1.51774 +    pInfo->nData = nPayload;
 1.51775 +  }else{
 1.51776 +    pInfo->nData = 0;
 1.51777 +    n += getVarint32(&pCell[n], nPayload);
 1.51778 +    pInfo->nKey = nPayload;
 1.51779 +  }
 1.51780 +  pInfo->nPayload = nPayload;
 1.51781 +  pInfo->nHeader = n;
 1.51782 +  testcase( nPayload==pPage->maxLocal );
 1.51783 +  testcase( nPayload==pPage->maxLocal+1 );
 1.51784 +  if( likely(nPayload<=pPage->maxLocal) ){
 1.51785 +    /* This is the (easy) common case where the entire payload fits
 1.51786 +    ** on the local page.  No overflow is required.
 1.51787 +    */
 1.51788 +    if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
 1.51789 +    pInfo->nLocal = (u16)nPayload;
 1.51790 +    pInfo->iOverflow = 0;
 1.51791 +  }else{
 1.51792 +    /* If the payload will not fit completely on the local page, we have
 1.51793 +    ** to decide how much to store locally and how much to spill onto
 1.51794 +    ** overflow pages.  The strategy is to minimize the amount of unused
 1.51795 +    ** space on overflow pages while keeping the amount of local storage
 1.51796 +    ** in between minLocal and maxLocal.
 1.51797 +    **
 1.51798 +    ** Warning:  changing the way overflow payload is distributed in any
 1.51799 +    ** way will result in an incompatible file format.
 1.51800 +    */
 1.51801 +    int minLocal;  /* Minimum amount of payload held locally */
 1.51802 +    int maxLocal;  /* Maximum amount of payload held locally */
 1.51803 +    int surplus;   /* Overflow payload available for local storage */
 1.51804 +
 1.51805 +    minLocal = pPage->minLocal;
 1.51806 +    maxLocal = pPage->maxLocal;
 1.51807 +    surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
 1.51808 +    testcase( surplus==maxLocal );
 1.51809 +    testcase( surplus==maxLocal+1 );
 1.51810 +    if( surplus <= maxLocal ){
 1.51811 +      pInfo->nLocal = (u16)surplus;
 1.51812 +    }else{
 1.51813 +      pInfo->nLocal = (u16)minLocal;
 1.51814 +    }
 1.51815 +    pInfo->iOverflow = (u16)(pInfo->nLocal + n);
 1.51816 +    pInfo->nSize = pInfo->iOverflow + 4;
 1.51817 +  }
 1.51818 +}
 1.51819 +#define parseCell(pPage, iCell, pInfo) \
 1.51820 +  btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
 1.51821 +static void btreeParseCell(
 1.51822 +  MemPage *pPage,         /* Page containing the cell */
 1.51823 +  int iCell,              /* The cell index.  First cell is 0 */
 1.51824 +  CellInfo *pInfo         /* Fill in this structure */
 1.51825 +){
 1.51826 +  parseCell(pPage, iCell, pInfo);
 1.51827 +}
 1.51828 +
 1.51829 +/*
 1.51830 +** Compute the total number of bytes that a Cell needs in the cell
 1.51831 +** data area of the btree-page.  The return number includes the cell
 1.51832 +** data header and the local payload, but not any overflow page or
 1.51833 +** the space used by the cell pointer.
 1.51834 +*/
 1.51835 +static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
 1.51836 +  u8 *pIter = &pCell[pPage->childPtrSize];
 1.51837 +  u32 nSize;
 1.51838 +
 1.51839 +#ifdef SQLITE_DEBUG
 1.51840 +  /* The value returned by this function should always be the same as
 1.51841 +  ** the (CellInfo.nSize) value found by doing a full parse of the
 1.51842 +  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
 1.51843 +  ** this function verifies that this invariant is not violated. */
 1.51844 +  CellInfo debuginfo;
 1.51845 +  btreeParseCellPtr(pPage, pCell, &debuginfo);
 1.51846 +#endif
 1.51847 +
 1.51848 +  if( pPage->intKey ){
 1.51849 +    u8 *pEnd;
 1.51850 +    if( pPage->hasData ){
 1.51851 +      pIter += getVarint32(pIter, nSize);
 1.51852 +    }else{
 1.51853 +      nSize = 0;
 1.51854 +    }
 1.51855 +
 1.51856 +    /* pIter now points at the 64-bit integer key value, a variable length 
 1.51857 +    ** integer. The following block moves pIter to point at the first byte
 1.51858 +    ** past the end of the key value. */
 1.51859 +    pEnd = &pIter[9];
 1.51860 +    while( (*pIter++)&0x80 && pIter<pEnd );
 1.51861 +  }else{
 1.51862 +    pIter += getVarint32(pIter, nSize);
 1.51863 +  }
 1.51864 +
 1.51865 +  testcase( nSize==pPage->maxLocal );
 1.51866 +  testcase( nSize==pPage->maxLocal+1 );
 1.51867 +  if( nSize>pPage->maxLocal ){
 1.51868 +    int minLocal = pPage->minLocal;
 1.51869 +    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
 1.51870 +    testcase( nSize==pPage->maxLocal );
 1.51871 +    testcase( nSize==pPage->maxLocal+1 );
 1.51872 +    if( nSize>pPage->maxLocal ){
 1.51873 +      nSize = minLocal;
 1.51874 +    }
 1.51875 +    nSize += 4;
 1.51876 +  }
 1.51877 +  nSize += (u32)(pIter - pCell);
 1.51878 +
 1.51879 +  /* The minimum size of any cell is 4 bytes. */
 1.51880 +  if( nSize<4 ){
 1.51881 +    nSize = 4;
 1.51882 +  }
 1.51883 +
 1.51884 +  assert( nSize==debuginfo.nSize );
 1.51885 +  return (u16)nSize;
 1.51886 +}
 1.51887 +
 1.51888 +#ifdef SQLITE_DEBUG
 1.51889 +/* This variation on cellSizePtr() is used inside of assert() statements
 1.51890 +** only. */
 1.51891 +static u16 cellSize(MemPage *pPage, int iCell){
 1.51892 +  return cellSizePtr(pPage, findCell(pPage, iCell));
 1.51893 +}
 1.51894 +#endif
 1.51895 +
 1.51896 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.51897 +/*
 1.51898 +** If the cell pCell, part of page pPage contains a pointer
 1.51899 +** to an overflow page, insert an entry into the pointer-map
 1.51900 +** for the overflow page.
 1.51901 +*/
 1.51902 +static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
 1.51903 +  CellInfo info;
 1.51904 +  if( *pRC ) return;
 1.51905 +  assert( pCell!=0 );
 1.51906 +  btreeParseCellPtr(pPage, pCell, &info);
 1.51907 +  assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
 1.51908 +  if( info.iOverflow ){
 1.51909 +    Pgno ovfl = get4byte(&pCell[info.iOverflow]);
 1.51910 +    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
 1.51911 +  }
 1.51912 +}
 1.51913 +#endif
 1.51914 +
 1.51915 +
 1.51916 +/*
 1.51917 +** Defragment the page given.  All Cells are moved to the
 1.51918 +** end of the page and all free space is collected into one
 1.51919 +** big FreeBlk that occurs in between the header and cell
 1.51920 +** pointer array and the cell content area.
 1.51921 +*/
 1.51922 +static int defragmentPage(MemPage *pPage){
 1.51923 +  int i;                     /* Loop counter */
 1.51924 +  int pc;                    /* Address of a i-th cell */
 1.51925 +  int hdr;                   /* Offset to the page header */
 1.51926 +  int size;                  /* Size of a cell */
 1.51927 +  int usableSize;            /* Number of usable bytes on a page */
 1.51928 +  int cellOffset;            /* Offset to the cell pointer array */
 1.51929 +  int cbrk;                  /* Offset to the cell content area */
 1.51930 +  int nCell;                 /* Number of cells on the page */
 1.51931 +  unsigned char *data;       /* The page data */
 1.51932 +  unsigned char *temp;       /* Temp area for cell content */
 1.51933 +  int iCellFirst;            /* First allowable cell index */
 1.51934 +  int iCellLast;             /* Last possible cell index */
 1.51935 +
 1.51936 +
 1.51937 +  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 1.51938 +  assert( pPage->pBt!=0 );
 1.51939 +  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
 1.51940 +  assert( pPage->nOverflow==0 );
 1.51941 +  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 1.51942 +  temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
 1.51943 +  data = pPage->aData;
 1.51944 +  hdr = pPage->hdrOffset;
 1.51945 +  cellOffset = pPage->cellOffset;
 1.51946 +  nCell = pPage->nCell;
 1.51947 +  assert( nCell==get2byte(&data[hdr+3]) );
 1.51948 +  usableSize = pPage->pBt->usableSize;
 1.51949 +  cbrk = get2byte(&data[hdr+5]);
 1.51950 +  memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
 1.51951 +  cbrk = usableSize;
 1.51952 +  iCellFirst = cellOffset + 2*nCell;
 1.51953 +  iCellLast = usableSize - 4;
 1.51954 +  for(i=0; i<nCell; i++){
 1.51955 +    u8 *pAddr;     /* The i-th cell pointer */
 1.51956 +    pAddr = &data[cellOffset + i*2];
 1.51957 +    pc = get2byte(pAddr);
 1.51958 +    testcase( pc==iCellFirst );
 1.51959 +    testcase( pc==iCellLast );
 1.51960 +#if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
 1.51961 +    /* These conditions have already been verified in btreeInitPage()
 1.51962 +    ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined 
 1.51963 +    */
 1.51964 +    if( pc<iCellFirst || pc>iCellLast ){
 1.51965 +      return SQLITE_CORRUPT_BKPT;
 1.51966 +    }
 1.51967 +#endif
 1.51968 +    assert( pc>=iCellFirst && pc<=iCellLast );
 1.51969 +    size = cellSizePtr(pPage, &temp[pc]);
 1.51970 +    cbrk -= size;
 1.51971 +#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
 1.51972 +    if( cbrk<iCellFirst ){
 1.51973 +      return SQLITE_CORRUPT_BKPT;
 1.51974 +    }
 1.51975 +#else
 1.51976 +    if( cbrk<iCellFirst || pc+size>usableSize ){
 1.51977 +      return SQLITE_CORRUPT_BKPT;
 1.51978 +    }
 1.51979 +#endif
 1.51980 +    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
 1.51981 +    testcase( cbrk+size==usableSize );
 1.51982 +    testcase( pc+size==usableSize );
 1.51983 +    memcpy(&data[cbrk], &temp[pc], size);
 1.51984 +    put2byte(pAddr, cbrk);
 1.51985 +  }
 1.51986 +  assert( cbrk>=iCellFirst );
 1.51987 +  put2byte(&data[hdr+5], cbrk);
 1.51988 +  data[hdr+1] = 0;
 1.51989 +  data[hdr+2] = 0;
 1.51990 +  data[hdr+7] = 0;
 1.51991 +  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
 1.51992 +  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 1.51993 +  if( cbrk-iCellFirst!=pPage->nFree ){
 1.51994 +    return SQLITE_CORRUPT_BKPT;
 1.51995 +  }
 1.51996 +  return SQLITE_OK;
 1.51997 +}
 1.51998 +
 1.51999 +/*
 1.52000 +** Allocate nByte bytes of space from within the B-Tree page passed
 1.52001 +** as the first argument. Write into *pIdx the index into pPage->aData[]
 1.52002 +** of the first byte of allocated space. Return either SQLITE_OK or
 1.52003 +** an error code (usually SQLITE_CORRUPT).
 1.52004 +**
 1.52005 +** The caller guarantees that there is sufficient space to make the
 1.52006 +** allocation.  This routine might need to defragment in order to bring
 1.52007 +** all the space together, however.  This routine will avoid using
 1.52008 +** the first two bytes past the cell pointer area since presumably this
 1.52009 +** allocation is being made in order to insert a new cell, so we will
 1.52010 +** also end up needing a new cell pointer.
 1.52011 +*/
 1.52012 +static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
 1.52013 +  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
 1.52014 +  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
 1.52015 +  int nFrag;                           /* Number of fragmented bytes on pPage */
 1.52016 +  int top;                             /* First byte of cell content area */
 1.52017 +  int gap;        /* First byte of gap between cell pointers and cell content */
 1.52018 +  int rc;         /* Integer return code */
 1.52019 +  int usableSize; /* Usable size of the page */
 1.52020 +  
 1.52021 +  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 1.52022 +  assert( pPage->pBt );
 1.52023 +  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 1.52024 +  assert( nByte>=0 );  /* Minimum cell size is 4 */
 1.52025 +  assert( pPage->nFree>=nByte );
 1.52026 +  assert( pPage->nOverflow==0 );
 1.52027 +  usableSize = pPage->pBt->usableSize;
 1.52028 +  assert( nByte < usableSize-8 );
 1.52029 +
 1.52030 +  nFrag = data[hdr+7];
 1.52031 +  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
 1.52032 +  gap = pPage->cellOffset + 2*pPage->nCell;
 1.52033 +  top = get2byteNotZero(&data[hdr+5]);
 1.52034 +  if( gap>top ) return SQLITE_CORRUPT_BKPT;
 1.52035 +  testcase( gap+2==top );
 1.52036 +  testcase( gap+1==top );
 1.52037 +  testcase( gap==top );
 1.52038 +
 1.52039 +  if( nFrag>=60 ){
 1.52040 +    /* Always defragment highly fragmented pages */
 1.52041 +    rc = defragmentPage(pPage);
 1.52042 +    if( rc ) return rc;
 1.52043 +    top = get2byteNotZero(&data[hdr+5]);
 1.52044 +  }else if( gap+2<=top ){
 1.52045 +    /* Search the freelist looking for a free slot big enough to satisfy 
 1.52046 +    ** the request. The allocation is made from the first free slot in 
 1.52047 +    ** the list that is large enough to accommodate it.
 1.52048 +    */
 1.52049 +    int pc, addr;
 1.52050 +    for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
 1.52051 +      int size;            /* Size of the free slot */
 1.52052 +      if( pc>usableSize-4 || pc<addr+4 ){
 1.52053 +        return SQLITE_CORRUPT_BKPT;
 1.52054 +      }
 1.52055 +      size = get2byte(&data[pc+2]);
 1.52056 +      if( size>=nByte ){
 1.52057 +        int x = size - nByte;
 1.52058 +        testcase( x==4 );
 1.52059 +        testcase( x==3 );
 1.52060 +        if( x<4 ){
 1.52061 +          /* Remove the slot from the free-list. Update the number of
 1.52062 +          ** fragmented bytes within the page. */
 1.52063 +          memcpy(&data[addr], &data[pc], 2);
 1.52064 +          data[hdr+7] = (u8)(nFrag + x);
 1.52065 +        }else if( size+pc > usableSize ){
 1.52066 +          return SQLITE_CORRUPT_BKPT;
 1.52067 +        }else{
 1.52068 +          /* The slot remains on the free-list. Reduce its size to account
 1.52069 +          ** for the portion used by the new allocation. */
 1.52070 +          put2byte(&data[pc+2], x);
 1.52071 +        }
 1.52072 +        *pIdx = pc + x;
 1.52073 +        return SQLITE_OK;
 1.52074 +      }
 1.52075 +    }
 1.52076 +  }
 1.52077 +
 1.52078 +  /* Check to make sure there is enough space in the gap to satisfy
 1.52079 +  ** the allocation.  If not, defragment.
 1.52080 +  */
 1.52081 +  testcase( gap+2+nByte==top );
 1.52082 +  if( gap+2+nByte>top ){
 1.52083 +    rc = defragmentPage(pPage);
 1.52084 +    if( rc ) return rc;
 1.52085 +    top = get2byteNotZero(&data[hdr+5]);
 1.52086 +    assert( gap+nByte<=top );
 1.52087 +  }
 1.52088 +
 1.52089 +
 1.52090 +  /* Allocate memory from the gap in between the cell pointer array
 1.52091 +  ** and the cell content area.  The btreeInitPage() call has already
 1.52092 +  ** validated the freelist.  Given that the freelist is valid, there
 1.52093 +  ** is no way that the allocation can extend off the end of the page.
 1.52094 +  ** The assert() below verifies the previous sentence.
 1.52095 +  */
 1.52096 +  top -= nByte;
 1.52097 +  put2byte(&data[hdr+5], top);
 1.52098 +  assert( top+nByte <= (int)pPage->pBt->usableSize );
 1.52099 +  *pIdx = top;
 1.52100 +  return SQLITE_OK;
 1.52101 +}
 1.52102 +
 1.52103 +/*
 1.52104 +** Return a section of the pPage->aData to the freelist.
 1.52105 +** The first byte of the new free block is pPage->aDisk[start]
 1.52106 +** and the size of the block is "size" bytes.
 1.52107 +**
 1.52108 +** Most of the effort here is involved in coalesing adjacent
 1.52109 +** free blocks into a single big free block.
 1.52110 +*/
 1.52111 +static int freeSpace(MemPage *pPage, int start, int size){
 1.52112 +  int addr, pbegin, hdr;
 1.52113 +  int iLast;                        /* Largest possible freeblock offset */
 1.52114 +  unsigned char *data = pPage->aData;
 1.52115 +
 1.52116 +  assert( pPage->pBt!=0 );
 1.52117 +  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 1.52118 +  assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
 1.52119 +  assert( (start + size) <= (int)pPage->pBt->usableSize );
 1.52120 +  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 1.52121 +  assert( size>=0 );   /* Minimum cell size is 4 */
 1.52122 +
 1.52123 +  if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
 1.52124 +    /* Overwrite deleted information with zeros when the secure_delete
 1.52125 +    ** option is enabled */
 1.52126 +    memset(&data[start], 0, size);
 1.52127 +  }
 1.52128 +
 1.52129 +  /* Add the space back into the linked list of freeblocks.  Note that
 1.52130 +  ** even though the freeblock list was checked by btreeInitPage(),
 1.52131 +  ** btreeInitPage() did not detect overlapping cells or
 1.52132 +  ** freeblocks that overlapped cells.   Nor does it detect when the
 1.52133 +  ** cell content area exceeds the value in the page header.  If these
 1.52134 +  ** situations arise, then subsequent insert operations might corrupt
 1.52135 +  ** the freelist.  So we do need to check for corruption while scanning
 1.52136 +  ** the freelist.
 1.52137 +  */
 1.52138 +  hdr = pPage->hdrOffset;
 1.52139 +  addr = hdr + 1;
 1.52140 +  iLast = pPage->pBt->usableSize - 4;
 1.52141 +  assert( start<=iLast );
 1.52142 +  while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
 1.52143 +    if( pbegin<addr+4 ){
 1.52144 +      return SQLITE_CORRUPT_BKPT;
 1.52145 +    }
 1.52146 +    addr = pbegin;
 1.52147 +  }
 1.52148 +  if( pbegin>iLast ){
 1.52149 +    return SQLITE_CORRUPT_BKPT;
 1.52150 +  }
 1.52151 +  assert( pbegin>addr || pbegin==0 );
 1.52152 +  put2byte(&data[addr], start);
 1.52153 +  put2byte(&data[start], pbegin);
 1.52154 +  put2byte(&data[start+2], size);
 1.52155 +  pPage->nFree = pPage->nFree + (u16)size;
 1.52156 +
 1.52157 +  /* Coalesce adjacent free blocks */
 1.52158 +  addr = hdr + 1;
 1.52159 +  while( (pbegin = get2byte(&data[addr]))>0 ){
 1.52160 +    int pnext, psize, x;
 1.52161 +    assert( pbegin>addr );
 1.52162 +    assert( pbegin <= (int)pPage->pBt->usableSize-4 );
 1.52163 +    pnext = get2byte(&data[pbegin]);
 1.52164 +    psize = get2byte(&data[pbegin+2]);
 1.52165 +    if( pbegin + psize + 3 >= pnext && pnext>0 ){
 1.52166 +      int frag = pnext - (pbegin+psize);
 1.52167 +      if( (frag<0) || (frag>(int)data[hdr+7]) ){
 1.52168 +        return SQLITE_CORRUPT_BKPT;
 1.52169 +      }
 1.52170 +      data[hdr+7] -= (u8)frag;
 1.52171 +      x = get2byte(&data[pnext]);
 1.52172 +      put2byte(&data[pbegin], x);
 1.52173 +      x = pnext + get2byte(&data[pnext+2]) - pbegin;
 1.52174 +      put2byte(&data[pbegin+2], x);
 1.52175 +    }else{
 1.52176 +      addr = pbegin;
 1.52177 +    }
 1.52178 +  }
 1.52179 +
 1.52180 +  /* If the cell content area begins with a freeblock, remove it. */
 1.52181 +  if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
 1.52182 +    int top;
 1.52183 +    pbegin = get2byte(&data[hdr+1]);
 1.52184 +    memcpy(&data[hdr+1], &data[pbegin], 2);
 1.52185 +    top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
 1.52186 +    put2byte(&data[hdr+5], top);
 1.52187 +  }
 1.52188 +  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 1.52189 +  return SQLITE_OK;
 1.52190 +}
 1.52191 +
 1.52192 +/*
 1.52193 +** Decode the flags byte (the first byte of the header) for a page
 1.52194 +** and initialize fields of the MemPage structure accordingly.
 1.52195 +**
 1.52196 +** Only the following combinations are supported.  Anything different
 1.52197 +** indicates a corrupt database files:
 1.52198 +**
 1.52199 +**         PTF_ZERODATA
 1.52200 +**         PTF_ZERODATA | PTF_LEAF
 1.52201 +**         PTF_LEAFDATA | PTF_INTKEY
 1.52202 +**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
 1.52203 +*/
 1.52204 +static int decodeFlags(MemPage *pPage, int flagByte){
 1.52205 +  BtShared *pBt;     /* A copy of pPage->pBt */
 1.52206 +
 1.52207 +  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
 1.52208 +  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 1.52209 +  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
 1.52210 +  flagByte &= ~PTF_LEAF;
 1.52211 +  pPage->childPtrSize = 4-4*pPage->leaf;
 1.52212 +  pBt = pPage->pBt;
 1.52213 +  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
 1.52214 +    pPage->intKey = 1;
 1.52215 +    pPage->hasData = pPage->leaf;
 1.52216 +    pPage->maxLocal = pBt->maxLeaf;
 1.52217 +    pPage->minLocal = pBt->minLeaf;
 1.52218 +  }else if( flagByte==PTF_ZERODATA ){
 1.52219 +    pPage->intKey = 0;
 1.52220 +    pPage->hasData = 0;
 1.52221 +    pPage->maxLocal = pBt->maxLocal;
 1.52222 +    pPage->minLocal = pBt->minLocal;
 1.52223 +  }else{
 1.52224 +    return SQLITE_CORRUPT_BKPT;
 1.52225 +  }
 1.52226 +  pPage->max1bytePayload = pBt->max1bytePayload;
 1.52227 +  return SQLITE_OK;
 1.52228 +}
 1.52229 +
 1.52230 +/*
 1.52231 +** Initialize the auxiliary information for a disk block.
 1.52232 +**
 1.52233 +** Return SQLITE_OK on success.  If we see that the page does
 1.52234 +** not contain a well-formed database page, then return 
 1.52235 +** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
 1.52236 +** guarantee that the page is well-formed.  It only shows that
 1.52237 +** we failed to detect any corruption.
 1.52238 +*/
 1.52239 +static int btreeInitPage(MemPage *pPage){
 1.52240 +
 1.52241 +  assert( pPage->pBt!=0 );
 1.52242 +  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 1.52243 +  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
 1.52244 +  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
 1.52245 +  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
 1.52246 +
 1.52247 +  if( !pPage->isInit ){
 1.52248 +    u16 pc;            /* Address of a freeblock within pPage->aData[] */
 1.52249 +    u8 hdr;            /* Offset to beginning of page header */
 1.52250 +    u8 *data;          /* Equal to pPage->aData */
 1.52251 +    BtShared *pBt;        /* The main btree structure */
 1.52252 +    int usableSize;    /* Amount of usable space on each page */
 1.52253 +    u16 cellOffset;    /* Offset from start of page to first cell pointer */
 1.52254 +    int nFree;         /* Number of unused bytes on the page */
 1.52255 +    int top;           /* First byte of the cell content area */
 1.52256 +    int iCellFirst;    /* First allowable cell or freeblock offset */
 1.52257 +    int iCellLast;     /* Last possible cell or freeblock offset */
 1.52258 +
 1.52259 +    pBt = pPage->pBt;
 1.52260 +
 1.52261 +    hdr = pPage->hdrOffset;
 1.52262 +    data = pPage->aData;
 1.52263 +    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
 1.52264 +    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
 1.52265 +    pPage->maskPage = (u16)(pBt->pageSize - 1);
 1.52266 +    pPage->nOverflow = 0;
 1.52267 +    usableSize = pBt->usableSize;
 1.52268 +    pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
 1.52269 +    pPage->aDataEnd = &data[usableSize];
 1.52270 +    pPage->aCellIdx = &data[cellOffset];
 1.52271 +    top = get2byteNotZero(&data[hdr+5]);
 1.52272 +    pPage->nCell = get2byte(&data[hdr+3]);
 1.52273 +    if( pPage->nCell>MX_CELL(pBt) ){
 1.52274 +      /* To many cells for a single page.  The page must be corrupt */
 1.52275 +      return SQLITE_CORRUPT_BKPT;
 1.52276 +    }
 1.52277 +    testcase( pPage->nCell==MX_CELL(pBt) );
 1.52278 +
 1.52279 +    /* A malformed database page might cause us to read past the end
 1.52280 +    ** of page when parsing a cell.  
 1.52281 +    **
 1.52282 +    ** The following block of code checks early to see if a cell extends
 1.52283 +    ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
 1.52284 +    ** returned if it does.
 1.52285 +    */
 1.52286 +    iCellFirst = cellOffset + 2*pPage->nCell;
 1.52287 +    iCellLast = usableSize - 4;
 1.52288 +#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
 1.52289 +    {
 1.52290 +      int i;            /* Index into the cell pointer array */
 1.52291 +      int sz;           /* Size of a cell */
 1.52292 +
 1.52293 +      if( !pPage->leaf ) iCellLast--;
 1.52294 +      for(i=0; i<pPage->nCell; i++){
 1.52295 +        pc = get2byte(&data[cellOffset+i*2]);
 1.52296 +        testcase( pc==iCellFirst );
 1.52297 +        testcase( pc==iCellLast );
 1.52298 +        if( pc<iCellFirst || pc>iCellLast ){
 1.52299 +          return SQLITE_CORRUPT_BKPT;
 1.52300 +        }
 1.52301 +        sz = cellSizePtr(pPage, &data[pc]);
 1.52302 +        testcase( pc+sz==usableSize );
 1.52303 +        if( pc+sz>usableSize ){
 1.52304 +          return SQLITE_CORRUPT_BKPT;
 1.52305 +        }
 1.52306 +      }
 1.52307 +      if( !pPage->leaf ) iCellLast++;
 1.52308 +    }  
 1.52309 +#endif
 1.52310 +
 1.52311 +    /* Compute the total free space on the page */
 1.52312 +    pc = get2byte(&data[hdr+1]);
 1.52313 +    nFree = data[hdr+7] + top;
 1.52314 +    while( pc>0 ){
 1.52315 +      u16 next, size;
 1.52316 +      if( pc<iCellFirst || pc>iCellLast ){
 1.52317 +        /* Start of free block is off the page */
 1.52318 +        return SQLITE_CORRUPT_BKPT; 
 1.52319 +      }
 1.52320 +      next = get2byte(&data[pc]);
 1.52321 +      size = get2byte(&data[pc+2]);
 1.52322 +      if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
 1.52323 +        /* Free blocks must be in ascending order. And the last byte of
 1.52324 +        ** the free-block must lie on the database page.  */
 1.52325 +        return SQLITE_CORRUPT_BKPT; 
 1.52326 +      }
 1.52327 +      nFree = nFree + size;
 1.52328 +      pc = next;
 1.52329 +    }
 1.52330 +
 1.52331 +    /* At this point, nFree contains the sum of the offset to the start
 1.52332 +    ** of the cell-content area plus the number of free bytes within
 1.52333 +    ** the cell-content area. If this is greater than the usable-size
 1.52334 +    ** of the page, then the page must be corrupted. This check also
 1.52335 +    ** serves to verify that the offset to the start of the cell-content
 1.52336 +    ** area, according to the page header, lies within the page.
 1.52337 +    */
 1.52338 +    if( nFree>usableSize ){
 1.52339 +      return SQLITE_CORRUPT_BKPT; 
 1.52340 +    }
 1.52341 +    pPage->nFree = (u16)(nFree - iCellFirst);
 1.52342 +    pPage->isInit = 1;
 1.52343 +  }
 1.52344 +  return SQLITE_OK;
 1.52345 +}
 1.52346 +
 1.52347 +/*
 1.52348 +** Set up a raw page so that it looks like a database page holding
 1.52349 +** no entries.
 1.52350 +*/
 1.52351 +static void zeroPage(MemPage *pPage, int flags){
 1.52352 +  unsigned char *data = pPage->aData;
 1.52353 +  BtShared *pBt = pPage->pBt;
 1.52354 +  u8 hdr = pPage->hdrOffset;
 1.52355 +  u16 first;
 1.52356 +
 1.52357 +  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
 1.52358 +  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
 1.52359 +  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
 1.52360 +  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 1.52361 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.52362 +  if( pBt->btsFlags & BTS_SECURE_DELETE ){
 1.52363 +    memset(&data[hdr], 0, pBt->usableSize - hdr);
 1.52364 +  }
 1.52365 +  data[hdr] = (char)flags;
 1.52366 +  first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
 1.52367 +  memset(&data[hdr+1], 0, 4);
 1.52368 +  data[hdr+7] = 0;
 1.52369 +  put2byte(&data[hdr+5], pBt->usableSize);
 1.52370 +  pPage->nFree = (u16)(pBt->usableSize - first);
 1.52371 +  decodeFlags(pPage, flags);
 1.52372 +  pPage->cellOffset = first;
 1.52373 +  pPage->aDataEnd = &data[pBt->usableSize];
 1.52374 +  pPage->aCellIdx = &data[first];
 1.52375 +  pPage->nOverflow = 0;
 1.52376 +  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
 1.52377 +  pPage->maskPage = (u16)(pBt->pageSize - 1);
 1.52378 +  pPage->nCell = 0;
 1.52379 +  pPage->isInit = 1;
 1.52380 +}
 1.52381 +
 1.52382 +
 1.52383 +/*
 1.52384 +** Convert a DbPage obtained from the pager into a MemPage used by
 1.52385 +** the btree layer.
 1.52386 +*/
 1.52387 +static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
 1.52388 +  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
 1.52389 +  pPage->aData = sqlite3PagerGetData(pDbPage);
 1.52390 +  pPage->pDbPage = pDbPage;
 1.52391 +  pPage->pBt = pBt;
 1.52392 +  pPage->pgno = pgno;
 1.52393 +  pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
 1.52394 +  return pPage; 
 1.52395 +}
 1.52396 +
 1.52397 +/*
 1.52398 +** Get a page from the pager.  Initialize the MemPage.pBt and
 1.52399 +** MemPage.aData elements if needed.
 1.52400 +**
 1.52401 +** If the noContent flag is set, it means that we do not care about
 1.52402 +** the content of the page at this time.  So do not go to the disk
 1.52403 +** to fetch the content.  Just fill in the content with zeros for now.
 1.52404 +** If in the future we call sqlite3PagerWrite() on this page, that
 1.52405 +** means we have started to be concerned about content and the disk
 1.52406 +** read should occur at that point.
 1.52407 +*/
 1.52408 +static int btreeGetPage(
 1.52409 +  BtShared *pBt,       /* The btree */
 1.52410 +  Pgno pgno,           /* Number of the page to fetch */
 1.52411 +  MemPage **ppPage,    /* Return the page in this parameter */
 1.52412 +  int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
 1.52413 +){
 1.52414 +  int rc;
 1.52415 +  DbPage *pDbPage;
 1.52416 +
 1.52417 +  assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
 1.52418 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.52419 +  rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
 1.52420 +  if( rc ) return rc;
 1.52421 +  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
 1.52422 +  return SQLITE_OK;
 1.52423 +}
 1.52424 +
 1.52425 +/*
 1.52426 +** Retrieve a page from the pager cache. If the requested page is not
 1.52427 +** already in the pager cache return NULL. Initialize the MemPage.pBt and
 1.52428 +** MemPage.aData elements if needed.
 1.52429 +*/
 1.52430 +static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
 1.52431 +  DbPage *pDbPage;
 1.52432 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.52433 +  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
 1.52434 +  if( pDbPage ){
 1.52435 +    return btreePageFromDbPage(pDbPage, pgno, pBt);
 1.52436 +  }
 1.52437 +  return 0;
 1.52438 +}
 1.52439 +
 1.52440 +/*
 1.52441 +** Return the size of the database file in pages. If there is any kind of
 1.52442 +** error, return ((unsigned int)-1).
 1.52443 +*/
 1.52444 +static Pgno btreePagecount(BtShared *pBt){
 1.52445 +  return pBt->nPage;
 1.52446 +}
 1.52447 +SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
 1.52448 +  assert( sqlite3BtreeHoldsMutex(p) );
 1.52449 +  assert( ((p->pBt->nPage)&0x8000000)==0 );
 1.52450 +  return (int)btreePagecount(p->pBt);
 1.52451 +}
 1.52452 +
 1.52453 +/*
 1.52454 +** Get a page from the pager and initialize it.  This routine is just a
 1.52455 +** convenience wrapper around separate calls to btreeGetPage() and 
 1.52456 +** btreeInitPage().
 1.52457 +**
 1.52458 +** If an error occurs, then the value *ppPage is set to is undefined. It
 1.52459 +** may remain unchanged, or it may be set to an invalid value.
 1.52460 +*/
 1.52461 +static int getAndInitPage(
 1.52462 +  BtShared *pBt,                  /* The database file */
 1.52463 +  Pgno pgno,                      /* Number of the page to get */
 1.52464 +  MemPage **ppPage,               /* Write the page pointer here */
 1.52465 +  int bReadonly                   /* PAGER_GET_READONLY or 0 */
 1.52466 +){
 1.52467 +  int rc;
 1.52468 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.52469 +  assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
 1.52470 +
 1.52471 +  if( pgno>btreePagecount(pBt) ){
 1.52472 +    rc = SQLITE_CORRUPT_BKPT;
 1.52473 +  }else{
 1.52474 +    rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
 1.52475 +    if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
 1.52476 +      rc = btreeInitPage(*ppPage);
 1.52477 +      if( rc!=SQLITE_OK ){
 1.52478 +        releasePage(*ppPage);
 1.52479 +      }
 1.52480 +    }
 1.52481 +  }
 1.52482 +
 1.52483 +  testcase( pgno==0 );
 1.52484 +  assert( pgno!=0 || rc==SQLITE_CORRUPT );
 1.52485 +  return rc;
 1.52486 +}
 1.52487 +
 1.52488 +/*
 1.52489 +** Release a MemPage.  This should be called once for each prior
 1.52490 +** call to btreeGetPage.
 1.52491 +*/
 1.52492 +static void releasePage(MemPage *pPage){
 1.52493 +  if( pPage ){
 1.52494 +    assert( pPage->aData );
 1.52495 +    assert( pPage->pBt );
 1.52496 +    assert( pPage->pDbPage!=0 );
 1.52497 +    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
 1.52498 +    assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
 1.52499 +    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 1.52500 +    sqlite3PagerUnrefNotNull(pPage->pDbPage);
 1.52501 +  }
 1.52502 +}
 1.52503 +
 1.52504 +/*
 1.52505 +** During a rollback, when the pager reloads information into the cache
 1.52506 +** so that the cache is restored to its original state at the start of
 1.52507 +** the transaction, for each page restored this routine is called.
 1.52508 +**
 1.52509 +** This routine needs to reset the extra data section at the end of the
 1.52510 +** page to agree with the restored data.
 1.52511 +*/
 1.52512 +static void pageReinit(DbPage *pData){
 1.52513 +  MemPage *pPage;
 1.52514 +  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
 1.52515 +  assert( sqlite3PagerPageRefcount(pData)>0 );
 1.52516 +  if( pPage->isInit ){
 1.52517 +    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 1.52518 +    pPage->isInit = 0;
 1.52519 +    if( sqlite3PagerPageRefcount(pData)>1 ){
 1.52520 +      /* pPage might not be a btree page;  it might be an overflow page
 1.52521 +      ** or ptrmap page or a free page.  In those cases, the following
 1.52522 +      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
 1.52523 +      ** But no harm is done by this.  And it is very important that
 1.52524 +      ** btreeInitPage() be called on every btree page so we make
 1.52525 +      ** the call for every page that comes in for re-initing. */
 1.52526 +      btreeInitPage(pPage);
 1.52527 +    }
 1.52528 +  }
 1.52529 +}
 1.52530 +
 1.52531 +/*
 1.52532 +** Invoke the busy handler for a btree.
 1.52533 +*/
 1.52534 +static int btreeInvokeBusyHandler(void *pArg){
 1.52535 +  BtShared *pBt = (BtShared*)pArg;
 1.52536 +  assert( pBt->db );
 1.52537 +  assert( sqlite3_mutex_held(pBt->db->mutex) );
 1.52538 +  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
 1.52539 +}
 1.52540 +
 1.52541 +/*
 1.52542 +** Open a database file.
 1.52543 +** 
 1.52544 +** zFilename is the name of the database file.  If zFilename is NULL
 1.52545 +** then an ephemeral database is created.  The ephemeral database might
 1.52546 +** be exclusively in memory, or it might use a disk-based memory cache.
 1.52547 +** Either way, the ephemeral database will be automatically deleted 
 1.52548 +** when sqlite3BtreeClose() is called.
 1.52549 +**
 1.52550 +** If zFilename is ":memory:" then an in-memory database is created
 1.52551 +** that is automatically destroyed when it is closed.
 1.52552 +**
 1.52553 +** The "flags" parameter is a bitmask that might contain bits like
 1.52554 +** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
 1.52555 +**
 1.52556 +** If the database is already opened in the same database connection
 1.52557 +** and we are in shared cache mode, then the open will fail with an
 1.52558 +** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
 1.52559 +** objects in the same database connection since doing so will lead
 1.52560 +** to problems with locking.
 1.52561 +*/
 1.52562 +SQLITE_PRIVATE int sqlite3BtreeOpen(
 1.52563 +  sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
 1.52564 +  const char *zFilename,  /* Name of the file containing the BTree database */
 1.52565 +  sqlite3 *db,            /* Associated database handle */
 1.52566 +  Btree **ppBtree,        /* Pointer to new Btree object written here */
 1.52567 +  int flags,              /* Options */
 1.52568 +  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
 1.52569 +){
 1.52570 +  BtShared *pBt = 0;             /* Shared part of btree structure */
 1.52571 +  Btree *p;                      /* Handle to return */
 1.52572 +  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
 1.52573 +  int rc = SQLITE_OK;            /* Result code from this function */
 1.52574 +  u8 nReserve;                   /* Byte of unused space on each page */
 1.52575 +  unsigned char zDbHeader[100];  /* Database header content */
 1.52576 +
 1.52577 +  /* True if opening an ephemeral, temporary database */
 1.52578 +  const int isTempDb = zFilename==0 || zFilename[0]==0;
 1.52579 +
 1.52580 +  /* Set the variable isMemdb to true for an in-memory database, or 
 1.52581 +  ** false for a file-based database.
 1.52582 +  */
 1.52583 +#ifdef SQLITE_OMIT_MEMORYDB
 1.52584 +  const int isMemdb = 0;
 1.52585 +#else
 1.52586 +  const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
 1.52587 +                       || (isTempDb && sqlite3TempInMemory(db))
 1.52588 +                       || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
 1.52589 +#endif
 1.52590 +
 1.52591 +  assert( db!=0 );
 1.52592 +  assert( pVfs!=0 );
 1.52593 +  assert( sqlite3_mutex_held(db->mutex) );
 1.52594 +  assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
 1.52595 +
 1.52596 +  /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
 1.52597 +  assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
 1.52598 +
 1.52599 +  /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
 1.52600 +  assert( (flags & BTREE_SINGLE)==0 || isTempDb );
 1.52601 +
 1.52602 +  if( isMemdb ){
 1.52603 +    flags |= BTREE_MEMORY;
 1.52604 +  }
 1.52605 +  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
 1.52606 +    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
 1.52607 +  }
 1.52608 +  p = sqlite3MallocZero(sizeof(Btree));
 1.52609 +  if( !p ){
 1.52610 +    return SQLITE_NOMEM;
 1.52611 +  }
 1.52612 +  p->inTrans = TRANS_NONE;
 1.52613 +  p->db = db;
 1.52614 +#ifndef SQLITE_OMIT_SHARED_CACHE
 1.52615 +  p->lock.pBtree = p;
 1.52616 +  p->lock.iTable = 1;
 1.52617 +#endif
 1.52618 +
 1.52619 +#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
 1.52620 +  /*
 1.52621 +  ** If this Btree is a candidate for shared cache, try to find an
 1.52622 +  ** existing BtShared object that we can share with
 1.52623 +  */
 1.52624 +  if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
 1.52625 +    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
 1.52626 +      int nFullPathname = pVfs->mxPathname+1;
 1.52627 +      char *zFullPathname = sqlite3Malloc(nFullPathname);
 1.52628 +      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
 1.52629 +      p->sharable = 1;
 1.52630 +      if( !zFullPathname ){
 1.52631 +        sqlite3_free(p);
 1.52632 +        return SQLITE_NOMEM;
 1.52633 +      }
 1.52634 +      if( isMemdb ){
 1.52635 +        memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
 1.52636 +      }else{
 1.52637 +        rc = sqlite3OsFullPathname(pVfs, zFilename,
 1.52638 +                                   nFullPathname, zFullPathname);
 1.52639 +        if( rc ){
 1.52640 +          sqlite3_free(zFullPathname);
 1.52641 +          sqlite3_free(p);
 1.52642 +          return rc;
 1.52643 +        }
 1.52644 +      }
 1.52645 +#if SQLITE_THREADSAFE
 1.52646 +      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
 1.52647 +      sqlite3_mutex_enter(mutexOpen);
 1.52648 +      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
 1.52649 +      sqlite3_mutex_enter(mutexShared);
 1.52650 +#endif
 1.52651 +      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
 1.52652 +        assert( pBt->nRef>0 );
 1.52653 +        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
 1.52654 +                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
 1.52655 +          int iDb;
 1.52656 +          for(iDb=db->nDb-1; iDb>=0; iDb--){
 1.52657 +            Btree *pExisting = db->aDb[iDb].pBt;
 1.52658 +            if( pExisting && pExisting->pBt==pBt ){
 1.52659 +              sqlite3_mutex_leave(mutexShared);
 1.52660 +              sqlite3_mutex_leave(mutexOpen);
 1.52661 +              sqlite3_free(zFullPathname);
 1.52662 +              sqlite3_free(p);
 1.52663 +              return SQLITE_CONSTRAINT;
 1.52664 +            }
 1.52665 +          }
 1.52666 +          p->pBt = pBt;
 1.52667 +          pBt->nRef++;
 1.52668 +          break;
 1.52669 +        }
 1.52670 +      }
 1.52671 +      sqlite3_mutex_leave(mutexShared);
 1.52672 +      sqlite3_free(zFullPathname);
 1.52673 +    }
 1.52674 +#ifdef SQLITE_DEBUG
 1.52675 +    else{
 1.52676 +      /* In debug mode, we mark all persistent databases as sharable
 1.52677 +      ** even when they are not.  This exercises the locking code and
 1.52678 +      ** gives more opportunity for asserts(sqlite3_mutex_held())
 1.52679 +      ** statements to find locking problems.
 1.52680 +      */
 1.52681 +      p->sharable = 1;
 1.52682 +    }
 1.52683 +#endif
 1.52684 +  }
 1.52685 +#endif
 1.52686 +  if( pBt==0 ){
 1.52687 +    /*
 1.52688 +    ** The following asserts make sure that structures used by the btree are
 1.52689 +    ** the right size.  This is to guard against size changes that result
 1.52690 +    ** when compiling on a different architecture.
 1.52691 +    */
 1.52692 +    assert( sizeof(i64)==8 || sizeof(i64)==4 );
 1.52693 +    assert( sizeof(u64)==8 || sizeof(u64)==4 );
 1.52694 +    assert( sizeof(u32)==4 );
 1.52695 +    assert( sizeof(u16)==2 );
 1.52696 +    assert( sizeof(Pgno)==4 );
 1.52697 +  
 1.52698 +    pBt = sqlite3MallocZero( sizeof(*pBt) );
 1.52699 +    if( pBt==0 ){
 1.52700 +      rc = SQLITE_NOMEM;
 1.52701 +      goto btree_open_out;
 1.52702 +    }
 1.52703 +    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
 1.52704 +                          EXTRA_SIZE, flags, vfsFlags, pageReinit);
 1.52705 +    if( rc==SQLITE_OK ){
 1.52706 +      sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
 1.52707 +      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
 1.52708 +    }
 1.52709 +    if( rc!=SQLITE_OK ){
 1.52710 +      goto btree_open_out;
 1.52711 +    }
 1.52712 +    pBt->openFlags = (u8)flags;
 1.52713 +    pBt->db = db;
 1.52714 +    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
 1.52715 +    p->pBt = pBt;
 1.52716 +  
 1.52717 +    pBt->pCursor = 0;
 1.52718 +    pBt->pPage1 = 0;
 1.52719 +    if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
 1.52720 +#ifdef SQLITE_SECURE_DELETE
 1.52721 +    pBt->btsFlags |= BTS_SECURE_DELETE;
 1.52722 +#endif
 1.52723 +    pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
 1.52724 +    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
 1.52725 +         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
 1.52726 +      pBt->pageSize = 0;
 1.52727 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.52728 +      /* If the magic name ":memory:" will create an in-memory database, then
 1.52729 +      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
 1.52730 +      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
 1.52731 +      ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
 1.52732 +      ** regular file-name. In this case the auto-vacuum applies as per normal.
 1.52733 +      */
 1.52734 +      if( zFilename && !isMemdb ){
 1.52735 +        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
 1.52736 +        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
 1.52737 +      }
 1.52738 +#endif
 1.52739 +      nReserve = 0;
 1.52740 +    }else{
 1.52741 +      nReserve = zDbHeader[20];
 1.52742 +      pBt->btsFlags |= BTS_PAGESIZE_FIXED;
 1.52743 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.52744 +      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
 1.52745 +      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
 1.52746 +#endif
 1.52747 +    }
 1.52748 +    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
 1.52749 +    if( rc ) goto btree_open_out;
 1.52750 +    pBt->usableSize = pBt->pageSize - nReserve;
 1.52751 +    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
 1.52752 +   
 1.52753 +#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
 1.52754 +    /* Add the new BtShared object to the linked list sharable BtShareds.
 1.52755 +    */
 1.52756 +    if( p->sharable ){
 1.52757 +      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
 1.52758 +      pBt->nRef = 1;
 1.52759 +      MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
 1.52760 +      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
 1.52761 +        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
 1.52762 +        if( pBt->mutex==0 ){
 1.52763 +          rc = SQLITE_NOMEM;
 1.52764 +          db->mallocFailed = 0;
 1.52765 +          goto btree_open_out;
 1.52766 +        }
 1.52767 +      }
 1.52768 +      sqlite3_mutex_enter(mutexShared);
 1.52769 +      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
 1.52770 +      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
 1.52771 +      sqlite3_mutex_leave(mutexShared);
 1.52772 +    }
 1.52773 +#endif
 1.52774 +  }
 1.52775 +
 1.52776 +#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
 1.52777 +  /* If the new Btree uses a sharable pBtShared, then link the new
 1.52778 +  ** Btree into the list of all sharable Btrees for the same connection.
 1.52779 +  ** The list is kept in ascending order by pBt address.
 1.52780 +  */
 1.52781 +  if( p->sharable ){
 1.52782 +    int i;
 1.52783 +    Btree *pSib;
 1.52784 +    for(i=0; i<db->nDb; i++){
 1.52785 +      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
 1.52786 +        while( pSib->pPrev ){ pSib = pSib->pPrev; }
 1.52787 +        if( p->pBt<pSib->pBt ){
 1.52788 +          p->pNext = pSib;
 1.52789 +          p->pPrev = 0;
 1.52790 +          pSib->pPrev = p;
 1.52791 +        }else{
 1.52792 +          while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
 1.52793 +            pSib = pSib->pNext;
 1.52794 +          }
 1.52795 +          p->pNext = pSib->pNext;
 1.52796 +          p->pPrev = pSib;
 1.52797 +          if( p->pNext ){
 1.52798 +            p->pNext->pPrev = p;
 1.52799 +          }
 1.52800 +          pSib->pNext = p;
 1.52801 +        }
 1.52802 +        break;
 1.52803 +      }
 1.52804 +    }
 1.52805 +  }
 1.52806 +#endif
 1.52807 +  *ppBtree = p;
 1.52808 +
 1.52809 +btree_open_out:
 1.52810 +  if( rc!=SQLITE_OK ){
 1.52811 +    if( pBt && pBt->pPager ){
 1.52812 +      sqlite3PagerClose(pBt->pPager);
 1.52813 +    }
 1.52814 +    sqlite3_free(pBt);
 1.52815 +    sqlite3_free(p);
 1.52816 +    *ppBtree = 0;
 1.52817 +  }else{
 1.52818 +    /* If the B-Tree was successfully opened, set the pager-cache size to the
 1.52819 +    ** default value. Except, when opening on an existing shared pager-cache,
 1.52820 +    ** do not change the pager-cache size.
 1.52821 +    */
 1.52822 +    if( sqlite3BtreeSchema(p, 0, 0)==0 ){
 1.52823 +      sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
 1.52824 +    }
 1.52825 +  }
 1.52826 +  if( mutexOpen ){
 1.52827 +    assert( sqlite3_mutex_held(mutexOpen) );
 1.52828 +    sqlite3_mutex_leave(mutexOpen);
 1.52829 +  }
 1.52830 +  return rc;
 1.52831 +}
 1.52832 +
 1.52833 +/*
 1.52834 +** Decrement the BtShared.nRef counter.  When it reaches zero,
 1.52835 +** remove the BtShared structure from the sharing list.  Return
 1.52836 +** true if the BtShared.nRef counter reaches zero and return
 1.52837 +** false if it is still positive.
 1.52838 +*/
 1.52839 +static int removeFromSharingList(BtShared *pBt){
 1.52840 +#ifndef SQLITE_OMIT_SHARED_CACHE
 1.52841 +  MUTEX_LOGIC( sqlite3_mutex *pMaster; )
 1.52842 +  BtShared *pList;
 1.52843 +  int removed = 0;
 1.52844 +
 1.52845 +  assert( sqlite3_mutex_notheld(pBt->mutex) );
 1.52846 +  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
 1.52847 +  sqlite3_mutex_enter(pMaster);
 1.52848 +  pBt->nRef--;
 1.52849 +  if( pBt->nRef<=0 ){
 1.52850 +    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
 1.52851 +      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
 1.52852 +    }else{
 1.52853 +      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
 1.52854 +      while( ALWAYS(pList) && pList->pNext!=pBt ){
 1.52855 +        pList=pList->pNext;
 1.52856 +      }
 1.52857 +      if( ALWAYS(pList) ){
 1.52858 +        pList->pNext = pBt->pNext;
 1.52859 +      }
 1.52860 +    }
 1.52861 +    if( SQLITE_THREADSAFE ){
 1.52862 +      sqlite3_mutex_free(pBt->mutex);
 1.52863 +    }
 1.52864 +    removed = 1;
 1.52865 +  }
 1.52866 +  sqlite3_mutex_leave(pMaster);
 1.52867 +  return removed;
 1.52868 +#else
 1.52869 +  return 1;
 1.52870 +#endif
 1.52871 +}
 1.52872 +
 1.52873 +/*
 1.52874 +** Make sure pBt->pTmpSpace points to an allocation of 
 1.52875 +** MX_CELL_SIZE(pBt) bytes.
 1.52876 +*/
 1.52877 +static void allocateTempSpace(BtShared *pBt){
 1.52878 +  if( !pBt->pTmpSpace ){
 1.52879 +    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
 1.52880 +
 1.52881 +    /* One of the uses of pBt->pTmpSpace is to format cells before
 1.52882 +    ** inserting them into a leaf page (function fillInCell()). If
 1.52883 +    ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
 1.52884 +    ** by the various routines that manipulate binary cells. Which
 1.52885 +    ** can mean that fillInCell() only initializes the first 2 or 3
 1.52886 +    ** bytes of pTmpSpace, but that the first 4 bytes are copied from
 1.52887 +    ** it into a database page. This is not actually a problem, but it
 1.52888 +    ** does cause a valgrind error when the 1 or 2 bytes of unitialized 
 1.52889 +    ** data is passed to system call write(). So to avoid this error,
 1.52890 +    ** zero the first 4 bytes of temp space here.  */
 1.52891 +    if( pBt->pTmpSpace ) memset(pBt->pTmpSpace, 0, 4);
 1.52892 +  }
 1.52893 +}
 1.52894 +
 1.52895 +/*
 1.52896 +** Free the pBt->pTmpSpace allocation
 1.52897 +*/
 1.52898 +static void freeTempSpace(BtShared *pBt){
 1.52899 +  sqlite3PageFree( pBt->pTmpSpace);
 1.52900 +  pBt->pTmpSpace = 0;
 1.52901 +}
 1.52902 +
 1.52903 +/*
 1.52904 +** Close an open database and invalidate all cursors.
 1.52905 +*/
 1.52906 +SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
 1.52907 +  BtShared *pBt = p->pBt;
 1.52908 +  BtCursor *pCur;
 1.52909 +
 1.52910 +  /* Close all cursors opened via this handle.  */
 1.52911 +  assert( sqlite3_mutex_held(p->db->mutex) );
 1.52912 +  sqlite3BtreeEnter(p);
 1.52913 +  pCur = pBt->pCursor;
 1.52914 +  while( pCur ){
 1.52915 +    BtCursor *pTmp = pCur;
 1.52916 +    pCur = pCur->pNext;
 1.52917 +    if( pTmp->pBtree==p ){
 1.52918 +      sqlite3BtreeCloseCursor(pTmp);
 1.52919 +    }
 1.52920 +  }
 1.52921 +
 1.52922 +  /* Rollback any active transaction and free the handle structure.
 1.52923 +  ** The call to sqlite3BtreeRollback() drops any table-locks held by
 1.52924 +  ** this handle.
 1.52925 +  */
 1.52926 +  sqlite3BtreeRollback(p, SQLITE_OK);
 1.52927 +  sqlite3BtreeLeave(p);
 1.52928 +
 1.52929 +  /* If there are still other outstanding references to the shared-btree
 1.52930 +  ** structure, return now. The remainder of this procedure cleans 
 1.52931 +  ** up the shared-btree.
 1.52932 +  */
 1.52933 +  assert( p->wantToLock==0 && p->locked==0 );
 1.52934 +  if( !p->sharable || removeFromSharingList(pBt) ){
 1.52935 +    /* The pBt is no longer on the sharing list, so we can access
 1.52936 +    ** it without having to hold the mutex.
 1.52937 +    **
 1.52938 +    ** Clean out and delete the BtShared object.
 1.52939 +    */
 1.52940 +    assert( !pBt->pCursor );
 1.52941 +    sqlite3PagerClose(pBt->pPager);
 1.52942 +    if( pBt->xFreeSchema && pBt->pSchema ){
 1.52943 +      pBt->xFreeSchema(pBt->pSchema);
 1.52944 +    }
 1.52945 +    sqlite3DbFree(0, pBt->pSchema);
 1.52946 +    freeTempSpace(pBt);
 1.52947 +    sqlite3_free(pBt);
 1.52948 +  }
 1.52949 +
 1.52950 +#ifndef SQLITE_OMIT_SHARED_CACHE
 1.52951 +  assert( p->wantToLock==0 );
 1.52952 +  assert( p->locked==0 );
 1.52953 +  if( p->pPrev ) p->pPrev->pNext = p->pNext;
 1.52954 +  if( p->pNext ) p->pNext->pPrev = p->pPrev;
 1.52955 +#endif
 1.52956 +
 1.52957 +  sqlite3_free(p);
 1.52958 +  return SQLITE_OK;
 1.52959 +}
 1.52960 +
 1.52961 +/*
 1.52962 +** Change the limit on the number of pages allowed in the cache.
 1.52963 +**
 1.52964 +** The maximum number of cache pages is set to the absolute
 1.52965 +** value of mxPage.  If mxPage is negative, the pager will
 1.52966 +** operate asynchronously - it will not stop to do fsync()s
 1.52967 +** to insure data is written to the disk surface before
 1.52968 +** continuing.  Transactions still work if synchronous is off,
 1.52969 +** and the database cannot be corrupted if this program
 1.52970 +** crashes.  But if the operating system crashes or there is
 1.52971 +** an abrupt power failure when synchronous is off, the database
 1.52972 +** could be left in an inconsistent and unrecoverable state.
 1.52973 +** Synchronous is on by default so database corruption is not
 1.52974 +** normally a worry.
 1.52975 +*/
 1.52976 +SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
 1.52977 +  BtShared *pBt = p->pBt;
 1.52978 +  assert( sqlite3_mutex_held(p->db->mutex) );
 1.52979 +  sqlite3BtreeEnter(p);
 1.52980 +  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
 1.52981 +  sqlite3BtreeLeave(p);
 1.52982 +  return SQLITE_OK;
 1.52983 +}
 1.52984 +
 1.52985 +/*
 1.52986 +** Change the limit on the amount of the database file that may be
 1.52987 +** memory mapped.
 1.52988 +*/
 1.52989 +SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
 1.52990 +  BtShared *pBt = p->pBt;
 1.52991 +  assert( sqlite3_mutex_held(p->db->mutex) );
 1.52992 +  sqlite3BtreeEnter(p);
 1.52993 +  sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
 1.52994 +  sqlite3BtreeLeave(p);
 1.52995 +  return SQLITE_OK;
 1.52996 +}
 1.52997 +
 1.52998 +/*
 1.52999 +** Change the way data is synced to disk in order to increase or decrease
 1.53000 +** how well the database resists damage due to OS crashes and power
 1.53001 +** failures.  Level 1 is the same as asynchronous (no syncs() occur and
 1.53002 +** there is a high probability of damage)  Level 2 is the default.  There
 1.53003 +** is a very low but non-zero probability of damage.  Level 3 reduces the
 1.53004 +** probability of damage to near zero but with a write performance reduction.
 1.53005 +*/
 1.53006 +#ifndef SQLITE_OMIT_PAGER_PRAGMAS
 1.53007 +SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
 1.53008 +  Btree *p,              /* The btree to set the safety level on */
 1.53009 +  unsigned pgFlags       /* Various PAGER_* flags */
 1.53010 +){
 1.53011 +  BtShared *pBt = p->pBt;
 1.53012 +  assert( sqlite3_mutex_held(p->db->mutex) );
 1.53013 +  sqlite3BtreeEnter(p);
 1.53014 +  sqlite3PagerSetFlags(pBt->pPager, pgFlags);
 1.53015 +  sqlite3BtreeLeave(p);
 1.53016 +  return SQLITE_OK;
 1.53017 +}
 1.53018 +#endif
 1.53019 +
 1.53020 +/*
 1.53021 +** Return TRUE if the given btree is set to safety level 1.  In other
 1.53022 +** words, return TRUE if no sync() occurs on the disk files.
 1.53023 +*/
 1.53024 +SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
 1.53025 +  BtShared *pBt = p->pBt;
 1.53026 +  int rc;
 1.53027 +  assert( sqlite3_mutex_held(p->db->mutex) );  
 1.53028 +  sqlite3BtreeEnter(p);
 1.53029 +  assert( pBt && pBt->pPager );
 1.53030 +  rc = sqlite3PagerNosync(pBt->pPager);
 1.53031 +  sqlite3BtreeLeave(p);
 1.53032 +  return rc;
 1.53033 +}
 1.53034 +
 1.53035 +/*
 1.53036 +** Change the default pages size and the number of reserved bytes per page.
 1.53037 +** Or, if the page size has already been fixed, return SQLITE_READONLY 
 1.53038 +** without changing anything.
 1.53039 +**
 1.53040 +** The page size must be a power of 2 between 512 and 65536.  If the page
 1.53041 +** size supplied does not meet this constraint then the page size is not
 1.53042 +** changed.
 1.53043 +**
 1.53044 +** Page sizes are constrained to be a power of two so that the region
 1.53045 +** of the database file used for locking (beginning at PENDING_BYTE,
 1.53046 +** the first byte past the 1GB boundary, 0x40000000) needs to occur
 1.53047 +** at the beginning of a page.
 1.53048 +**
 1.53049 +** If parameter nReserve is less than zero, then the number of reserved
 1.53050 +** bytes per page is left unchanged.
 1.53051 +**
 1.53052 +** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
 1.53053 +** and autovacuum mode can no longer be changed.
 1.53054 +*/
 1.53055 +SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
 1.53056 +  int rc = SQLITE_OK;
 1.53057 +  BtShared *pBt = p->pBt;
 1.53058 +  assert( nReserve>=-1 && nReserve<=255 );
 1.53059 +  sqlite3BtreeEnter(p);
 1.53060 +  if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
 1.53061 +    sqlite3BtreeLeave(p);
 1.53062 +    return SQLITE_READONLY;
 1.53063 +  }
 1.53064 +  if( nReserve<0 ){
 1.53065 +    nReserve = pBt->pageSize - pBt->usableSize;
 1.53066 +  }
 1.53067 +  assert( nReserve>=0 && nReserve<=255 );
 1.53068 +  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
 1.53069 +        ((pageSize-1)&pageSize)==0 ){
 1.53070 +    assert( (pageSize & 7)==0 );
 1.53071 +    assert( !pBt->pPage1 && !pBt->pCursor );
 1.53072 +    pBt->pageSize = (u32)pageSize;
 1.53073 +    freeTempSpace(pBt);
 1.53074 +  }
 1.53075 +  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
 1.53076 +  pBt->usableSize = pBt->pageSize - (u16)nReserve;
 1.53077 +  if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
 1.53078 +  sqlite3BtreeLeave(p);
 1.53079 +  return rc;
 1.53080 +}
 1.53081 +
 1.53082 +/*
 1.53083 +** Return the currently defined page size
 1.53084 +*/
 1.53085 +SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
 1.53086 +  return p->pBt->pageSize;
 1.53087 +}
 1.53088 +
 1.53089 +#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
 1.53090 +/*
 1.53091 +** This function is similar to sqlite3BtreeGetReserve(), except that it
 1.53092 +** may only be called if it is guaranteed that the b-tree mutex is already
 1.53093 +** held.
 1.53094 +**
 1.53095 +** This is useful in one special case in the backup API code where it is
 1.53096 +** known that the shared b-tree mutex is held, but the mutex on the 
 1.53097 +** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
 1.53098 +** were to be called, it might collide with some other operation on the
 1.53099 +** database handle that owns *p, causing undefined behavior.
 1.53100 +*/
 1.53101 +SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
 1.53102 +  assert( sqlite3_mutex_held(p->pBt->mutex) );
 1.53103 +  return p->pBt->pageSize - p->pBt->usableSize;
 1.53104 +}
 1.53105 +#endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
 1.53106 +
 1.53107 +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
 1.53108 +/*
 1.53109 +** Return the number of bytes of space at the end of every page that
 1.53110 +** are intentually left unused.  This is the "reserved" space that is
 1.53111 +** sometimes used by extensions.
 1.53112 +*/
 1.53113 +SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
 1.53114 +  int n;
 1.53115 +  sqlite3BtreeEnter(p);
 1.53116 +  n = p->pBt->pageSize - p->pBt->usableSize;
 1.53117 +  sqlite3BtreeLeave(p);
 1.53118 +  return n;
 1.53119 +}
 1.53120 +
 1.53121 +/*
 1.53122 +** Set the maximum page count for a database if mxPage is positive.
 1.53123 +** No changes are made if mxPage is 0 or negative.
 1.53124 +** Regardless of the value of mxPage, return the maximum page count.
 1.53125 +*/
 1.53126 +SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
 1.53127 +  int n;
 1.53128 +  sqlite3BtreeEnter(p);
 1.53129 +  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
 1.53130 +  sqlite3BtreeLeave(p);
 1.53131 +  return n;
 1.53132 +}
 1.53133 +
 1.53134 +/*
 1.53135 +** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
 1.53136 +** then make no changes.  Always return the value of the BTS_SECURE_DELETE
 1.53137 +** setting after the change.
 1.53138 +*/
 1.53139 +SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
 1.53140 +  int b;
 1.53141 +  if( p==0 ) return 0;
 1.53142 +  sqlite3BtreeEnter(p);
 1.53143 +  if( newFlag>=0 ){
 1.53144 +    p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
 1.53145 +    if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
 1.53146 +  } 
 1.53147 +  b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
 1.53148 +  sqlite3BtreeLeave(p);
 1.53149 +  return b;
 1.53150 +}
 1.53151 +#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
 1.53152 +
 1.53153 +/*
 1.53154 +** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
 1.53155 +** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
 1.53156 +** is disabled. The default value for the auto-vacuum property is 
 1.53157 +** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
 1.53158 +*/
 1.53159 +SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
 1.53160 +#ifdef SQLITE_OMIT_AUTOVACUUM
 1.53161 +  return SQLITE_READONLY;
 1.53162 +#else
 1.53163 +  BtShared *pBt = p->pBt;
 1.53164 +  int rc = SQLITE_OK;
 1.53165 +  u8 av = (u8)autoVacuum;
 1.53166 +
 1.53167 +  sqlite3BtreeEnter(p);
 1.53168 +  if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
 1.53169 +    rc = SQLITE_READONLY;
 1.53170 +  }else{
 1.53171 +    pBt->autoVacuum = av ?1:0;
 1.53172 +    pBt->incrVacuum = av==2 ?1:0;
 1.53173 +  }
 1.53174 +  sqlite3BtreeLeave(p);
 1.53175 +  return rc;
 1.53176 +#endif
 1.53177 +}
 1.53178 +
 1.53179 +/*
 1.53180 +** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
 1.53181 +** enabled 1 is returned. Otherwise 0.
 1.53182 +*/
 1.53183 +SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
 1.53184 +#ifdef SQLITE_OMIT_AUTOVACUUM
 1.53185 +  return BTREE_AUTOVACUUM_NONE;
 1.53186 +#else
 1.53187 +  int rc;
 1.53188 +  sqlite3BtreeEnter(p);
 1.53189 +  rc = (
 1.53190 +    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
 1.53191 +    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
 1.53192 +    BTREE_AUTOVACUUM_INCR
 1.53193 +  );
 1.53194 +  sqlite3BtreeLeave(p);
 1.53195 +  return rc;
 1.53196 +#endif
 1.53197 +}
 1.53198 +
 1.53199 +
 1.53200 +/*
 1.53201 +** Get a reference to pPage1 of the database file.  This will
 1.53202 +** also acquire a readlock on that file.
 1.53203 +**
 1.53204 +** SQLITE_OK is returned on success.  If the file is not a
 1.53205 +** well-formed database file, then SQLITE_CORRUPT is returned.
 1.53206 +** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
 1.53207 +** is returned if we run out of memory. 
 1.53208 +*/
 1.53209 +static int lockBtree(BtShared *pBt){
 1.53210 +  int rc;              /* Result code from subfunctions */
 1.53211 +  MemPage *pPage1;     /* Page 1 of the database file */
 1.53212 +  int nPage;           /* Number of pages in the database */
 1.53213 +  int nPageFile = 0;   /* Number of pages in the database file */
 1.53214 +  int nPageHeader;     /* Number of pages in the database according to hdr */
 1.53215 +
 1.53216 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.53217 +  assert( pBt->pPage1==0 );
 1.53218 +  rc = sqlite3PagerSharedLock(pBt->pPager);
 1.53219 +  if( rc!=SQLITE_OK ) return rc;
 1.53220 +  rc = btreeGetPage(pBt, 1, &pPage1, 0);
 1.53221 +  if( rc!=SQLITE_OK ) return rc;
 1.53222 +
 1.53223 +  /* Do some checking to help insure the file we opened really is
 1.53224 +  ** a valid database file. 
 1.53225 +  */
 1.53226 +  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
 1.53227 +  sqlite3PagerPagecount(pBt->pPager, &nPageFile);
 1.53228 +  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
 1.53229 +    nPage = nPageFile;
 1.53230 +  }
 1.53231 +  if( nPage>0 ){
 1.53232 +    u32 pageSize;
 1.53233 +    u32 usableSize;
 1.53234 +    u8 *page1 = pPage1->aData;
 1.53235 +    rc = SQLITE_NOTADB;
 1.53236 +    if( memcmp(page1, zMagicHeader, 16)!=0 ){
 1.53237 +      goto page1_init_failed;
 1.53238 +    }
 1.53239 +
 1.53240 +#ifdef SQLITE_OMIT_WAL
 1.53241 +    if( page1[18]>1 ){
 1.53242 +      pBt->btsFlags |= BTS_READ_ONLY;
 1.53243 +    }
 1.53244 +    if( page1[19]>1 ){
 1.53245 +      goto page1_init_failed;
 1.53246 +    }
 1.53247 +#else
 1.53248 +    if( page1[18]>2 ){
 1.53249 +      pBt->btsFlags |= BTS_READ_ONLY;
 1.53250 +    }
 1.53251 +    if( page1[19]>2 ){
 1.53252 +      goto page1_init_failed;
 1.53253 +    }
 1.53254 +
 1.53255 +    /* If the write version is set to 2, this database should be accessed
 1.53256 +    ** in WAL mode. If the log is not already open, open it now. Then 
 1.53257 +    ** return SQLITE_OK and return without populating BtShared.pPage1.
 1.53258 +    ** The caller detects this and calls this function again. This is
 1.53259 +    ** required as the version of page 1 currently in the page1 buffer
 1.53260 +    ** may not be the latest version - there may be a newer one in the log
 1.53261 +    ** file.
 1.53262 +    */
 1.53263 +    if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
 1.53264 +      int isOpen = 0;
 1.53265 +      rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
 1.53266 +      if( rc!=SQLITE_OK ){
 1.53267 +        goto page1_init_failed;
 1.53268 +      }else if( isOpen==0 ){
 1.53269 +        releasePage(pPage1);
 1.53270 +        return SQLITE_OK;
 1.53271 +      }
 1.53272 +      rc = SQLITE_NOTADB;
 1.53273 +    }
 1.53274 +#endif
 1.53275 +
 1.53276 +    /* The maximum embedded fraction must be exactly 25%.  And the minimum
 1.53277 +    ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
 1.53278 +    ** The original design allowed these amounts to vary, but as of
 1.53279 +    ** version 3.6.0, we require them to be fixed.
 1.53280 +    */
 1.53281 +    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
 1.53282 +      goto page1_init_failed;
 1.53283 +    }
 1.53284 +    pageSize = (page1[16]<<8) | (page1[17]<<16);
 1.53285 +    if( ((pageSize-1)&pageSize)!=0
 1.53286 +     || pageSize>SQLITE_MAX_PAGE_SIZE 
 1.53287 +     || pageSize<=256 
 1.53288 +    ){
 1.53289 +      goto page1_init_failed;
 1.53290 +    }
 1.53291 +    assert( (pageSize & 7)==0 );
 1.53292 +    usableSize = pageSize - page1[20];
 1.53293 +    if( (u32)pageSize!=pBt->pageSize ){
 1.53294 +      /* After reading the first page of the database assuming a page size
 1.53295 +      ** of BtShared.pageSize, we have discovered that the page-size is
 1.53296 +      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
 1.53297 +      ** zero and return SQLITE_OK. The caller will call this function
 1.53298 +      ** again with the correct page-size.
 1.53299 +      */
 1.53300 +      releasePage(pPage1);
 1.53301 +      pBt->usableSize = usableSize;
 1.53302 +      pBt->pageSize = pageSize;
 1.53303 +      freeTempSpace(pBt);
 1.53304 +      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
 1.53305 +                                   pageSize-usableSize);
 1.53306 +      return rc;
 1.53307 +    }
 1.53308 +    if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
 1.53309 +      rc = SQLITE_CORRUPT_BKPT;
 1.53310 +      goto page1_init_failed;
 1.53311 +    }
 1.53312 +    if( usableSize<480 ){
 1.53313 +      goto page1_init_failed;
 1.53314 +    }
 1.53315 +    pBt->pageSize = pageSize;
 1.53316 +    pBt->usableSize = usableSize;
 1.53317 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.53318 +    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
 1.53319 +    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
 1.53320 +#endif
 1.53321 +  }
 1.53322 +
 1.53323 +  /* maxLocal is the maximum amount of payload to store locally for
 1.53324 +  ** a cell.  Make sure it is small enough so that at least minFanout
 1.53325 +  ** cells can will fit on one page.  We assume a 10-byte page header.
 1.53326 +  ** Besides the payload, the cell must store:
 1.53327 +  **     2-byte pointer to the cell
 1.53328 +  **     4-byte child pointer
 1.53329 +  **     9-byte nKey value
 1.53330 +  **     4-byte nData value
 1.53331 +  **     4-byte overflow page pointer
 1.53332 +  ** So a cell consists of a 2-byte pointer, a header which is as much as
 1.53333 +  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
 1.53334 +  ** page pointer.
 1.53335 +  */
 1.53336 +  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
 1.53337 +  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
 1.53338 +  pBt->maxLeaf = (u16)(pBt->usableSize - 35);
 1.53339 +  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
 1.53340 +  if( pBt->maxLocal>127 ){
 1.53341 +    pBt->max1bytePayload = 127;
 1.53342 +  }else{
 1.53343 +    pBt->max1bytePayload = (u8)pBt->maxLocal;
 1.53344 +  }
 1.53345 +  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
 1.53346 +  pBt->pPage1 = pPage1;
 1.53347 +  pBt->nPage = nPage;
 1.53348 +  return SQLITE_OK;
 1.53349 +
 1.53350 +page1_init_failed:
 1.53351 +  releasePage(pPage1);
 1.53352 +  pBt->pPage1 = 0;
 1.53353 +  return rc;
 1.53354 +}
 1.53355 +
 1.53356 +#ifndef NDEBUG
 1.53357 +/*
 1.53358 +** Return the number of cursors open on pBt. This is for use
 1.53359 +** in assert() expressions, so it is only compiled if NDEBUG is not
 1.53360 +** defined.
 1.53361 +**
 1.53362 +** Only write cursors are counted if wrOnly is true.  If wrOnly is
 1.53363 +** false then all cursors are counted.
 1.53364 +**
 1.53365 +** For the purposes of this routine, a cursor is any cursor that
 1.53366 +** is capable of reading or writing to the databse.  Cursors that
 1.53367 +** have been tripped into the CURSOR_FAULT state are not counted.
 1.53368 +*/
 1.53369 +static int countValidCursors(BtShared *pBt, int wrOnly){
 1.53370 +  BtCursor *pCur;
 1.53371 +  int r = 0;
 1.53372 +  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
 1.53373 +    if( (wrOnly==0 || pCur->wrFlag) && pCur->eState!=CURSOR_FAULT ) r++; 
 1.53374 +  }
 1.53375 +  return r;
 1.53376 +}
 1.53377 +#endif
 1.53378 +
 1.53379 +/*
 1.53380 +** If there are no outstanding cursors and we are not in the middle
 1.53381 +** of a transaction but there is a read lock on the database, then
 1.53382 +** this routine unrefs the first page of the database file which 
 1.53383 +** has the effect of releasing the read lock.
 1.53384 +**
 1.53385 +** If there is a transaction in progress, this routine is a no-op.
 1.53386 +*/
 1.53387 +static void unlockBtreeIfUnused(BtShared *pBt){
 1.53388 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.53389 +  assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
 1.53390 +  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
 1.53391 +    assert( pBt->pPage1->aData );
 1.53392 +    assert( sqlite3PagerRefcount(pBt->pPager)==1 );
 1.53393 +    assert( pBt->pPage1->aData );
 1.53394 +    releasePage(pBt->pPage1);
 1.53395 +    pBt->pPage1 = 0;
 1.53396 +  }
 1.53397 +}
 1.53398 +
 1.53399 +/*
 1.53400 +** If pBt points to an empty file then convert that empty file
 1.53401 +** into a new empty database by initializing the first page of
 1.53402 +** the database.
 1.53403 +*/
 1.53404 +static int newDatabase(BtShared *pBt){
 1.53405 +  MemPage *pP1;
 1.53406 +  unsigned char *data;
 1.53407 +  int rc;
 1.53408 +
 1.53409 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.53410 +  if( pBt->nPage>0 ){
 1.53411 +    return SQLITE_OK;
 1.53412 +  }
 1.53413 +  pP1 = pBt->pPage1;
 1.53414 +  assert( pP1!=0 );
 1.53415 +  data = pP1->aData;
 1.53416 +  rc = sqlite3PagerWrite(pP1->pDbPage);
 1.53417 +  if( rc ) return rc;
 1.53418 +  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
 1.53419 +  assert( sizeof(zMagicHeader)==16 );
 1.53420 +  data[16] = (u8)((pBt->pageSize>>8)&0xff);
 1.53421 +  data[17] = (u8)((pBt->pageSize>>16)&0xff);
 1.53422 +  data[18] = 1;
 1.53423 +  data[19] = 1;
 1.53424 +  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
 1.53425 +  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
 1.53426 +  data[21] = 64;
 1.53427 +  data[22] = 32;
 1.53428 +  data[23] = 32;
 1.53429 +  memset(&data[24], 0, 100-24);
 1.53430 +  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
 1.53431 +  pBt->btsFlags |= BTS_PAGESIZE_FIXED;
 1.53432 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.53433 +  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
 1.53434 +  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
 1.53435 +  put4byte(&data[36 + 4*4], pBt->autoVacuum);
 1.53436 +  put4byte(&data[36 + 7*4], pBt->incrVacuum);
 1.53437 +#endif
 1.53438 +  pBt->nPage = 1;
 1.53439 +  data[31] = 1;
 1.53440 +  return SQLITE_OK;
 1.53441 +}
 1.53442 +
 1.53443 +/*
 1.53444 +** Initialize the first page of the database file (creating a database
 1.53445 +** consisting of a single page and no schema objects). Return SQLITE_OK
 1.53446 +** if successful, or an SQLite error code otherwise.
 1.53447 +*/
 1.53448 +SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
 1.53449 +  int rc;
 1.53450 +  sqlite3BtreeEnter(p);
 1.53451 +  p->pBt->nPage = 0;
 1.53452 +  rc = newDatabase(p->pBt);
 1.53453 +  sqlite3BtreeLeave(p);
 1.53454 +  return rc;
 1.53455 +}
 1.53456 +
 1.53457 +/*
 1.53458 +** Attempt to start a new transaction. A write-transaction
 1.53459 +** is started if the second argument is nonzero, otherwise a read-
 1.53460 +** transaction.  If the second argument is 2 or more and exclusive
 1.53461 +** transaction is started, meaning that no other process is allowed
 1.53462 +** to access the database.  A preexisting transaction may not be
 1.53463 +** upgraded to exclusive by calling this routine a second time - the
 1.53464 +** exclusivity flag only works for a new transaction.
 1.53465 +**
 1.53466 +** A write-transaction must be started before attempting any 
 1.53467 +** changes to the database.  None of the following routines 
 1.53468 +** will work unless a transaction is started first:
 1.53469 +**
 1.53470 +**      sqlite3BtreeCreateTable()
 1.53471 +**      sqlite3BtreeCreateIndex()
 1.53472 +**      sqlite3BtreeClearTable()
 1.53473 +**      sqlite3BtreeDropTable()
 1.53474 +**      sqlite3BtreeInsert()
 1.53475 +**      sqlite3BtreeDelete()
 1.53476 +**      sqlite3BtreeUpdateMeta()
 1.53477 +**
 1.53478 +** If an initial attempt to acquire the lock fails because of lock contention
 1.53479 +** and the database was previously unlocked, then invoke the busy handler
 1.53480 +** if there is one.  But if there was previously a read-lock, do not
 1.53481 +** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
 1.53482 +** returned when there is already a read-lock in order to avoid a deadlock.
 1.53483 +**
 1.53484 +** Suppose there are two processes A and B.  A has a read lock and B has
 1.53485 +** a reserved lock.  B tries to promote to exclusive but is blocked because
 1.53486 +** of A's read lock.  A tries to promote to reserved but is blocked by B.
 1.53487 +** One or the other of the two processes must give way or there can be
 1.53488 +** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
 1.53489 +** when A already has a read lock, we encourage A to give up and let B
 1.53490 +** proceed.
 1.53491 +*/
 1.53492 +SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
 1.53493 +  sqlite3 *pBlock = 0;
 1.53494 +  BtShared *pBt = p->pBt;
 1.53495 +  int rc = SQLITE_OK;
 1.53496 +
 1.53497 +  sqlite3BtreeEnter(p);
 1.53498 +  btreeIntegrity(p);
 1.53499 +
 1.53500 +  /* If the btree is already in a write-transaction, or it
 1.53501 +  ** is already in a read-transaction and a read-transaction
 1.53502 +  ** is requested, this is a no-op.
 1.53503 +  */
 1.53504 +  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
 1.53505 +    goto trans_begun;
 1.53506 +  }
 1.53507 +  assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
 1.53508 +
 1.53509 +  /* Write transactions are not possible on a read-only database */
 1.53510 +  if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
 1.53511 +    rc = SQLITE_READONLY;
 1.53512 +    goto trans_begun;
 1.53513 +  }
 1.53514 +
 1.53515 +#ifndef SQLITE_OMIT_SHARED_CACHE
 1.53516 +  /* If another database handle has already opened a write transaction 
 1.53517 +  ** on this shared-btree structure and a second write transaction is
 1.53518 +  ** requested, return SQLITE_LOCKED.
 1.53519 +  */
 1.53520 +  if( (wrflag && pBt->inTransaction==TRANS_WRITE)
 1.53521 +   || (pBt->btsFlags & BTS_PENDING)!=0
 1.53522 +  ){
 1.53523 +    pBlock = pBt->pWriter->db;
 1.53524 +  }else if( wrflag>1 ){
 1.53525 +    BtLock *pIter;
 1.53526 +    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
 1.53527 +      if( pIter->pBtree!=p ){
 1.53528 +        pBlock = pIter->pBtree->db;
 1.53529 +        break;
 1.53530 +      }
 1.53531 +    }
 1.53532 +  }
 1.53533 +  if( pBlock ){
 1.53534 +    sqlite3ConnectionBlocked(p->db, pBlock);
 1.53535 +    rc = SQLITE_LOCKED_SHAREDCACHE;
 1.53536 +    goto trans_begun;
 1.53537 +  }
 1.53538 +#endif
 1.53539 +
 1.53540 +  /* Any read-only or read-write transaction implies a read-lock on 
 1.53541 +  ** page 1. So if some other shared-cache client already has a write-lock 
 1.53542 +  ** on page 1, the transaction cannot be opened. */
 1.53543 +  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
 1.53544 +  if( SQLITE_OK!=rc ) goto trans_begun;
 1.53545 +
 1.53546 +  pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
 1.53547 +  if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
 1.53548 +  do {
 1.53549 +    /* Call lockBtree() until either pBt->pPage1 is populated or
 1.53550 +    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
 1.53551 +    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
 1.53552 +    ** reading page 1 it discovers that the page-size of the database 
 1.53553 +    ** file is not pBt->pageSize. In this case lockBtree() will update
 1.53554 +    ** pBt->pageSize to the page-size of the file on disk.
 1.53555 +    */
 1.53556 +    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
 1.53557 +
 1.53558 +    if( rc==SQLITE_OK && wrflag ){
 1.53559 +      if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
 1.53560 +        rc = SQLITE_READONLY;
 1.53561 +      }else{
 1.53562 +        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
 1.53563 +        if( rc==SQLITE_OK ){
 1.53564 +          rc = newDatabase(pBt);
 1.53565 +        }
 1.53566 +      }
 1.53567 +    }
 1.53568 +  
 1.53569 +    if( rc!=SQLITE_OK ){
 1.53570 +      unlockBtreeIfUnused(pBt);
 1.53571 +    }
 1.53572 +  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
 1.53573 +          btreeInvokeBusyHandler(pBt) );
 1.53574 +
 1.53575 +  if( rc==SQLITE_OK ){
 1.53576 +    if( p->inTrans==TRANS_NONE ){
 1.53577 +      pBt->nTransaction++;
 1.53578 +#ifndef SQLITE_OMIT_SHARED_CACHE
 1.53579 +      if( p->sharable ){
 1.53580 +        assert( p->lock.pBtree==p && p->lock.iTable==1 );
 1.53581 +        p->lock.eLock = READ_LOCK;
 1.53582 +        p->lock.pNext = pBt->pLock;
 1.53583 +        pBt->pLock = &p->lock;
 1.53584 +      }
 1.53585 +#endif
 1.53586 +    }
 1.53587 +    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
 1.53588 +    if( p->inTrans>pBt->inTransaction ){
 1.53589 +      pBt->inTransaction = p->inTrans;
 1.53590 +    }
 1.53591 +    if( wrflag ){
 1.53592 +      MemPage *pPage1 = pBt->pPage1;
 1.53593 +#ifndef SQLITE_OMIT_SHARED_CACHE
 1.53594 +      assert( !pBt->pWriter );
 1.53595 +      pBt->pWriter = p;
 1.53596 +      pBt->btsFlags &= ~BTS_EXCLUSIVE;
 1.53597 +      if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
 1.53598 +#endif
 1.53599 +
 1.53600 +      /* If the db-size header field is incorrect (as it may be if an old
 1.53601 +      ** client has been writing the database file), update it now. Doing
 1.53602 +      ** this sooner rather than later means the database size can safely 
 1.53603 +      ** re-read the database size from page 1 if a savepoint or transaction
 1.53604 +      ** rollback occurs within the transaction.
 1.53605 +      */
 1.53606 +      if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
 1.53607 +        rc = sqlite3PagerWrite(pPage1->pDbPage);
 1.53608 +        if( rc==SQLITE_OK ){
 1.53609 +          put4byte(&pPage1->aData[28], pBt->nPage);
 1.53610 +        }
 1.53611 +      }
 1.53612 +    }
 1.53613 +  }
 1.53614 +
 1.53615 +
 1.53616 +trans_begun:
 1.53617 +  if( rc==SQLITE_OK && wrflag ){
 1.53618 +    /* This call makes sure that the pager has the correct number of
 1.53619 +    ** open savepoints. If the second parameter is greater than 0 and
 1.53620 +    ** the sub-journal is not already open, then it will be opened here.
 1.53621 +    */
 1.53622 +    rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
 1.53623 +  }
 1.53624 +
 1.53625 +  btreeIntegrity(p);
 1.53626 +  sqlite3BtreeLeave(p);
 1.53627 +  return rc;
 1.53628 +}
 1.53629 +
 1.53630 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.53631 +
 1.53632 +/*
 1.53633 +** Set the pointer-map entries for all children of page pPage. Also, if
 1.53634 +** pPage contains cells that point to overflow pages, set the pointer
 1.53635 +** map entries for the overflow pages as well.
 1.53636 +*/
 1.53637 +static int setChildPtrmaps(MemPage *pPage){
 1.53638 +  int i;                             /* Counter variable */
 1.53639 +  int nCell;                         /* Number of cells in page pPage */
 1.53640 +  int rc;                            /* Return code */
 1.53641 +  BtShared *pBt = pPage->pBt;
 1.53642 +  u8 isInitOrig = pPage->isInit;
 1.53643 +  Pgno pgno = pPage->pgno;
 1.53644 +
 1.53645 +  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 1.53646 +  rc = btreeInitPage(pPage);
 1.53647 +  if( rc!=SQLITE_OK ){
 1.53648 +    goto set_child_ptrmaps_out;
 1.53649 +  }
 1.53650 +  nCell = pPage->nCell;
 1.53651 +
 1.53652 +  for(i=0; i<nCell; i++){
 1.53653 +    u8 *pCell = findCell(pPage, i);
 1.53654 +
 1.53655 +    ptrmapPutOvflPtr(pPage, pCell, &rc);
 1.53656 +
 1.53657 +    if( !pPage->leaf ){
 1.53658 +      Pgno childPgno = get4byte(pCell);
 1.53659 +      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
 1.53660 +    }
 1.53661 +  }
 1.53662 +
 1.53663 +  if( !pPage->leaf ){
 1.53664 +    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
 1.53665 +    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
 1.53666 +  }
 1.53667 +
 1.53668 +set_child_ptrmaps_out:
 1.53669 +  pPage->isInit = isInitOrig;
 1.53670 +  return rc;
 1.53671 +}
 1.53672 +
 1.53673 +/*
 1.53674 +** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
 1.53675 +** that it points to iTo. Parameter eType describes the type of pointer to
 1.53676 +** be modified, as  follows:
 1.53677 +**
 1.53678 +** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
 1.53679 +**                   page of pPage.
 1.53680 +**
 1.53681 +** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
 1.53682 +**                   page pointed to by one of the cells on pPage.
 1.53683 +**
 1.53684 +** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
 1.53685 +**                   overflow page in the list.
 1.53686 +*/
 1.53687 +static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
 1.53688 +  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 1.53689 +  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 1.53690 +  if( eType==PTRMAP_OVERFLOW2 ){
 1.53691 +    /* The pointer is always the first 4 bytes of the page in this case.  */
 1.53692 +    if( get4byte(pPage->aData)!=iFrom ){
 1.53693 +      return SQLITE_CORRUPT_BKPT;
 1.53694 +    }
 1.53695 +    put4byte(pPage->aData, iTo);
 1.53696 +  }else{
 1.53697 +    u8 isInitOrig = pPage->isInit;
 1.53698 +    int i;
 1.53699 +    int nCell;
 1.53700 +
 1.53701 +    btreeInitPage(pPage);
 1.53702 +    nCell = pPage->nCell;
 1.53703 +
 1.53704 +    for(i=0; i<nCell; i++){
 1.53705 +      u8 *pCell = findCell(pPage, i);
 1.53706 +      if( eType==PTRMAP_OVERFLOW1 ){
 1.53707 +        CellInfo info;
 1.53708 +        btreeParseCellPtr(pPage, pCell, &info);
 1.53709 +        if( info.iOverflow
 1.53710 +         && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
 1.53711 +         && iFrom==get4byte(&pCell[info.iOverflow])
 1.53712 +        ){
 1.53713 +          put4byte(&pCell[info.iOverflow], iTo);
 1.53714 +          break;
 1.53715 +        }
 1.53716 +      }else{
 1.53717 +        if( get4byte(pCell)==iFrom ){
 1.53718 +          put4byte(pCell, iTo);
 1.53719 +          break;
 1.53720 +        }
 1.53721 +      }
 1.53722 +    }
 1.53723 +  
 1.53724 +    if( i==nCell ){
 1.53725 +      if( eType!=PTRMAP_BTREE || 
 1.53726 +          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
 1.53727 +        return SQLITE_CORRUPT_BKPT;
 1.53728 +      }
 1.53729 +      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
 1.53730 +    }
 1.53731 +
 1.53732 +    pPage->isInit = isInitOrig;
 1.53733 +  }
 1.53734 +  return SQLITE_OK;
 1.53735 +}
 1.53736 +
 1.53737 +
 1.53738 +/*
 1.53739 +** Move the open database page pDbPage to location iFreePage in the 
 1.53740 +** database. The pDbPage reference remains valid.
 1.53741 +**
 1.53742 +** The isCommit flag indicates that there is no need to remember that
 1.53743 +** the journal needs to be sync()ed before database page pDbPage->pgno 
 1.53744 +** can be written to. The caller has already promised not to write to that
 1.53745 +** page.
 1.53746 +*/
 1.53747 +static int relocatePage(
 1.53748 +  BtShared *pBt,           /* Btree */
 1.53749 +  MemPage *pDbPage,        /* Open page to move */
 1.53750 +  u8 eType,                /* Pointer map 'type' entry for pDbPage */
 1.53751 +  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
 1.53752 +  Pgno iFreePage,          /* The location to move pDbPage to */
 1.53753 +  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
 1.53754 +){
 1.53755 +  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
 1.53756 +  Pgno iDbPage = pDbPage->pgno;
 1.53757 +  Pager *pPager = pBt->pPager;
 1.53758 +  int rc;
 1.53759 +
 1.53760 +  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
 1.53761 +      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
 1.53762 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.53763 +  assert( pDbPage->pBt==pBt );
 1.53764 +
 1.53765 +  /* Move page iDbPage from its current location to page number iFreePage */
 1.53766 +  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
 1.53767 +      iDbPage, iFreePage, iPtrPage, eType));
 1.53768 +  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
 1.53769 +  if( rc!=SQLITE_OK ){
 1.53770 +    return rc;
 1.53771 +  }
 1.53772 +  pDbPage->pgno = iFreePage;
 1.53773 +
 1.53774 +  /* If pDbPage was a btree-page, then it may have child pages and/or cells
 1.53775 +  ** that point to overflow pages. The pointer map entries for all these
 1.53776 +  ** pages need to be changed.
 1.53777 +  **
 1.53778 +  ** If pDbPage is an overflow page, then the first 4 bytes may store a
 1.53779 +  ** pointer to a subsequent overflow page. If this is the case, then
 1.53780 +  ** the pointer map needs to be updated for the subsequent overflow page.
 1.53781 +  */
 1.53782 +  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
 1.53783 +    rc = setChildPtrmaps(pDbPage);
 1.53784 +    if( rc!=SQLITE_OK ){
 1.53785 +      return rc;
 1.53786 +    }
 1.53787 +  }else{
 1.53788 +    Pgno nextOvfl = get4byte(pDbPage->aData);
 1.53789 +    if( nextOvfl!=0 ){
 1.53790 +      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
 1.53791 +      if( rc!=SQLITE_OK ){
 1.53792 +        return rc;
 1.53793 +      }
 1.53794 +    }
 1.53795 +  }
 1.53796 +
 1.53797 +  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
 1.53798 +  ** that it points at iFreePage. Also fix the pointer map entry for
 1.53799 +  ** iPtrPage.
 1.53800 +  */
 1.53801 +  if( eType!=PTRMAP_ROOTPAGE ){
 1.53802 +    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
 1.53803 +    if( rc!=SQLITE_OK ){
 1.53804 +      return rc;
 1.53805 +    }
 1.53806 +    rc = sqlite3PagerWrite(pPtrPage->pDbPage);
 1.53807 +    if( rc!=SQLITE_OK ){
 1.53808 +      releasePage(pPtrPage);
 1.53809 +      return rc;
 1.53810 +    }
 1.53811 +    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
 1.53812 +    releasePage(pPtrPage);
 1.53813 +    if( rc==SQLITE_OK ){
 1.53814 +      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
 1.53815 +    }
 1.53816 +  }
 1.53817 +  return rc;
 1.53818 +}
 1.53819 +
 1.53820 +/* Forward declaration required by incrVacuumStep(). */
 1.53821 +static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
 1.53822 +
 1.53823 +/*
 1.53824 +** Perform a single step of an incremental-vacuum. If successful, return
 1.53825 +** SQLITE_OK. If there is no work to do (and therefore no point in 
 1.53826 +** calling this function again), return SQLITE_DONE. Or, if an error 
 1.53827 +** occurs, return some other error code.
 1.53828 +**
 1.53829 +** More specificly, this function attempts to re-organize the database so 
 1.53830 +** that the last page of the file currently in use is no longer in use.
 1.53831 +**
 1.53832 +** Parameter nFin is the number of pages that this database would contain
 1.53833 +** were this function called until it returns SQLITE_DONE.
 1.53834 +**
 1.53835 +** If the bCommit parameter is non-zero, this function assumes that the 
 1.53836 +** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE 
 1.53837 +** or an error. bCommit is passed true for an auto-vacuum-on-commmit 
 1.53838 +** operation, or false for an incremental vacuum.
 1.53839 +*/
 1.53840 +static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
 1.53841 +  Pgno nFreeList;           /* Number of pages still on the free-list */
 1.53842 +  int rc;
 1.53843 +
 1.53844 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.53845 +  assert( iLastPg>nFin );
 1.53846 +
 1.53847 +  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
 1.53848 +    u8 eType;
 1.53849 +    Pgno iPtrPage;
 1.53850 +
 1.53851 +    nFreeList = get4byte(&pBt->pPage1->aData[36]);
 1.53852 +    if( nFreeList==0 ){
 1.53853 +      return SQLITE_DONE;
 1.53854 +    }
 1.53855 +
 1.53856 +    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
 1.53857 +    if( rc!=SQLITE_OK ){
 1.53858 +      return rc;
 1.53859 +    }
 1.53860 +    if( eType==PTRMAP_ROOTPAGE ){
 1.53861 +      return SQLITE_CORRUPT_BKPT;
 1.53862 +    }
 1.53863 +
 1.53864 +    if( eType==PTRMAP_FREEPAGE ){
 1.53865 +      if( bCommit==0 ){
 1.53866 +        /* Remove the page from the files free-list. This is not required
 1.53867 +        ** if bCommit is non-zero. In that case, the free-list will be
 1.53868 +        ** truncated to zero after this function returns, so it doesn't 
 1.53869 +        ** matter if it still contains some garbage entries.
 1.53870 +        */
 1.53871 +        Pgno iFreePg;
 1.53872 +        MemPage *pFreePg;
 1.53873 +        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
 1.53874 +        if( rc!=SQLITE_OK ){
 1.53875 +          return rc;
 1.53876 +        }
 1.53877 +        assert( iFreePg==iLastPg );
 1.53878 +        releasePage(pFreePg);
 1.53879 +      }
 1.53880 +    } else {
 1.53881 +      Pgno iFreePg;             /* Index of free page to move pLastPg to */
 1.53882 +      MemPage *pLastPg;
 1.53883 +      u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
 1.53884 +      Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
 1.53885 +
 1.53886 +      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
 1.53887 +      if( rc!=SQLITE_OK ){
 1.53888 +        return rc;
 1.53889 +      }
 1.53890 +
 1.53891 +      /* If bCommit is zero, this loop runs exactly once and page pLastPg
 1.53892 +      ** is swapped with the first free page pulled off the free list.
 1.53893 +      **
 1.53894 +      ** On the other hand, if bCommit is greater than zero, then keep
 1.53895 +      ** looping until a free-page located within the first nFin pages
 1.53896 +      ** of the file is found.
 1.53897 +      */
 1.53898 +      if( bCommit==0 ){
 1.53899 +        eMode = BTALLOC_LE;
 1.53900 +        iNear = nFin;
 1.53901 +      }
 1.53902 +      do {
 1.53903 +        MemPage *pFreePg;
 1.53904 +        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
 1.53905 +        if( rc!=SQLITE_OK ){
 1.53906 +          releasePage(pLastPg);
 1.53907 +          return rc;
 1.53908 +        }
 1.53909 +        releasePage(pFreePg);
 1.53910 +      }while( bCommit && iFreePg>nFin );
 1.53911 +      assert( iFreePg<iLastPg );
 1.53912 +      
 1.53913 +      rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
 1.53914 +      releasePage(pLastPg);
 1.53915 +      if( rc!=SQLITE_OK ){
 1.53916 +        return rc;
 1.53917 +      }
 1.53918 +    }
 1.53919 +  }
 1.53920 +
 1.53921 +  if( bCommit==0 ){
 1.53922 +    do {
 1.53923 +      iLastPg--;
 1.53924 +    }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
 1.53925 +    pBt->bDoTruncate = 1;
 1.53926 +    pBt->nPage = iLastPg;
 1.53927 +  }
 1.53928 +  return SQLITE_OK;
 1.53929 +}
 1.53930 +
 1.53931 +/*
 1.53932 +** The database opened by the first argument is an auto-vacuum database
 1.53933 +** nOrig pages in size containing nFree free pages. Return the expected 
 1.53934 +** size of the database in pages following an auto-vacuum operation.
 1.53935 +*/
 1.53936 +static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
 1.53937 +  int nEntry;                     /* Number of entries on one ptrmap page */
 1.53938 +  Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
 1.53939 +  Pgno nFin;                      /* Return value */
 1.53940 +
 1.53941 +  nEntry = pBt->usableSize/5;
 1.53942 +  nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
 1.53943 +  nFin = nOrig - nFree - nPtrmap;
 1.53944 +  if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
 1.53945 +    nFin--;
 1.53946 +  }
 1.53947 +  while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
 1.53948 +    nFin--;
 1.53949 +  }
 1.53950 +
 1.53951 +  return nFin;
 1.53952 +}
 1.53953 +
 1.53954 +/*
 1.53955 +** A write-transaction must be opened before calling this function.
 1.53956 +** It performs a single unit of work towards an incremental vacuum.
 1.53957 +**
 1.53958 +** If the incremental vacuum is finished after this function has run,
 1.53959 +** SQLITE_DONE is returned. If it is not finished, but no error occurred,
 1.53960 +** SQLITE_OK is returned. Otherwise an SQLite error code. 
 1.53961 +*/
 1.53962 +SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
 1.53963 +  int rc;
 1.53964 +  BtShared *pBt = p->pBt;
 1.53965 +
 1.53966 +  sqlite3BtreeEnter(p);
 1.53967 +  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
 1.53968 +  if( !pBt->autoVacuum ){
 1.53969 +    rc = SQLITE_DONE;
 1.53970 +  }else{
 1.53971 +    Pgno nOrig = btreePagecount(pBt);
 1.53972 +    Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
 1.53973 +    Pgno nFin = finalDbSize(pBt, nOrig, nFree);
 1.53974 +
 1.53975 +    if( nOrig<nFin ){
 1.53976 +      rc = SQLITE_CORRUPT_BKPT;
 1.53977 +    }else if( nFree>0 ){
 1.53978 +      rc = saveAllCursors(pBt, 0, 0);
 1.53979 +      if( rc==SQLITE_OK ){
 1.53980 +        invalidateAllOverflowCache(pBt);
 1.53981 +        rc = incrVacuumStep(pBt, nFin, nOrig, 0);
 1.53982 +      }
 1.53983 +      if( rc==SQLITE_OK ){
 1.53984 +        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
 1.53985 +        put4byte(&pBt->pPage1->aData[28], pBt->nPage);
 1.53986 +      }
 1.53987 +    }else{
 1.53988 +      rc = SQLITE_DONE;
 1.53989 +    }
 1.53990 +  }
 1.53991 +  sqlite3BtreeLeave(p);
 1.53992 +  return rc;
 1.53993 +}
 1.53994 +
 1.53995 +/*
 1.53996 +** This routine is called prior to sqlite3PagerCommit when a transaction
 1.53997 +** is committed for an auto-vacuum database.
 1.53998 +**
 1.53999 +** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
 1.54000 +** the database file should be truncated to during the commit process. 
 1.54001 +** i.e. the database has been reorganized so that only the first *pnTrunc
 1.54002 +** pages are in use.
 1.54003 +*/
 1.54004 +static int autoVacuumCommit(BtShared *pBt){
 1.54005 +  int rc = SQLITE_OK;
 1.54006 +  Pager *pPager = pBt->pPager;
 1.54007 +  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
 1.54008 +
 1.54009 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.54010 +  invalidateAllOverflowCache(pBt);
 1.54011 +  assert(pBt->autoVacuum);
 1.54012 +  if( !pBt->incrVacuum ){
 1.54013 +    Pgno nFin;         /* Number of pages in database after autovacuuming */
 1.54014 +    Pgno nFree;        /* Number of pages on the freelist initially */
 1.54015 +    Pgno iFree;        /* The next page to be freed */
 1.54016 +    Pgno nOrig;        /* Database size before freeing */
 1.54017 +
 1.54018 +    nOrig = btreePagecount(pBt);
 1.54019 +    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
 1.54020 +      /* It is not possible to create a database for which the final page
 1.54021 +      ** is either a pointer-map page or the pending-byte page. If one
 1.54022 +      ** is encountered, this indicates corruption.
 1.54023 +      */
 1.54024 +      return SQLITE_CORRUPT_BKPT;
 1.54025 +    }
 1.54026 +
 1.54027 +    nFree = get4byte(&pBt->pPage1->aData[36]);
 1.54028 +    nFin = finalDbSize(pBt, nOrig, nFree);
 1.54029 +    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
 1.54030 +    if( nFin<nOrig ){
 1.54031 +      rc = saveAllCursors(pBt, 0, 0);
 1.54032 +    }
 1.54033 +    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
 1.54034 +      rc = incrVacuumStep(pBt, nFin, iFree, 1);
 1.54035 +    }
 1.54036 +    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
 1.54037 +      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
 1.54038 +      put4byte(&pBt->pPage1->aData[32], 0);
 1.54039 +      put4byte(&pBt->pPage1->aData[36], 0);
 1.54040 +      put4byte(&pBt->pPage1->aData[28], nFin);
 1.54041 +      pBt->bDoTruncate = 1;
 1.54042 +      pBt->nPage = nFin;
 1.54043 +    }
 1.54044 +    if( rc!=SQLITE_OK ){
 1.54045 +      sqlite3PagerRollback(pPager);
 1.54046 +    }
 1.54047 +  }
 1.54048 +
 1.54049 +  assert( nRef>=sqlite3PagerRefcount(pPager) );
 1.54050 +  return rc;
 1.54051 +}
 1.54052 +
 1.54053 +#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
 1.54054 +# define setChildPtrmaps(x) SQLITE_OK
 1.54055 +#endif
 1.54056 +
 1.54057 +/*
 1.54058 +** This routine does the first phase of a two-phase commit.  This routine
 1.54059 +** causes a rollback journal to be created (if it does not already exist)
 1.54060 +** and populated with enough information so that if a power loss occurs
 1.54061 +** the database can be restored to its original state by playing back
 1.54062 +** the journal.  Then the contents of the journal are flushed out to
 1.54063 +** the disk.  After the journal is safely on oxide, the changes to the
 1.54064 +** database are written into the database file and flushed to oxide.
 1.54065 +** At the end of this call, the rollback journal still exists on the
 1.54066 +** disk and we are still holding all locks, so the transaction has not
 1.54067 +** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
 1.54068 +** commit process.
 1.54069 +**
 1.54070 +** This call is a no-op if no write-transaction is currently active on pBt.
 1.54071 +**
 1.54072 +** Otherwise, sync the database file for the btree pBt. zMaster points to
 1.54073 +** the name of a master journal file that should be written into the
 1.54074 +** individual journal file, or is NULL, indicating no master journal file 
 1.54075 +** (single database transaction).
 1.54076 +**
 1.54077 +** When this is called, the master journal should already have been
 1.54078 +** created, populated with this journal pointer and synced to disk.
 1.54079 +**
 1.54080 +** Once this is routine has returned, the only thing required to commit
 1.54081 +** the write-transaction for this database file is to delete the journal.
 1.54082 +*/
 1.54083 +SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
 1.54084 +  int rc = SQLITE_OK;
 1.54085 +  if( p->inTrans==TRANS_WRITE ){
 1.54086 +    BtShared *pBt = p->pBt;
 1.54087 +    sqlite3BtreeEnter(p);
 1.54088 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.54089 +    if( pBt->autoVacuum ){
 1.54090 +      rc = autoVacuumCommit(pBt);
 1.54091 +      if( rc!=SQLITE_OK ){
 1.54092 +        sqlite3BtreeLeave(p);
 1.54093 +        return rc;
 1.54094 +      }
 1.54095 +    }
 1.54096 +    if( pBt->bDoTruncate ){
 1.54097 +      sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
 1.54098 +    }
 1.54099 +#endif
 1.54100 +    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
 1.54101 +    sqlite3BtreeLeave(p);
 1.54102 +  }
 1.54103 +  return rc;
 1.54104 +}
 1.54105 +
 1.54106 +/*
 1.54107 +** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
 1.54108 +** at the conclusion of a transaction.
 1.54109 +*/
 1.54110 +static void btreeEndTransaction(Btree *p){
 1.54111 +  BtShared *pBt = p->pBt;
 1.54112 +  sqlite3 *db = p->db;
 1.54113 +  assert( sqlite3BtreeHoldsMutex(p) );
 1.54114 +
 1.54115 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.54116 +  pBt->bDoTruncate = 0;
 1.54117 +#endif
 1.54118 +  if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
 1.54119 +    /* If there are other active statements that belong to this database
 1.54120 +    ** handle, downgrade to a read-only transaction. The other statements
 1.54121 +    ** may still be reading from the database.  */
 1.54122 +    downgradeAllSharedCacheTableLocks(p);
 1.54123 +    p->inTrans = TRANS_READ;
 1.54124 +  }else{
 1.54125 +    /* If the handle had any kind of transaction open, decrement the 
 1.54126 +    ** transaction count of the shared btree. If the transaction count 
 1.54127 +    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
 1.54128 +    ** call below will unlock the pager.  */
 1.54129 +    if( p->inTrans!=TRANS_NONE ){
 1.54130 +      clearAllSharedCacheTableLocks(p);
 1.54131 +      pBt->nTransaction--;
 1.54132 +      if( 0==pBt->nTransaction ){
 1.54133 +        pBt->inTransaction = TRANS_NONE;
 1.54134 +      }
 1.54135 +    }
 1.54136 +
 1.54137 +    /* Set the current transaction state to TRANS_NONE and unlock the 
 1.54138 +    ** pager if this call closed the only read or write transaction.  */
 1.54139 +    p->inTrans = TRANS_NONE;
 1.54140 +    unlockBtreeIfUnused(pBt);
 1.54141 +  }
 1.54142 +
 1.54143 +  btreeIntegrity(p);
 1.54144 +}
 1.54145 +
 1.54146 +/*
 1.54147 +** Commit the transaction currently in progress.
 1.54148 +**
 1.54149 +** This routine implements the second phase of a 2-phase commit.  The
 1.54150 +** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
 1.54151 +** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
 1.54152 +** routine did all the work of writing information out to disk and flushing the
 1.54153 +** contents so that they are written onto the disk platter.  All this
 1.54154 +** routine has to do is delete or truncate or zero the header in the
 1.54155 +** the rollback journal (which causes the transaction to commit) and
 1.54156 +** drop locks.
 1.54157 +**
 1.54158 +** Normally, if an error occurs while the pager layer is attempting to 
 1.54159 +** finalize the underlying journal file, this function returns an error and
 1.54160 +** the upper layer will attempt a rollback. However, if the second argument
 1.54161 +** is non-zero then this b-tree transaction is part of a multi-file 
 1.54162 +** transaction. In this case, the transaction has already been committed 
 1.54163 +** (by deleting a master journal file) and the caller will ignore this 
 1.54164 +** functions return code. So, even if an error occurs in the pager layer,
 1.54165 +** reset the b-tree objects internal state to indicate that the write
 1.54166 +** transaction has been closed. This is quite safe, as the pager will have
 1.54167 +** transitioned to the error state.
 1.54168 +**
 1.54169 +** This will release the write lock on the database file.  If there
 1.54170 +** are no active cursors, it also releases the read lock.
 1.54171 +*/
 1.54172 +SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
 1.54173 +
 1.54174 +  if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
 1.54175 +  sqlite3BtreeEnter(p);
 1.54176 +  btreeIntegrity(p);
 1.54177 +
 1.54178 +  /* If the handle has a write-transaction open, commit the shared-btrees 
 1.54179 +  ** transaction and set the shared state to TRANS_READ.
 1.54180 +  */
 1.54181 +  if( p->inTrans==TRANS_WRITE ){
 1.54182 +    int rc;
 1.54183 +    BtShared *pBt = p->pBt;
 1.54184 +    assert( pBt->inTransaction==TRANS_WRITE );
 1.54185 +    assert( pBt->nTransaction>0 );
 1.54186 +    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
 1.54187 +    if( rc!=SQLITE_OK && bCleanup==0 ){
 1.54188 +      sqlite3BtreeLeave(p);
 1.54189 +      return rc;
 1.54190 +    }
 1.54191 +    pBt->inTransaction = TRANS_READ;
 1.54192 +    btreeClearHasContent(pBt);
 1.54193 +  }
 1.54194 +
 1.54195 +  btreeEndTransaction(p);
 1.54196 +  sqlite3BtreeLeave(p);
 1.54197 +  return SQLITE_OK;
 1.54198 +}
 1.54199 +
 1.54200 +/*
 1.54201 +** Do both phases of a commit.
 1.54202 +*/
 1.54203 +SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
 1.54204 +  int rc;
 1.54205 +  sqlite3BtreeEnter(p);
 1.54206 +  rc = sqlite3BtreeCommitPhaseOne(p, 0);
 1.54207 +  if( rc==SQLITE_OK ){
 1.54208 +    rc = sqlite3BtreeCommitPhaseTwo(p, 0);
 1.54209 +  }
 1.54210 +  sqlite3BtreeLeave(p);
 1.54211 +  return rc;
 1.54212 +}
 1.54213 +
 1.54214 +/*
 1.54215 +** This routine sets the state to CURSOR_FAULT and the error
 1.54216 +** code to errCode for every cursor on BtShared that pBtree
 1.54217 +** references.
 1.54218 +**
 1.54219 +** Every cursor is tripped, including cursors that belong
 1.54220 +** to other database connections that happen to be sharing
 1.54221 +** the cache with pBtree.
 1.54222 +**
 1.54223 +** This routine gets called when a rollback occurs.
 1.54224 +** All cursors using the same cache must be tripped
 1.54225 +** to prevent them from trying to use the btree after
 1.54226 +** the rollback.  The rollback may have deleted tables
 1.54227 +** or moved root pages, so it is not sufficient to
 1.54228 +** save the state of the cursor.  The cursor must be
 1.54229 +** invalidated.
 1.54230 +*/
 1.54231 +SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
 1.54232 +  BtCursor *p;
 1.54233 +  if( pBtree==0 ) return;
 1.54234 +  sqlite3BtreeEnter(pBtree);
 1.54235 +  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
 1.54236 +    int i;
 1.54237 +    sqlite3BtreeClearCursor(p);
 1.54238 +    p->eState = CURSOR_FAULT;
 1.54239 +    p->skipNext = errCode;
 1.54240 +    for(i=0; i<=p->iPage; i++){
 1.54241 +      releasePage(p->apPage[i]);
 1.54242 +      p->apPage[i] = 0;
 1.54243 +    }
 1.54244 +  }
 1.54245 +  sqlite3BtreeLeave(pBtree);
 1.54246 +}
 1.54247 +
 1.54248 +/*
 1.54249 +** Rollback the transaction in progress.  All cursors will be
 1.54250 +** invalided by this operation.  Any attempt to use a cursor
 1.54251 +** that was open at the beginning of this operation will result
 1.54252 +** in an error.
 1.54253 +**
 1.54254 +** This will release the write lock on the database file.  If there
 1.54255 +** are no active cursors, it also releases the read lock.
 1.54256 +*/
 1.54257 +SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
 1.54258 +  int rc;
 1.54259 +  BtShared *pBt = p->pBt;
 1.54260 +  MemPage *pPage1;
 1.54261 +
 1.54262 +  sqlite3BtreeEnter(p);
 1.54263 +  if( tripCode==SQLITE_OK ){
 1.54264 +    rc = tripCode = saveAllCursors(pBt, 0, 0);
 1.54265 +  }else{
 1.54266 +    rc = SQLITE_OK;
 1.54267 +  }
 1.54268 +  if( tripCode ){
 1.54269 +    sqlite3BtreeTripAllCursors(p, tripCode);
 1.54270 +  }
 1.54271 +  btreeIntegrity(p);
 1.54272 +
 1.54273 +  if( p->inTrans==TRANS_WRITE ){
 1.54274 +    int rc2;
 1.54275 +
 1.54276 +    assert( TRANS_WRITE==pBt->inTransaction );
 1.54277 +    rc2 = sqlite3PagerRollback(pBt->pPager);
 1.54278 +    if( rc2!=SQLITE_OK ){
 1.54279 +      rc = rc2;
 1.54280 +    }
 1.54281 +
 1.54282 +    /* The rollback may have destroyed the pPage1->aData value.  So
 1.54283 +    ** call btreeGetPage() on page 1 again to make
 1.54284 +    ** sure pPage1->aData is set correctly. */
 1.54285 +    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
 1.54286 +      int nPage = get4byte(28+(u8*)pPage1->aData);
 1.54287 +      testcase( nPage==0 );
 1.54288 +      if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
 1.54289 +      testcase( pBt->nPage!=nPage );
 1.54290 +      pBt->nPage = nPage;
 1.54291 +      releasePage(pPage1);
 1.54292 +    }
 1.54293 +    assert( countValidCursors(pBt, 1)==0 );
 1.54294 +    pBt->inTransaction = TRANS_READ;
 1.54295 +    btreeClearHasContent(pBt);
 1.54296 +  }
 1.54297 +
 1.54298 +  btreeEndTransaction(p);
 1.54299 +  sqlite3BtreeLeave(p);
 1.54300 +  return rc;
 1.54301 +}
 1.54302 +
 1.54303 +/*
 1.54304 +** Start a statement subtransaction. The subtransaction can can be rolled
 1.54305 +** back independently of the main transaction. You must start a transaction 
 1.54306 +** before starting a subtransaction. The subtransaction is ended automatically 
 1.54307 +** if the main transaction commits or rolls back.
 1.54308 +**
 1.54309 +** Statement subtransactions are used around individual SQL statements
 1.54310 +** that are contained within a BEGIN...COMMIT block.  If a constraint
 1.54311 +** error occurs within the statement, the effect of that one statement
 1.54312 +** can be rolled back without having to rollback the entire transaction.
 1.54313 +**
 1.54314 +** A statement sub-transaction is implemented as an anonymous savepoint. The
 1.54315 +** value passed as the second parameter is the total number of savepoints,
 1.54316 +** including the new anonymous savepoint, open on the B-Tree. i.e. if there
 1.54317 +** are no active savepoints and no other statement-transactions open,
 1.54318 +** iStatement is 1. This anonymous savepoint can be released or rolled back
 1.54319 +** using the sqlite3BtreeSavepoint() function.
 1.54320 +*/
 1.54321 +SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
 1.54322 +  int rc;
 1.54323 +  BtShared *pBt = p->pBt;
 1.54324 +  sqlite3BtreeEnter(p);
 1.54325 +  assert( p->inTrans==TRANS_WRITE );
 1.54326 +  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
 1.54327 +  assert( iStatement>0 );
 1.54328 +  assert( iStatement>p->db->nSavepoint );
 1.54329 +  assert( pBt->inTransaction==TRANS_WRITE );
 1.54330 +  /* At the pager level, a statement transaction is a savepoint with
 1.54331 +  ** an index greater than all savepoints created explicitly using
 1.54332 +  ** SQL statements. It is illegal to open, release or rollback any
 1.54333 +  ** such savepoints while the statement transaction savepoint is active.
 1.54334 +  */
 1.54335 +  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
 1.54336 +  sqlite3BtreeLeave(p);
 1.54337 +  return rc;
 1.54338 +}
 1.54339 +
 1.54340 +/*
 1.54341 +** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
 1.54342 +** or SAVEPOINT_RELEASE. This function either releases or rolls back the
 1.54343 +** savepoint identified by parameter iSavepoint, depending on the value 
 1.54344 +** of op.
 1.54345 +**
 1.54346 +** Normally, iSavepoint is greater than or equal to zero. However, if op is
 1.54347 +** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
 1.54348 +** contents of the entire transaction are rolled back. This is different
 1.54349 +** from a normal transaction rollback, as no locks are released and the
 1.54350 +** transaction remains open.
 1.54351 +*/
 1.54352 +SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
 1.54353 +  int rc = SQLITE_OK;
 1.54354 +  if( p && p->inTrans==TRANS_WRITE ){
 1.54355 +    BtShared *pBt = p->pBt;
 1.54356 +    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
 1.54357 +    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
 1.54358 +    sqlite3BtreeEnter(p);
 1.54359 +    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
 1.54360 +    if( rc==SQLITE_OK ){
 1.54361 +      if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
 1.54362 +        pBt->nPage = 0;
 1.54363 +      }
 1.54364 +      rc = newDatabase(pBt);
 1.54365 +      pBt->nPage = get4byte(28 + pBt->pPage1->aData);
 1.54366 +
 1.54367 +      /* The database size was written into the offset 28 of the header
 1.54368 +      ** when the transaction started, so we know that the value at offset
 1.54369 +      ** 28 is nonzero. */
 1.54370 +      assert( pBt->nPage>0 );
 1.54371 +    }
 1.54372 +    sqlite3BtreeLeave(p);
 1.54373 +  }
 1.54374 +  return rc;
 1.54375 +}
 1.54376 +
 1.54377 +/*
 1.54378 +** Create a new cursor for the BTree whose root is on the page
 1.54379 +** iTable. If a read-only cursor is requested, it is assumed that
 1.54380 +** the caller already has at least a read-only transaction open
 1.54381 +** on the database already. If a write-cursor is requested, then
 1.54382 +** the caller is assumed to have an open write transaction.
 1.54383 +**
 1.54384 +** If wrFlag==0, then the cursor can only be used for reading.
 1.54385 +** If wrFlag==1, then the cursor can be used for reading or for
 1.54386 +** writing if other conditions for writing are also met.  These
 1.54387 +** are the conditions that must be met in order for writing to
 1.54388 +** be allowed:
 1.54389 +**
 1.54390 +** 1:  The cursor must have been opened with wrFlag==1
 1.54391 +**
 1.54392 +** 2:  Other database connections that share the same pager cache
 1.54393 +**     but which are not in the READ_UNCOMMITTED state may not have
 1.54394 +**     cursors open with wrFlag==0 on the same table.  Otherwise
 1.54395 +**     the changes made by this write cursor would be visible to
 1.54396 +**     the read cursors in the other database connection.
 1.54397 +**
 1.54398 +** 3:  The database must be writable (not on read-only media)
 1.54399 +**
 1.54400 +** 4:  There must be an active transaction.
 1.54401 +**
 1.54402 +** No checking is done to make sure that page iTable really is the
 1.54403 +** root page of a b-tree.  If it is not, then the cursor acquired
 1.54404 +** will not work correctly.
 1.54405 +**
 1.54406 +** It is assumed that the sqlite3BtreeCursorZero() has been called
 1.54407 +** on pCur to initialize the memory space prior to invoking this routine.
 1.54408 +*/
 1.54409 +static int btreeCursor(
 1.54410 +  Btree *p,                              /* The btree */
 1.54411 +  int iTable,                            /* Root page of table to open */
 1.54412 +  int wrFlag,                            /* 1 to write. 0 read-only */
 1.54413 +  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
 1.54414 +  BtCursor *pCur                         /* Space for new cursor */
 1.54415 +){
 1.54416 +  BtShared *pBt = p->pBt;                /* Shared b-tree handle */
 1.54417 +
 1.54418 +  assert( sqlite3BtreeHoldsMutex(p) );
 1.54419 +  assert( wrFlag==0 || wrFlag==1 );
 1.54420 +
 1.54421 +  /* The following assert statements verify that if this is a sharable 
 1.54422 +  ** b-tree database, the connection is holding the required table locks, 
 1.54423 +  ** and that no other connection has any open cursor that conflicts with 
 1.54424 +  ** this lock.  */
 1.54425 +  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
 1.54426 +  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
 1.54427 +
 1.54428 +  /* Assert that the caller has opened the required transaction. */
 1.54429 +  assert( p->inTrans>TRANS_NONE );
 1.54430 +  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
 1.54431 +  assert( pBt->pPage1 && pBt->pPage1->aData );
 1.54432 +
 1.54433 +  if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
 1.54434 +    return SQLITE_READONLY;
 1.54435 +  }
 1.54436 +  if( iTable==1 && btreePagecount(pBt)==0 ){
 1.54437 +    assert( wrFlag==0 );
 1.54438 +    iTable = 0;
 1.54439 +  }
 1.54440 +
 1.54441 +  /* Now that no other errors can occur, finish filling in the BtCursor
 1.54442 +  ** variables and link the cursor into the BtShared list.  */
 1.54443 +  pCur->pgnoRoot = (Pgno)iTable;
 1.54444 +  pCur->iPage = -1;
 1.54445 +  pCur->pKeyInfo = pKeyInfo;
 1.54446 +  pCur->pBtree = p;
 1.54447 +  pCur->pBt = pBt;
 1.54448 +  pCur->wrFlag = (u8)wrFlag;
 1.54449 +  pCur->pNext = pBt->pCursor;
 1.54450 +  if( pCur->pNext ){
 1.54451 +    pCur->pNext->pPrev = pCur;
 1.54452 +  }
 1.54453 +  pBt->pCursor = pCur;
 1.54454 +  pCur->eState = CURSOR_INVALID;
 1.54455 +  return SQLITE_OK;
 1.54456 +}
 1.54457 +SQLITE_PRIVATE int sqlite3BtreeCursor(
 1.54458 +  Btree *p,                                   /* The btree */
 1.54459 +  int iTable,                                 /* Root page of table to open */
 1.54460 +  int wrFlag,                                 /* 1 to write. 0 read-only */
 1.54461 +  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
 1.54462 +  BtCursor *pCur                              /* Write new cursor here */
 1.54463 +){
 1.54464 +  int rc;
 1.54465 +  sqlite3BtreeEnter(p);
 1.54466 +  rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
 1.54467 +  sqlite3BtreeLeave(p);
 1.54468 +  return rc;
 1.54469 +}
 1.54470 +
 1.54471 +/*
 1.54472 +** Return the size of a BtCursor object in bytes.
 1.54473 +**
 1.54474 +** This interfaces is needed so that users of cursors can preallocate
 1.54475 +** sufficient storage to hold a cursor.  The BtCursor object is opaque
 1.54476 +** to users so they cannot do the sizeof() themselves - they must call
 1.54477 +** this routine.
 1.54478 +*/
 1.54479 +SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
 1.54480 +  return ROUND8(sizeof(BtCursor));
 1.54481 +}
 1.54482 +
 1.54483 +/*
 1.54484 +** Initialize memory that will be converted into a BtCursor object.
 1.54485 +**
 1.54486 +** The simple approach here would be to memset() the entire object
 1.54487 +** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
 1.54488 +** do not need to be zeroed and they are large, so we can save a lot
 1.54489 +** of run-time by skipping the initialization of those elements.
 1.54490 +*/
 1.54491 +SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
 1.54492 +  memset(p, 0, offsetof(BtCursor, iPage));
 1.54493 +}
 1.54494 +
 1.54495 +/*
 1.54496 +** Close a cursor.  The read lock on the database file is released
 1.54497 +** when the last cursor is closed.
 1.54498 +*/
 1.54499 +SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
 1.54500 +  Btree *pBtree = pCur->pBtree;
 1.54501 +  if( pBtree ){
 1.54502 +    int i;
 1.54503 +    BtShared *pBt = pCur->pBt;
 1.54504 +    sqlite3BtreeEnter(pBtree);
 1.54505 +    sqlite3BtreeClearCursor(pCur);
 1.54506 +    if( pCur->pPrev ){
 1.54507 +      pCur->pPrev->pNext = pCur->pNext;
 1.54508 +    }else{
 1.54509 +      pBt->pCursor = pCur->pNext;
 1.54510 +    }
 1.54511 +    if( pCur->pNext ){
 1.54512 +      pCur->pNext->pPrev = pCur->pPrev;
 1.54513 +    }
 1.54514 +    for(i=0; i<=pCur->iPage; i++){
 1.54515 +      releasePage(pCur->apPage[i]);
 1.54516 +    }
 1.54517 +    unlockBtreeIfUnused(pBt);
 1.54518 +    invalidateOverflowCache(pCur);
 1.54519 +    /* sqlite3_free(pCur); */
 1.54520 +    sqlite3BtreeLeave(pBtree);
 1.54521 +  }
 1.54522 +  return SQLITE_OK;
 1.54523 +}
 1.54524 +
 1.54525 +/*
 1.54526 +** Make sure the BtCursor* given in the argument has a valid
 1.54527 +** BtCursor.info structure.  If it is not already valid, call
 1.54528 +** btreeParseCell() to fill it in.
 1.54529 +**
 1.54530 +** BtCursor.info is a cache of the information in the current cell.
 1.54531 +** Using this cache reduces the number of calls to btreeParseCell().
 1.54532 +**
 1.54533 +** 2007-06-25:  There is a bug in some versions of MSVC that cause the
 1.54534 +** compiler to crash when getCellInfo() is implemented as a macro.
 1.54535 +** But there is a measureable speed advantage to using the macro on gcc
 1.54536 +** (when less compiler optimizations like -Os or -O0 are used and the
 1.54537 +** compiler is not doing agressive inlining.)  So we use a real function
 1.54538 +** for MSVC and a macro for everything else.  Ticket #2457.
 1.54539 +*/
 1.54540 +#ifndef NDEBUG
 1.54541 +  static void assertCellInfo(BtCursor *pCur){
 1.54542 +    CellInfo info;
 1.54543 +    int iPage = pCur->iPage;
 1.54544 +    memset(&info, 0, sizeof(info));
 1.54545 +    btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
 1.54546 +    assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
 1.54547 +  }
 1.54548 +#else
 1.54549 +  #define assertCellInfo(x)
 1.54550 +#endif
 1.54551 +#ifdef _MSC_VER
 1.54552 +  /* Use a real function in MSVC to work around bugs in that compiler. */
 1.54553 +  static void getCellInfo(BtCursor *pCur){
 1.54554 +    if( pCur->info.nSize==0 ){
 1.54555 +      int iPage = pCur->iPage;
 1.54556 +      btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
 1.54557 +      pCur->validNKey = 1;
 1.54558 +    }else{
 1.54559 +      assertCellInfo(pCur);
 1.54560 +    }
 1.54561 +  }
 1.54562 +#else /* if not _MSC_VER */
 1.54563 +  /* Use a macro in all other compilers so that the function is inlined */
 1.54564 +#define getCellInfo(pCur)                                                      \
 1.54565 +  if( pCur->info.nSize==0 ){                                                   \
 1.54566 +    int iPage = pCur->iPage;                                                   \
 1.54567 +    btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
 1.54568 +    pCur->validNKey = 1;                                                       \
 1.54569 +  }else{                                                                       \
 1.54570 +    assertCellInfo(pCur);                                                      \
 1.54571 +  }
 1.54572 +#endif /* _MSC_VER */
 1.54573 +
 1.54574 +#ifndef NDEBUG  /* The next routine used only within assert() statements */
 1.54575 +/*
 1.54576 +** Return true if the given BtCursor is valid.  A valid cursor is one
 1.54577 +** that is currently pointing to a row in a (non-empty) table.
 1.54578 +** This is a verification routine is used only within assert() statements.
 1.54579 +*/
 1.54580 +SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
 1.54581 +  return pCur && pCur->eState==CURSOR_VALID;
 1.54582 +}
 1.54583 +#endif /* NDEBUG */
 1.54584 +
 1.54585 +/*
 1.54586 +** Set *pSize to the size of the buffer needed to hold the value of
 1.54587 +** the key for the current entry.  If the cursor is not pointing
 1.54588 +** to a valid entry, *pSize is set to 0. 
 1.54589 +**
 1.54590 +** For a table with the INTKEY flag set, this routine returns the key
 1.54591 +** itself, not the number of bytes in the key.
 1.54592 +**
 1.54593 +** The caller must position the cursor prior to invoking this routine.
 1.54594 +** 
 1.54595 +** This routine cannot fail.  It always returns SQLITE_OK.  
 1.54596 +*/
 1.54597 +SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
 1.54598 +  assert( cursorHoldsMutex(pCur) );
 1.54599 +  assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
 1.54600 +  if( pCur->eState!=CURSOR_VALID ){
 1.54601 +    *pSize = 0;
 1.54602 +  }else{
 1.54603 +    getCellInfo(pCur);
 1.54604 +    *pSize = pCur->info.nKey;
 1.54605 +  }
 1.54606 +  return SQLITE_OK;
 1.54607 +}
 1.54608 +
 1.54609 +/*
 1.54610 +** Set *pSize to the number of bytes of data in the entry the
 1.54611 +** cursor currently points to.
 1.54612 +**
 1.54613 +** The caller must guarantee that the cursor is pointing to a non-NULL
 1.54614 +** valid entry.  In other words, the calling procedure must guarantee
 1.54615 +** that the cursor has Cursor.eState==CURSOR_VALID.
 1.54616 +**
 1.54617 +** Failure is not possible.  This function always returns SQLITE_OK.
 1.54618 +** It might just as well be a procedure (returning void) but we continue
 1.54619 +** to return an integer result code for historical reasons.
 1.54620 +*/
 1.54621 +SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
 1.54622 +  assert( cursorHoldsMutex(pCur) );
 1.54623 +  assert( pCur->eState==CURSOR_VALID );
 1.54624 +  getCellInfo(pCur);
 1.54625 +  *pSize = pCur->info.nData;
 1.54626 +  return SQLITE_OK;
 1.54627 +}
 1.54628 +
 1.54629 +/*
 1.54630 +** Given the page number of an overflow page in the database (parameter
 1.54631 +** ovfl), this function finds the page number of the next page in the 
 1.54632 +** linked list of overflow pages. If possible, it uses the auto-vacuum
 1.54633 +** pointer-map data instead of reading the content of page ovfl to do so. 
 1.54634 +**
 1.54635 +** If an error occurs an SQLite error code is returned. Otherwise:
 1.54636 +**
 1.54637 +** The page number of the next overflow page in the linked list is 
 1.54638 +** written to *pPgnoNext. If page ovfl is the last page in its linked 
 1.54639 +** list, *pPgnoNext is set to zero. 
 1.54640 +**
 1.54641 +** If ppPage is not NULL, and a reference to the MemPage object corresponding
 1.54642 +** to page number pOvfl was obtained, then *ppPage is set to point to that
 1.54643 +** reference. It is the responsibility of the caller to call releasePage()
 1.54644 +** on *ppPage to free the reference. In no reference was obtained (because
 1.54645 +** the pointer-map was used to obtain the value for *pPgnoNext), then
 1.54646 +** *ppPage is set to zero.
 1.54647 +*/
 1.54648 +static int getOverflowPage(
 1.54649 +  BtShared *pBt,               /* The database file */
 1.54650 +  Pgno ovfl,                   /* Current overflow page number */
 1.54651 +  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
 1.54652 +  Pgno *pPgnoNext              /* OUT: Next overflow page number */
 1.54653 +){
 1.54654 +  Pgno next = 0;
 1.54655 +  MemPage *pPage = 0;
 1.54656 +  int rc = SQLITE_OK;
 1.54657 +
 1.54658 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.54659 +  assert(pPgnoNext);
 1.54660 +
 1.54661 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.54662 +  /* Try to find the next page in the overflow list using the
 1.54663 +  ** autovacuum pointer-map pages. Guess that the next page in 
 1.54664 +  ** the overflow list is page number (ovfl+1). If that guess turns 
 1.54665 +  ** out to be wrong, fall back to loading the data of page 
 1.54666 +  ** number ovfl to determine the next page number.
 1.54667 +  */
 1.54668 +  if( pBt->autoVacuum ){
 1.54669 +    Pgno pgno;
 1.54670 +    Pgno iGuess = ovfl+1;
 1.54671 +    u8 eType;
 1.54672 +
 1.54673 +    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
 1.54674 +      iGuess++;
 1.54675 +    }
 1.54676 +
 1.54677 +    if( iGuess<=btreePagecount(pBt) ){
 1.54678 +      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
 1.54679 +      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
 1.54680 +        next = iGuess;
 1.54681 +        rc = SQLITE_DONE;
 1.54682 +      }
 1.54683 +    }
 1.54684 +  }
 1.54685 +#endif
 1.54686 +
 1.54687 +  assert( next==0 || rc==SQLITE_DONE );
 1.54688 +  if( rc==SQLITE_OK ){
 1.54689 +    rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
 1.54690 +    assert( rc==SQLITE_OK || pPage==0 );
 1.54691 +    if( rc==SQLITE_OK ){
 1.54692 +      next = get4byte(pPage->aData);
 1.54693 +    }
 1.54694 +  }
 1.54695 +
 1.54696 +  *pPgnoNext = next;
 1.54697 +  if( ppPage ){
 1.54698 +    *ppPage = pPage;
 1.54699 +  }else{
 1.54700 +    releasePage(pPage);
 1.54701 +  }
 1.54702 +  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
 1.54703 +}
 1.54704 +
 1.54705 +/*
 1.54706 +** Copy data from a buffer to a page, or from a page to a buffer.
 1.54707 +**
 1.54708 +** pPayload is a pointer to data stored on database page pDbPage.
 1.54709 +** If argument eOp is false, then nByte bytes of data are copied
 1.54710 +** from pPayload to the buffer pointed at by pBuf. If eOp is true,
 1.54711 +** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
 1.54712 +** of data are copied from the buffer pBuf to pPayload.
 1.54713 +**
 1.54714 +** SQLITE_OK is returned on success, otherwise an error code.
 1.54715 +*/
 1.54716 +static int copyPayload(
 1.54717 +  void *pPayload,           /* Pointer to page data */
 1.54718 +  void *pBuf,               /* Pointer to buffer */
 1.54719 +  int nByte,                /* Number of bytes to copy */
 1.54720 +  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
 1.54721 +  DbPage *pDbPage           /* Page containing pPayload */
 1.54722 +){
 1.54723 +  if( eOp ){
 1.54724 +    /* Copy data from buffer to page (a write operation) */
 1.54725 +    int rc = sqlite3PagerWrite(pDbPage);
 1.54726 +    if( rc!=SQLITE_OK ){
 1.54727 +      return rc;
 1.54728 +    }
 1.54729 +    memcpy(pPayload, pBuf, nByte);
 1.54730 +  }else{
 1.54731 +    /* Copy data from page to buffer (a read operation) */
 1.54732 +    memcpy(pBuf, pPayload, nByte);
 1.54733 +  }
 1.54734 +  return SQLITE_OK;
 1.54735 +}
 1.54736 +
 1.54737 +/*
 1.54738 +** This function is used to read or overwrite payload information
 1.54739 +** for the entry that the pCur cursor is pointing to. If the eOp
 1.54740 +** parameter is 0, this is a read operation (data copied into
 1.54741 +** buffer pBuf). If it is non-zero, a write (data copied from
 1.54742 +** buffer pBuf).
 1.54743 +**
 1.54744 +** A total of "amt" bytes are read or written beginning at "offset".
 1.54745 +** Data is read to or from the buffer pBuf.
 1.54746 +**
 1.54747 +** The content being read or written might appear on the main page
 1.54748 +** or be scattered out on multiple overflow pages.
 1.54749 +**
 1.54750 +** If the BtCursor.isIncrblobHandle flag is set, and the current
 1.54751 +** cursor entry uses one or more overflow pages, this function
 1.54752 +** allocates space for and lazily popluates the overflow page-list 
 1.54753 +** cache array (BtCursor.aOverflow). Subsequent calls use this
 1.54754 +** cache to make seeking to the supplied offset more efficient.
 1.54755 +**
 1.54756 +** Once an overflow page-list cache has been allocated, it may be
 1.54757 +** invalidated if some other cursor writes to the same table, or if
 1.54758 +** the cursor is moved to a different row. Additionally, in auto-vacuum
 1.54759 +** mode, the following events may invalidate an overflow page-list cache.
 1.54760 +**
 1.54761 +**   * An incremental vacuum,
 1.54762 +**   * A commit in auto_vacuum="full" mode,
 1.54763 +**   * Creating a table (may require moving an overflow page).
 1.54764 +*/
 1.54765 +static int accessPayload(
 1.54766 +  BtCursor *pCur,      /* Cursor pointing to entry to read from */
 1.54767 +  u32 offset,          /* Begin reading this far into payload */
 1.54768 +  u32 amt,             /* Read this many bytes */
 1.54769 +  unsigned char *pBuf, /* Write the bytes into this buffer */ 
 1.54770 +  int eOp              /* zero to read. non-zero to write. */
 1.54771 +){
 1.54772 +  unsigned char *aPayload;
 1.54773 +  int rc = SQLITE_OK;
 1.54774 +  u32 nKey;
 1.54775 +  int iIdx = 0;
 1.54776 +  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
 1.54777 +  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
 1.54778 +
 1.54779 +  assert( pPage );
 1.54780 +  assert( pCur->eState==CURSOR_VALID );
 1.54781 +  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
 1.54782 +  assert( cursorHoldsMutex(pCur) );
 1.54783 +
 1.54784 +  getCellInfo(pCur);
 1.54785 +  aPayload = pCur->info.pCell + pCur->info.nHeader;
 1.54786 +  nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
 1.54787 +
 1.54788 +  if( NEVER(offset+amt > nKey+pCur->info.nData) 
 1.54789 +   || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
 1.54790 +  ){
 1.54791 +    /* Trying to read or write past the end of the data is an error */
 1.54792 +    return SQLITE_CORRUPT_BKPT;
 1.54793 +  }
 1.54794 +
 1.54795 +  /* Check if data must be read/written to/from the btree page itself. */
 1.54796 +  if( offset<pCur->info.nLocal ){
 1.54797 +    int a = amt;
 1.54798 +    if( a+offset>pCur->info.nLocal ){
 1.54799 +      a = pCur->info.nLocal - offset;
 1.54800 +    }
 1.54801 +    rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
 1.54802 +    offset = 0;
 1.54803 +    pBuf += a;
 1.54804 +    amt -= a;
 1.54805 +  }else{
 1.54806 +    offset -= pCur->info.nLocal;
 1.54807 +  }
 1.54808 +
 1.54809 +  if( rc==SQLITE_OK && amt>0 ){
 1.54810 +    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
 1.54811 +    Pgno nextPage;
 1.54812 +
 1.54813 +    nextPage = get4byte(&aPayload[pCur->info.nLocal]);
 1.54814 +
 1.54815 +#ifndef SQLITE_OMIT_INCRBLOB
 1.54816 +    /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
 1.54817 +    ** has not been allocated, allocate it now. The array is sized at
 1.54818 +    ** one entry for each overflow page in the overflow chain. The
 1.54819 +    ** page number of the first overflow page is stored in aOverflow[0],
 1.54820 +    ** etc. A value of 0 in the aOverflow[] array means "not yet known"
 1.54821 +    ** (the cache is lazily populated).
 1.54822 +    */
 1.54823 +    if( pCur->isIncrblobHandle && !pCur->aOverflow ){
 1.54824 +      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
 1.54825 +      pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
 1.54826 +      /* nOvfl is always positive.  If it were zero, fetchPayload would have
 1.54827 +      ** been used instead of this routine. */
 1.54828 +      if( ALWAYS(nOvfl) && !pCur->aOverflow ){
 1.54829 +        rc = SQLITE_NOMEM;
 1.54830 +      }
 1.54831 +    }
 1.54832 +
 1.54833 +    /* If the overflow page-list cache has been allocated and the
 1.54834 +    ** entry for the first required overflow page is valid, skip
 1.54835 +    ** directly to it.
 1.54836 +    */
 1.54837 +    if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
 1.54838 +      iIdx = (offset/ovflSize);
 1.54839 +      nextPage = pCur->aOverflow[iIdx];
 1.54840 +      offset = (offset%ovflSize);
 1.54841 +    }
 1.54842 +#endif
 1.54843 +
 1.54844 +    for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
 1.54845 +
 1.54846 +#ifndef SQLITE_OMIT_INCRBLOB
 1.54847 +      /* If required, populate the overflow page-list cache. */
 1.54848 +      if( pCur->aOverflow ){
 1.54849 +        assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
 1.54850 +        pCur->aOverflow[iIdx] = nextPage;
 1.54851 +      }
 1.54852 +#endif
 1.54853 +
 1.54854 +      if( offset>=ovflSize ){
 1.54855 +        /* The only reason to read this page is to obtain the page
 1.54856 +        ** number for the next page in the overflow chain. The page
 1.54857 +        ** data is not required. So first try to lookup the overflow
 1.54858 +        ** page-list cache, if any, then fall back to the getOverflowPage()
 1.54859 +        ** function.
 1.54860 +        */
 1.54861 +#ifndef SQLITE_OMIT_INCRBLOB
 1.54862 +        if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
 1.54863 +          nextPage = pCur->aOverflow[iIdx+1];
 1.54864 +        } else 
 1.54865 +#endif
 1.54866 +          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
 1.54867 +        offset -= ovflSize;
 1.54868 +      }else{
 1.54869 +        /* Need to read this page properly. It contains some of the
 1.54870 +        ** range of data that is being read (eOp==0) or written (eOp!=0).
 1.54871 +        */
 1.54872 +#ifdef SQLITE_DIRECT_OVERFLOW_READ
 1.54873 +        sqlite3_file *fd;
 1.54874 +#endif
 1.54875 +        int a = amt;
 1.54876 +        if( a + offset > ovflSize ){
 1.54877 +          a = ovflSize - offset;
 1.54878 +        }
 1.54879 +
 1.54880 +#ifdef SQLITE_DIRECT_OVERFLOW_READ
 1.54881 +        /* If all the following are true:
 1.54882 +        **
 1.54883 +        **   1) this is a read operation, and 
 1.54884 +        **   2) data is required from the start of this overflow page, and
 1.54885 +        **   3) the database is file-backed, and
 1.54886 +        **   4) there is no open write-transaction, and
 1.54887 +        **   5) the database is not a WAL database,
 1.54888 +        **
 1.54889 +        ** then data can be read directly from the database file into the
 1.54890 +        ** output buffer, bypassing the page-cache altogether. This speeds
 1.54891 +        ** up loading large records that span many overflow pages.
 1.54892 +        */
 1.54893 +        if( eOp==0                                             /* (1) */
 1.54894 +         && offset==0                                          /* (2) */
 1.54895 +         && pBt->inTransaction==TRANS_READ                     /* (4) */
 1.54896 +         && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
 1.54897 +         && pBt->pPage1->aData[19]==0x01                       /* (5) */
 1.54898 +        ){
 1.54899 +          u8 aSave[4];
 1.54900 +          u8 *aWrite = &pBuf[-4];
 1.54901 +          memcpy(aSave, aWrite, 4);
 1.54902 +          rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
 1.54903 +          nextPage = get4byte(aWrite);
 1.54904 +          memcpy(aWrite, aSave, 4);
 1.54905 +        }else
 1.54906 +#endif
 1.54907 +
 1.54908 +        {
 1.54909 +          DbPage *pDbPage;
 1.54910 +          rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
 1.54911 +              (eOp==0 ? PAGER_GET_READONLY : 0)
 1.54912 +          );
 1.54913 +          if( rc==SQLITE_OK ){
 1.54914 +            aPayload = sqlite3PagerGetData(pDbPage);
 1.54915 +            nextPage = get4byte(aPayload);
 1.54916 +            rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
 1.54917 +            sqlite3PagerUnref(pDbPage);
 1.54918 +            offset = 0;
 1.54919 +          }
 1.54920 +        }
 1.54921 +        amt -= a;
 1.54922 +        pBuf += a;
 1.54923 +      }
 1.54924 +    }
 1.54925 +  }
 1.54926 +
 1.54927 +  if( rc==SQLITE_OK && amt>0 ){
 1.54928 +    return SQLITE_CORRUPT_BKPT;
 1.54929 +  }
 1.54930 +  return rc;
 1.54931 +}
 1.54932 +
 1.54933 +/*
 1.54934 +** Read part of the key associated with cursor pCur.  Exactly
 1.54935 +** "amt" bytes will be transfered into pBuf[].  The transfer
 1.54936 +** begins at "offset".
 1.54937 +**
 1.54938 +** The caller must ensure that pCur is pointing to a valid row
 1.54939 +** in the table.
 1.54940 +**
 1.54941 +** Return SQLITE_OK on success or an error code if anything goes
 1.54942 +** wrong.  An error is returned if "offset+amt" is larger than
 1.54943 +** the available payload.
 1.54944 +*/
 1.54945 +SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
 1.54946 +  assert( cursorHoldsMutex(pCur) );
 1.54947 +  assert( pCur->eState==CURSOR_VALID );
 1.54948 +  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
 1.54949 +  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
 1.54950 +  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
 1.54951 +}
 1.54952 +
 1.54953 +/*
 1.54954 +** Read part of the data associated with cursor pCur.  Exactly
 1.54955 +** "amt" bytes will be transfered into pBuf[].  The transfer
 1.54956 +** begins at "offset".
 1.54957 +**
 1.54958 +** Return SQLITE_OK on success or an error code if anything goes
 1.54959 +** wrong.  An error is returned if "offset+amt" is larger than
 1.54960 +** the available payload.
 1.54961 +*/
 1.54962 +SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
 1.54963 +  int rc;
 1.54964 +
 1.54965 +#ifndef SQLITE_OMIT_INCRBLOB
 1.54966 +  if ( pCur->eState==CURSOR_INVALID ){
 1.54967 +    return SQLITE_ABORT;
 1.54968 +  }
 1.54969 +#endif
 1.54970 +
 1.54971 +  assert( cursorHoldsMutex(pCur) );
 1.54972 +  rc = restoreCursorPosition(pCur);
 1.54973 +  if( rc==SQLITE_OK ){
 1.54974 +    assert( pCur->eState==CURSOR_VALID );
 1.54975 +    assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
 1.54976 +    assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
 1.54977 +    rc = accessPayload(pCur, offset, amt, pBuf, 0);
 1.54978 +  }
 1.54979 +  return rc;
 1.54980 +}
 1.54981 +
 1.54982 +/*
 1.54983 +** Return a pointer to payload information from the entry that the 
 1.54984 +** pCur cursor is pointing to.  The pointer is to the beginning of
 1.54985 +** the key if index btrees (pPage->intKey==0) and is the data for
 1.54986 +** table btrees (pPage->intKey==1). The number of bytes of available
 1.54987 +** key/data is written into *pAmt.  If *pAmt==0, then the value
 1.54988 +** returned will not be a valid pointer.
 1.54989 +**
 1.54990 +** This routine is an optimization.  It is common for the entire key
 1.54991 +** and data to fit on the local page and for there to be no overflow
 1.54992 +** pages.  When that is so, this routine can be used to access the
 1.54993 +** key and data without making a copy.  If the key and/or data spills
 1.54994 +** onto overflow pages, then accessPayload() must be used to reassemble
 1.54995 +** the key/data and copy it into a preallocated buffer.
 1.54996 +**
 1.54997 +** The pointer returned by this routine looks directly into the cached
 1.54998 +** page of the database.  The data might change or move the next time
 1.54999 +** any btree routine is called.
 1.55000 +*/
 1.55001 +static const void *fetchPayload(
 1.55002 +  BtCursor *pCur,      /* Cursor pointing to entry to read from */
 1.55003 +  u32 *pAmt            /* Write the number of available bytes here */
 1.55004 +){
 1.55005 +  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
 1.55006 +  assert( pCur->eState==CURSOR_VALID );
 1.55007 +  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
 1.55008 +  assert( cursorHoldsMutex(pCur) );
 1.55009 +  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
 1.55010 +  if( pCur->info.nSize==0 ){
 1.55011 +    btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
 1.55012 +                   &pCur->info);
 1.55013 +  }
 1.55014 +  *pAmt = pCur->info.nLocal;
 1.55015 +  return (void*)(pCur->info.pCell + pCur->info.nHeader);
 1.55016 +}
 1.55017 +
 1.55018 +
 1.55019 +/*
 1.55020 +** For the entry that cursor pCur is point to, return as
 1.55021 +** many bytes of the key or data as are available on the local
 1.55022 +** b-tree page.  Write the number of available bytes into *pAmt.
 1.55023 +**
 1.55024 +** The pointer returned is ephemeral.  The key/data may move
 1.55025 +** or be destroyed on the next call to any Btree routine,
 1.55026 +** including calls from other threads against the same cache.
 1.55027 +** Hence, a mutex on the BtShared should be held prior to calling
 1.55028 +** this routine.
 1.55029 +**
 1.55030 +** These routines is used to get quick access to key and data
 1.55031 +** in the common case where no overflow pages are used.
 1.55032 +*/
 1.55033 +SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
 1.55034 +  return fetchPayload(pCur, pAmt);
 1.55035 +}
 1.55036 +SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
 1.55037 +  return fetchPayload(pCur, pAmt);
 1.55038 +}
 1.55039 +
 1.55040 +
 1.55041 +/*
 1.55042 +** Move the cursor down to a new child page.  The newPgno argument is the
 1.55043 +** page number of the child page to move to.
 1.55044 +**
 1.55045 +** This function returns SQLITE_CORRUPT if the page-header flags field of
 1.55046 +** the new child page does not match the flags field of the parent (i.e.
 1.55047 +** if an intkey page appears to be the parent of a non-intkey page, or
 1.55048 +** vice-versa).
 1.55049 +*/
 1.55050 +static int moveToChild(BtCursor *pCur, u32 newPgno){
 1.55051 +  int rc;
 1.55052 +  int i = pCur->iPage;
 1.55053 +  MemPage *pNewPage;
 1.55054 +  BtShared *pBt = pCur->pBt;
 1.55055 +
 1.55056 +  assert( cursorHoldsMutex(pCur) );
 1.55057 +  assert( pCur->eState==CURSOR_VALID );
 1.55058 +  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
 1.55059 +  assert( pCur->iPage>=0 );
 1.55060 +  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
 1.55061 +    return SQLITE_CORRUPT_BKPT;
 1.55062 +  }
 1.55063 +  rc = getAndInitPage(pBt, newPgno, &pNewPage,
 1.55064 +               pCur->wrFlag==0 ? PAGER_GET_READONLY : 0);
 1.55065 +  if( rc ) return rc;
 1.55066 +  pCur->apPage[i+1] = pNewPage;
 1.55067 +  pCur->aiIdx[i+1] = 0;
 1.55068 +  pCur->iPage++;
 1.55069 +
 1.55070 +  pCur->info.nSize = 0;
 1.55071 +  pCur->validNKey = 0;
 1.55072 +  if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
 1.55073 +    return SQLITE_CORRUPT_BKPT;
 1.55074 +  }
 1.55075 +  return SQLITE_OK;
 1.55076 +}
 1.55077 +
 1.55078 +#if 0
 1.55079 +/*
 1.55080 +** Page pParent is an internal (non-leaf) tree page. This function 
 1.55081 +** asserts that page number iChild is the left-child if the iIdx'th
 1.55082 +** cell in page pParent. Or, if iIdx is equal to the total number of
 1.55083 +** cells in pParent, that page number iChild is the right-child of
 1.55084 +** the page.
 1.55085 +*/
 1.55086 +static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
 1.55087 +  assert( iIdx<=pParent->nCell );
 1.55088 +  if( iIdx==pParent->nCell ){
 1.55089 +    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
 1.55090 +  }else{
 1.55091 +    assert( get4byte(findCell(pParent, iIdx))==iChild );
 1.55092 +  }
 1.55093 +}
 1.55094 +#else
 1.55095 +#  define assertParentIndex(x,y,z) 
 1.55096 +#endif
 1.55097 +
 1.55098 +/*
 1.55099 +** Move the cursor up to the parent page.
 1.55100 +**
 1.55101 +** pCur->idx is set to the cell index that contains the pointer
 1.55102 +** to the page we are coming from.  If we are coming from the
 1.55103 +** right-most child page then pCur->idx is set to one more than
 1.55104 +** the largest cell index.
 1.55105 +*/
 1.55106 +static void moveToParent(BtCursor *pCur){
 1.55107 +  assert( cursorHoldsMutex(pCur) );
 1.55108 +  assert( pCur->eState==CURSOR_VALID );
 1.55109 +  assert( pCur->iPage>0 );
 1.55110 +  assert( pCur->apPage[pCur->iPage] );
 1.55111 +
 1.55112 +  /* UPDATE: It is actually possible for the condition tested by the assert
 1.55113 +  ** below to be untrue if the database file is corrupt. This can occur if
 1.55114 +  ** one cursor has modified page pParent while a reference to it is held 
 1.55115 +  ** by a second cursor. Which can only happen if a single page is linked
 1.55116 +  ** into more than one b-tree structure in a corrupt database.  */
 1.55117 +#if 0
 1.55118 +  assertParentIndex(
 1.55119 +    pCur->apPage[pCur->iPage-1], 
 1.55120 +    pCur->aiIdx[pCur->iPage-1], 
 1.55121 +    pCur->apPage[pCur->iPage]->pgno
 1.55122 +  );
 1.55123 +#endif
 1.55124 +  testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
 1.55125 +
 1.55126 +  releasePage(pCur->apPage[pCur->iPage]);
 1.55127 +  pCur->iPage--;
 1.55128 +  pCur->info.nSize = 0;
 1.55129 +  pCur->validNKey = 0;
 1.55130 +}
 1.55131 +
 1.55132 +/*
 1.55133 +** Move the cursor to point to the root page of its b-tree structure.
 1.55134 +**
 1.55135 +** If the table has a virtual root page, then the cursor is moved to point
 1.55136 +** to the virtual root page instead of the actual root page. A table has a
 1.55137 +** virtual root page when the actual root page contains no cells and a 
 1.55138 +** single child page. This can only happen with the table rooted at page 1.
 1.55139 +**
 1.55140 +** If the b-tree structure is empty, the cursor state is set to 
 1.55141 +** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
 1.55142 +** cell located on the root (or virtual root) page and the cursor state
 1.55143 +** is set to CURSOR_VALID.
 1.55144 +**
 1.55145 +** If this function returns successfully, it may be assumed that the
 1.55146 +** page-header flags indicate that the [virtual] root-page is the expected 
 1.55147 +** kind of b-tree page (i.e. if when opening the cursor the caller did not
 1.55148 +** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
 1.55149 +** indicating a table b-tree, or if the caller did specify a KeyInfo 
 1.55150 +** structure the flags byte is set to 0x02 or 0x0A, indicating an index
 1.55151 +** b-tree).
 1.55152 +*/
 1.55153 +static int moveToRoot(BtCursor *pCur){
 1.55154 +  MemPage *pRoot;
 1.55155 +  int rc = SQLITE_OK;
 1.55156 +
 1.55157 +  assert( cursorHoldsMutex(pCur) );
 1.55158 +  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
 1.55159 +  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
 1.55160 +  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
 1.55161 +  if( pCur->eState>=CURSOR_REQUIRESEEK ){
 1.55162 +    if( pCur->eState==CURSOR_FAULT ){
 1.55163 +      assert( pCur->skipNext!=SQLITE_OK );
 1.55164 +      return pCur->skipNext;
 1.55165 +    }
 1.55166 +    sqlite3BtreeClearCursor(pCur);
 1.55167 +  }
 1.55168 +
 1.55169 +  if( pCur->iPage>=0 ){
 1.55170 +    while( pCur->iPage ) releasePage(pCur->apPage[pCur->iPage--]);
 1.55171 +  }else if( pCur->pgnoRoot==0 ){
 1.55172 +    pCur->eState = CURSOR_INVALID;
 1.55173 +    return SQLITE_OK;
 1.55174 +  }else{
 1.55175 +    rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
 1.55176 +                        pCur->wrFlag==0 ? PAGER_GET_READONLY : 0);
 1.55177 +    if( rc!=SQLITE_OK ){
 1.55178 +      pCur->eState = CURSOR_INVALID;
 1.55179 +      return rc;
 1.55180 +    }
 1.55181 +    pCur->iPage = 0;
 1.55182 +  }
 1.55183 +  pRoot = pCur->apPage[0];
 1.55184 +  assert( pRoot->pgno==pCur->pgnoRoot );
 1.55185 +
 1.55186 +  /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
 1.55187 +  ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
 1.55188 +  ** NULL, the caller expects a table b-tree. If this is not the case,
 1.55189 +  ** return an SQLITE_CORRUPT error. 
 1.55190 +  **
 1.55191 +  ** Earlier versions of SQLite assumed that this test could not fail
 1.55192 +  ** if the root page was already loaded when this function was called (i.e.
 1.55193 +  ** if pCur->iPage>=0). But this is not so if the database is corrupted 
 1.55194 +  ** in such a way that page pRoot is linked into a second b-tree table 
 1.55195 +  ** (or the freelist).  */
 1.55196 +  assert( pRoot->intKey==1 || pRoot->intKey==0 );
 1.55197 +  if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
 1.55198 +    return SQLITE_CORRUPT_BKPT;
 1.55199 +  }
 1.55200 +
 1.55201 +  pCur->aiIdx[0] = 0;
 1.55202 +  pCur->info.nSize = 0;
 1.55203 +  pCur->atLast = 0;
 1.55204 +  pCur->validNKey = 0;
 1.55205 +
 1.55206 +  if( pRoot->nCell>0 ){
 1.55207 +    pCur->eState = CURSOR_VALID;
 1.55208 +  }else if( !pRoot->leaf ){
 1.55209 +    Pgno subpage;
 1.55210 +    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
 1.55211 +    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
 1.55212 +    pCur->eState = CURSOR_VALID;
 1.55213 +    rc = moveToChild(pCur, subpage);
 1.55214 +  }else{
 1.55215 +    pCur->eState = CURSOR_INVALID;
 1.55216 +  }
 1.55217 +  return rc;
 1.55218 +}
 1.55219 +
 1.55220 +/*
 1.55221 +** Move the cursor down to the left-most leaf entry beneath the
 1.55222 +** entry to which it is currently pointing.
 1.55223 +**
 1.55224 +** The left-most leaf is the one with the smallest key - the first
 1.55225 +** in ascending order.
 1.55226 +*/
 1.55227 +static int moveToLeftmost(BtCursor *pCur){
 1.55228 +  Pgno pgno;
 1.55229 +  int rc = SQLITE_OK;
 1.55230 +  MemPage *pPage;
 1.55231 +
 1.55232 +  assert( cursorHoldsMutex(pCur) );
 1.55233 +  assert( pCur->eState==CURSOR_VALID );
 1.55234 +  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
 1.55235 +    assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
 1.55236 +    pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
 1.55237 +    rc = moveToChild(pCur, pgno);
 1.55238 +  }
 1.55239 +  return rc;
 1.55240 +}
 1.55241 +
 1.55242 +/*
 1.55243 +** Move the cursor down to the right-most leaf entry beneath the
 1.55244 +** page to which it is currently pointing.  Notice the difference
 1.55245 +** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
 1.55246 +** finds the left-most entry beneath the *entry* whereas moveToRightmost()
 1.55247 +** finds the right-most entry beneath the *page*.
 1.55248 +**
 1.55249 +** The right-most entry is the one with the largest key - the last
 1.55250 +** key in ascending order.
 1.55251 +*/
 1.55252 +static int moveToRightmost(BtCursor *pCur){
 1.55253 +  Pgno pgno;
 1.55254 +  int rc = SQLITE_OK;
 1.55255 +  MemPage *pPage = 0;
 1.55256 +
 1.55257 +  assert( cursorHoldsMutex(pCur) );
 1.55258 +  assert( pCur->eState==CURSOR_VALID );
 1.55259 +  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
 1.55260 +    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
 1.55261 +    pCur->aiIdx[pCur->iPage] = pPage->nCell;
 1.55262 +    rc = moveToChild(pCur, pgno);
 1.55263 +  }
 1.55264 +  if( rc==SQLITE_OK ){
 1.55265 +    pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
 1.55266 +    pCur->info.nSize = 0;
 1.55267 +    pCur->validNKey = 0;
 1.55268 +  }
 1.55269 +  return rc;
 1.55270 +}
 1.55271 +
 1.55272 +/* Move the cursor to the first entry in the table.  Return SQLITE_OK
 1.55273 +** on success.  Set *pRes to 0 if the cursor actually points to something
 1.55274 +** or set *pRes to 1 if the table is empty.
 1.55275 +*/
 1.55276 +SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
 1.55277 +  int rc;
 1.55278 +
 1.55279 +  assert( cursorHoldsMutex(pCur) );
 1.55280 +  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
 1.55281 +  rc = moveToRoot(pCur);
 1.55282 +  if( rc==SQLITE_OK ){
 1.55283 +    if( pCur->eState==CURSOR_INVALID ){
 1.55284 +      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
 1.55285 +      *pRes = 1;
 1.55286 +    }else{
 1.55287 +      assert( pCur->apPage[pCur->iPage]->nCell>0 );
 1.55288 +      *pRes = 0;
 1.55289 +      rc = moveToLeftmost(pCur);
 1.55290 +    }
 1.55291 +  }
 1.55292 +  return rc;
 1.55293 +}
 1.55294 +
 1.55295 +/* Move the cursor to the last entry in the table.  Return SQLITE_OK
 1.55296 +** on success.  Set *pRes to 0 if the cursor actually points to something
 1.55297 +** or set *pRes to 1 if the table is empty.
 1.55298 +*/
 1.55299 +SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
 1.55300 +  int rc;
 1.55301 + 
 1.55302 +  assert( cursorHoldsMutex(pCur) );
 1.55303 +  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
 1.55304 +
 1.55305 +  /* If the cursor already points to the last entry, this is a no-op. */
 1.55306 +  if( CURSOR_VALID==pCur->eState && pCur->atLast ){
 1.55307 +#ifdef SQLITE_DEBUG
 1.55308 +    /* This block serves to assert() that the cursor really does point 
 1.55309 +    ** to the last entry in the b-tree. */
 1.55310 +    int ii;
 1.55311 +    for(ii=0; ii<pCur->iPage; ii++){
 1.55312 +      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
 1.55313 +    }
 1.55314 +    assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
 1.55315 +    assert( pCur->apPage[pCur->iPage]->leaf );
 1.55316 +#endif
 1.55317 +    return SQLITE_OK;
 1.55318 +  }
 1.55319 +
 1.55320 +  rc = moveToRoot(pCur);
 1.55321 +  if( rc==SQLITE_OK ){
 1.55322 +    if( CURSOR_INVALID==pCur->eState ){
 1.55323 +      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
 1.55324 +      *pRes = 1;
 1.55325 +    }else{
 1.55326 +      assert( pCur->eState==CURSOR_VALID );
 1.55327 +      *pRes = 0;
 1.55328 +      rc = moveToRightmost(pCur);
 1.55329 +      pCur->atLast = rc==SQLITE_OK ?1:0;
 1.55330 +    }
 1.55331 +  }
 1.55332 +  return rc;
 1.55333 +}
 1.55334 +
 1.55335 +/* Move the cursor so that it points to an entry near the key 
 1.55336 +** specified by pIdxKey or intKey.   Return a success code.
 1.55337 +**
 1.55338 +** For INTKEY tables, the intKey parameter is used.  pIdxKey 
 1.55339 +** must be NULL.  For index tables, pIdxKey is used and intKey
 1.55340 +** is ignored.
 1.55341 +**
 1.55342 +** If an exact match is not found, then the cursor is always
 1.55343 +** left pointing at a leaf page which would hold the entry if it
 1.55344 +** were present.  The cursor might point to an entry that comes
 1.55345 +** before or after the key.
 1.55346 +**
 1.55347 +** An integer is written into *pRes which is the result of
 1.55348 +** comparing the key with the entry to which the cursor is 
 1.55349 +** pointing.  The meaning of the integer written into
 1.55350 +** *pRes is as follows:
 1.55351 +**
 1.55352 +**     *pRes<0      The cursor is left pointing at an entry that
 1.55353 +**                  is smaller than intKey/pIdxKey or if the table is empty
 1.55354 +**                  and the cursor is therefore left point to nothing.
 1.55355 +**
 1.55356 +**     *pRes==0     The cursor is left pointing at an entry that
 1.55357 +**                  exactly matches intKey/pIdxKey.
 1.55358 +**
 1.55359 +**     *pRes>0      The cursor is left pointing at an entry that
 1.55360 +**                  is larger than intKey/pIdxKey.
 1.55361 +**
 1.55362 +*/
 1.55363 +SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
 1.55364 +  BtCursor *pCur,          /* The cursor to be moved */
 1.55365 +  UnpackedRecord *pIdxKey, /* Unpacked index key */
 1.55366 +  i64 intKey,              /* The table key */
 1.55367 +  int biasRight,           /* If true, bias the search to the high end */
 1.55368 +  int *pRes                /* Write search results here */
 1.55369 +){
 1.55370 +  int rc;
 1.55371 +  RecordCompare xRecordCompare;
 1.55372 +
 1.55373 +  assert( cursorHoldsMutex(pCur) );
 1.55374 +  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
 1.55375 +  assert( pRes );
 1.55376 +  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
 1.55377 +
 1.55378 +  /* If the cursor is already positioned at the point we are trying
 1.55379 +  ** to move to, then just return without doing any work */
 1.55380 +  if( pCur->eState==CURSOR_VALID && pCur->validNKey 
 1.55381 +   && pCur->apPage[0]->intKey 
 1.55382 +  ){
 1.55383 +    if( pCur->info.nKey==intKey ){
 1.55384 +      *pRes = 0;
 1.55385 +      return SQLITE_OK;
 1.55386 +    }
 1.55387 +    if( pCur->atLast && pCur->info.nKey<intKey ){
 1.55388 +      *pRes = -1;
 1.55389 +      return SQLITE_OK;
 1.55390 +    }
 1.55391 +  }
 1.55392 +
 1.55393 +  if( pIdxKey ){
 1.55394 +    xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
 1.55395 +    assert( pIdxKey->default_rc==1 
 1.55396 +         || pIdxKey->default_rc==0 
 1.55397 +         || pIdxKey->default_rc==-1
 1.55398 +    );
 1.55399 +  }else{
 1.55400 +    xRecordCompare = 0; /* All keys are integers */
 1.55401 +  }
 1.55402 +
 1.55403 +  rc = moveToRoot(pCur);
 1.55404 +  if( rc ){
 1.55405 +    return rc;
 1.55406 +  }
 1.55407 +  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
 1.55408 +  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
 1.55409 +  assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
 1.55410 +  if( pCur->eState==CURSOR_INVALID ){
 1.55411 +    *pRes = -1;
 1.55412 +    assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
 1.55413 +    return SQLITE_OK;
 1.55414 +  }
 1.55415 +  assert( pCur->apPage[0]->intKey || pIdxKey );
 1.55416 +  for(;;){
 1.55417 +    int lwr, upr, idx, c;
 1.55418 +    Pgno chldPg;
 1.55419 +    MemPage *pPage = pCur->apPage[pCur->iPage];
 1.55420 +    u8 *pCell;                          /* Pointer to current cell in pPage */
 1.55421 +
 1.55422 +    /* pPage->nCell must be greater than zero. If this is the root-page
 1.55423 +    ** the cursor would have been INVALID above and this for(;;) loop
 1.55424 +    ** not run. If this is not the root-page, then the moveToChild() routine
 1.55425 +    ** would have already detected db corruption. Similarly, pPage must
 1.55426 +    ** be the right kind (index or table) of b-tree page. Otherwise
 1.55427 +    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
 1.55428 +    assert( pPage->nCell>0 );
 1.55429 +    assert( pPage->intKey==(pIdxKey==0) );
 1.55430 +    lwr = 0;
 1.55431 +    upr = pPage->nCell-1;
 1.55432 +    assert( biasRight==0 || biasRight==1 );
 1.55433 +    idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
 1.55434 +    pCur->aiIdx[pCur->iPage] = (u16)idx;
 1.55435 +    if( xRecordCompare==0 ){
 1.55436 +      for(;;){
 1.55437 +        i64 nCellKey;
 1.55438 +        pCell = findCell(pPage, idx) + pPage->childPtrSize;
 1.55439 +        if( pPage->hasData ){
 1.55440 +          while( 0x80 <= *(pCell++) ){
 1.55441 +            if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
 1.55442 +          }
 1.55443 +        }
 1.55444 +        getVarint(pCell, (u64*)&nCellKey);
 1.55445 +        if( nCellKey<intKey ){
 1.55446 +          lwr = idx+1;
 1.55447 +          if( lwr>upr ){ c = -1; break; }
 1.55448 +        }else if( nCellKey>intKey ){
 1.55449 +          upr = idx-1;
 1.55450 +          if( lwr>upr ){ c = +1; break; }
 1.55451 +        }else{
 1.55452 +          assert( nCellKey==intKey );
 1.55453 +          pCur->validNKey = 1;
 1.55454 +          pCur->info.nKey = nCellKey;
 1.55455 +          pCur->aiIdx[pCur->iPage] = (u16)idx;
 1.55456 +          if( !pPage->leaf ){
 1.55457 +            lwr = idx;
 1.55458 +            goto moveto_next_layer;
 1.55459 +          }else{
 1.55460 +            *pRes = 0;
 1.55461 +            rc = SQLITE_OK;
 1.55462 +            goto moveto_finish;
 1.55463 +          }
 1.55464 +        }
 1.55465 +        assert( lwr+upr>=0 );
 1.55466 +        idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
 1.55467 +      }
 1.55468 +    }else{
 1.55469 +      for(;;){
 1.55470 +        int nCell;
 1.55471 +        pCell = findCell(pPage, idx) + pPage->childPtrSize;
 1.55472 +
 1.55473 +        /* The maximum supported page-size is 65536 bytes. This means that
 1.55474 +        ** the maximum number of record bytes stored on an index B-Tree
 1.55475 +        ** page is less than 16384 bytes and may be stored as a 2-byte
 1.55476 +        ** varint. This information is used to attempt to avoid parsing 
 1.55477 +        ** the entire cell by checking for the cases where the record is 
 1.55478 +        ** stored entirely within the b-tree page by inspecting the first 
 1.55479 +        ** 2 bytes of the cell.
 1.55480 +        */
 1.55481 +        nCell = pCell[0];
 1.55482 +        if( nCell<=pPage->max1bytePayload ){
 1.55483 +          /* This branch runs if the record-size field of the cell is a
 1.55484 +          ** single byte varint and the record fits entirely on the main
 1.55485 +          ** b-tree page.  */
 1.55486 +          testcase( pCell+nCell+1==pPage->aDataEnd );
 1.55487 +          c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey, 0);
 1.55488 +        }else if( !(pCell[1] & 0x80) 
 1.55489 +          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
 1.55490 +        ){
 1.55491 +          /* The record-size field is a 2 byte varint and the record 
 1.55492 +          ** fits entirely on the main b-tree page.  */
 1.55493 +          testcase( pCell+nCell+2==pPage->aDataEnd );
 1.55494 +          c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey, 0);
 1.55495 +        }else{
 1.55496 +          /* The record flows over onto one or more overflow pages. In
 1.55497 +          ** this case the whole cell needs to be parsed, a buffer allocated
 1.55498 +          ** and accessPayload() used to retrieve the record into the
 1.55499 +          ** buffer before VdbeRecordCompare() can be called. */
 1.55500 +          void *pCellKey;
 1.55501 +          u8 * const pCellBody = pCell - pPage->childPtrSize;
 1.55502 +          btreeParseCellPtr(pPage, pCellBody, &pCur->info);
 1.55503 +          nCell = (int)pCur->info.nKey;
 1.55504 +          pCellKey = sqlite3Malloc( nCell );
 1.55505 +          if( pCellKey==0 ){
 1.55506 +            rc = SQLITE_NOMEM;
 1.55507 +            goto moveto_finish;
 1.55508 +          }
 1.55509 +          pCur->aiIdx[pCur->iPage] = (u16)idx;
 1.55510 +          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
 1.55511 +          if( rc ){
 1.55512 +            sqlite3_free(pCellKey);
 1.55513 +            goto moveto_finish;
 1.55514 +          }
 1.55515 +          c = xRecordCompare(nCell, pCellKey, pIdxKey, 0);
 1.55516 +          sqlite3_free(pCellKey);
 1.55517 +        }
 1.55518 +        if( c<0 ){
 1.55519 +          lwr = idx+1;
 1.55520 +        }else if( c>0 ){
 1.55521 +          upr = idx-1;
 1.55522 +        }else{
 1.55523 +          assert( c==0 );
 1.55524 +          *pRes = 0;
 1.55525 +          rc = SQLITE_OK;
 1.55526 +          pCur->aiIdx[pCur->iPage] = (u16)idx;
 1.55527 +          goto moveto_finish;
 1.55528 +        }
 1.55529 +        if( lwr>upr ) break;
 1.55530 +        assert( lwr+upr>=0 );
 1.55531 +        idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
 1.55532 +      }
 1.55533 +    }
 1.55534 +    assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
 1.55535 +    assert( pPage->isInit );
 1.55536 +    if( pPage->leaf ){
 1.55537 +      assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
 1.55538 +      pCur->aiIdx[pCur->iPage] = (u16)idx;
 1.55539 +      *pRes = c;
 1.55540 +      rc = SQLITE_OK;
 1.55541 +      goto moveto_finish;
 1.55542 +    }
 1.55543 +moveto_next_layer:
 1.55544 +    if( lwr>=pPage->nCell ){
 1.55545 +      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
 1.55546 +    }else{
 1.55547 +      chldPg = get4byte(findCell(pPage, lwr));
 1.55548 +    }
 1.55549 +    pCur->aiIdx[pCur->iPage] = (u16)lwr;
 1.55550 +    rc = moveToChild(pCur, chldPg);
 1.55551 +    if( rc ) break;
 1.55552 +  }
 1.55553 +moveto_finish:
 1.55554 +  pCur->info.nSize = 0;
 1.55555 +  pCur->validNKey = 0;
 1.55556 +  return rc;
 1.55557 +}
 1.55558 +
 1.55559 +
 1.55560 +/*
 1.55561 +** Return TRUE if the cursor is not pointing at an entry of the table.
 1.55562 +**
 1.55563 +** TRUE will be returned after a call to sqlite3BtreeNext() moves
 1.55564 +** past the last entry in the table or sqlite3BtreePrev() moves past
 1.55565 +** the first entry.  TRUE is also returned if the table is empty.
 1.55566 +*/
 1.55567 +SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
 1.55568 +  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
 1.55569 +  ** have been deleted? This API will need to change to return an error code
 1.55570 +  ** as well as the boolean result value.
 1.55571 +  */
 1.55572 +  return (CURSOR_VALID!=pCur->eState);
 1.55573 +}
 1.55574 +
 1.55575 +/*
 1.55576 +** Advance the cursor to the next entry in the database.  If
 1.55577 +** successful then set *pRes=0.  If the cursor
 1.55578 +** was already pointing to the last entry in the database before
 1.55579 +** this routine was called, then set *pRes=1.
 1.55580 +**
 1.55581 +** The calling function will set *pRes to 0 or 1.  The initial *pRes value
 1.55582 +** will be 1 if the cursor being stepped corresponds to an SQL index and
 1.55583 +** if this routine could have been skipped if that SQL index had been
 1.55584 +** a unique index.  Otherwise the caller will have set *pRes to zero.
 1.55585 +** Zero is the common case. The btree implementation is free to use the
 1.55586 +** initial *pRes value as a hint to improve performance, but the current
 1.55587 +** SQLite btree implementation does not. (Note that the comdb2 btree
 1.55588 +** implementation does use this hint, however.)
 1.55589 +*/
 1.55590 +SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
 1.55591 +  int rc;
 1.55592 +  int idx;
 1.55593 +  MemPage *pPage;
 1.55594 +
 1.55595 +  assert( cursorHoldsMutex(pCur) );
 1.55596 +  assert( pRes!=0 );
 1.55597 +  assert( *pRes==0 || *pRes==1 );
 1.55598 +  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
 1.55599 +  if( pCur->eState!=CURSOR_VALID ){
 1.55600 +    rc = restoreCursorPosition(pCur);
 1.55601 +    if( rc!=SQLITE_OK ){
 1.55602 +      *pRes = 0;
 1.55603 +      return rc;
 1.55604 +    }
 1.55605 +    if( CURSOR_INVALID==pCur->eState ){
 1.55606 +      *pRes = 1;
 1.55607 +      return SQLITE_OK;
 1.55608 +    }
 1.55609 +    if( pCur->skipNext ){
 1.55610 +      assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
 1.55611 +      pCur->eState = CURSOR_VALID;
 1.55612 +      if( pCur->skipNext>0 ){
 1.55613 +        pCur->skipNext = 0;
 1.55614 +        *pRes = 0;
 1.55615 +        return SQLITE_OK;
 1.55616 +      }
 1.55617 +      pCur->skipNext = 0;
 1.55618 +    }
 1.55619 +  }
 1.55620 +
 1.55621 +  pPage = pCur->apPage[pCur->iPage];
 1.55622 +  idx = ++pCur->aiIdx[pCur->iPage];
 1.55623 +  assert( pPage->isInit );
 1.55624 +
 1.55625 +  /* If the database file is corrupt, it is possible for the value of idx 
 1.55626 +  ** to be invalid here. This can only occur if a second cursor modifies
 1.55627 +  ** the page while cursor pCur is holding a reference to it. Which can
 1.55628 +  ** only happen if the database is corrupt in such a way as to link the
 1.55629 +  ** page into more than one b-tree structure. */
 1.55630 +  testcase( idx>pPage->nCell );
 1.55631 +
 1.55632 +  pCur->info.nSize = 0;
 1.55633 +  pCur->validNKey = 0;
 1.55634 +  if( idx>=pPage->nCell ){
 1.55635 +    if( !pPage->leaf ){
 1.55636 +      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
 1.55637 +      if( rc ){
 1.55638 +        *pRes = 0;
 1.55639 +        return rc;
 1.55640 +      }
 1.55641 +      rc = moveToLeftmost(pCur);
 1.55642 +      *pRes = 0;
 1.55643 +      return rc;
 1.55644 +    }
 1.55645 +    do{
 1.55646 +      if( pCur->iPage==0 ){
 1.55647 +        *pRes = 1;
 1.55648 +        pCur->eState = CURSOR_INVALID;
 1.55649 +        return SQLITE_OK;
 1.55650 +      }
 1.55651 +      moveToParent(pCur);
 1.55652 +      pPage = pCur->apPage[pCur->iPage];
 1.55653 +    }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
 1.55654 +    *pRes = 0;
 1.55655 +    if( pPage->intKey ){
 1.55656 +      rc = sqlite3BtreeNext(pCur, pRes);
 1.55657 +    }else{
 1.55658 +      rc = SQLITE_OK;
 1.55659 +    }
 1.55660 +    return rc;
 1.55661 +  }
 1.55662 +  *pRes = 0;
 1.55663 +  if( pPage->leaf ){
 1.55664 +    return SQLITE_OK;
 1.55665 +  }
 1.55666 +  rc = moveToLeftmost(pCur);
 1.55667 +  return rc;
 1.55668 +}
 1.55669 +
 1.55670 +
 1.55671 +/*
 1.55672 +** Step the cursor to the back to the previous entry in the database.  If
 1.55673 +** successful then set *pRes=0.  If the cursor
 1.55674 +** was already pointing to the first entry in the database before
 1.55675 +** this routine was called, then set *pRes=1.
 1.55676 +**
 1.55677 +** The calling function will set *pRes to 0 or 1.  The initial *pRes value
 1.55678 +** will be 1 if the cursor being stepped corresponds to an SQL index and
 1.55679 +** if this routine could have been skipped if that SQL index had been
 1.55680 +** a unique index.  Otherwise the caller will have set *pRes to zero.
 1.55681 +** Zero is the common case. The btree implementation is free to use the
 1.55682 +** initial *pRes value as a hint to improve performance, but the current
 1.55683 +** SQLite btree implementation does not. (Note that the comdb2 btree
 1.55684 +** implementation does use this hint, however.)
 1.55685 +*/
 1.55686 +SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
 1.55687 +  int rc;
 1.55688 +  MemPage *pPage;
 1.55689 +
 1.55690 +  assert( cursorHoldsMutex(pCur) );
 1.55691 +  assert( pRes!=0 );
 1.55692 +  assert( *pRes==0 || *pRes==1 );
 1.55693 +  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
 1.55694 +  pCur->atLast = 0;
 1.55695 +  if( pCur->eState!=CURSOR_VALID ){
 1.55696 +    if( ALWAYS(pCur->eState>=CURSOR_REQUIRESEEK) ){
 1.55697 +      rc = btreeRestoreCursorPosition(pCur);
 1.55698 +      if( rc!=SQLITE_OK ){
 1.55699 +        *pRes = 0;
 1.55700 +        return rc;
 1.55701 +      }
 1.55702 +    }
 1.55703 +    if( CURSOR_INVALID==pCur->eState ){
 1.55704 +      *pRes = 1;
 1.55705 +      return SQLITE_OK;
 1.55706 +    }
 1.55707 +    if( pCur->skipNext ){
 1.55708 +      assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
 1.55709 +      pCur->eState = CURSOR_VALID;
 1.55710 +      if( pCur->skipNext<0 ){
 1.55711 +        pCur->skipNext = 0;
 1.55712 +        *pRes = 0;
 1.55713 +        return SQLITE_OK;
 1.55714 +      }
 1.55715 +      pCur->skipNext = 0;
 1.55716 +    }
 1.55717 +  }
 1.55718 +
 1.55719 +  pPage = pCur->apPage[pCur->iPage];
 1.55720 +  assert( pPage->isInit );
 1.55721 +  if( !pPage->leaf ){
 1.55722 +    int idx = pCur->aiIdx[pCur->iPage];
 1.55723 +    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
 1.55724 +    if( rc ){
 1.55725 +      *pRes = 0;
 1.55726 +      return rc;
 1.55727 +    }
 1.55728 +    rc = moveToRightmost(pCur);
 1.55729 +  }else{
 1.55730 +    while( pCur->aiIdx[pCur->iPage]==0 ){
 1.55731 +      if( pCur->iPage==0 ){
 1.55732 +        pCur->eState = CURSOR_INVALID;
 1.55733 +        *pRes = 1;
 1.55734 +        return SQLITE_OK;
 1.55735 +      }
 1.55736 +      moveToParent(pCur);
 1.55737 +    }
 1.55738 +    pCur->info.nSize = 0;
 1.55739 +    pCur->validNKey = 0;
 1.55740 +
 1.55741 +    pCur->aiIdx[pCur->iPage]--;
 1.55742 +    pPage = pCur->apPage[pCur->iPage];
 1.55743 +    if( pPage->intKey && !pPage->leaf ){
 1.55744 +      rc = sqlite3BtreePrevious(pCur, pRes);
 1.55745 +    }else{
 1.55746 +      rc = SQLITE_OK;
 1.55747 +    }
 1.55748 +  }
 1.55749 +  *pRes = 0;
 1.55750 +  return rc;
 1.55751 +}
 1.55752 +
 1.55753 +/*
 1.55754 +** Allocate a new page from the database file.
 1.55755 +**
 1.55756 +** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
 1.55757 +** has already been called on the new page.)  The new page has also
 1.55758 +** been referenced and the calling routine is responsible for calling
 1.55759 +** sqlite3PagerUnref() on the new page when it is done.
 1.55760 +**
 1.55761 +** SQLITE_OK is returned on success.  Any other return value indicates
 1.55762 +** an error.  *ppPage and *pPgno are undefined in the event of an error.
 1.55763 +** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
 1.55764 +**
 1.55765 +** If the "nearby" parameter is not 0, then an effort is made to 
 1.55766 +** locate a page close to the page number "nearby".  This can be used in an
 1.55767 +** attempt to keep related pages close to each other in the database file,
 1.55768 +** which in turn can make database access faster.
 1.55769 +**
 1.55770 +** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
 1.55771 +** anywhere on the free-list, then it is guaranteed to be returned.  If
 1.55772 +** eMode is BTALLOC_LT then the page returned will be less than or equal
 1.55773 +** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
 1.55774 +** are no restrictions on which page is returned.
 1.55775 +*/
 1.55776 +static int allocateBtreePage(
 1.55777 +  BtShared *pBt,         /* The btree */
 1.55778 +  MemPage **ppPage,      /* Store pointer to the allocated page here */
 1.55779 +  Pgno *pPgno,           /* Store the page number here */
 1.55780 +  Pgno nearby,           /* Search for a page near this one */
 1.55781 +  u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
 1.55782 +){
 1.55783 +  MemPage *pPage1;
 1.55784 +  int rc;
 1.55785 +  u32 n;     /* Number of pages on the freelist */
 1.55786 +  u32 k;     /* Number of leaves on the trunk of the freelist */
 1.55787 +  MemPage *pTrunk = 0;
 1.55788 +  MemPage *pPrevTrunk = 0;
 1.55789 +  Pgno mxPage;     /* Total size of the database file */
 1.55790 +
 1.55791 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.55792 +  assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
 1.55793 +  pPage1 = pBt->pPage1;
 1.55794 +  mxPage = btreePagecount(pBt);
 1.55795 +  n = get4byte(&pPage1->aData[36]);
 1.55796 +  testcase( n==mxPage-1 );
 1.55797 +  if( n>=mxPage ){
 1.55798 +    return SQLITE_CORRUPT_BKPT;
 1.55799 +  }
 1.55800 +  if( n>0 ){
 1.55801 +    /* There are pages on the freelist.  Reuse one of those pages. */
 1.55802 +    Pgno iTrunk;
 1.55803 +    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
 1.55804 +    
 1.55805 +    /* If eMode==BTALLOC_EXACT and a query of the pointer-map
 1.55806 +    ** shows that the page 'nearby' is somewhere on the free-list, then
 1.55807 +    ** the entire-list will be searched for that page.
 1.55808 +    */
 1.55809 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.55810 +    if( eMode==BTALLOC_EXACT ){
 1.55811 +      if( nearby<=mxPage ){
 1.55812 +        u8 eType;
 1.55813 +        assert( nearby>0 );
 1.55814 +        assert( pBt->autoVacuum );
 1.55815 +        rc = ptrmapGet(pBt, nearby, &eType, 0);
 1.55816 +        if( rc ) return rc;
 1.55817 +        if( eType==PTRMAP_FREEPAGE ){
 1.55818 +          searchList = 1;
 1.55819 +        }
 1.55820 +      }
 1.55821 +    }else if( eMode==BTALLOC_LE ){
 1.55822 +      searchList = 1;
 1.55823 +    }
 1.55824 +#endif
 1.55825 +
 1.55826 +    /* Decrement the free-list count by 1. Set iTrunk to the index of the
 1.55827 +    ** first free-list trunk page. iPrevTrunk is initially 1.
 1.55828 +    */
 1.55829 +    rc = sqlite3PagerWrite(pPage1->pDbPage);
 1.55830 +    if( rc ) return rc;
 1.55831 +    put4byte(&pPage1->aData[36], n-1);
 1.55832 +
 1.55833 +    /* The code within this loop is run only once if the 'searchList' variable
 1.55834 +    ** is not true. Otherwise, it runs once for each trunk-page on the
 1.55835 +    ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
 1.55836 +    ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
 1.55837 +    */
 1.55838 +    do {
 1.55839 +      pPrevTrunk = pTrunk;
 1.55840 +      if( pPrevTrunk ){
 1.55841 +        iTrunk = get4byte(&pPrevTrunk->aData[0]);
 1.55842 +      }else{
 1.55843 +        iTrunk = get4byte(&pPage1->aData[32]);
 1.55844 +      }
 1.55845 +      testcase( iTrunk==mxPage );
 1.55846 +      if( iTrunk>mxPage ){
 1.55847 +        rc = SQLITE_CORRUPT_BKPT;
 1.55848 +      }else{
 1.55849 +        rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
 1.55850 +      }
 1.55851 +      if( rc ){
 1.55852 +        pTrunk = 0;
 1.55853 +        goto end_allocate_page;
 1.55854 +      }
 1.55855 +      assert( pTrunk!=0 );
 1.55856 +      assert( pTrunk->aData!=0 );
 1.55857 +
 1.55858 +      k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
 1.55859 +      if( k==0 && !searchList ){
 1.55860 +        /* The trunk has no leaves and the list is not being searched. 
 1.55861 +        ** So extract the trunk page itself and use it as the newly 
 1.55862 +        ** allocated page */
 1.55863 +        assert( pPrevTrunk==0 );
 1.55864 +        rc = sqlite3PagerWrite(pTrunk->pDbPage);
 1.55865 +        if( rc ){
 1.55866 +          goto end_allocate_page;
 1.55867 +        }
 1.55868 +        *pPgno = iTrunk;
 1.55869 +        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
 1.55870 +        *ppPage = pTrunk;
 1.55871 +        pTrunk = 0;
 1.55872 +        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
 1.55873 +      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
 1.55874 +        /* Value of k is out of range.  Database corruption */
 1.55875 +        rc = SQLITE_CORRUPT_BKPT;
 1.55876 +        goto end_allocate_page;
 1.55877 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.55878 +      }else if( searchList 
 1.55879 +            && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE)) 
 1.55880 +      ){
 1.55881 +        /* The list is being searched and this trunk page is the page
 1.55882 +        ** to allocate, regardless of whether it has leaves.
 1.55883 +        */
 1.55884 +        *pPgno = iTrunk;
 1.55885 +        *ppPage = pTrunk;
 1.55886 +        searchList = 0;
 1.55887 +        rc = sqlite3PagerWrite(pTrunk->pDbPage);
 1.55888 +        if( rc ){
 1.55889 +          goto end_allocate_page;
 1.55890 +        }
 1.55891 +        if( k==0 ){
 1.55892 +          if( !pPrevTrunk ){
 1.55893 +            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
 1.55894 +          }else{
 1.55895 +            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
 1.55896 +            if( rc!=SQLITE_OK ){
 1.55897 +              goto end_allocate_page;
 1.55898 +            }
 1.55899 +            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
 1.55900 +          }
 1.55901 +        }else{
 1.55902 +          /* The trunk page is required by the caller but it contains 
 1.55903 +          ** pointers to free-list leaves. The first leaf becomes a trunk
 1.55904 +          ** page in this case.
 1.55905 +          */
 1.55906 +          MemPage *pNewTrunk;
 1.55907 +          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
 1.55908 +          if( iNewTrunk>mxPage ){ 
 1.55909 +            rc = SQLITE_CORRUPT_BKPT;
 1.55910 +            goto end_allocate_page;
 1.55911 +          }
 1.55912 +          testcase( iNewTrunk==mxPage );
 1.55913 +          rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
 1.55914 +          if( rc!=SQLITE_OK ){
 1.55915 +            goto end_allocate_page;
 1.55916 +          }
 1.55917 +          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
 1.55918 +          if( rc!=SQLITE_OK ){
 1.55919 +            releasePage(pNewTrunk);
 1.55920 +            goto end_allocate_page;
 1.55921 +          }
 1.55922 +          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
 1.55923 +          put4byte(&pNewTrunk->aData[4], k-1);
 1.55924 +          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
 1.55925 +          releasePage(pNewTrunk);
 1.55926 +          if( !pPrevTrunk ){
 1.55927 +            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
 1.55928 +            put4byte(&pPage1->aData[32], iNewTrunk);
 1.55929 +          }else{
 1.55930 +            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
 1.55931 +            if( rc ){
 1.55932 +              goto end_allocate_page;
 1.55933 +            }
 1.55934 +            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
 1.55935 +          }
 1.55936 +        }
 1.55937 +        pTrunk = 0;
 1.55938 +        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
 1.55939 +#endif
 1.55940 +      }else if( k>0 ){
 1.55941 +        /* Extract a leaf from the trunk */
 1.55942 +        u32 closest;
 1.55943 +        Pgno iPage;
 1.55944 +        unsigned char *aData = pTrunk->aData;
 1.55945 +        if( nearby>0 ){
 1.55946 +          u32 i;
 1.55947 +          closest = 0;
 1.55948 +          if( eMode==BTALLOC_LE ){
 1.55949 +            for(i=0; i<k; i++){
 1.55950 +              iPage = get4byte(&aData[8+i*4]);
 1.55951 +              if( iPage<=nearby ){
 1.55952 +                closest = i;
 1.55953 +                break;
 1.55954 +              }
 1.55955 +            }
 1.55956 +          }else{
 1.55957 +            int dist;
 1.55958 +            dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
 1.55959 +            for(i=1; i<k; i++){
 1.55960 +              int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
 1.55961 +              if( d2<dist ){
 1.55962 +                closest = i;
 1.55963 +                dist = d2;
 1.55964 +              }
 1.55965 +            }
 1.55966 +          }
 1.55967 +        }else{
 1.55968 +          closest = 0;
 1.55969 +        }
 1.55970 +
 1.55971 +        iPage = get4byte(&aData[8+closest*4]);
 1.55972 +        testcase( iPage==mxPage );
 1.55973 +        if( iPage>mxPage ){
 1.55974 +          rc = SQLITE_CORRUPT_BKPT;
 1.55975 +          goto end_allocate_page;
 1.55976 +        }
 1.55977 +        testcase( iPage==mxPage );
 1.55978 +        if( !searchList 
 1.55979 +         || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE)) 
 1.55980 +        ){
 1.55981 +          int noContent;
 1.55982 +          *pPgno = iPage;
 1.55983 +          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
 1.55984 +                 ": %d more free pages\n",
 1.55985 +                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
 1.55986 +          rc = sqlite3PagerWrite(pTrunk->pDbPage);
 1.55987 +          if( rc ) goto end_allocate_page;
 1.55988 +          if( closest<k-1 ){
 1.55989 +            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
 1.55990 +          }
 1.55991 +          put4byte(&aData[4], k-1);
 1.55992 +          noContent = !btreeGetHasContent(pBt, *pPgno) ? PAGER_GET_NOCONTENT : 0;
 1.55993 +          rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
 1.55994 +          if( rc==SQLITE_OK ){
 1.55995 +            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
 1.55996 +            if( rc!=SQLITE_OK ){
 1.55997 +              releasePage(*ppPage);
 1.55998 +            }
 1.55999 +          }
 1.56000 +          searchList = 0;
 1.56001 +        }
 1.56002 +      }
 1.56003 +      releasePage(pPrevTrunk);
 1.56004 +      pPrevTrunk = 0;
 1.56005 +    }while( searchList );
 1.56006 +  }else{
 1.56007 +    /* There are no pages on the freelist, so append a new page to the
 1.56008 +    ** database image.
 1.56009 +    **
 1.56010 +    ** Normally, new pages allocated by this block can be requested from the
 1.56011 +    ** pager layer with the 'no-content' flag set. This prevents the pager
 1.56012 +    ** from trying to read the pages content from disk. However, if the
 1.56013 +    ** current transaction has already run one or more incremental-vacuum
 1.56014 +    ** steps, then the page we are about to allocate may contain content
 1.56015 +    ** that is required in the event of a rollback. In this case, do
 1.56016 +    ** not set the no-content flag. This causes the pager to load and journal
 1.56017 +    ** the current page content before overwriting it.
 1.56018 +    **
 1.56019 +    ** Note that the pager will not actually attempt to load or journal 
 1.56020 +    ** content for any page that really does lie past the end of the database
 1.56021 +    ** file on disk. So the effects of disabling the no-content optimization
 1.56022 +    ** here are confined to those pages that lie between the end of the
 1.56023 +    ** database image and the end of the database file.
 1.56024 +    */
 1.56025 +    int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate)) ? PAGER_GET_NOCONTENT : 0;
 1.56026 +
 1.56027 +    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
 1.56028 +    if( rc ) return rc;
 1.56029 +    pBt->nPage++;
 1.56030 +    if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
 1.56031 +
 1.56032 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.56033 +    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
 1.56034 +      /* If *pPgno refers to a pointer-map page, allocate two new pages
 1.56035 +      ** at the end of the file instead of one. The first allocated page
 1.56036 +      ** becomes a new pointer-map page, the second is used by the caller.
 1.56037 +      */
 1.56038 +      MemPage *pPg = 0;
 1.56039 +      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
 1.56040 +      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
 1.56041 +      rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
 1.56042 +      if( rc==SQLITE_OK ){
 1.56043 +        rc = sqlite3PagerWrite(pPg->pDbPage);
 1.56044 +        releasePage(pPg);
 1.56045 +      }
 1.56046 +      if( rc ) return rc;
 1.56047 +      pBt->nPage++;
 1.56048 +      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
 1.56049 +    }
 1.56050 +#endif
 1.56051 +    put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
 1.56052 +    *pPgno = pBt->nPage;
 1.56053 +
 1.56054 +    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
 1.56055 +    rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
 1.56056 +    if( rc ) return rc;
 1.56057 +    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
 1.56058 +    if( rc!=SQLITE_OK ){
 1.56059 +      releasePage(*ppPage);
 1.56060 +    }
 1.56061 +    TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
 1.56062 +  }
 1.56063 +
 1.56064 +  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
 1.56065 +
 1.56066 +end_allocate_page:
 1.56067 +  releasePage(pTrunk);
 1.56068 +  releasePage(pPrevTrunk);
 1.56069 +  if( rc==SQLITE_OK ){
 1.56070 +    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
 1.56071 +      releasePage(*ppPage);
 1.56072 +      *ppPage = 0;
 1.56073 +      return SQLITE_CORRUPT_BKPT;
 1.56074 +    }
 1.56075 +    (*ppPage)->isInit = 0;
 1.56076 +  }else{
 1.56077 +    *ppPage = 0;
 1.56078 +  }
 1.56079 +  assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
 1.56080 +  return rc;
 1.56081 +}
 1.56082 +
 1.56083 +/*
 1.56084 +** This function is used to add page iPage to the database file free-list. 
 1.56085 +** It is assumed that the page is not already a part of the free-list.
 1.56086 +**
 1.56087 +** The value passed as the second argument to this function is optional.
 1.56088 +** If the caller happens to have a pointer to the MemPage object 
 1.56089 +** corresponding to page iPage handy, it may pass it as the second value. 
 1.56090 +** Otherwise, it may pass NULL.
 1.56091 +**
 1.56092 +** If a pointer to a MemPage object is passed as the second argument,
 1.56093 +** its reference count is not altered by this function.
 1.56094 +*/
 1.56095 +static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
 1.56096 +  MemPage *pTrunk = 0;                /* Free-list trunk page */
 1.56097 +  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
 1.56098 +  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
 1.56099 +  MemPage *pPage;                     /* Page being freed. May be NULL. */
 1.56100 +  int rc;                             /* Return Code */
 1.56101 +  int nFree;                          /* Initial number of pages on free-list */
 1.56102 +
 1.56103 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.56104 +  assert( iPage>1 );
 1.56105 +  assert( !pMemPage || pMemPage->pgno==iPage );
 1.56106 +
 1.56107 +  if( pMemPage ){
 1.56108 +    pPage = pMemPage;
 1.56109 +    sqlite3PagerRef(pPage->pDbPage);
 1.56110 +  }else{
 1.56111 +    pPage = btreePageLookup(pBt, iPage);
 1.56112 +  }
 1.56113 +
 1.56114 +  /* Increment the free page count on pPage1 */
 1.56115 +  rc = sqlite3PagerWrite(pPage1->pDbPage);
 1.56116 +  if( rc ) goto freepage_out;
 1.56117 +  nFree = get4byte(&pPage1->aData[36]);
 1.56118 +  put4byte(&pPage1->aData[36], nFree+1);
 1.56119 +
 1.56120 +  if( pBt->btsFlags & BTS_SECURE_DELETE ){
 1.56121 +    /* If the secure_delete option is enabled, then
 1.56122 +    ** always fully overwrite deleted information with zeros.
 1.56123 +    */
 1.56124 +    if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
 1.56125 +     ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
 1.56126 +    ){
 1.56127 +      goto freepage_out;
 1.56128 +    }
 1.56129 +    memset(pPage->aData, 0, pPage->pBt->pageSize);
 1.56130 +  }
 1.56131 +
 1.56132 +  /* If the database supports auto-vacuum, write an entry in the pointer-map
 1.56133 +  ** to indicate that the page is free.
 1.56134 +  */
 1.56135 +  if( ISAUTOVACUUM ){
 1.56136 +    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
 1.56137 +    if( rc ) goto freepage_out;
 1.56138 +  }
 1.56139 +
 1.56140 +  /* Now manipulate the actual database free-list structure. There are two
 1.56141 +  ** possibilities. If the free-list is currently empty, or if the first
 1.56142 +  ** trunk page in the free-list is full, then this page will become a
 1.56143 +  ** new free-list trunk page. Otherwise, it will become a leaf of the
 1.56144 +  ** first trunk page in the current free-list. This block tests if it
 1.56145 +  ** is possible to add the page as a new free-list leaf.
 1.56146 +  */
 1.56147 +  if( nFree!=0 ){
 1.56148 +    u32 nLeaf;                /* Initial number of leaf cells on trunk page */
 1.56149 +
 1.56150 +    iTrunk = get4byte(&pPage1->aData[32]);
 1.56151 +    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
 1.56152 +    if( rc!=SQLITE_OK ){
 1.56153 +      goto freepage_out;
 1.56154 +    }
 1.56155 +
 1.56156 +    nLeaf = get4byte(&pTrunk->aData[4]);
 1.56157 +    assert( pBt->usableSize>32 );
 1.56158 +    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
 1.56159 +      rc = SQLITE_CORRUPT_BKPT;
 1.56160 +      goto freepage_out;
 1.56161 +    }
 1.56162 +    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
 1.56163 +      /* In this case there is room on the trunk page to insert the page
 1.56164 +      ** being freed as a new leaf.
 1.56165 +      **
 1.56166 +      ** Note that the trunk page is not really full until it contains
 1.56167 +      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
 1.56168 +      ** coded.  But due to a coding error in versions of SQLite prior to
 1.56169 +      ** 3.6.0, databases with freelist trunk pages holding more than
 1.56170 +      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
 1.56171 +      ** to maintain backwards compatibility with older versions of SQLite,
 1.56172 +      ** we will continue to restrict the number of entries to usableSize/4 - 8
 1.56173 +      ** for now.  At some point in the future (once everyone has upgraded
 1.56174 +      ** to 3.6.0 or later) we should consider fixing the conditional above
 1.56175 +      ** to read "usableSize/4-2" instead of "usableSize/4-8".
 1.56176 +      */
 1.56177 +      rc = sqlite3PagerWrite(pTrunk->pDbPage);
 1.56178 +      if( rc==SQLITE_OK ){
 1.56179 +        put4byte(&pTrunk->aData[4], nLeaf+1);
 1.56180 +        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
 1.56181 +        if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
 1.56182 +          sqlite3PagerDontWrite(pPage->pDbPage);
 1.56183 +        }
 1.56184 +        rc = btreeSetHasContent(pBt, iPage);
 1.56185 +      }
 1.56186 +      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
 1.56187 +      goto freepage_out;
 1.56188 +    }
 1.56189 +  }
 1.56190 +
 1.56191 +  /* If control flows to this point, then it was not possible to add the
 1.56192 +  ** the page being freed as a leaf page of the first trunk in the free-list.
 1.56193 +  ** Possibly because the free-list is empty, or possibly because the 
 1.56194 +  ** first trunk in the free-list is full. Either way, the page being freed
 1.56195 +  ** will become the new first trunk page in the free-list.
 1.56196 +  */
 1.56197 +  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
 1.56198 +    goto freepage_out;
 1.56199 +  }
 1.56200 +  rc = sqlite3PagerWrite(pPage->pDbPage);
 1.56201 +  if( rc!=SQLITE_OK ){
 1.56202 +    goto freepage_out;
 1.56203 +  }
 1.56204 +  put4byte(pPage->aData, iTrunk);
 1.56205 +  put4byte(&pPage->aData[4], 0);
 1.56206 +  put4byte(&pPage1->aData[32], iPage);
 1.56207 +  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
 1.56208 +
 1.56209 +freepage_out:
 1.56210 +  if( pPage ){
 1.56211 +    pPage->isInit = 0;
 1.56212 +  }
 1.56213 +  releasePage(pPage);
 1.56214 +  releasePage(pTrunk);
 1.56215 +  return rc;
 1.56216 +}
 1.56217 +static void freePage(MemPage *pPage, int *pRC){
 1.56218 +  if( (*pRC)==SQLITE_OK ){
 1.56219 +    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
 1.56220 +  }
 1.56221 +}
 1.56222 +
 1.56223 +/*
 1.56224 +** Free any overflow pages associated with the given Cell.
 1.56225 +*/
 1.56226 +static int clearCell(MemPage *pPage, unsigned char *pCell){
 1.56227 +  BtShared *pBt = pPage->pBt;
 1.56228 +  CellInfo info;
 1.56229 +  Pgno ovflPgno;
 1.56230 +  int rc;
 1.56231 +  int nOvfl;
 1.56232 +  u32 ovflPageSize;
 1.56233 +
 1.56234 +  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 1.56235 +  btreeParseCellPtr(pPage, pCell, &info);
 1.56236 +  if( info.iOverflow==0 ){
 1.56237 +    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
 1.56238 +  }
 1.56239 +  if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
 1.56240 +    return SQLITE_CORRUPT_BKPT;  /* Cell extends past end of page */
 1.56241 +  }
 1.56242 +  ovflPgno = get4byte(&pCell[info.iOverflow]);
 1.56243 +  assert( pBt->usableSize > 4 );
 1.56244 +  ovflPageSize = pBt->usableSize - 4;
 1.56245 +  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
 1.56246 +  assert( ovflPgno==0 || nOvfl>0 );
 1.56247 +  while( nOvfl-- ){
 1.56248 +    Pgno iNext = 0;
 1.56249 +    MemPage *pOvfl = 0;
 1.56250 +    if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
 1.56251 +      /* 0 is not a legal page number and page 1 cannot be an 
 1.56252 +      ** overflow page. Therefore if ovflPgno<2 or past the end of the 
 1.56253 +      ** file the database must be corrupt. */
 1.56254 +      return SQLITE_CORRUPT_BKPT;
 1.56255 +    }
 1.56256 +    if( nOvfl ){
 1.56257 +      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
 1.56258 +      if( rc ) return rc;
 1.56259 +    }
 1.56260 +
 1.56261 +    if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
 1.56262 +     && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
 1.56263 +    ){
 1.56264 +      /* There is no reason any cursor should have an outstanding reference 
 1.56265 +      ** to an overflow page belonging to a cell that is being deleted/updated.
 1.56266 +      ** So if there exists more than one reference to this page, then it 
 1.56267 +      ** must not really be an overflow page and the database must be corrupt. 
 1.56268 +      ** It is helpful to detect this before calling freePage2(), as 
 1.56269 +      ** freePage2() may zero the page contents if secure-delete mode is
 1.56270 +      ** enabled. If this 'overflow' page happens to be a page that the
 1.56271 +      ** caller is iterating through or using in some other way, this
 1.56272 +      ** can be problematic.
 1.56273 +      */
 1.56274 +      rc = SQLITE_CORRUPT_BKPT;
 1.56275 +    }else{
 1.56276 +      rc = freePage2(pBt, pOvfl, ovflPgno);
 1.56277 +    }
 1.56278 +
 1.56279 +    if( pOvfl ){
 1.56280 +      sqlite3PagerUnref(pOvfl->pDbPage);
 1.56281 +    }
 1.56282 +    if( rc ) return rc;
 1.56283 +    ovflPgno = iNext;
 1.56284 +  }
 1.56285 +  return SQLITE_OK;
 1.56286 +}
 1.56287 +
 1.56288 +/*
 1.56289 +** Create the byte sequence used to represent a cell on page pPage
 1.56290 +** and write that byte sequence into pCell[].  Overflow pages are
 1.56291 +** allocated and filled in as necessary.  The calling procedure
 1.56292 +** is responsible for making sure sufficient space has been allocated
 1.56293 +** for pCell[].
 1.56294 +**
 1.56295 +** Note that pCell does not necessary need to point to the pPage->aData
 1.56296 +** area.  pCell might point to some temporary storage.  The cell will
 1.56297 +** be constructed in this temporary area then copied into pPage->aData
 1.56298 +** later.
 1.56299 +*/
 1.56300 +static int fillInCell(
 1.56301 +  MemPage *pPage,                /* The page that contains the cell */
 1.56302 +  unsigned char *pCell,          /* Complete text of the cell */
 1.56303 +  const void *pKey, i64 nKey,    /* The key */
 1.56304 +  const void *pData,int nData,   /* The data */
 1.56305 +  int nZero,                     /* Extra zero bytes to append to pData */
 1.56306 +  int *pnSize                    /* Write cell size here */
 1.56307 +){
 1.56308 +  int nPayload;
 1.56309 +  const u8 *pSrc;
 1.56310 +  int nSrc, n, rc;
 1.56311 +  int spaceLeft;
 1.56312 +  MemPage *pOvfl = 0;
 1.56313 +  MemPage *pToRelease = 0;
 1.56314 +  unsigned char *pPrior;
 1.56315 +  unsigned char *pPayload;
 1.56316 +  BtShared *pBt = pPage->pBt;
 1.56317 +  Pgno pgnoOvfl = 0;
 1.56318 +  int nHeader;
 1.56319 +  CellInfo info;
 1.56320 +
 1.56321 +  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 1.56322 +
 1.56323 +  /* pPage is not necessarily writeable since pCell might be auxiliary
 1.56324 +  ** buffer space that is separate from the pPage buffer area */
 1.56325 +  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
 1.56326 +            || sqlite3PagerIswriteable(pPage->pDbPage) );
 1.56327 +
 1.56328 +  /* Fill in the header. */
 1.56329 +  nHeader = 0;
 1.56330 +  if( !pPage->leaf ){
 1.56331 +    nHeader += 4;
 1.56332 +  }
 1.56333 +  if( pPage->hasData ){
 1.56334 +    nHeader += putVarint32(&pCell[nHeader], nData+nZero);
 1.56335 +  }else{
 1.56336 +    nData = nZero = 0;
 1.56337 +  }
 1.56338 +  nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
 1.56339 +  btreeParseCellPtr(pPage, pCell, &info);
 1.56340 +  assert( info.nHeader==nHeader );
 1.56341 +  assert( info.nKey==nKey );
 1.56342 +  assert( info.nData==(u32)(nData+nZero) );
 1.56343 +  
 1.56344 +  /* Fill in the payload */
 1.56345 +  nPayload = nData + nZero;
 1.56346 +  if( pPage->intKey ){
 1.56347 +    pSrc = pData;
 1.56348 +    nSrc = nData;
 1.56349 +    nData = 0;
 1.56350 +  }else{ 
 1.56351 +    if( NEVER(nKey>0x7fffffff || pKey==0) ){
 1.56352 +      return SQLITE_CORRUPT_BKPT;
 1.56353 +    }
 1.56354 +    nPayload += (int)nKey;
 1.56355 +    pSrc = pKey;
 1.56356 +    nSrc = (int)nKey;
 1.56357 +  }
 1.56358 +  *pnSize = info.nSize;
 1.56359 +  spaceLeft = info.nLocal;
 1.56360 +  pPayload = &pCell[nHeader];
 1.56361 +  pPrior = &pCell[info.iOverflow];
 1.56362 +
 1.56363 +  while( nPayload>0 ){
 1.56364 +    if( spaceLeft==0 ){
 1.56365 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.56366 +      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
 1.56367 +      if( pBt->autoVacuum ){
 1.56368 +        do{
 1.56369 +          pgnoOvfl++;
 1.56370 +        } while( 
 1.56371 +          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
 1.56372 +        );
 1.56373 +      }
 1.56374 +#endif
 1.56375 +      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
 1.56376 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.56377 +      /* If the database supports auto-vacuum, and the second or subsequent
 1.56378 +      ** overflow page is being allocated, add an entry to the pointer-map
 1.56379 +      ** for that page now. 
 1.56380 +      **
 1.56381 +      ** If this is the first overflow page, then write a partial entry 
 1.56382 +      ** to the pointer-map. If we write nothing to this pointer-map slot,
 1.56383 +      ** then the optimistic overflow chain processing in clearCell()
 1.56384 +      ** may misinterpret the uninitialized values and delete the
 1.56385 +      ** wrong pages from the database.
 1.56386 +      */
 1.56387 +      if( pBt->autoVacuum && rc==SQLITE_OK ){
 1.56388 +        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
 1.56389 +        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
 1.56390 +        if( rc ){
 1.56391 +          releasePage(pOvfl);
 1.56392 +        }
 1.56393 +      }
 1.56394 +#endif
 1.56395 +      if( rc ){
 1.56396 +        releasePage(pToRelease);
 1.56397 +        return rc;
 1.56398 +      }
 1.56399 +
 1.56400 +      /* If pToRelease is not zero than pPrior points into the data area
 1.56401 +      ** of pToRelease.  Make sure pToRelease is still writeable. */
 1.56402 +      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
 1.56403 +
 1.56404 +      /* If pPrior is part of the data area of pPage, then make sure pPage
 1.56405 +      ** is still writeable */
 1.56406 +      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
 1.56407 +            || sqlite3PagerIswriteable(pPage->pDbPage) );
 1.56408 +
 1.56409 +      put4byte(pPrior, pgnoOvfl);
 1.56410 +      releasePage(pToRelease);
 1.56411 +      pToRelease = pOvfl;
 1.56412 +      pPrior = pOvfl->aData;
 1.56413 +      put4byte(pPrior, 0);
 1.56414 +      pPayload = &pOvfl->aData[4];
 1.56415 +      spaceLeft = pBt->usableSize - 4;
 1.56416 +    }
 1.56417 +    n = nPayload;
 1.56418 +    if( n>spaceLeft ) n = spaceLeft;
 1.56419 +
 1.56420 +    /* If pToRelease is not zero than pPayload points into the data area
 1.56421 +    ** of pToRelease.  Make sure pToRelease is still writeable. */
 1.56422 +    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
 1.56423 +
 1.56424 +    /* If pPayload is part of the data area of pPage, then make sure pPage
 1.56425 +    ** is still writeable */
 1.56426 +    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
 1.56427 +            || sqlite3PagerIswriteable(pPage->pDbPage) );
 1.56428 +
 1.56429 +    if( nSrc>0 ){
 1.56430 +      if( n>nSrc ) n = nSrc;
 1.56431 +      assert( pSrc );
 1.56432 +      memcpy(pPayload, pSrc, n);
 1.56433 +    }else{
 1.56434 +      memset(pPayload, 0, n);
 1.56435 +    }
 1.56436 +    nPayload -= n;
 1.56437 +    pPayload += n;
 1.56438 +    pSrc += n;
 1.56439 +    nSrc -= n;
 1.56440 +    spaceLeft -= n;
 1.56441 +    if( nSrc==0 ){
 1.56442 +      nSrc = nData;
 1.56443 +      pSrc = pData;
 1.56444 +    }
 1.56445 +  }
 1.56446 +  releasePage(pToRelease);
 1.56447 +  return SQLITE_OK;
 1.56448 +}
 1.56449 +
 1.56450 +/*
 1.56451 +** Remove the i-th cell from pPage.  This routine effects pPage only.
 1.56452 +** The cell content is not freed or deallocated.  It is assumed that
 1.56453 +** the cell content has been copied someplace else.  This routine just
 1.56454 +** removes the reference to the cell from pPage.
 1.56455 +**
 1.56456 +** "sz" must be the number of bytes in the cell.
 1.56457 +*/
 1.56458 +static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
 1.56459 +  u32 pc;         /* Offset to cell content of cell being deleted */
 1.56460 +  u8 *data;       /* pPage->aData */
 1.56461 +  u8 *ptr;        /* Used to move bytes around within data[] */
 1.56462 +  int rc;         /* The return code */
 1.56463 +  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
 1.56464 +
 1.56465 +  if( *pRC ) return;
 1.56466 +
 1.56467 +  assert( idx>=0 && idx<pPage->nCell );
 1.56468 +  assert( sz==cellSize(pPage, idx) );
 1.56469 +  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 1.56470 +  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 1.56471 +  data = pPage->aData;
 1.56472 +  ptr = &pPage->aCellIdx[2*idx];
 1.56473 +  pc = get2byte(ptr);
 1.56474 +  hdr = pPage->hdrOffset;
 1.56475 +  testcase( pc==get2byte(&data[hdr+5]) );
 1.56476 +  testcase( pc+sz==pPage->pBt->usableSize );
 1.56477 +  if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
 1.56478 +    *pRC = SQLITE_CORRUPT_BKPT;
 1.56479 +    return;
 1.56480 +  }
 1.56481 +  rc = freeSpace(pPage, pc, sz);
 1.56482 +  if( rc ){
 1.56483 +    *pRC = rc;
 1.56484 +    return;
 1.56485 +  }
 1.56486 +  pPage->nCell--;
 1.56487 +  memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
 1.56488 +  put2byte(&data[hdr+3], pPage->nCell);
 1.56489 +  pPage->nFree += 2;
 1.56490 +}
 1.56491 +
 1.56492 +/*
 1.56493 +** Insert a new cell on pPage at cell index "i".  pCell points to the
 1.56494 +** content of the cell.
 1.56495 +**
 1.56496 +** If the cell content will fit on the page, then put it there.  If it
 1.56497 +** will not fit, then make a copy of the cell content into pTemp if
 1.56498 +** pTemp is not null.  Regardless of pTemp, allocate a new entry
 1.56499 +** in pPage->apOvfl[] and make it point to the cell content (either
 1.56500 +** in pTemp or the original pCell) and also record its index. 
 1.56501 +** Allocating a new entry in pPage->aCell[] implies that 
 1.56502 +** pPage->nOverflow is incremented.
 1.56503 +**
 1.56504 +** If nSkip is non-zero, then do not copy the first nSkip bytes of the
 1.56505 +** cell. The caller will overwrite them after this function returns. If
 1.56506 +** nSkip is non-zero, then pCell may not point to an invalid memory location 
 1.56507 +** (but pCell+nSkip is always valid).
 1.56508 +*/
 1.56509 +static void insertCell(
 1.56510 +  MemPage *pPage,   /* Page into which we are copying */
 1.56511 +  int i,            /* New cell becomes the i-th cell of the page */
 1.56512 +  u8 *pCell,        /* Content of the new cell */
 1.56513 +  int sz,           /* Bytes of content in pCell */
 1.56514 +  u8 *pTemp,        /* Temp storage space for pCell, if needed */
 1.56515 +  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
 1.56516 +  int *pRC          /* Read and write return code from here */
 1.56517 +){
 1.56518 +  int idx = 0;      /* Where to write new cell content in data[] */
 1.56519 +  int j;            /* Loop counter */
 1.56520 +  int end;          /* First byte past the last cell pointer in data[] */
 1.56521 +  int ins;          /* Index in data[] where new cell pointer is inserted */
 1.56522 +  int cellOffset;   /* Address of first cell pointer in data[] */
 1.56523 +  u8 *data;         /* The content of the whole page */
 1.56524 +  int nSkip = (iChild ? 4 : 0);
 1.56525 +
 1.56526 +  if( *pRC ) return;
 1.56527 +
 1.56528 +  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
 1.56529 +  assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
 1.56530 +  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
 1.56531 +  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
 1.56532 +  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 1.56533 +  /* The cell should normally be sized correctly.  However, when moving a
 1.56534 +  ** malformed cell from a leaf page to an interior page, if the cell size
 1.56535 +  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
 1.56536 +  ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
 1.56537 +  ** the term after the || in the following assert(). */
 1.56538 +  assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
 1.56539 +  if( pPage->nOverflow || sz+2>pPage->nFree ){
 1.56540 +    if( pTemp ){
 1.56541 +      memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
 1.56542 +      pCell = pTemp;
 1.56543 +    }
 1.56544 +    if( iChild ){
 1.56545 +      put4byte(pCell, iChild);
 1.56546 +    }
 1.56547 +    j = pPage->nOverflow++;
 1.56548 +    assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
 1.56549 +    pPage->apOvfl[j] = pCell;
 1.56550 +    pPage->aiOvfl[j] = (u16)i;
 1.56551 +  }else{
 1.56552 +    int rc = sqlite3PagerWrite(pPage->pDbPage);
 1.56553 +    if( rc!=SQLITE_OK ){
 1.56554 +      *pRC = rc;
 1.56555 +      return;
 1.56556 +    }
 1.56557 +    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 1.56558 +    data = pPage->aData;
 1.56559 +    cellOffset = pPage->cellOffset;
 1.56560 +    end = cellOffset + 2*pPage->nCell;
 1.56561 +    ins = cellOffset + 2*i;
 1.56562 +    rc = allocateSpace(pPage, sz, &idx);
 1.56563 +    if( rc ){ *pRC = rc; return; }
 1.56564 +    /* The allocateSpace() routine guarantees the following two properties
 1.56565 +    ** if it returns success */
 1.56566 +    assert( idx >= end+2 );
 1.56567 +    assert( idx+sz <= (int)pPage->pBt->usableSize );
 1.56568 +    pPage->nCell++;
 1.56569 +    pPage->nFree -= (u16)(2 + sz);
 1.56570 +    memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
 1.56571 +    if( iChild ){
 1.56572 +      put4byte(&data[idx], iChild);
 1.56573 +    }
 1.56574 +    memmove(&data[ins+2], &data[ins], end-ins);
 1.56575 +    put2byte(&data[ins], idx);
 1.56576 +    put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
 1.56577 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.56578 +    if( pPage->pBt->autoVacuum ){
 1.56579 +      /* The cell may contain a pointer to an overflow page. If so, write
 1.56580 +      ** the entry for the overflow page into the pointer map.
 1.56581 +      */
 1.56582 +      ptrmapPutOvflPtr(pPage, pCell, pRC);
 1.56583 +    }
 1.56584 +#endif
 1.56585 +  }
 1.56586 +}
 1.56587 +
 1.56588 +/*
 1.56589 +** Add a list of cells to a page.  The page should be initially empty.
 1.56590 +** The cells are guaranteed to fit on the page.
 1.56591 +*/
 1.56592 +static void assemblePage(
 1.56593 +  MemPage *pPage,   /* The page to be assemblied */
 1.56594 +  int nCell,        /* The number of cells to add to this page */
 1.56595 +  u8 **apCell,      /* Pointers to cell bodies */
 1.56596 +  u16 *aSize        /* Sizes of the cells */
 1.56597 +){
 1.56598 +  int i;            /* Loop counter */
 1.56599 +  u8 *pCellptr;     /* Address of next cell pointer */
 1.56600 +  int cellbody;     /* Address of next cell body */
 1.56601 +  u8 * const data = pPage->aData;             /* Pointer to data for pPage */
 1.56602 +  const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
 1.56603 +  const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
 1.56604 +
 1.56605 +  assert( pPage->nOverflow==0 );
 1.56606 +  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 1.56607 +  assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
 1.56608 +            && (int)MX_CELL(pPage->pBt)<=10921);
 1.56609 +  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 1.56610 +
 1.56611 +  /* Check that the page has just been zeroed by zeroPage() */
 1.56612 +  assert( pPage->nCell==0 );
 1.56613 +  assert( get2byteNotZero(&data[hdr+5])==nUsable );
 1.56614 +
 1.56615 +  pCellptr = &pPage->aCellIdx[nCell*2];
 1.56616 +  cellbody = nUsable;
 1.56617 +  for(i=nCell-1; i>=0; i--){
 1.56618 +    u16 sz = aSize[i];
 1.56619 +    pCellptr -= 2;
 1.56620 +    cellbody -= sz;
 1.56621 +    put2byte(pCellptr, cellbody);
 1.56622 +    memcpy(&data[cellbody], apCell[i], sz);
 1.56623 +  }
 1.56624 +  put2byte(&data[hdr+3], nCell);
 1.56625 +  put2byte(&data[hdr+5], cellbody);
 1.56626 +  pPage->nFree -= (nCell*2 + nUsable - cellbody);
 1.56627 +  pPage->nCell = (u16)nCell;
 1.56628 +}
 1.56629 +
 1.56630 +/*
 1.56631 +** The following parameters determine how many adjacent pages get involved
 1.56632 +** in a balancing operation.  NN is the number of neighbors on either side
 1.56633 +** of the page that participate in the balancing operation.  NB is the
 1.56634 +** total number of pages that participate, including the target page and
 1.56635 +** NN neighbors on either side.
 1.56636 +**
 1.56637 +** The minimum value of NN is 1 (of course).  Increasing NN above 1
 1.56638 +** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
 1.56639 +** in exchange for a larger degradation in INSERT and UPDATE performance.
 1.56640 +** The value of NN appears to give the best results overall.
 1.56641 +*/
 1.56642 +#define NN 1             /* Number of neighbors on either side of pPage */
 1.56643 +#define NB (NN*2+1)      /* Total pages involved in the balance */
 1.56644 +
 1.56645 +
 1.56646 +#ifndef SQLITE_OMIT_QUICKBALANCE
 1.56647 +/*
 1.56648 +** This version of balance() handles the common special case where
 1.56649 +** a new entry is being inserted on the extreme right-end of the
 1.56650 +** tree, in other words, when the new entry will become the largest
 1.56651 +** entry in the tree.
 1.56652 +**
 1.56653 +** Instead of trying to balance the 3 right-most leaf pages, just add
 1.56654 +** a new page to the right-hand side and put the one new entry in
 1.56655 +** that page.  This leaves the right side of the tree somewhat
 1.56656 +** unbalanced.  But odds are that we will be inserting new entries
 1.56657 +** at the end soon afterwards so the nearly empty page will quickly
 1.56658 +** fill up.  On average.
 1.56659 +**
 1.56660 +** pPage is the leaf page which is the right-most page in the tree.
 1.56661 +** pParent is its parent.  pPage must have a single overflow entry
 1.56662 +** which is also the right-most entry on the page.
 1.56663 +**
 1.56664 +** The pSpace buffer is used to store a temporary copy of the divider
 1.56665 +** cell that will be inserted into pParent. Such a cell consists of a 4
 1.56666 +** byte page number followed by a variable length integer. In other
 1.56667 +** words, at most 13 bytes. Hence the pSpace buffer must be at
 1.56668 +** least 13 bytes in size.
 1.56669 +*/
 1.56670 +static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
 1.56671 +  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
 1.56672 +  MemPage *pNew;                       /* Newly allocated page */
 1.56673 +  int rc;                              /* Return Code */
 1.56674 +  Pgno pgnoNew;                        /* Page number of pNew */
 1.56675 +
 1.56676 +  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 1.56677 +  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
 1.56678 +  assert( pPage->nOverflow==1 );
 1.56679 +
 1.56680 +  /* This error condition is now caught prior to reaching this function */
 1.56681 +  if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
 1.56682 +
 1.56683 +  /* Allocate a new page. This page will become the right-sibling of 
 1.56684 +  ** pPage. Make the parent page writable, so that the new divider cell
 1.56685 +  ** may be inserted. If both these operations are successful, proceed.
 1.56686 +  */
 1.56687 +  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
 1.56688 +
 1.56689 +  if( rc==SQLITE_OK ){
 1.56690 +
 1.56691 +    u8 *pOut = &pSpace[4];
 1.56692 +    u8 *pCell = pPage->apOvfl[0];
 1.56693 +    u16 szCell = cellSizePtr(pPage, pCell);
 1.56694 +    u8 *pStop;
 1.56695 +
 1.56696 +    assert( sqlite3PagerIswriteable(pNew->pDbPage) );
 1.56697 +    assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
 1.56698 +    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
 1.56699 +    assemblePage(pNew, 1, &pCell, &szCell);
 1.56700 +
 1.56701 +    /* If this is an auto-vacuum database, update the pointer map
 1.56702 +    ** with entries for the new page, and any pointer from the 
 1.56703 +    ** cell on the page to an overflow page. If either of these
 1.56704 +    ** operations fails, the return code is set, but the contents
 1.56705 +    ** of the parent page are still manipulated by thh code below.
 1.56706 +    ** That is Ok, at this point the parent page is guaranteed to
 1.56707 +    ** be marked as dirty. Returning an error code will cause a
 1.56708 +    ** rollback, undoing any changes made to the parent page.
 1.56709 +    */
 1.56710 +    if( ISAUTOVACUUM ){
 1.56711 +      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
 1.56712 +      if( szCell>pNew->minLocal ){
 1.56713 +        ptrmapPutOvflPtr(pNew, pCell, &rc);
 1.56714 +      }
 1.56715 +    }
 1.56716 +  
 1.56717 +    /* Create a divider cell to insert into pParent. The divider cell
 1.56718 +    ** consists of a 4-byte page number (the page number of pPage) and
 1.56719 +    ** a variable length key value (which must be the same value as the
 1.56720 +    ** largest key on pPage).
 1.56721 +    **
 1.56722 +    ** To find the largest key value on pPage, first find the right-most 
 1.56723 +    ** cell on pPage. The first two fields of this cell are the 
 1.56724 +    ** record-length (a variable length integer at most 32-bits in size)
 1.56725 +    ** and the key value (a variable length integer, may have any value).
 1.56726 +    ** The first of the while(...) loops below skips over the record-length
 1.56727 +    ** field. The second while(...) loop copies the key value from the
 1.56728 +    ** cell on pPage into the pSpace buffer.
 1.56729 +    */
 1.56730 +    pCell = findCell(pPage, pPage->nCell-1);
 1.56731 +    pStop = &pCell[9];
 1.56732 +    while( (*(pCell++)&0x80) && pCell<pStop );
 1.56733 +    pStop = &pCell[9];
 1.56734 +    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
 1.56735 +
 1.56736 +    /* Insert the new divider cell into pParent. */
 1.56737 +    insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
 1.56738 +               0, pPage->pgno, &rc);
 1.56739 +
 1.56740 +    /* Set the right-child pointer of pParent to point to the new page. */
 1.56741 +    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
 1.56742 +  
 1.56743 +    /* Release the reference to the new page. */
 1.56744 +    releasePage(pNew);
 1.56745 +  }
 1.56746 +
 1.56747 +  return rc;
 1.56748 +}
 1.56749 +#endif /* SQLITE_OMIT_QUICKBALANCE */
 1.56750 +
 1.56751 +#if 0
 1.56752 +/*
 1.56753 +** This function does not contribute anything to the operation of SQLite.
 1.56754 +** it is sometimes activated temporarily while debugging code responsible 
 1.56755 +** for setting pointer-map entries.
 1.56756 +*/
 1.56757 +static int ptrmapCheckPages(MemPage **apPage, int nPage){
 1.56758 +  int i, j;
 1.56759 +  for(i=0; i<nPage; i++){
 1.56760 +    Pgno n;
 1.56761 +    u8 e;
 1.56762 +    MemPage *pPage = apPage[i];
 1.56763 +    BtShared *pBt = pPage->pBt;
 1.56764 +    assert( pPage->isInit );
 1.56765 +
 1.56766 +    for(j=0; j<pPage->nCell; j++){
 1.56767 +      CellInfo info;
 1.56768 +      u8 *z;
 1.56769 +     
 1.56770 +      z = findCell(pPage, j);
 1.56771 +      btreeParseCellPtr(pPage, z, &info);
 1.56772 +      if( info.iOverflow ){
 1.56773 +        Pgno ovfl = get4byte(&z[info.iOverflow]);
 1.56774 +        ptrmapGet(pBt, ovfl, &e, &n);
 1.56775 +        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
 1.56776 +      }
 1.56777 +      if( !pPage->leaf ){
 1.56778 +        Pgno child = get4byte(z);
 1.56779 +        ptrmapGet(pBt, child, &e, &n);
 1.56780 +        assert( n==pPage->pgno && e==PTRMAP_BTREE );
 1.56781 +      }
 1.56782 +    }
 1.56783 +    if( !pPage->leaf ){
 1.56784 +      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
 1.56785 +      ptrmapGet(pBt, child, &e, &n);
 1.56786 +      assert( n==pPage->pgno && e==PTRMAP_BTREE );
 1.56787 +    }
 1.56788 +  }
 1.56789 +  return 1;
 1.56790 +}
 1.56791 +#endif
 1.56792 +
 1.56793 +/*
 1.56794 +** This function is used to copy the contents of the b-tree node stored 
 1.56795 +** on page pFrom to page pTo. If page pFrom was not a leaf page, then
 1.56796 +** the pointer-map entries for each child page are updated so that the
 1.56797 +** parent page stored in the pointer map is page pTo. If pFrom contained
 1.56798 +** any cells with overflow page pointers, then the corresponding pointer
 1.56799 +** map entries are also updated so that the parent page is page pTo.
 1.56800 +**
 1.56801 +** If pFrom is currently carrying any overflow cells (entries in the
 1.56802 +** MemPage.apOvfl[] array), they are not copied to pTo. 
 1.56803 +**
 1.56804 +** Before returning, page pTo is reinitialized using btreeInitPage().
 1.56805 +**
 1.56806 +** The performance of this function is not critical. It is only used by 
 1.56807 +** the balance_shallower() and balance_deeper() procedures, neither of
 1.56808 +** which are called often under normal circumstances.
 1.56809 +*/
 1.56810 +static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
 1.56811 +  if( (*pRC)==SQLITE_OK ){
 1.56812 +    BtShared * const pBt = pFrom->pBt;
 1.56813 +    u8 * const aFrom = pFrom->aData;
 1.56814 +    u8 * const aTo = pTo->aData;
 1.56815 +    int const iFromHdr = pFrom->hdrOffset;
 1.56816 +    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
 1.56817 +    int rc;
 1.56818 +    int iData;
 1.56819 +  
 1.56820 +  
 1.56821 +    assert( pFrom->isInit );
 1.56822 +    assert( pFrom->nFree>=iToHdr );
 1.56823 +    assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
 1.56824 +  
 1.56825 +    /* Copy the b-tree node content from page pFrom to page pTo. */
 1.56826 +    iData = get2byte(&aFrom[iFromHdr+5]);
 1.56827 +    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
 1.56828 +    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
 1.56829 +  
 1.56830 +    /* Reinitialize page pTo so that the contents of the MemPage structure
 1.56831 +    ** match the new data. The initialization of pTo can actually fail under
 1.56832 +    ** fairly obscure circumstances, even though it is a copy of initialized 
 1.56833 +    ** page pFrom.
 1.56834 +    */
 1.56835 +    pTo->isInit = 0;
 1.56836 +    rc = btreeInitPage(pTo);
 1.56837 +    if( rc!=SQLITE_OK ){
 1.56838 +      *pRC = rc;
 1.56839 +      return;
 1.56840 +    }
 1.56841 +  
 1.56842 +    /* If this is an auto-vacuum database, update the pointer-map entries
 1.56843 +    ** for any b-tree or overflow pages that pTo now contains the pointers to.
 1.56844 +    */
 1.56845 +    if( ISAUTOVACUUM ){
 1.56846 +      *pRC = setChildPtrmaps(pTo);
 1.56847 +    }
 1.56848 +  }
 1.56849 +}
 1.56850 +
 1.56851 +/*
 1.56852 +** This routine redistributes cells on the iParentIdx'th child of pParent
 1.56853 +** (hereafter "the page") and up to 2 siblings so that all pages have about the
 1.56854 +** same amount of free space. Usually a single sibling on either side of the
 1.56855 +** page are used in the balancing, though both siblings might come from one
 1.56856 +** side if the page is the first or last child of its parent. If the page 
 1.56857 +** has fewer than 2 siblings (something which can only happen if the page
 1.56858 +** is a root page or a child of a root page) then all available siblings
 1.56859 +** participate in the balancing.
 1.56860 +**
 1.56861 +** The number of siblings of the page might be increased or decreased by 
 1.56862 +** one or two in an effort to keep pages nearly full but not over full. 
 1.56863 +**
 1.56864 +** Note that when this routine is called, some of the cells on the page
 1.56865 +** might not actually be stored in MemPage.aData[]. This can happen
 1.56866 +** if the page is overfull. This routine ensures that all cells allocated
 1.56867 +** to the page and its siblings fit into MemPage.aData[] before returning.
 1.56868 +**
 1.56869 +** In the course of balancing the page and its siblings, cells may be
 1.56870 +** inserted into or removed from the parent page (pParent). Doing so
 1.56871 +** may cause the parent page to become overfull or underfull. If this
 1.56872 +** happens, it is the responsibility of the caller to invoke the correct
 1.56873 +** balancing routine to fix this problem (see the balance() routine). 
 1.56874 +**
 1.56875 +** If this routine fails for any reason, it might leave the database
 1.56876 +** in a corrupted state. So if this routine fails, the database should
 1.56877 +** be rolled back.
 1.56878 +**
 1.56879 +** The third argument to this function, aOvflSpace, is a pointer to a
 1.56880 +** buffer big enough to hold one page. If while inserting cells into the parent
 1.56881 +** page (pParent) the parent page becomes overfull, this buffer is
 1.56882 +** used to store the parent's overflow cells. Because this function inserts
 1.56883 +** a maximum of four divider cells into the parent page, and the maximum
 1.56884 +** size of a cell stored within an internal node is always less than 1/4
 1.56885 +** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
 1.56886 +** enough for all overflow cells.
 1.56887 +**
 1.56888 +** If aOvflSpace is set to a null pointer, this function returns 
 1.56889 +** SQLITE_NOMEM.
 1.56890 +*/
 1.56891 +#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
 1.56892 +#pragma optimize("", off)
 1.56893 +#endif
 1.56894 +static int balance_nonroot(
 1.56895 +  MemPage *pParent,               /* Parent page of siblings being balanced */
 1.56896 +  int iParentIdx,                 /* Index of "the page" in pParent */
 1.56897 +  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
 1.56898 +  int isRoot,                     /* True if pParent is a root-page */
 1.56899 +  int bBulk                       /* True if this call is part of a bulk load */
 1.56900 +){
 1.56901 +  BtShared *pBt;               /* The whole database */
 1.56902 +  int nCell = 0;               /* Number of cells in apCell[] */
 1.56903 +  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
 1.56904 +  int nNew = 0;                /* Number of pages in apNew[] */
 1.56905 +  int nOld;                    /* Number of pages in apOld[] */
 1.56906 +  int i, j, k;                 /* Loop counters */
 1.56907 +  int nxDiv;                   /* Next divider slot in pParent->aCell[] */
 1.56908 +  int rc = SQLITE_OK;          /* The return code */
 1.56909 +  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
 1.56910 +  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
 1.56911 +  int usableSpace;             /* Bytes in pPage beyond the header */
 1.56912 +  int pageFlags;               /* Value of pPage->aData[0] */
 1.56913 +  int subtotal;                /* Subtotal of bytes in cells on one page */
 1.56914 +  int iSpace1 = 0;             /* First unused byte of aSpace1[] */
 1.56915 +  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
 1.56916 +  int szScratch;               /* Size of scratch memory requested */
 1.56917 +  MemPage *apOld[NB];          /* pPage and up to two siblings */
 1.56918 +  MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
 1.56919 +  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
 1.56920 +  u8 *pRight;                  /* Location in parent of right-sibling pointer */
 1.56921 +  u8 *apDiv[NB-1];             /* Divider cells in pParent */
 1.56922 +  int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
 1.56923 +  int szNew[NB+2];             /* Combined size of cells place on i-th page */
 1.56924 +  u8 **apCell = 0;             /* All cells begin balanced */
 1.56925 +  u16 *szCell;                 /* Local size of all cells in apCell[] */
 1.56926 +  u8 *aSpace1;                 /* Space for copies of dividers cells */
 1.56927 +  Pgno pgno;                   /* Temp var to store a page number in */
 1.56928 +
 1.56929 +  pBt = pParent->pBt;
 1.56930 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.56931 +  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
 1.56932 +
 1.56933 +#if 0
 1.56934 +  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
 1.56935 +#endif
 1.56936 +
 1.56937 +  /* At this point pParent may have at most one overflow cell. And if
 1.56938 +  ** this overflow cell is present, it must be the cell with 
 1.56939 +  ** index iParentIdx. This scenario comes about when this function
 1.56940 +  ** is called (indirectly) from sqlite3BtreeDelete().
 1.56941 +  */
 1.56942 +  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
 1.56943 +  assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
 1.56944 +
 1.56945 +  if( !aOvflSpace ){
 1.56946 +    return SQLITE_NOMEM;
 1.56947 +  }
 1.56948 +
 1.56949 +  /* Find the sibling pages to balance. Also locate the cells in pParent 
 1.56950 +  ** that divide the siblings. An attempt is made to find NN siblings on 
 1.56951 +  ** either side of pPage. More siblings are taken from one side, however, 
 1.56952 +  ** if there are fewer than NN siblings on the other side. If pParent
 1.56953 +  ** has NB or fewer children then all children of pParent are taken.  
 1.56954 +  **
 1.56955 +  ** This loop also drops the divider cells from the parent page. This
 1.56956 +  ** way, the remainder of the function does not have to deal with any
 1.56957 +  ** overflow cells in the parent page, since if any existed they will
 1.56958 +  ** have already been removed.
 1.56959 +  */
 1.56960 +  i = pParent->nOverflow + pParent->nCell;
 1.56961 +  if( i<2 ){
 1.56962 +    nxDiv = 0;
 1.56963 +  }else{
 1.56964 +    assert( bBulk==0 || bBulk==1 );
 1.56965 +    if( iParentIdx==0 ){                 
 1.56966 +      nxDiv = 0;
 1.56967 +    }else if( iParentIdx==i ){
 1.56968 +      nxDiv = i-2+bBulk;
 1.56969 +    }else{
 1.56970 +      assert( bBulk==0 );
 1.56971 +      nxDiv = iParentIdx-1;
 1.56972 +    }
 1.56973 +    i = 2-bBulk;
 1.56974 +  }
 1.56975 +  nOld = i+1;
 1.56976 +  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
 1.56977 +    pRight = &pParent->aData[pParent->hdrOffset+8];
 1.56978 +  }else{
 1.56979 +    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
 1.56980 +  }
 1.56981 +  pgno = get4byte(pRight);
 1.56982 +  while( 1 ){
 1.56983 +    rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
 1.56984 +    if( rc ){
 1.56985 +      memset(apOld, 0, (i+1)*sizeof(MemPage*));
 1.56986 +      goto balance_cleanup;
 1.56987 +    }
 1.56988 +    nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
 1.56989 +    if( (i--)==0 ) break;
 1.56990 +
 1.56991 +    if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
 1.56992 +      apDiv[i] = pParent->apOvfl[0];
 1.56993 +      pgno = get4byte(apDiv[i]);
 1.56994 +      szNew[i] = cellSizePtr(pParent, apDiv[i]);
 1.56995 +      pParent->nOverflow = 0;
 1.56996 +    }else{
 1.56997 +      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
 1.56998 +      pgno = get4byte(apDiv[i]);
 1.56999 +      szNew[i] = cellSizePtr(pParent, apDiv[i]);
 1.57000 +
 1.57001 +      /* Drop the cell from the parent page. apDiv[i] still points to
 1.57002 +      ** the cell within the parent, even though it has been dropped.
 1.57003 +      ** This is safe because dropping a cell only overwrites the first
 1.57004 +      ** four bytes of it, and this function does not need the first
 1.57005 +      ** four bytes of the divider cell. So the pointer is safe to use
 1.57006 +      ** later on.  
 1.57007 +      **
 1.57008 +      ** But not if we are in secure-delete mode. In secure-delete mode,
 1.57009 +      ** the dropCell() routine will overwrite the entire cell with zeroes.
 1.57010 +      ** In this case, temporarily copy the cell into the aOvflSpace[]
 1.57011 +      ** buffer. It will be copied out again as soon as the aSpace[] buffer
 1.57012 +      ** is allocated.  */
 1.57013 +      if( pBt->btsFlags & BTS_SECURE_DELETE ){
 1.57014 +        int iOff;
 1.57015 +
 1.57016 +        iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
 1.57017 +        if( (iOff+szNew[i])>(int)pBt->usableSize ){
 1.57018 +          rc = SQLITE_CORRUPT_BKPT;
 1.57019 +          memset(apOld, 0, (i+1)*sizeof(MemPage*));
 1.57020 +          goto balance_cleanup;
 1.57021 +        }else{
 1.57022 +          memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
 1.57023 +          apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
 1.57024 +        }
 1.57025 +      }
 1.57026 +      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
 1.57027 +    }
 1.57028 +  }
 1.57029 +
 1.57030 +  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
 1.57031 +  ** alignment */
 1.57032 +  nMaxCells = (nMaxCells + 3)&~3;
 1.57033 +
 1.57034 +  /*
 1.57035 +  ** Allocate space for memory structures
 1.57036 +  */
 1.57037 +  k = pBt->pageSize + ROUND8(sizeof(MemPage));
 1.57038 +  szScratch =
 1.57039 +       nMaxCells*sizeof(u8*)                       /* apCell */
 1.57040 +     + nMaxCells*sizeof(u16)                       /* szCell */
 1.57041 +     + pBt->pageSize                               /* aSpace1 */
 1.57042 +     + k*nOld;                                     /* Page copies (apCopy) */
 1.57043 +  apCell = sqlite3ScratchMalloc( szScratch ); 
 1.57044 +  if( apCell==0 ){
 1.57045 +    rc = SQLITE_NOMEM;
 1.57046 +    goto balance_cleanup;
 1.57047 +  }
 1.57048 +  szCell = (u16*)&apCell[nMaxCells];
 1.57049 +  aSpace1 = (u8*)&szCell[nMaxCells];
 1.57050 +  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
 1.57051 +
 1.57052 +  /*
 1.57053 +  ** Load pointers to all cells on sibling pages and the divider cells
 1.57054 +  ** into the local apCell[] array.  Make copies of the divider cells
 1.57055 +  ** into space obtained from aSpace1[] and remove the divider cells
 1.57056 +  ** from pParent.
 1.57057 +  **
 1.57058 +  ** If the siblings are on leaf pages, then the child pointers of the
 1.57059 +  ** divider cells are stripped from the cells before they are copied
 1.57060 +  ** into aSpace1[].  In this way, all cells in apCell[] are without
 1.57061 +  ** child pointers.  If siblings are not leaves, then all cell in
 1.57062 +  ** apCell[] include child pointers.  Either way, all cells in apCell[]
 1.57063 +  ** are alike.
 1.57064 +  **
 1.57065 +  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
 1.57066 +  **       leafData:  1 if pPage holds key+data and pParent holds only keys.
 1.57067 +  */
 1.57068 +  leafCorrection = apOld[0]->leaf*4;
 1.57069 +  leafData = apOld[0]->hasData;
 1.57070 +  for(i=0; i<nOld; i++){
 1.57071 +    int limit;
 1.57072 +    
 1.57073 +    /* Before doing anything else, take a copy of the i'th original sibling
 1.57074 +    ** The rest of this function will use data from the copies rather
 1.57075 +    ** that the original pages since the original pages will be in the
 1.57076 +    ** process of being overwritten.  */
 1.57077 +    MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
 1.57078 +    memcpy(pOld, apOld[i], sizeof(MemPage));
 1.57079 +    pOld->aData = (void*)&pOld[1];
 1.57080 +    memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
 1.57081 +
 1.57082 +    limit = pOld->nCell+pOld->nOverflow;
 1.57083 +    if( pOld->nOverflow>0 ){
 1.57084 +      for(j=0; j<limit; j++){
 1.57085 +        assert( nCell<nMaxCells );
 1.57086 +        apCell[nCell] = findOverflowCell(pOld, j);
 1.57087 +        szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
 1.57088 +        nCell++;
 1.57089 +      }
 1.57090 +    }else{
 1.57091 +      u8 *aData = pOld->aData;
 1.57092 +      u16 maskPage = pOld->maskPage;
 1.57093 +      u16 cellOffset = pOld->cellOffset;
 1.57094 +      for(j=0; j<limit; j++){
 1.57095 +        assert( nCell<nMaxCells );
 1.57096 +        apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
 1.57097 +        szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
 1.57098 +        nCell++;
 1.57099 +      }
 1.57100 +    }       
 1.57101 +    if( i<nOld-1 && !leafData){
 1.57102 +      u16 sz = (u16)szNew[i];
 1.57103 +      u8 *pTemp;
 1.57104 +      assert( nCell<nMaxCells );
 1.57105 +      szCell[nCell] = sz;
 1.57106 +      pTemp = &aSpace1[iSpace1];
 1.57107 +      iSpace1 += sz;
 1.57108 +      assert( sz<=pBt->maxLocal+23 );
 1.57109 +      assert( iSpace1 <= (int)pBt->pageSize );
 1.57110 +      memcpy(pTemp, apDiv[i], sz);
 1.57111 +      apCell[nCell] = pTemp+leafCorrection;
 1.57112 +      assert( leafCorrection==0 || leafCorrection==4 );
 1.57113 +      szCell[nCell] = szCell[nCell] - leafCorrection;
 1.57114 +      if( !pOld->leaf ){
 1.57115 +        assert( leafCorrection==0 );
 1.57116 +        assert( pOld->hdrOffset==0 );
 1.57117 +        /* The right pointer of the child page pOld becomes the left
 1.57118 +        ** pointer of the divider cell */
 1.57119 +        memcpy(apCell[nCell], &pOld->aData[8], 4);
 1.57120 +      }else{
 1.57121 +        assert( leafCorrection==4 );
 1.57122 +        if( szCell[nCell]<4 ){
 1.57123 +          /* Do not allow any cells smaller than 4 bytes. */
 1.57124 +          szCell[nCell] = 4;
 1.57125 +        }
 1.57126 +      }
 1.57127 +      nCell++;
 1.57128 +    }
 1.57129 +  }
 1.57130 +
 1.57131 +  /*
 1.57132 +  ** Figure out the number of pages needed to hold all nCell cells.
 1.57133 +  ** Store this number in "k".  Also compute szNew[] which is the total
 1.57134 +  ** size of all cells on the i-th page and cntNew[] which is the index
 1.57135 +  ** in apCell[] of the cell that divides page i from page i+1.  
 1.57136 +  ** cntNew[k] should equal nCell.
 1.57137 +  **
 1.57138 +  ** Values computed by this block:
 1.57139 +  **
 1.57140 +  **           k: The total number of sibling pages
 1.57141 +  **    szNew[i]: Spaced used on the i-th sibling page.
 1.57142 +  **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
 1.57143 +  **              the right of the i-th sibling page.
 1.57144 +  ** usableSpace: Number of bytes of space available on each sibling.
 1.57145 +  ** 
 1.57146 +  */
 1.57147 +  usableSpace = pBt->usableSize - 12 + leafCorrection;
 1.57148 +  for(subtotal=k=i=0; i<nCell; i++){
 1.57149 +    assert( i<nMaxCells );
 1.57150 +    subtotal += szCell[i] + 2;
 1.57151 +    if( subtotal > usableSpace ){
 1.57152 +      szNew[k] = subtotal - szCell[i];
 1.57153 +      cntNew[k] = i;
 1.57154 +      if( leafData ){ i--; }
 1.57155 +      subtotal = 0;
 1.57156 +      k++;
 1.57157 +      if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
 1.57158 +    }
 1.57159 +  }
 1.57160 +  szNew[k] = subtotal;
 1.57161 +  cntNew[k] = nCell;
 1.57162 +  k++;
 1.57163 +
 1.57164 +  /*
 1.57165 +  ** The packing computed by the previous block is biased toward the siblings
 1.57166 +  ** on the left side.  The left siblings are always nearly full, while the
 1.57167 +  ** right-most sibling might be nearly empty.  This block of code attempts
 1.57168 +  ** to adjust the packing of siblings to get a better balance.
 1.57169 +  **
 1.57170 +  ** This adjustment is more than an optimization.  The packing above might
 1.57171 +  ** be so out of balance as to be illegal.  For example, the right-most
 1.57172 +  ** sibling might be completely empty.  This adjustment is not optional.
 1.57173 +  */
 1.57174 +  for(i=k-1; i>0; i--){
 1.57175 +    int szRight = szNew[i];  /* Size of sibling on the right */
 1.57176 +    int szLeft = szNew[i-1]; /* Size of sibling on the left */
 1.57177 +    int r;              /* Index of right-most cell in left sibling */
 1.57178 +    int d;              /* Index of first cell to the left of right sibling */
 1.57179 +
 1.57180 +    r = cntNew[i-1] - 1;
 1.57181 +    d = r + 1 - leafData;
 1.57182 +    assert( d<nMaxCells );
 1.57183 +    assert( r<nMaxCells );
 1.57184 +    while( szRight==0 
 1.57185 +       || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2)) 
 1.57186 +    ){
 1.57187 +      szRight += szCell[d] + 2;
 1.57188 +      szLeft -= szCell[r] + 2;
 1.57189 +      cntNew[i-1]--;
 1.57190 +      r = cntNew[i-1] - 1;
 1.57191 +      d = r + 1 - leafData;
 1.57192 +    }
 1.57193 +    szNew[i] = szRight;
 1.57194 +    szNew[i-1] = szLeft;
 1.57195 +  }
 1.57196 +
 1.57197 +  /* Either we found one or more cells (cntnew[0])>0) or pPage is
 1.57198 +  ** a virtual root page.  A virtual root page is when the real root
 1.57199 +  ** page is page 1 and we are the only child of that page.
 1.57200 +  **
 1.57201 +  ** UPDATE:  The assert() below is not necessarily true if the database
 1.57202 +  ** file is corrupt.  The corruption will be detected and reported later
 1.57203 +  ** in this procedure so there is no need to act upon it now.
 1.57204 +  */
 1.57205 +#if 0
 1.57206 +  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
 1.57207 +#endif
 1.57208 +
 1.57209 +  TRACE(("BALANCE: old: %d %d %d  ",
 1.57210 +    apOld[0]->pgno, 
 1.57211 +    nOld>=2 ? apOld[1]->pgno : 0,
 1.57212 +    nOld>=3 ? apOld[2]->pgno : 0
 1.57213 +  ));
 1.57214 +
 1.57215 +  /*
 1.57216 +  ** Allocate k new pages.  Reuse old pages where possible.
 1.57217 +  */
 1.57218 +  if( apOld[0]->pgno<=1 ){
 1.57219 +    rc = SQLITE_CORRUPT_BKPT;
 1.57220 +    goto balance_cleanup;
 1.57221 +  }
 1.57222 +  pageFlags = apOld[0]->aData[0];
 1.57223 +  for(i=0; i<k; i++){
 1.57224 +    MemPage *pNew;
 1.57225 +    if( i<nOld ){
 1.57226 +      pNew = apNew[i] = apOld[i];
 1.57227 +      apOld[i] = 0;
 1.57228 +      rc = sqlite3PagerWrite(pNew->pDbPage);
 1.57229 +      nNew++;
 1.57230 +      if( rc ) goto balance_cleanup;
 1.57231 +    }else{
 1.57232 +      assert( i>0 );
 1.57233 +      rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
 1.57234 +      if( rc ) goto balance_cleanup;
 1.57235 +      apNew[i] = pNew;
 1.57236 +      nNew++;
 1.57237 +
 1.57238 +      /* Set the pointer-map entry for the new sibling page. */
 1.57239 +      if( ISAUTOVACUUM ){
 1.57240 +        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
 1.57241 +        if( rc!=SQLITE_OK ){
 1.57242 +          goto balance_cleanup;
 1.57243 +        }
 1.57244 +      }
 1.57245 +    }
 1.57246 +  }
 1.57247 +
 1.57248 +  /* Free any old pages that were not reused as new pages.
 1.57249 +  */
 1.57250 +  while( i<nOld ){
 1.57251 +    freePage(apOld[i], &rc);
 1.57252 +    if( rc ) goto balance_cleanup;
 1.57253 +    releasePage(apOld[i]);
 1.57254 +    apOld[i] = 0;
 1.57255 +    i++;
 1.57256 +  }
 1.57257 +
 1.57258 +  /*
 1.57259 +  ** Put the new pages in accending order.  This helps to
 1.57260 +  ** keep entries in the disk file in order so that a scan
 1.57261 +  ** of the table is a linear scan through the file.  That
 1.57262 +  ** in turn helps the operating system to deliver pages
 1.57263 +  ** from the disk more rapidly.
 1.57264 +  **
 1.57265 +  ** An O(n^2) insertion sort algorithm is used, but since
 1.57266 +  ** n is never more than NB (a small constant), that should
 1.57267 +  ** not be a problem.
 1.57268 +  **
 1.57269 +  ** When NB==3, this one optimization makes the database
 1.57270 +  ** about 25% faster for large insertions and deletions.
 1.57271 +  */
 1.57272 +  for(i=0; i<k-1; i++){
 1.57273 +    int minV = apNew[i]->pgno;
 1.57274 +    int minI = i;
 1.57275 +    for(j=i+1; j<k; j++){
 1.57276 +      if( apNew[j]->pgno<(unsigned)minV ){
 1.57277 +        minI = j;
 1.57278 +        minV = apNew[j]->pgno;
 1.57279 +      }
 1.57280 +    }
 1.57281 +    if( minI>i ){
 1.57282 +      MemPage *pT;
 1.57283 +      pT = apNew[i];
 1.57284 +      apNew[i] = apNew[minI];
 1.57285 +      apNew[minI] = pT;
 1.57286 +    }
 1.57287 +  }
 1.57288 +  TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
 1.57289 +    apNew[0]->pgno, szNew[0],
 1.57290 +    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
 1.57291 +    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
 1.57292 +    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
 1.57293 +    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
 1.57294 +
 1.57295 +  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
 1.57296 +  put4byte(pRight, apNew[nNew-1]->pgno);
 1.57297 +
 1.57298 +  /*
 1.57299 +  ** Evenly distribute the data in apCell[] across the new pages.
 1.57300 +  ** Insert divider cells into pParent as necessary.
 1.57301 +  */
 1.57302 +  j = 0;
 1.57303 +  for(i=0; i<nNew; i++){
 1.57304 +    /* Assemble the new sibling page. */
 1.57305 +    MemPage *pNew = apNew[i];
 1.57306 +    assert( j<nMaxCells );
 1.57307 +    zeroPage(pNew, pageFlags);
 1.57308 +    assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
 1.57309 +    assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
 1.57310 +    assert( pNew->nOverflow==0 );
 1.57311 +
 1.57312 +    j = cntNew[i];
 1.57313 +
 1.57314 +    /* If the sibling page assembled above was not the right-most sibling,
 1.57315 +    ** insert a divider cell into the parent page.
 1.57316 +    */
 1.57317 +    assert( i<nNew-1 || j==nCell );
 1.57318 +    if( j<nCell ){
 1.57319 +      u8 *pCell;
 1.57320 +      u8 *pTemp;
 1.57321 +      int sz;
 1.57322 +
 1.57323 +      assert( j<nMaxCells );
 1.57324 +      pCell = apCell[j];
 1.57325 +      sz = szCell[j] + leafCorrection;
 1.57326 +      pTemp = &aOvflSpace[iOvflSpace];
 1.57327 +      if( !pNew->leaf ){
 1.57328 +        memcpy(&pNew->aData[8], pCell, 4);
 1.57329 +      }else if( leafData ){
 1.57330 +        /* If the tree is a leaf-data tree, and the siblings are leaves, 
 1.57331 +        ** then there is no divider cell in apCell[]. Instead, the divider 
 1.57332 +        ** cell consists of the integer key for the right-most cell of 
 1.57333 +        ** the sibling-page assembled above only.
 1.57334 +        */
 1.57335 +        CellInfo info;
 1.57336 +        j--;
 1.57337 +        btreeParseCellPtr(pNew, apCell[j], &info);
 1.57338 +        pCell = pTemp;
 1.57339 +        sz = 4 + putVarint(&pCell[4], info.nKey);
 1.57340 +        pTemp = 0;
 1.57341 +      }else{
 1.57342 +        pCell -= 4;
 1.57343 +        /* Obscure case for non-leaf-data trees: If the cell at pCell was
 1.57344 +        ** previously stored on a leaf node, and its reported size was 4
 1.57345 +        ** bytes, then it may actually be smaller than this 
 1.57346 +        ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
 1.57347 +        ** any cell). But it is important to pass the correct size to 
 1.57348 +        ** insertCell(), so reparse the cell now.
 1.57349 +        **
 1.57350 +        ** Note that this can never happen in an SQLite data file, as all
 1.57351 +        ** cells are at least 4 bytes. It only happens in b-trees used
 1.57352 +        ** to evaluate "IN (SELECT ...)" and similar clauses.
 1.57353 +        */
 1.57354 +        if( szCell[j]==4 ){
 1.57355 +          assert(leafCorrection==4);
 1.57356 +          sz = cellSizePtr(pParent, pCell);
 1.57357 +        }
 1.57358 +      }
 1.57359 +      iOvflSpace += sz;
 1.57360 +      assert( sz<=pBt->maxLocal+23 );
 1.57361 +      assert( iOvflSpace <= (int)pBt->pageSize );
 1.57362 +      insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
 1.57363 +      if( rc!=SQLITE_OK ) goto balance_cleanup;
 1.57364 +      assert( sqlite3PagerIswriteable(pParent->pDbPage) );
 1.57365 +
 1.57366 +      j++;
 1.57367 +      nxDiv++;
 1.57368 +    }
 1.57369 +  }
 1.57370 +  assert( j==nCell );
 1.57371 +  assert( nOld>0 );
 1.57372 +  assert( nNew>0 );
 1.57373 +  if( (pageFlags & PTF_LEAF)==0 ){
 1.57374 +    u8 *zChild = &apCopy[nOld-1]->aData[8];
 1.57375 +    memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
 1.57376 +  }
 1.57377 +
 1.57378 +  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
 1.57379 +    /* The root page of the b-tree now contains no cells. The only sibling
 1.57380 +    ** page is the right-child of the parent. Copy the contents of the
 1.57381 +    ** child page into the parent, decreasing the overall height of the
 1.57382 +    ** b-tree structure by one. This is described as the "balance-shallower"
 1.57383 +    ** sub-algorithm in some documentation.
 1.57384 +    **
 1.57385 +    ** If this is an auto-vacuum database, the call to copyNodeContent() 
 1.57386 +    ** sets all pointer-map entries corresponding to database image pages 
 1.57387 +    ** for which the pointer is stored within the content being copied.
 1.57388 +    **
 1.57389 +    ** The second assert below verifies that the child page is defragmented
 1.57390 +    ** (it must be, as it was just reconstructed using assemblePage()). This
 1.57391 +    ** is important if the parent page happens to be page 1 of the database
 1.57392 +    ** image.  */
 1.57393 +    assert( nNew==1 );
 1.57394 +    assert( apNew[0]->nFree == 
 1.57395 +        (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) 
 1.57396 +    );
 1.57397 +    copyNodeContent(apNew[0], pParent, &rc);
 1.57398 +    freePage(apNew[0], &rc);
 1.57399 +  }else if( ISAUTOVACUUM ){
 1.57400 +    /* Fix the pointer-map entries for all the cells that were shifted around. 
 1.57401 +    ** There are several different types of pointer-map entries that need to
 1.57402 +    ** be dealt with by this routine. Some of these have been set already, but
 1.57403 +    ** many have not. The following is a summary:
 1.57404 +    **
 1.57405 +    **   1) The entries associated with new sibling pages that were not
 1.57406 +    **      siblings when this function was called. These have already
 1.57407 +    **      been set. We don't need to worry about old siblings that were
 1.57408 +    **      moved to the free-list - the freePage() code has taken care
 1.57409 +    **      of those.
 1.57410 +    **
 1.57411 +    **   2) The pointer-map entries associated with the first overflow
 1.57412 +    **      page in any overflow chains used by new divider cells. These 
 1.57413 +    **      have also already been taken care of by the insertCell() code.
 1.57414 +    **
 1.57415 +    **   3) If the sibling pages are not leaves, then the child pages of
 1.57416 +    **      cells stored on the sibling pages may need to be updated.
 1.57417 +    **
 1.57418 +    **   4) If the sibling pages are not internal intkey nodes, then any
 1.57419 +    **      overflow pages used by these cells may need to be updated
 1.57420 +    **      (internal intkey nodes never contain pointers to overflow pages).
 1.57421 +    **
 1.57422 +    **   5) If the sibling pages are not leaves, then the pointer-map
 1.57423 +    **      entries for the right-child pages of each sibling may need
 1.57424 +    **      to be updated.
 1.57425 +    **
 1.57426 +    ** Cases 1 and 2 are dealt with above by other code. The next
 1.57427 +    ** block deals with cases 3 and 4 and the one after that, case 5. Since
 1.57428 +    ** setting a pointer map entry is a relatively expensive operation, this
 1.57429 +    ** code only sets pointer map entries for child or overflow pages that have
 1.57430 +    ** actually moved between pages.  */
 1.57431 +    MemPage *pNew = apNew[0];
 1.57432 +    MemPage *pOld = apCopy[0];
 1.57433 +    int nOverflow = pOld->nOverflow;
 1.57434 +    int iNextOld = pOld->nCell + nOverflow;
 1.57435 +    int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
 1.57436 +    j = 0;                             /* Current 'old' sibling page */
 1.57437 +    k = 0;                             /* Current 'new' sibling page */
 1.57438 +    for(i=0; i<nCell; i++){
 1.57439 +      int isDivider = 0;
 1.57440 +      while( i==iNextOld ){
 1.57441 +        /* Cell i is the cell immediately following the last cell on old
 1.57442 +        ** sibling page j. If the siblings are not leaf pages of an
 1.57443 +        ** intkey b-tree, then cell i was a divider cell. */
 1.57444 +        assert( j+1 < ArraySize(apCopy) );
 1.57445 +        assert( j+1 < nOld );
 1.57446 +        pOld = apCopy[++j];
 1.57447 +        iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
 1.57448 +        if( pOld->nOverflow ){
 1.57449 +          nOverflow = pOld->nOverflow;
 1.57450 +          iOverflow = i + !leafData + pOld->aiOvfl[0];
 1.57451 +        }
 1.57452 +        isDivider = !leafData;  
 1.57453 +      }
 1.57454 +
 1.57455 +      assert(nOverflow>0 || iOverflow<i );
 1.57456 +      assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
 1.57457 +      assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
 1.57458 +      if( i==iOverflow ){
 1.57459 +        isDivider = 1;
 1.57460 +        if( (--nOverflow)>0 ){
 1.57461 +          iOverflow++;
 1.57462 +        }
 1.57463 +      }
 1.57464 +
 1.57465 +      if( i==cntNew[k] ){
 1.57466 +        /* Cell i is the cell immediately following the last cell on new
 1.57467 +        ** sibling page k. If the siblings are not leaf pages of an
 1.57468 +        ** intkey b-tree, then cell i is a divider cell.  */
 1.57469 +        pNew = apNew[++k];
 1.57470 +        if( !leafData ) continue;
 1.57471 +      }
 1.57472 +      assert( j<nOld );
 1.57473 +      assert( k<nNew );
 1.57474 +
 1.57475 +      /* If the cell was originally divider cell (and is not now) or
 1.57476 +      ** an overflow cell, or if the cell was located on a different sibling
 1.57477 +      ** page before the balancing, then the pointer map entries associated
 1.57478 +      ** with any child or overflow pages need to be updated.  */
 1.57479 +      if( isDivider || pOld->pgno!=pNew->pgno ){
 1.57480 +        if( !leafCorrection ){
 1.57481 +          ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
 1.57482 +        }
 1.57483 +        if( szCell[i]>pNew->minLocal ){
 1.57484 +          ptrmapPutOvflPtr(pNew, apCell[i], &rc);
 1.57485 +        }
 1.57486 +      }
 1.57487 +    }
 1.57488 +
 1.57489 +    if( !leafCorrection ){
 1.57490 +      for(i=0; i<nNew; i++){
 1.57491 +        u32 key = get4byte(&apNew[i]->aData[8]);
 1.57492 +        ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
 1.57493 +      }
 1.57494 +    }
 1.57495 +
 1.57496 +#if 0
 1.57497 +    /* The ptrmapCheckPages() contains assert() statements that verify that
 1.57498 +    ** all pointer map pages are set correctly. This is helpful while 
 1.57499 +    ** debugging. This is usually disabled because a corrupt database may
 1.57500 +    ** cause an assert() statement to fail.  */
 1.57501 +    ptrmapCheckPages(apNew, nNew);
 1.57502 +    ptrmapCheckPages(&pParent, 1);
 1.57503 +#endif
 1.57504 +  }
 1.57505 +
 1.57506 +  assert( pParent->isInit );
 1.57507 +  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
 1.57508 +          nOld, nNew, nCell));
 1.57509 +
 1.57510 +  /*
 1.57511 +  ** Cleanup before returning.
 1.57512 +  */
 1.57513 +balance_cleanup:
 1.57514 +  sqlite3ScratchFree(apCell);
 1.57515 +  for(i=0; i<nOld; i++){
 1.57516 +    releasePage(apOld[i]);
 1.57517 +  }
 1.57518 +  for(i=0; i<nNew; i++){
 1.57519 +    releasePage(apNew[i]);
 1.57520 +  }
 1.57521 +
 1.57522 +  return rc;
 1.57523 +}
 1.57524 +#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
 1.57525 +#pragma optimize("", on)
 1.57526 +#endif
 1.57527 +
 1.57528 +
 1.57529 +/*
 1.57530 +** This function is called when the root page of a b-tree structure is
 1.57531 +** overfull (has one or more overflow pages).
 1.57532 +**
 1.57533 +** A new child page is allocated and the contents of the current root
 1.57534 +** page, including overflow cells, are copied into the child. The root
 1.57535 +** page is then overwritten to make it an empty page with the right-child 
 1.57536 +** pointer pointing to the new page.
 1.57537 +**
 1.57538 +** Before returning, all pointer-map entries corresponding to pages 
 1.57539 +** that the new child-page now contains pointers to are updated. The
 1.57540 +** entry corresponding to the new right-child pointer of the root
 1.57541 +** page is also updated.
 1.57542 +**
 1.57543 +** If successful, *ppChild is set to contain a reference to the child 
 1.57544 +** page and SQLITE_OK is returned. In this case the caller is required
 1.57545 +** to call releasePage() on *ppChild exactly once. If an error occurs,
 1.57546 +** an error code is returned and *ppChild is set to 0.
 1.57547 +*/
 1.57548 +static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
 1.57549 +  int rc;                        /* Return value from subprocedures */
 1.57550 +  MemPage *pChild = 0;           /* Pointer to a new child page */
 1.57551 +  Pgno pgnoChild = 0;            /* Page number of the new child page */
 1.57552 +  BtShared *pBt = pRoot->pBt;    /* The BTree */
 1.57553 +
 1.57554 +  assert( pRoot->nOverflow>0 );
 1.57555 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.57556 +
 1.57557 +  /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
 1.57558 +  ** page that will become the new right-child of pPage. Copy the contents
 1.57559 +  ** of the node stored on pRoot into the new child page.
 1.57560 +  */
 1.57561 +  rc = sqlite3PagerWrite(pRoot->pDbPage);
 1.57562 +  if( rc==SQLITE_OK ){
 1.57563 +    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
 1.57564 +    copyNodeContent(pRoot, pChild, &rc);
 1.57565 +    if( ISAUTOVACUUM ){
 1.57566 +      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
 1.57567 +    }
 1.57568 +  }
 1.57569 +  if( rc ){
 1.57570 +    *ppChild = 0;
 1.57571 +    releasePage(pChild);
 1.57572 +    return rc;
 1.57573 +  }
 1.57574 +  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
 1.57575 +  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
 1.57576 +  assert( pChild->nCell==pRoot->nCell );
 1.57577 +
 1.57578 +  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
 1.57579 +
 1.57580 +  /* Copy the overflow cells from pRoot to pChild */
 1.57581 +  memcpy(pChild->aiOvfl, pRoot->aiOvfl,
 1.57582 +         pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
 1.57583 +  memcpy(pChild->apOvfl, pRoot->apOvfl,
 1.57584 +         pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
 1.57585 +  pChild->nOverflow = pRoot->nOverflow;
 1.57586 +
 1.57587 +  /* Zero the contents of pRoot. Then install pChild as the right-child. */
 1.57588 +  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
 1.57589 +  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
 1.57590 +
 1.57591 +  *ppChild = pChild;
 1.57592 +  return SQLITE_OK;
 1.57593 +}
 1.57594 +
 1.57595 +/*
 1.57596 +** The page that pCur currently points to has just been modified in
 1.57597 +** some way. This function figures out if this modification means the
 1.57598 +** tree needs to be balanced, and if so calls the appropriate balancing 
 1.57599 +** routine. Balancing routines are:
 1.57600 +**
 1.57601 +**   balance_quick()
 1.57602 +**   balance_deeper()
 1.57603 +**   balance_nonroot()
 1.57604 +*/
 1.57605 +static int balance(BtCursor *pCur){
 1.57606 +  int rc = SQLITE_OK;
 1.57607 +  const int nMin = pCur->pBt->usableSize * 2 / 3;
 1.57608 +  u8 aBalanceQuickSpace[13];
 1.57609 +  u8 *pFree = 0;
 1.57610 +
 1.57611 +  TESTONLY( int balance_quick_called = 0 );
 1.57612 +  TESTONLY( int balance_deeper_called = 0 );
 1.57613 +
 1.57614 +  do {
 1.57615 +    int iPage = pCur->iPage;
 1.57616 +    MemPage *pPage = pCur->apPage[iPage];
 1.57617 +
 1.57618 +    if( iPage==0 ){
 1.57619 +      if( pPage->nOverflow ){
 1.57620 +        /* The root page of the b-tree is overfull. In this case call the
 1.57621 +        ** balance_deeper() function to create a new child for the root-page
 1.57622 +        ** and copy the current contents of the root-page to it. The
 1.57623 +        ** next iteration of the do-loop will balance the child page.
 1.57624 +        */ 
 1.57625 +        assert( (balance_deeper_called++)==0 );
 1.57626 +        rc = balance_deeper(pPage, &pCur->apPage[1]);
 1.57627 +        if( rc==SQLITE_OK ){
 1.57628 +          pCur->iPage = 1;
 1.57629 +          pCur->aiIdx[0] = 0;
 1.57630 +          pCur->aiIdx[1] = 0;
 1.57631 +          assert( pCur->apPage[1]->nOverflow );
 1.57632 +        }
 1.57633 +      }else{
 1.57634 +        break;
 1.57635 +      }
 1.57636 +    }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
 1.57637 +      break;
 1.57638 +    }else{
 1.57639 +      MemPage * const pParent = pCur->apPage[iPage-1];
 1.57640 +      int const iIdx = pCur->aiIdx[iPage-1];
 1.57641 +
 1.57642 +      rc = sqlite3PagerWrite(pParent->pDbPage);
 1.57643 +      if( rc==SQLITE_OK ){
 1.57644 +#ifndef SQLITE_OMIT_QUICKBALANCE
 1.57645 +        if( pPage->hasData
 1.57646 +         && pPage->nOverflow==1
 1.57647 +         && pPage->aiOvfl[0]==pPage->nCell
 1.57648 +         && pParent->pgno!=1
 1.57649 +         && pParent->nCell==iIdx
 1.57650 +        ){
 1.57651 +          /* Call balance_quick() to create a new sibling of pPage on which
 1.57652 +          ** to store the overflow cell. balance_quick() inserts a new cell
 1.57653 +          ** into pParent, which may cause pParent overflow. If this
 1.57654 +          ** happens, the next interation of the do-loop will balance pParent 
 1.57655 +          ** use either balance_nonroot() or balance_deeper(). Until this
 1.57656 +          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
 1.57657 +          ** buffer. 
 1.57658 +          **
 1.57659 +          ** The purpose of the following assert() is to check that only a
 1.57660 +          ** single call to balance_quick() is made for each call to this
 1.57661 +          ** function. If this were not verified, a subtle bug involving reuse
 1.57662 +          ** of the aBalanceQuickSpace[] might sneak in.
 1.57663 +          */
 1.57664 +          assert( (balance_quick_called++)==0 );
 1.57665 +          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
 1.57666 +        }else
 1.57667 +#endif
 1.57668 +        {
 1.57669 +          /* In this case, call balance_nonroot() to redistribute cells
 1.57670 +          ** between pPage and up to 2 of its sibling pages. This involves
 1.57671 +          ** modifying the contents of pParent, which may cause pParent to
 1.57672 +          ** become overfull or underfull. The next iteration of the do-loop
 1.57673 +          ** will balance the parent page to correct this.
 1.57674 +          ** 
 1.57675 +          ** If the parent page becomes overfull, the overflow cell or cells
 1.57676 +          ** are stored in the pSpace buffer allocated immediately below. 
 1.57677 +          ** A subsequent iteration of the do-loop will deal with this by
 1.57678 +          ** calling balance_nonroot() (balance_deeper() may be called first,
 1.57679 +          ** but it doesn't deal with overflow cells - just moves them to a
 1.57680 +          ** different page). Once this subsequent call to balance_nonroot() 
 1.57681 +          ** has completed, it is safe to release the pSpace buffer used by
 1.57682 +          ** the previous call, as the overflow cell data will have been 
 1.57683 +          ** copied either into the body of a database page or into the new
 1.57684 +          ** pSpace buffer passed to the latter call to balance_nonroot().
 1.57685 +          */
 1.57686 +          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
 1.57687 +          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
 1.57688 +          if( pFree ){
 1.57689 +            /* If pFree is not NULL, it points to the pSpace buffer used 
 1.57690 +            ** by a previous call to balance_nonroot(). Its contents are
 1.57691 +            ** now stored either on real database pages or within the 
 1.57692 +            ** new pSpace buffer, so it may be safely freed here. */
 1.57693 +            sqlite3PageFree(pFree);
 1.57694 +          }
 1.57695 +
 1.57696 +          /* The pSpace buffer will be freed after the next call to
 1.57697 +          ** balance_nonroot(), or just before this function returns, whichever
 1.57698 +          ** comes first. */
 1.57699 +          pFree = pSpace;
 1.57700 +        }
 1.57701 +      }
 1.57702 +
 1.57703 +      pPage->nOverflow = 0;
 1.57704 +
 1.57705 +      /* The next iteration of the do-loop balances the parent page. */
 1.57706 +      releasePage(pPage);
 1.57707 +      pCur->iPage--;
 1.57708 +    }
 1.57709 +  }while( rc==SQLITE_OK );
 1.57710 +
 1.57711 +  if( pFree ){
 1.57712 +    sqlite3PageFree(pFree);
 1.57713 +  }
 1.57714 +  return rc;
 1.57715 +}
 1.57716 +
 1.57717 +
 1.57718 +/*
 1.57719 +** Insert a new record into the BTree.  The key is given by (pKey,nKey)
 1.57720 +** and the data is given by (pData,nData).  The cursor is used only to
 1.57721 +** define what table the record should be inserted into.  The cursor
 1.57722 +** is left pointing at a random location.
 1.57723 +**
 1.57724 +** For an INTKEY table, only the nKey value of the key is used.  pKey is
 1.57725 +** ignored.  For a ZERODATA table, the pData and nData are both ignored.
 1.57726 +**
 1.57727 +** If the seekResult parameter is non-zero, then a successful call to
 1.57728 +** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
 1.57729 +** been performed. seekResult is the search result returned (a negative
 1.57730 +** number if pCur points at an entry that is smaller than (pKey, nKey), or
 1.57731 +** a positive value if pCur points at an etry that is larger than 
 1.57732 +** (pKey, nKey)). 
 1.57733 +**
 1.57734 +** If the seekResult parameter is non-zero, then the caller guarantees that
 1.57735 +** cursor pCur is pointing at the existing copy of a row that is to be
 1.57736 +** overwritten.  If the seekResult parameter is 0, then cursor pCur may
 1.57737 +** point to any entry or to no entry at all and so this function has to seek
 1.57738 +** the cursor before the new key can be inserted.
 1.57739 +*/
 1.57740 +SQLITE_PRIVATE int sqlite3BtreeInsert(
 1.57741 +  BtCursor *pCur,                /* Insert data into the table of this cursor */
 1.57742 +  const void *pKey, i64 nKey,    /* The key of the new record */
 1.57743 +  const void *pData, int nData,  /* The data of the new record */
 1.57744 +  int nZero,                     /* Number of extra 0 bytes to append to data */
 1.57745 +  int appendBias,                /* True if this is likely an append */
 1.57746 +  int seekResult                 /* Result of prior MovetoUnpacked() call */
 1.57747 +){
 1.57748 +  int rc;
 1.57749 +  int loc = seekResult;          /* -1: before desired location  +1: after */
 1.57750 +  int szNew = 0;
 1.57751 +  int idx;
 1.57752 +  MemPage *pPage;
 1.57753 +  Btree *p = pCur->pBtree;
 1.57754 +  BtShared *pBt = p->pBt;
 1.57755 +  unsigned char *oldCell;
 1.57756 +  unsigned char *newCell = 0;
 1.57757 +
 1.57758 +  if( pCur->eState==CURSOR_FAULT ){
 1.57759 +    assert( pCur->skipNext!=SQLITE_OK );
 1.57760 +    return pCur->skipNext;
 1.57761 +  }
 1.57762 +
 1.57763 +  assert( cursorHoldsMutex(pCur) );
 1.57764 +  assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
 1.57765 +              && (pBt->btsFlags & BTS_READ_ONLY)==0 );
 1.57766 +  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
 1.57767 +
 1.57768 +  /* Assert that the caller has been consistent. If this cursor was opened
 1.57769 +  ** expecting an index b-tree, then the caller should be inserting blob
 1.57770 +  ** keys with no associated data. If the cursor was opened expecting an
 1.57771 +  ** intkey table, the caller should be inserting integer keys with a
 1.57772 +  ** blob of associated data.  */
 1.57773 +  assert( (pKey==0)==(pCur->pKeyInfo==0) );
 1.57774 +
 1.57775 +  /* Save the positions of any other cursors open on this table.
 1.57776 +  **
 1.57777 +  ** In some cases, the call to btreeMoveto() below is a no-op. For
 1.57778 +  ** example, when inserting data into a table with auto-generated integer
 1.57779 +  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
 1.57780 +  ** integer key to use. It then calls this function to actually insert the 
 1.57781 +  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
 1.57782 +  ** that the cursor is already where it needs to be and returns without
 1.57783 +  ** doing any work. To avoid thwarting these optimizations, it is important
 1.57784 +  ** not to clear the cursor here.
 1.57785 +  */
 1.57786 +  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
 1.57787 +  if( rc ) return rc;
 1.57788 +
 1.57789 +  if( pCur->pKeyInfo==0 ){
 1.57790 +    /* If this is an insert into a table b-tree, invalidate any incrblob 
 1.57791 +    ** cursors open on the row being replaced */
 1.57792 +    invalidateIncrblobCursors(p, nKey, 0);
 1.57793 +
 1.57794 +    /* If the cursor is currently on the last row and we are appending a
 1.57795 +    ** new row onto the end, set the "loc" to avoid an unnecessary btreeMoveto()
 1.57796 +    ** call */
 1.57797 +    if( pCur->validNKey && nKey>0 && pCur->info.nKey==nKey-1 ){
 1.57798 +      loc = -1;
 1.57799 +    }
 1.57800 +  }
 1.57801 +
 1.57802 +  if( !loc ){
 1.57803 +    rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
 1.57804 +    if( rc ) return rc;
 1.57805 +  }
 1.57806 +  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
 1.57807 +
 1.57808 +  pPage = pCur->apPage[pCur->iPage];
 1.57809 +  assert( pPage->intKey || nKey>=0 );
 1.57810 +  assert( pPage->leaf || !pPage->intKey );
 1.57811 +
 1.57812 +  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
 1.57813 +          pCur->pgnoRoot, nKey, nData, pPage->pgno,
 1.57814 +          loc==0 ? "overwrite" : "new entry"));
 1.57815 +  assert( pPage->isInit );
 1.57816 +  allocateTempSpace(pBt);
 1.57817 +  newCell = pBt->pTmpSpace;
 1.57818 +  if( newCell==0 ) return SQLITE_NOMEM;
 1.57819 +  rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
 1.57820 +  if( rc ) goto end_insert;
 1.57821 +  assert( szNew==cellSizePtr(pPage, newCell) );
 1.57822 +  assert( szNew <= MX_CELL_SIZE(pBt) );
 1.57823 +  idx = pCur->aiIdx[pCur->iPage];
 1.57824 +  if( loc==0 ){
 1.57825 +    u16 szOld;
 1.57826 +    assert( idx<pPage->nCell );
 1.57827 +    rc = sqlite3PagerWrite(pPage->pDbPage);
 1.57828 +    if( rc ){
 1.57829 +      goto end_insert;
 1.57830 +    }
 1.57831 +    oldCell = findCell(pPage, idx);
 1.57832 +    if( !pPage->leaf ){
 1.57833 +      memcpy(newCell, oldCell, 4);
 1.57834 +    }
 1.57835 +    szOld = cellSizePtr(pPage, oldCell);
 1.57836 +    rc = clearCell(pPage, oldCell);
 1.57837 +    dropCell(pPage, idx, szOld, &rc);
 1.57838 +    if( rc ) goto end_insert;
 1.57839 +  }else if( loc<0 && pPage->nCell>0 ){
 1.57840 +    assert( pPage->leaf );
 1.57841 +    idx = ++pCur->aiIdx[pCur->iPage];
 1.57842 +  }else{
 1.57843 +    assert( pPage->leaf );
 1.57844 +  }
 1.57845 +  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
 1.57846 +  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
 1.57847 +
 1.57848 +  /* If no error has occurred and pPage has an overflow cell, call balance() 
 1.57849 +  ** to redistribute the cells within the tree. Since balance() may move
 1.57850 +  ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
 1.57851 +  ** variables.
 1.57852 +  **
 1.57853 +  ** Previous versions of SQLite called moveToRoot() to move the cursor
 1.57854 +  ** back to the root page as balance() used to invalidate the contents
 1.57855 +  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
 1.57856 +  ** set the cursor state to "invalid". This makes common insert operations
 1.57857 +  ** slightly faster.
 1.57858 +  **
 1.57859 +  ** There is a subtle but important optimization here too. When inserting
 1.57860 +  ** multiple records into an intkey b-tree using a single cursor (as can
 1.57861 +  ** happen while processing an "INSERT INTO ... SELECT" statement), it
 1.57862 +  ** is advantageous to leave the cursor pointing to the last entry in
 1.57863 +  ** the b-tree if possible. If the cursor is left pointing to the last
 1.57864 +  ** entry in the table, and the next row inserted has an integer key
 1.57865 +  ** larger than the largest existing key, it is possible to insert the
 1.57866 +  ** row without seeking the cursor. This can be a big performance boost.
 1.57867 +  */
 1.57868 +  pCur->info.nSize = 0;
 1.57869 +  if( rc==SQLITE_OK && pPage->nOverflow ){
 1.57870 +    pCur->validNKey = 0;
 1.57871 +    rc = balance(pCur);
 1.57872 +
 1.57873 +    /* Must make sure nOverflow is reset to zero even if the balance()
 1.57874 +    ** fails. Internal data structure corruption will result otherwise. 
 1.57875 +    ** Also, set the cursor state to invalid. This stops saveCursorPosition()
 1.57876 +    ** from trying to save the current position of the cursor.  */
 1.57877 +    pCur->apPage[pCur->iPage]->nOverflow = 0;
 1.57878 +    pCur->eState = CURSOR_INVALID;
 1.57879 +  }
 1.57880 +  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
 1.57881 +
 1.57882 +end_insert:
 1.57883 +  return rc;
 1.57884 +}
 1.57885 +
 1.57886 +/*
 1.57887 +** Delete the entry that the cursor is pointing to.  The cursor
 1.57888 +** is left pointing at a arbitrary location.
 1.57889 +*/
 1.57890 +SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
 1.57891 +  Btree *p = pCur->pBtree;
 1.57892 +  BtShared *pBt = p->pBt;              
 1.57893 +  int rc;                              /* Return code */
 1.57894 +  MemPage *pPage;                      /* Page to delete cell from */
 1.57895 +  unsigned char *pCell;                /* Pointer to cell to delete */
 1.57896 +  int iCellIdx;                        /* Index of cell to delete */
 1.57897 +  int iCellDepth;                      /* Depth of node containing pCell */ 
 1.57898 +
 1.57899 +  assert( cursorHoldsMutex(pCur) );
 1.57900 +  assert( pBt->inTransaction==TRANS_WRITE );
 1.57901 +  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
 1.57902 +  assert( pCur->wrFlag );
 1.57903 +  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
 1.57904 +  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
 1.57905 +
 1.57906 +  if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) 
 1.57907 +   || NEVER(pCur->eState!=CURSOR_VALID)
 1.57908 +  ){
 1.57909 +    return SQLITE_ERROR;  /* Something has gone awry. */
 1.57910 +  }
 1.57911 +
 1.57912 +  iCellDepth = pCur->iPage;
 1.57913 +  iCellIdx = pCur->aiIdx[iCellDepth];
 1.57914 +  pPage = pCur->apPage[iCellDepth];
 1.57915 +  pCell = findCell(pPage, iCellIdx);
 1.57916 +
 1.57917 +  /* If the page containing the entry to delete is not a leaf page, move
 1.57918 +  ** the cursor to the largest entry in the tree that is smaller than
 1.57919 +  ** the entry being deleted. This cell will replace the cell being deleted
 1.57920 +  ** from the internal node. The 'previous' entry is used for this instead
 1.57921 +  ** of the 'next' entry, as the previous entry is always a part of the
 1.57922 +  ** sub-tree headed by the child page of the cell being deleted. This makes
 1.57923 +  ** balancing the tree following the delete operation easier.  */
 1.57924 +  if( !pPage->leaf ){
 1.57925 +    int notUsed = 0;
 1.57926 +    rc = sqlite3BtreePrevious(pCur, &notUsed);
 1.57927 +    if( rc ) return rc;
 1.57928 +  }
 1.57929 +
 1.57930 +  /* Save the positions of any other cursors open on this table before
 1.57931 +  ** making any modifications. Make the page containing the entry to be 
 1.57932 +  ** deleted writable. Then free any overflow pages associated with the 
 1.57933 +  ** entry and finally remove the cell itself from within the page.  
 1.57934 +  */
 1.57935 +  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
 1.57936 +  if( rc ) return rc;
 1.57937 +
 1.57938 +  /* If this is a delete operation to remove a row from a table b-tree,
 1.57939 +  ** invalidate any incrblob cursors open on the row being deleted.  */
 1.57940 +  if( pCur->pKeyInfo==0 ){
 1.57941 +    invalidateIncrblobCursors(p, pCur->info.nKey, 0);
 1.57942 +  }
 1.57943 +
 1.57944 +  rc = sqlite3PagerWrite(pPage->pDbPage);
 1.57945 +  if( rc ) return rc;
 1.57946 +  rc = clearCell(pPage, pCell);
 1.57947 +  dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
 1.57948 +  if( rc ) return rc;
 1.57949 +
 1.57950 +  /* If the cell deleted was not located on a leaf page, then the cursor
 1.57951 +  ** is currently pointing to the largest entry in the sub-tree headed
 1.57952 +  ** by the child-page of the cell that was just deleted from an internal
 1.57953 +  ** node. The cell from the leaf node needs to be moved to the internal
 1.57954 +  ** node to replace the deleted cell.  */
 1.57955 +  if( !pPage->leaf ){
 1.57956 +    MemPage *pLeaf = pCur->apPage[pCur->iPage];
 1.57957 +    int nCell;
 1.57958 +    Pgno n = pCur->apPage[iCellDepth+1]->pgno;
 1.57959 +    unsigned char *pTmp;
 1.57960 +
 1.57961 +    pCell = findCell(pLeaf, pLeaf->nCell-1);
 1.57962 +    nCell = cellSizePtr(pLeaf, pCell);
 1.57963 +    assert( MX_CELL_SIZE(pBt) >= nCell );
 1.57964 +
 1.57965 +    allocateTempSpace(pBt);
 1.57966 +    pTmp = pBt->pTmpSpace;
 1.57967 +
 1.57968 +    rc = sqlite3PagerWrite(pLeaf->pDbPage);
 1.57969 +    insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
 1.57970 +    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
 1.57971 +    if( rc ) return rc;
 1.57972 +  }
 1.57973 +
 1.57974 +  /* Balance the tree. If the entry deleted was located on a leaf page,
 1.57975 +  ** then the cursor still points to that page. In this case the first
 1.57976 +  ** call to balance() repairs the tree, and the if(...) condition is
 1.57977 +  ** never true.
 1.57978 +  **
 1.57979 +  ** Otherwise, if the entry deleted was on an internal node page, then
 1.57980 +  ** pCur is pointing to the leaf page from which a cell was removed to
 1.57981 +  ** replace the cell deleted from the internal node. This is slightly
 1.57982 +  ** tricky as the leaf node may be underfull, and the internal node may
 1.57983 +  ** be either under or overfull. In this case run the balancing algorithm
 1.57984 +  ** on the leaf node first. If the balance proceeds far enough up the
 1.57985 +  ** tree that we can be sure that any problem in the internal node has
 1.57986 +  ** been corrected, so be it. Otherwise, after balancing the leaf node,
 1.57987 +  ** walk the cursor up the tree to the internal node and balance it as 
 1.57988 +  ** well.  */
 1.57989 +  rc = balance(pCur);
 1.57990 +  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
 1.57991 +    while( pCur->iPage>iCellDepth ){
 1.57992 +      releasePage(pCur->apPage[pCur->iPage--]);
 1.57993 +    }
 1.57994 +    rc = balance(pCur);
 1.57995 +  }
 1.57996 +
 1.57997 +  if( rc==SQLITE_OK ){
 1.57998 +    moveToRoot(pCur);
 1.57999 +  }
 1.58000 +  return rc;
 1.58001 +}
 1.58002 +
 1.58003 +/*
 1.58004 +** Create a new BTree table.  Write into *piTable the page
 1.58005 +** number for the root page of the new table.
 1.58006 +**
 1.58007 +** The type of type is determined by the flags parameter.  Only the
 1.58008 +** following values of flags are currently in use.  Other values for
 1.58009 +** flags might not work:
 1.58010 +**
 1.58011 +**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
 1.58012 +**     BTREE_ZERODATA                  Used for SQL indices
 1.58013 +*/
 1.58014 +static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
 1.58015 +  BtShared *pBt = p->pBt;
 1.58016 +  MemPage *pRoot;
 1.58017 +  Pgno pgnoRoot;
 1.58018 +  int rc;
 1.58019 +  int ptfFlags;          /* Page-type flage for the root page of new table */
 1.58020 +
 1.58021 +  assert( sqlite3BtreeHoldsMutex(p) );
 1.58022 +  assert( pBt->inTransaction==TRANS_WRITE );
 1.58023 +  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
 1.58024 +
 1.58025 +#ifdef SQLITE_OMIT_AUTOVACUUM
 1.58026 +  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
 1.58027 +  if( rc ){
 1.58028 +    return rc;
 1.58029 +  }
 1.58030 +#else
 1.58031 +  if( pBt->autoVacuum ){
 1.58032 +    Pgno pgnoMove;      /* Move a page here to make room for the root-page */
 1.58033 +    MemPage *pPageMove; /* The page to move to. */
 1.58034 +
 1.58035 +    /* Creating a new table may probably require moving an existing database
 1.58036 +    ** to make room for the new tables root page. In case this page turns
 1.58037 +    ** out to be an overflow page, delete all overflow page-map caches
 1.58038 +    ** held by open cursors.
 1.58039 +    */
 1.58040 +    invalidateAllOverflowCache(pBt);
 1.58041 +
 1.58042 +    /* Read the value of meta[3] from the database to determine where the
 1.58043 +    ** root page of the new table should go. meta[3] is the largest root-page
 1.58044 +    ** created so far, so the new root-page is (meta[3]+1).
 1.58045 +    */
 1.58046 +    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
 1.58047 +    pgnoRoot++;
 1.58048 +
 1.58049 +    /* The new root-page may not be allocated on a pointer-map page, or the
 1.58050 +    ** PENDING_BYTE page.
 1.58051 +    */
 1.58052 +    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
 1.58053 +        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
 1.58054 +      pgnoRoot++;
 1.58055 +    }
 1.58056 +    assert( pgnoRoot>=3 );
 1.58057 +
 1.58058 +    /* Allocate a page. The page that currently resides at pgnoRoot will
 1.58059 +    ** be moved to the allocated page (unless the allocated page happens
 1.58060 +    ** to reside at pgnoRoot).
 1.58061 +    */
 1.58062 +    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
 1.58063 +    if( rc!=SQLITE_OK ){
 1.58064 +      return rc;
 1.58065 +    }
 1.58066 +
 1.58067 +    if( pgnoMove!=pgnoRoot ){
 1.58068 +      /* pgnoRoot is the page that will be used for the root-page of
 1.58069 +      ** the new table (assuming an error did not occur). But we were
 1.58070 +      ** allocated pgnoMove. If required (i.e. if it was not allocated
 1.58071 +      ** by extending the file), the current page at position pgnoMove
 1.58072 +      ** is already journaled.
 1.58073 +      */
 1.58074 +      u8 eType = 0;
 1.58075 +      Pgno iPtrPage = 0;
 1.58076 +
 1.58077 +      /* Save the positions of any open cursors. This is required in
 1.58078 +      ** case they are holding a reference to an xFetch reference
 1.58079 +      ** corresponding to page pgnoRoot.  */
 1.58080 +      rc = saveAllCursors(pBt, 0, 0);
 1.58081 +      releasePage(pPageMove);
 1.58082 +      if( rc!=SQLITE_OK ){
 1.58083 +        return rc;
 1.58084 +      }
 1.58085 +
 1.58086 +      /* Move the page currently at pgnoRoot to pgnoMove. */
 1.58087 +      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
 1.58088 +      if( rc!=SQLITE_OK ){
 1.58089 +        return rc;
 1.58090 +      }
 1.58091 +      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
 1.58092 +      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
 1.58093 +        rc = SQLITE_CORRUPT_BKPT;
 1.58094 +      }
 1.58095 +      if( rc!=SQLITE_OK ){
 1.58096 +        releasePage(pRoot);
 1.58097 +        return rc;
 1.58098 +      }
 1.58099 +      assert( eType!=PTRMAP_ROOTPAGE );
 1.58100 +      assert( eType!=PTRMAP_FREEPAGE );
 1.58101 +      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
 1.58102 +      releasePage(pRoot);
 1.58103 +
 1.58104 +      /* Obtain the page at pgnoRoot */
 1.58105 +      if( rc!=SQLITE_OK ){
 1.58106 +        return rc;
 1.58107 +      }
 1.58108 +      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
 1.58109 +      if( rc!=SQLITE_OK ){
 1.58110 +        return rc;
 1.58111 +      }
 1.58112 +      rc = sqlite3PagerWrite(pRoot->pDbPage);
 1.58113 +      if( rc!=SQLITE_OK ){
 1.58114 +        releasePage(pRoot);
 1.58115 +        return rc;
 1.58116 +      }
 1.58117 +    }else{
 1.58118 +      pRoot = pPageMove;
 1.58119 +    } 
 1.58120 +
 1.58121 +    /* Update the pointer-map and meta-data with the new root-page number. */
 1.58122 +    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
 1.58123 +    if( rc ){
 1.58124 +      releasePage(pRoot);
 1.58125 +      return rc;
 1.58126 +    }
 1.58127 +
 1.58128 +    /* When the new root page was allocated, page 1 was made writable in
 1.58129 +    ** order either to increase the database filesize, or to decrement the
 1.58130 +    ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
 1.58131 +    */
 1.58132 +    assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
 1.58133 +    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
 1.58134 +    if( NEVER(rc) ){
 1.58135 +      releasePage(pRoot);
 1.58136 +      return rc;
 1.58137 +    }
 1.58138 +
 1.58139 +  }else{
 1.58140 +    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
 1.58141 +    if( rc ) return rc;
 1.58142 +  }
 1.58143 +#endif
 1.58144 +  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
 1.58145 +  if( createTabFlags & BTREE_INTKEY ){
 1.58146 +    ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
 1.58147 +  }else{
 1.58148 +    ptfFlags = PTF_ZERODATA | PTF_LEAF;
 1.58149 +  }
 1.58150 +  zeroPage(pRoot, ptfFlags);
 1.58151 +  sqlite3PagerUnref(pRoot->pDbPage);
 1.58152 +  assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
 1.58153 +  *piTable = (int)pgnoRoot;
 1.58154 +  return SQLITE_OK;
 1.58155 +}
 1.58156 +SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
 1.58157 +  int rc;
 1.58158 +  sqlite3BtreeEnter(p);
 1.58159 +  rc = btreeCreateTable(p, piTable, flags);
 1.58160 +  sqlite3BtreeLeave(p);
 1.58161 +  return rc;
 1.58162 +}
 1.58163 +
 1.58164 +/*
 1.58165 +** Erase the given database page and all its children.  Return
 1.58166 +** the page to the freelist.
 1.58167 +*/
 1.58168 +static int clearDatabasePage(
 1.58169 +  BtShared *pBt,           /* The BTree that contains the table */
 1.58170 +  Pgno pgno,               /* Page number to clear */
 1.58171 +  int freePageFlag,        /* Deallocate page if true */
 1.58172 +  int *pnChange            /* Add number of Cells freed to this counter */
 1.58173 +){
 1.58174 +  MemPage *pPage;
 1.58175 +  int rc;
 1.58176 +  unsigned char *pCell;
 1.58177 +  int i;
 1.58178 +  int hdr;
 1.58179 +
 1.58180 +  assert( sqlite3_mutex_held(pBt->mutex) );
 1.58181 +  if( pgno>btreePagecount(pBt) ){
 1.58182 +    return SQLITE_CORRUPT_BKPT;
 1.58183 +  }
 1.58184 +
 1.58185 +  rc = getAndInitPage(pBt, pgno, &pPage, 0);
 1.58186 +  if( rc ) return rc;
 1.58187 +  hdr = pPage->hdrOffset;
 1.58188 +  for(i=0; i<pPage->nCell; i++){
 1.58189 +    pCell = findCell(pPage, i);
 1.58190 +    if( !pPage->leaf ){
 1.58191 +      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
 1.58192 +      if( rc ) goto cleardatabasepage_out;
 1.58193 +    }
 1.58194 +    rc = clearCell(pPage, pCell);
 1.58195 +    if( rc ) goto cleardatabasepage_out;
 1.58196 +  }
 1.58197 +  if( !pPage->leaf ){
 1.58198 +    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
 1.58199 +    if( rc ) goto cleardatabasepage_out;
 1.58200 +  }else if( pnChange ){
 1.58201 +    assert( pPage->intKey );
 1.58202 +    *pnChange += pPage->nCell;
 1.58203 +  }
 1.58204 +  if( freePageFlag ){
 1.58205 +    freePage(pPage, &rc);
 1.58206 +  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
 1.58207 +    zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
 1.58208 +  }
 1.58209 +
 1.58210 +cleardatabasepage_out:
 1.58211 +  releasePage(pPage);
 1.58212 +  return rc;
 1.58213 +}
 1.58214 +
 1.58215 +/*
 1.58216 +** Delete all information from a single table in the database.  iTable is
 1.58217 +** the page number of the root of the table.  After this routine returns,
 1.58218 +** the root page is empty, but still exists.
 1.58219 +**
 1.58220 +** This routine will fail with SQLITE_LOCKED if there are any open
 1.58221 +** read cursors on the table.  Open write cursors are moved to the
 1.58222 +** root of the table.
 1.58223 +**
 1.58224 +** If pnChange is not NULL, then table iTable must be an intkey table. The
 1.58225 +** integer value pointed to by pnChange is incremented by the number of
 1.58226 +** entries in the table.
 1.58227 +*/
 1.58228 +SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
 1.58229 +  int rc;
 1.58230 +  BtShared *pBt = p->pBt;
 1.58231 +  sqlite3BtreeEnter(p);
 1.58232 +  assert( p->inTrans==TRANS_WRITE );
 1.58233 +
 1.58234 +  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
 1.58235 +
 1.58236 +  if( SQLITE_OK==rc ){
 1.58237 +    /* Invalidate all incrblob cursors open on table iTable (assuming iTable
 1.58238 +    ** is the root of a table b-tree - if it is not, the following call is
 1.58239 +    ** a no-op).  */
 1.58240 +    invalidateIncrblobCursors(p, 0, 1);
 1.58241 +    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
 1.58242 +  }
 1.58243 +  sqlite3BtreeLeave(p);
 1.58244 +  return rc;
 1.58245 +}
 1.58246 +
 1.58247 +/*
 1.58248 +** Erase all information in a table and add the root of the table to
 1.58249 +** the freelist.  Except, the root of the principle table (the one on
 1.58250 +** page 1) is never added to the freelist.
 1.58251 +**
 1.58252 +** This routine will fail with SQLITE_LOCKED if there are any open
 1.58253 +** cursors on the table.
 1.58254 +**
 1.58255 +** If AUTOVACUUM is enabled and the page at iTable is not the last
 1.58256 +** root page in the database file, then the last root page 
 1.58257 +** in the database file is moved into the slot formerly occupied by
 1.58258 +** iTable and that last slot formerly occupied by the last root page
 1.58259 +** is added to the freelist instead of iTable.  In this say, all
 1.58260 +** root pages are kept at the beginning of the database file, which
 1.58261 +** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
 1.58262 +** page number that used to be the last root page in the file before
 1.58263 +** the move.  If no page gets moved, *piMoved is set to 0.
 1.58264 +** The last root page is recorded in meta[3] and the value of
 1.58265 +** meta[3] is updated by this procedure.
 1.58266 +*/
 1.58267 +static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
 1.58268 +  int rc;
 1.58269 +  MemPage *pPage = 0;
 1.58270 +  BtShared *pBt = p->pBt;
 1.58271 +
 1.58272 +  assert( sqlite3BtreeHoldsMutex(p) );
 1.58273 +  assert( p->inTrans==TRANS_WRITE );
 1.58274 +
 1.58275 +  /* It is illegal to drop a table if any cursors are open on the
 1.58276 +  ** database. This is because in auto-vacuum mode the backend may
 1.58277 +  ** need to move another root-page to fill a gap left by the deleted
 1.58278 +  ** root page. If an open cursor was using this page a problem would 
 1.58279 +  ** occur.
 1.58280 +  **
 1.58281 +  ** This error is caught long before control reaches this point.
 1.58282 +  */
 1.58283 +  if( NEVER(pBt->pCursor) ){
 1.58284 +    sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
 1.58285 +    return SQLITE_LOCKED_SHAREDCACHE;
 1.58286 +  }
 1.58287 +
 1.58288 +  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
 1.58289 +  if( rc ) return rc;
 1.58290 +  rc = sqlite3BtreeClearTable(p, iTable, 0);
 1.58291 +  if( rc ){
 1.58292 +    releasePage(pPage);
 1.58293 +    return rc;
 1.58294 +  }
 1.58295 +
 1.58296 +  *piMoved = 0;
 1.58297 +
 1.58298 +  if( iTable>1 ){
 1.58299 +#ifdef SQLITE_OMIT_AUTOVACUUM
 1.58300 +    freePage(pPage, &rc);
 1.58301 +    releasePage(pPage);
 1.58302 +#else
 1.58303 +    if( pBt->autoVacuum ){
 1.58304 +      Pgno maxRootPgno;
 1.58305 +      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
 1.58306 +
 1.58307 +      if( iTable==maxRootPgno ){
 1.58308 +        /* If the table being dropped is the table with the largest root-page
 1.58309 +        ** number in the database, put the root page on the free list. 
 1.58310 +        */
 1.58311 +        freePage(pPage, &rc);
 1.58312 +        releasePage(pPage);
 1.58313 +        if( rc!=SQLITE_OK ){
 1.58314 +          return rc;
 1.58315 +        }
 1.58316 +      }else{
 1.58317 +        /* The table being dropped does not have the largest root-page
 1.58318 +        ** number in the database. So move the page that does into the 
 1.58319 +        ** gap left by the deleted root-page.
 1.58320 +        */
 1.58321 +        MemPage *pMove;
 1.58322 +        releasePage(pPage);
 1.58323 +        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
 1.58324 +        if( rc!=SQLITE_OK ){
 1.58325 +          return rc;
 1.58326 +        }
 1.58327 +        rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
 1.58328 +        releasePage(pMove);
 1.58329 +        if( rc!=SQLITE_OK ){
 1.58330 +          return rc;
 1.58331 +        }
 1.58332 +        pMove = 0;
 1.58333 +        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
 1.58334 +        freePage(pMove, &rc);
 1.58335 +        releasePage(pMove);
 1.58336 +        if( rc!=SQLITE_OK ){
 1.58337 +          return rc;
 1.58338 +        }
 1.58339 +        *piMoved = maxRootPgno;
 1.58340 +      }
 1.58341 +
 1.58342 +      /* Set the new 'max-root-page' value in the database header. This
 1.58343 +      ** is the old value less one, less one more if that happens to
 1.58344 +      ** be a root-page number, less one again if that is the
 1.58345 +      ** PENDING_BYTE_PAGE.
 1.58346 +      */
 1.58347 +      maxRootPgno--;
 1.58348 +      while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
 1.58349 +             || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
 1.58350 +        maxRootPgno--;
 1.58351 +      }
 1.58352 +      assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
 1.58353 +
 1.58354 +      rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
 1.58355 +    }else{
 1.58356 +      freePage(pPage, &rc);
 1.58357 +      releasePage(pPage);
 1.58358 +    }
 1.58359 +#endif
 1.58360 +  }else{
 1.58361 +    /* If sqlite3BtreeDropTable was called on page 1.
 1.58362 +    ** This really never should happen except in a corrupt
 1.58363 +    ** database. 
 1.58364 +    */
 1.58365 +    zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
 1.58366 +    releasePage(pPage);
 1.58367 +  }
 1.58368 +  return rc;  
 1.58369 +}
 1.58370 +SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
 1.58371 +  int rc;
 1.58372 +  sqlite3BtreeEnter(p);
 1.58373 +  rc = btreeDropTable(p, iTable, piMoved);
 1.58374 +  sqlite3BtreeLeave(p);
 1.58375 +  return rc;
 1.58376 +}
 1.58377 +
 1.58378 +
 1.58379 +/*
 1.58380 +** This function may only be called if the b-tree connection already
 1.58381 +** has a read or write transaction open on the database.
 1.58382 +**
 1.58383 +** Read the meta-information out of a database file.  Meta[0]
 1.58384 +** is the number of free pages currently in the database.  Meta[1]
 1.58385 +** through meta[15] are available for use by higher layers.  Meta[0]
 1.58386 +** is read-only, the others are read/write.
 1.58387 +** 
 1.58388 +** The schema layer numbers meta values differently.  At the schema
 1.58389 +** layer (and the SetCookie and ReadCookie opcodes) the number of
 1.58390 +** free pages is not visible.  So Cookie[0] is the same as Meta[1].
 1.58391 +*/
 1.58392 +SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
 1.58393 +  BtShared *pBt = p->pBt;
 1.58394 +
 1.58395 +  sqlite3BtreeEnter(p);
 1.58396 +  assert( p->inTrans>TRANS_NONE );
 1.58397 +  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
 1.58398 +  assert( pBt->pPage1 );
 1.58399 +  assert( idx>=0 && idx<=15 );
 1.58400 +
 1.58401 +  *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
 1.58402 +
 1.58403 +  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
 1.58404 +  ** database, mark the database as read-only.  */
 1.58405 +#ifdef SQLITE_OMIT_AUTOVACUUM
 1.58406 +  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
 1.58407 +    pBt->btsFlags |= BTS_READ_ONLY;
 1.58408 +  }
 1.58409 +#endif
 1.58410 +
 1.58411 +  sqlite3BtreeLeave(p);
 1.58412 +}
 1.58413 +
 1.58414 +/*
 1.58415 +** Write meta-information back into the database.  Meta[0] is
 1.58416 +** read-only and may not be written.
 1.58417 +*/
 1.58418 +SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
 1.58419 +  BtShared *pBt = p->pBt;
 1.58420 +  unsigned char *pP1;
 1.58421 +  int rc;
 1.58422 +  assert( idx>=1 && idx<=15 );
 1.58423 +  sqlite3BtreeEnter(p);
 1.58424 +  assert( p->inTrans==TRANS_WRITE );
 1.58425 +  assert( pBt->pPage1!=0 );
 1.58426 +  pP1 = pBt->pPage1->aData;
 1.58427 +  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
 1.58428 +  if( rc==SQLITE_OK ){
 1.58429 +    put4byte(&pP1[36 + idx*4], iMeta);
 1.58430 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.58431 +    if( idx==BTREE_INCR_VACUUM ){
 1.58432 +      assert( pBt->autoVacuum || iMeta==0 );
 1.58433 +      assert( iMeta==0 || iMeta==1 );
 1.58434 +      pBt->incrVacuum = (u8)iMeta;
 1.58435 +    }
 1.58436 +#endif
 1.58437 +  }
 1.58438 +  sqlite3BtreeLeave(p);
 1.58439 +  return rc;
 1.58440 +}
 1.58441 +
 1.58442 +#ifndef SQLITE_OMIT_BTREECOUNT
 1.58443 +/*
 1.58444 +** The first argument, pCur, is a cursor opened on some b-tree. Count the
 1.58445 +** number of entries in the b-tree and write the result to *pnEntry.
 1.58446 +**
 1.58447 +** SQLITE_OK is returned if the operation is successfully executed. 
 1.58448 +** Otherwise, if an error is encountered (i.e. an IO error or database
 1.58449 +** corruption) an SQLite error code is returned.
 1.58450 +*/
 1.58451 +SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
 1.58452 +  i64 nEntry = 0;                      /* Value to return in *pnEntry */
 1.58453 +  int rc;                              /* Return code */
 1.58454 +
 1.58455 +  if( pCur->pgnoRoot==0 ){
 1.58456 +    *pnEntry = 0;
 1.58457 +    return SQLITE_OK;
 1.58458 +  }
 1.58459 +  rc = moveToRoot(pCur);
 1.58460 +
 1.58461 +  /* Unless an error occurs, the following loop runs one iteration for each
 1.58462 +  ** page in the B-Tree structure (not including overflow pages). 
 1.58463 +  */
 1.58464 +  while( rc==SQLITE_OK ){
 1.58465 +    int iIdx;                          /* Index of child node in parent */
 1.58466 +    MemPage *pPage;                    /* Current page of the b-tree */
 1.58467 +
 1.58468 +    /* If this is a leaf page or the tree is not an int-key tree, then 
 1.58469 +    ** this page contains countable entries. Increment the entry counter
 1.58470 +    ** accordingly.
 1.58471 +    */
 1.58472 +    pPage = pCur->apPage[pCur->iPage];
 1.58473 +    if( pPage->leaf || !pPage->intKey ){
 1.58474 +      nEntry += pPage->nCell;
 1.58475 +    }
 1.58476 +
 1.58477 +    /* pPage is a leaf node. This loop navigates the cursor so that it 
 1.58478 +    ** points to the first interior cell that it points to the parent of
 1.58479 +    ** the next page in the tree that has not yet been visited. The
 1.58480 +    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
 1.58481 +    ** of the page, or to the number of cells in the page if the next page
 1.58482 +    ** to visit is the right-child of its parent.
 1.58483 +    **
 1.58484 +    ** If all pages in the tree have been visited, return SQLITE_OK to the
 1.58485 +    ** caller.
 1.58486 +    */
 1.58487 +    if( pPage->leaf ){
 1.58488 +      do {
 1.58489 +        if( pCur->iPage==0 ){
 1.58490 +          /* All pages of the b-tree have been visited. Return successfully. */
 1.58491 +          *pnEntry = nEntry;
 1.58492 +          return SQLITE_OK;
 1.58493 +        }
 1.58494 +        moveToParent(pCur);
 1.58495 +      }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
 1.58496 +
 1.58497 +      pCur->aiIdx[pCur->iPage]++;
 1.58498 +      pPage = pCur->apPage[pCur->iPage];
 1.58499 +    }
 1.58500 +
 1.58501 +    /* Descend to the child node of the cell that the cursor currently 
 1.58502 +    ** points at. This is the right-child if (iIdx==pPage->nCell).
 1.58503 +    */
 1.58504 +    iIdx = pCur->aiIdx[pCur->iPage];
 1.58505 +    if( iIdx==pPage->nCell ){
 1.58506 +      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
 1.58507 +    }else{
 1.58508 +      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
 1.58509 +    }
 1.58510 +  }
 1.58511 +
 1.58512 +  /* An error has occurred. Return an error code. */
 1.58513 +  return rc;
 1.58514 +}
 1.58515 +#endif
 1.58516 +
 1.58517 +/*
 1.58518 +** Return the pager associated with a BTree.  This routine is used for
 1.58519 +** testing and debugging only.
 1.58520 +*/
 1.58521 +SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
 1.58522 +  return p->pBt->pPager;
 1.58523 +}
 1.58524 +
 1.58525 +#ifndef SQLITE_OMIT_INTEGRITY_CHECK
 1.58526 +/*
 1.58527 +** Append a message to the error message string.
 1.58528 +*/
 1.58529 +static void checkAppendMsg(
 1.58530 +  IntegrityCk *pCheck,
 1.58531 +  char *zMsg1,
 1.58532 +  const char *zFormat,
 1.58533 +  ...
 1.58534 +){
 1.58535 +  va_list ap;
 1.58536 +  if( !pCheck->mxErr ) return;
 1.58537 +  pCheck->mxErr--;
 1.58538 +  pCheck->nErr++;
 1.58539 +  va_start(ap, zFormat);
 1.58540 +  if( pCheck->errMsg.nChar ){
 1.58541 +    sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
 1.58542 +  }
 1.58543 +  if( zMsg1 ){
 1.58544 +    sqlite3StrAccumAppendAll(&pCheck->errMsg, zMsg1);
 1.58545 +  }
 1.58546 +  sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
 1.58547 +  va_end(ap);
 1.58548 +  if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
 1.58549 +    pCheck->mallocFailed = 1;
 1.58550 +  }
 1.58551 +}
 1.58552 +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
 1.58553 +
 1.58554 +#ifndef SQLITE_OMIT_INTEGRITY_CHECK
 1.58555 +
 1.58556 +/*
 1.58557 +** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
 1.58558 +** corresponds to page iPg is already set.
 1.58559 +*/
 1.58560 +static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
 1.58561 +  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
 1.58562 +  return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
 1.58563 +}
 1.58564 +
 1.58565 +/*
 1.58566 +** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
 1.58567 +*/
 1.58568 +static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
 1.58569 +  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
 1.58570 +  pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
 1.58571 +}
 1.58572 +
 1.58573 +
 1.58574 +/*
 1.58575 +** Add 1 to the reference count for page iPage.  If this is the second
 1.58576 +** reference to the page, add an error message to pCheck->zErrMsg.
 1.58577 +** Return 1 if there are 2 ore more references to the page and 0 if
 1.58578 +** if this is the first reference to the page.
 1.58579 +**
 1.58580 +** Also check that the page number is in bounds.
 1.58581 +*/
 1.58582 +static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
 1.58583 +  if( iPage==0 ) return 1;
 1.58584 +  if( iPage>pCheck->nPage ){
 1.58585 +    checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
 1.58586 +    return 1;
 1.58587 +  }
 1.58588 +  if( getPageReferenced(pCheck, iPage) ){
 1.58589 +    checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
 1.58590 +    return 1;
 1.58591 +  }
 1.58592 +  setPageReferenced(pCheck, iPage);
 1.58593 +  return 0;
 1.58594 +}
 1.58595 +
 1.58596 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.58597 +/*
 1.58598 +** Check that the entry in the pointer-map for page iChild maps to 
 1.58599 +** page iParent, pointer type ptrType. If not, append an error message
 1.58600 +** to pCheck.
 1.58601 +*/
 1.58602 +static void checkPtrmap(
 1.58603 +  IntegrityCk *pCheck,   /* Integrity check context */
 1.58604 +  Pgno iChild,           /* Child page number */
 1.58605 +  u8 eType,              /* Expected pointer map type */
 1.58606 +  Pgno iParent,          /* Expected pointer map parent page number */
 1.58607 +  char *zContext         /* Context description (used for error msg) */
 1.58608 +){
 1.58609 +  int rc;
 1.58610 +  u8 ePtrmapType;
 1.58611 +  Pgno iPtrmapParent;
 1.58612 +
 1.58613 +  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
 1.58614 +  if( rc!=SQLITE_OK ){
 1.58615 +    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
 1.58616 +    checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
 1.58617 +    return;
 1.58618 +  }
 1.58619 +
 1.58620 +  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
 1.58621 +    checkAppendMsg(pCheck, zContext, 
 1.58622 +      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
 1.58623 +      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
 1.58624 +  }
 1.58625 +}
 1.58626 +#endif
 1.58627 +
 1.58628 +/*
 1.58629 +** Check the integrity of the freelist or of an overflow page list.
 1.58630 +** Verify that the number of pages on the list is N.
 1.58631 +*/
 1.58632 +static void checkList(
 1.58633 +  IntegrityCk *pCheck,  /* Integrity checking context */
 1.58634 +  int isFreeList,       /* True for a freelist.  False for overflow page list */
 1.58635 +  int iPage,            /* Page number for first page in the list */
 1.58636 +  int N,                /* Expected number of pages in the list */
 1.58637 +  char *zContext        /* Context for error messages */
 1.58638 +){
 1.58639 +  int i;
 1.58640 +  int expected = N;
 1.58641 +  int iFirst = iPage;
 1.58642 +  while( N-- > 0 && pCheck->mxErr ){
 1.58643 +    DbPage *pOvflPage;
 1.58644 +    unsigned char *pOvflData;
 1.58645 +    if( iPage<1 ){
 1.58646 +      checkAppendMsg(pCheck, zContext,
 1.58647 +         "%d of %d pages missing from overflow list starting at %d",
 1.58648 +          N+1, expected, iFirst);
 1.58649 +      break;
 1.58650 +    }
 1.58651 +    if( checkRef(pCheck, iPage, zContext) ) break;
 1.58652 +    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
 1.58653 +      checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
 1.58654 +      break;
 1.58655 +    }
 1.58656 +    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
 1.58657 +    if( isFreeList ){
 1.58658 +      int n = get4byte(&pOvflData[4]);
 1.58659 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.58660 +      if( pCheck->pBt->autoVacuum ){
 1.58661 +        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
 1.58662 +      }
 1.58663 +#endif
 1.58664 +      if( n>(int)pCheck->pBt->usableSize/4-2 ){
 1.58665 +        checkAppendMsg(pCheck, zContext,
 1.58666 +           "freelist leaf count too big on page %d", iPage);
 1.58667 +        N--;
 1.58668 +      }else{
 1.58669 +        for(i=0; i<n; i++){
 1.58670 +          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
 1.58671 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.58672 +          if( pCheck->pBt->autoVacuum ){
 1.58673 +            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
 1.58674 +          }
 1.58675 +#endif
 1.58676 +          checkRef(pCheck, iFreePage, zContext);
 1.58677 +        }
 1.58678 +        N -= n;
 1.58679 +      }
 1.58680 +    }
 1.58681 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.58682 +    else{
 1.58683 +      /* If this database supports auto-vacuum and iPage is not the last
 1.58684 +      ** page in this overflow list, check that the pointer-map entry for
 1.58685 +      ** the following page matches iPage.
 1.58686 +      */
 1.58687 +      if( pCheck->pBt->autoVacuum && N>0 ){
 1.58688 +        i = get4byte(pOvflData);
 1.58689 +        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
 1.58690 +      }
 1.58691 +    }
 1.58692 +#endif
 1.58693 +    iPage = get4byte(pOvflData);
 1.58694 +    sqlite3PagerUnref(pOvflPage);
 1.58695 +  }
 1.58696 +}
 1.58697 +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
 1.58698 +
 1.58699 +#ifndef SQLITE_OMIT_INTEGRITY_CHECK
 1.58700 +/*
 1.58701 +** Do various sanity checks on a single page of a tree.  Return
 1.58702 +** the tree depth.  Root pages return 0.  Parents of root pages
 1.58703 +** return 1, and so forth.
 1.58704 +** 
 1.58705 +** These checks are done:
 1.58706 +**
 1.58707 +**      1.  Make sure that cells and freeblocks do not overlap
 1.58708 +**          but combine to completely cover the page.
 1.58709 +**  NO  2.  Make sure cell keys are in order.
 1.58710 +**  NO  3.  Make sure no key is less than or equal to zLowerBound.
 1.58711 +**  NO  4.  Make sure no key is greater than or equal to zUpperBound.
 1.58712 +**      5.  Check the integrity of overflow pages.
 1.58713 +**      6.  Recursively call checkTreePage on all children.
 1.58714 +**      7.  Verify that the depth of all children is the same.
 1.58715 +**      8.  Make sure this page is at least 33% full or else it is
 1.58716 +**          the root of the tree.
 1.58717 +*/
 1.58718 +static int checkTreePage(
 1.58719 +  IntegrityCk *pCheck,  /* Context for the sanity check */
 1.58720 +  int iPage,            /* Page number of the page to check */
 1.58721 +  char *zParentContext, /* Parent context */
 1.58722 +  i64 *pnParentMinKey, 
 1.58723 +  i64 *pnParentMaxKey
 1.58724 +){
 1.58725 +  MemPage *pPage;
 1.58726 +  int i, rc, depth, d2, pgno, cnt;
 1.58727 +  int hdr, cellStart;
 1.58728 +  int nCell;
 1.58729 +  u8 *data;
 1.58730 +  BtShared *pBt;
 1.58731 +  int usableSize;
 1.58732 +  char zContext[100];
 1.58733 +  char *hit = 0;
 1.58734 +  i64 nMinKey = 0;
 1.58735 +  i64 nMaxKey = 0;
 1.58736 +
 1.58737 +  sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
 1.58738 +
 1.58739 +  /* Check that the page exists
 1.58740 +  */
 1.58741 +  pBt = pCheck->pBt;
 1.58742 +  usableSize = pBt->usableSize;
 1.58743 +  if( iPage==0 ) return 0;
 1.58744 +  if( checkRef(pCheck, iPage, zParentContext) ) return 0;
 1.58745 +  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
 1.58746 +    checkAppendMsg(pCheck, zContext,
 1.58747 +       "unable to get the page. error code=%d", rc);
 1.58748 +    return 0;
 1.58749 +  }
 1.58750 +
 1.58751 +  /* Clear MemPage.isInit to make sure the corruption detection code in
 1.58752 +  ** btreeInitPage() is executed.  */
 1.58753 +  pPage->isInit = 0;
 1.58754 +  if( (rc = btreeInitPage(pPage))!=0 ){
 1.58755 +    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
 1.58756 +    checkAppendMsg(pCheck, zContext, 
 1.58757 +                   "btreeInitPage() returns error code %d", rc);
 1.58758 +    releasePage(pPage);
 1.58759 +    return 0;
 1.58760 +  }
 1.58761 +
 1.58762 +  /* Check out all the cells.
 1.58763 +  */
 1.58764 +  depth = 0;
 1.58765 +  for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
 1.58766 +    u8 *pCell;
 1.58767 +    u32 sz;
 1.58768 +    CellInfo info;
 1.58769 +
 1.58770 +    /* Check payload overflow pages
 1.58771 +    */
 1.58772 +    sqlite3_snprintf(sizeof(zContext), zContext,
 1.58773 +             "On tree page %d cell %d: ", iPage, i);
 1.58774 +    pCell = findCell(pPage,i);
 1.58775 +    btreeParseCellPtr(pPage, pCell, &info);
 1.58776 +    sz = info.nData;
 1.58777 +    if( !pPage->intKey ) sz += (int)info.nKey;
 1.58778 +    /* For intKey pages, check that the keys are in order.
 1.58779 +    */
 1.58780 +    else if( i==0 ) nMinKey = nMaxKey = info.nKey;
 1.58781 +    else{
 1.58782 +      if( info.nKey <= nMaxKey ){
 1.58783 +        checkAppendMsg(pCheck, zContext, 
 1.58784 +            "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
 1.58785 +      }
 1.58786 +      nMaxKey = info.nKey;
 1.58787 +    }
 1.58788 +    assert( sz==info.nPayload );
 1.58789 +    if( (sz>info.nLocal) 
 1.58790 +     && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
 1.58791 +    ){
 1.58792 +      int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
 1.58793 +      Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
 1.58794 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.58795 +      if( pBt->autoVacuum ){
 1.58796 +        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
 1.58797 +      }
 1.58798 +#endif
 1.58799 +      checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
 1.58800 +    }
 1.58801 +
 1.58802 +    /* Check sanity of left child page.
 1.58803 +    */
 1.58804 +    if( !pPage->leaf ){
 1.58805 +      pgno = get4byte(pCell);
 1.58806 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.58807 +      if( pBt->autoVacuum ){
 1.58808 +        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
 1.58809 +      }
 1.58810 +#endif
 1.58811 +      d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
 1.58812 +      if( i>0 && d2!=depth ){
 1.58813 +        checkAppendMsg(pCheck, zContext, "Child page depth differs");
 1.58814 +      }
 1.58815 +      depth = d2;
 1.58816 +    }
 1.58817 +  }
 1.58818 +
 1.58819 +  if( !pPage->leaf ){
 1.58820 +    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
 1.58821 +    sqlite3_snprintf(sizeof(zContext), zContext, 
 1.58822 +                     "On page %d at right child: ", iPage);
 1.58823 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.58824 +    if( pBt->autoVacuum ){
 1.58825 +      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
 1.58826 +    }
 1.58827 +#endif
 1.58828 +    checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
 1.58829 +  }
 1.58830 + 
 1.58831 +  /* For intKey leaf pages, check that the min/max keys are in order
 1.58832 +  ** with any left/parent/right pages.
 1.58833 +  */
 1.58834 +  if( pPage->leaf && pPage->intKey ){
 1.58835 +    /* if we are a left child page */
 1.58836 +    if( pnParentMinKey ){
 1.58837 +      /* if we are the left most child page */
 1.58838 +      if( !pnParentMaxKey ){
 1.58839 +        if( nMaxKey > *pnParentMinKey ){
 1.58840 +          checkAppendMsg(pCheck, zContext, 
 1.58841 +              "Rowid %lld out of order (max larger than parent min of %lld)",
 1.58842 +              nMaxKey, *pnParentMinKey);
 1.58843 +        }
 1.58844 +      }else{
 1.58845 +        if( nMinKey <= *pnParentMinKey ){
 1.58846 +          checkAppendMsg(pCheck, zContext, 
 1.58847 +              "Rowid %lld out of order (min less than parent min of %lld)",
 1.58848 +              nMinKey, *pnParentMinKey);
 1.58849 +        }
 1.58850 +        if( nMaxKey > *pnParentMaxKey ){
 1.58851 +          checkAppendMsg(pCheck, zContext, 
 1.58852 +              "Rowid %lld out of order (max larger than parent max of %lld)",
 1.58853 +              nMaxKey, *pnParentMaxKey);
 1.58854 +        }
 1.58855 +        *pnParentMinKey = nMaxKey;
 1.58856 +      }
 1.58857 +    /* else if we're a right child page */
 1.58858 +    } else if( pnParentMaxKey ){
 1.58859 +      if( nMinKey <= *pnParentMaxKey ){
 1.58860 +        checkAppendMsg(pCheck, zContext, 
 1.58861 +            "Rowid %lld out of order (min less than parent max of %lld)",
 1.58862 +            nMinKey, *pnParentMaxKey);
 1.58863 +      }
 1.58864 +    }
 1.58865 +  }
 1.58866 +
 1.58867 +  /* Check for complete coverage of the page
 1.58868 +  */
 1.58869 +  data = pPage->aData;
 1.58870 +  hdr = pPage->hdrOffset;
 1.58871 +  hit = sqlite3PageMalloc( pBt->pageSize );
 1.58872 +  if( hit==0 ){
 1.58873 +    pCheck->mallocFailed = 1;
 1.58874 +  }else{
 1.58875 +    int contentOffset = get2byteNotZero(&data[hdr+5]);
 1.58876 +    assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
 1.58877 +    memset(hit+contentOffset, 0, usableSize-contentOffset);
 1.58878 +    memset(hit, 1, contentOffset);
 1.58879 +    nCell = get2byte(&data[hdr+3]);
 1.58880 +    cellStart = hdr + 12 - 4*pPage->leaf;
 1.58881 +    for(i=0; i<nCell; i++){
 1.58882 +      int pc = get2byte(&data[cellStart+i*2]);
 1.58883 +      u32 size = 65536;
 1.58884 +      int j;
 1.58885 +      if( pc<=usableSize-4 ){
 1.58886 +        size = cellSizePtr(pPage, &data[pc]);
 1.58887 +      }
 1.58888 +      if( (int)(pc+size-1)>=usableSize ){
 1.58889 +        checkAppendMsg(pCheck, 0, 
 1.58890 +            "Corruption detected in cell %d on page %d",i,iPage);
 1.58891 +      }else{
 1.58892 +        for(j=pc+size-1; j>=pc; j--) hit[j]++;
 1.58893 +      }
 1.58894 +    }
 1.58895 +    i = get2byte(&data[hdr+1]);
 1.58896 +    while( i>0 ){
 1.58897 +      int size, j;
 1.58898 +      assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
 1.58899 +      size = get2byte(&data[i+2]);
 1.58900 +      assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
 1.58901 +      for(j=i+size-1; j>=i; j--) hit[j]++;
 1.58902 +      j = get2byte(&data[i]);
 1.58903 +      assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
 1.58904 +      assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
 1.58905 +      i = j;
 1.58906 +    }
 1.58907 +    for(i=cnt=0; i<usableSize; i++){
 1.58908 +      if( hit[i]==0 ){
 1.58909 +        cnt++;
 1.58910 +      }else if( hit[i]>1 ){
 1.58911 +        checkAppendMsg(pCheck, 0,
 1.58912 +          "Multiple uses for byte %d of page %d", i, iPage);
 1.58913 +        break;
 1.58914 +      }
 1.58915 +    }
 1.58916 +    if( cnt!=data[hdr+7] ){
 1.58917 +      checkAppendMsg(pCheck, 0, 
 1.58918 +          "Fragmentation of %d bytes reported as %d on page %d",
 1.58919 +          cnt, data[hdr+7], iPage);
 1.58920 +    }
 1.58921 +  }
 1.58922 +  sqlite3PageFree(hit);
 1.58923 +  releasePage(pPage);
 1.58924 +  return depth+1;
 1.58925 +}
 1.58926 +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
 1.58927 +
 1.58928 +#ifndef SQLITE_OMIT_INTEGRITY_CHECK
 1.58929 +/*
 1.58930 +** This routine does a complete check of the given BTree file.  aRoot[] is
 1.58931 +** an array of pages numbers were each page number is the root page of
 1.58932 +** a table.  nRoot is the number of entries in aRoot.
 1.58933 +**
 1.58934 +** A read-only or read-write transaction must be opened before calling
 1.58935 +** this function.
 1.58936 +**
 1.58937 +** Write the number of error seen in *pnErr.  Except for some memory
 1.58938 +** allocation errors,  an error message held in memory obtained from
 1.58939 +** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
 1.58940 +** returned.  If a memory allocation error occurs, NULL is returned.
 1.58941 +*/
 1.58942 +SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
 1.58943 +  Btree *p,     /* The btree to be checked */
 1.58944 +  int *aRoot,   /* An array of root pages numbers for individual trees */
 1.58945 +  int nRoot,    /* Number of entries in aRoot[] */
 1.58946 +  int mxErr,    /* Stop reporting errors after this many */
 1.58947 +  int *pnErr    /* Write number of errors seen to this variable */
 1.58948 +){
 1.58949 +  Pgno i;
 1.58950 +  int nRef;
 1.58951 +  IntegrityCk sCheck;
 1.58952 +  BtShared *pBt = p->pBt;
 1.58953 +  char zErr[100];
 1.58954 +
 1.58955 +  sqlite3BtreeEnter(p);
 1.58956 +  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
 1.58957 +  nRef = sqlite3PagerRefcount(pBt->pPager);
 1.58958 +  sCheck.pBt = pBt;
 1.58959 +  sCheck.pPager = pBt->pPager;
 1.58960 +  sCheck.nPage = btreePagecount(sCheck.pBt);
 1.58961 +  sCheck.mxErr = mxErr;
 1.58962 +  sCheck.nErr = 0;
 1.58963 +  sCheck.mallocFailed = 0;
 1.58964 +  *pnErr = 0;
 1.58965 +  if( sCheck.nPage==0 ){
 1.58966 +    sqlite3BtreeLeave(p);
 1.58967 +    return 0;
 1.58968 +  }
 1.58969 +
 1.58970 +  sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
 1.58971 +  if( !sCheck.aPgRef ){
 1.58972 +    *pnErr = 1;
 1.58973 +    sqlite3BtreeLeave(p);
 1.58974 +    return 0;
 1.58975 +  }
 1.58976 +  i = PENDING_BYTE_PAGE(pBt);
 1.58977 +  if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
 1.58978 +  sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
 1.58979 +  sCheck.errMsg.useMalloc = 2;
 1.58980 +
 1.58981 +  /* Check the integrity of the freelist
 1.58982 +  */
 1.58983 +  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
 1.58984 +            get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
 1.58985 +
 1.58986 +  /* Check all the tables.
 1.58987 +  */
 1.58988 +  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
 1.58989 +    if( aRoot[i]==0 ) continue;
 1.58990 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.58991 +    if( pBt->autoVacuum && aRoot[i]>1 ){
 1.58992 +      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
 1.58993 +    }
 1.58994 +#endif
 1.58995 +    checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
 1.58996 +  }
 1.58997 +
 1.58998 +  /* Make sure every page in the file is referenced
 1.58999 +  */
 1.59000 +  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
 1.59001 +#ifdef SQLITE_OMIT_AUTOVACUUM
 1.59002 +    if( getPageReferenced(&sCheck, i)==0 ){
 1.59003 +      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
 1.59004 +    }
 1.59005 +#else
 1.59006 +    /* If the database supports auto-vacuum, make sure no tables contain
 1.59007 +    ** references to pointer-map pages.
 1.59008 +    */
 1.59009 +    if( getPageReferenced(&sCheck, i)==0 && 
 1.59010 +       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
 1.59011 +      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
 1.59012 +    }
 1.59013 +    if( getPageReferenced(&sCheck, i)!=0 && 
 1.59014 +       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
 1.59015 +      checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
 1.59016 +    }
 1.59017 +#endif
 1.59018 +  }
 1.59019 +
 1.59020 +  /* Make sure this analysis did not leave any unref() pages.
 1.59021 +  ** This is an internal consistency check; an integrity check
 1.59022 +  ** of the integrity check.
 1.59023 +  */
 1.59024 +  if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
 1.59025 +    checkAppendMsg(&sCheck, 0, 
 1.59026 +      "Outstanding page count goes from %d to %d during this analysis",
 1.59027 +      nRef, sqlite3PagerRefcount(pBt->pPager)
 1.59028 +    );
 1.59029 +  }
 1.59030 +
 1.59031 +  /* Clean  up and report errors.
 1.59032 +  */
 1.59033 +  sqlite3BtreeLeave(p);
 1.59034 +  sqlite3_free(sCheck.aPgRef);
 1.59035 +  if( sCheck.mallocFailed ){
 1.59036 +    sqlite3StrAccumReset(&sCheck.errMsg);
 1.59037 +    *pnErr = sCheck.nErr+1;
 1.59038 +    return 0;
 1.59039 +  }
 1.59040 +  *pnErr = sCheck.nErr;
 1.59041 +  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
 1.59042 +  return sqlite3StrAccumFinish(&sCheck.errMsg);
 1.59043 +}
 1.59044 +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
 1.59045 +
 1.59046 +/*
 1.59047 +** Return the full pathname of the underlying database file.  Return
 1.59048 +** an empty string if the database is in-memory or a TEMP database.
 1.59049 +**
 1.59050 +** The pager filename is invariant as long as the pager is
 1.59051 +** open so it is safe to access without the BtShared mutex.
 1.59052 +*/
 1.59053 +SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
 1.59054 +  assert( p->pBt->pPager!=0 );
 1.59055 +  return sqlite3PagerFilename(p->pBt->pPager, 1);
 1.59056 +}
 1.59057 +
 1.59058 +/*
 1.59059 +** Return the pathname of the journal file for this database. The return
 1.59060 +** value of this routine is the same regardless of whether the journal file
 1.59061 +** has been created or not.
 1.59062 +**
 1.59063 +** The pager journal filename is invariant as long as the pager is
 1.59064 +** open so it is safe to access without the BtShared mutex.
 1.59065 +*/
 1.59066 +SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
 1.59067 +  assert( p->pBt->pPager!=0 );
 1.59068 +  return sqlite3PagerJournalname(p->pBt->pPager);
 1.59069 +}
 1.59070 +
 1.59071 +/*
 1.59072 +** Return non-zero if a transaction is active.
 1.59073 +*/
 1.59074 +SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
 1.59075 +  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
 1.59076 +  return (p && (p->inTrans==TRANS_WRITE));
 1.59077 +}
 1.59078 +
 1.59079 +#ifndef SQLITE_OMIT_WAL
 1.59080 +/*
 1.59081 +** Run a checkpoint on the Btree passed as the first argument.
 1.59082 +**
 1.59083 +** Return SQLITE_LOCKED if this or any other connection has an open 
 1.59084 +** transaction on the shared-cache the argument Btree is connected to.
 1.59085 +**
 1.59086 +** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
 1.59087 +*/
 1.59088 +SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
 1.59089 +  int rc = SQLITE_OK;
 1.59090 +  if( p ){
 1.59091 +    BtShared *pBt = p->pBt;
 1.59092 +    sqlite3BtreeEnter(p);
 1.59093 +    if( pBt->inTransaction!=TRANS_NONE ){
 1.59094 +      rc = SQLITE_LOCKED;
 1.59095 +    }else{
 1.59096 +      rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
 1.59097 +    }
 1.59098 +    sqlite3BtreeLeave(p);
 1.59099 +  }
 1.59100 +  return rc;
 1.59101 +}
 1.59102 +#endif
 1.59103 +
 1.59104 +/*
 1.59105 +** Return non-zero if a read (or write) transaction is active.
 1.59106 +*/
 1.59107 +SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
 1.59108 +  assert( p );
 1.59109 +  assert( sqlite3_mutex_held(p->db->mutex) );
 1.59110 +  return p->inTrans!=TRANS_NONE;
 1.59111 +}
 1.59112 +
 1.59113 +SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
 1.59114 +  assert( p );
 1.59115 +  assert( sqlite3_mutex_held(p->db->mutex) );
 1.59116 +  return p->nBackup!=0;
 1.59117 +}
 1.59118 +
 1.59119 +/*
 1.59120 +** This function returns a pointer to a blob of memory associated with
 1.59121 +** a single shared-btree. The memory is used by client code for its own
 1.59122 +** purposes (for example, to store a high-level schema associated with 
 1.59123 +** the shared-btree). The btree layer manages reference counting issues.
 1.59124 +**
 1.59125 +** The first time this is called on a shared-btree, nBytes bytes of memory
 1.59126 +** are allocated, zeroed, and returned to the caller. For each subsequent 
 1.59127 +** call the nBytes parameter is ignored and a pointer to the same blob
 1.59128 +** of memory returned. 
 1.59129 +**
 1.59130 +** If the nBytes parameter is 0 and the blob of memory has not yet been
 1.59131 +** allocated, a null pointer is returned. If the blob has already been
 1.59132 +** allocated, it is returned as normal.
 1.59133 +**
 1.59134 +** Just before the shared-btree is closed, the function passed as the 
 1.59135 +** xFree argument when the memory allocation was made is invoked on the 
 1.59136 +** blob of allocated memory. The xFree function should not call sqlite3_free()
 1.59137 +** on the memory, the btree layer does that.
 1.59138 +*/
 1.59139 +SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
 1.59140 +  BtShared *pBt = p->pBt;
 1.59141 +  sqlite3BtreeEnter(p);
 1.59142 +  if( !pBt->pSchema && nBytes ){
 1.59143 +    pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
 1.59144 +    pBt->xFreeSchema = xFree;
 1.59145 +  }
 1.59146 +  sqlite3BtreeLeave(p);
 1.59147 +  return pBt->pSchema;
 1.59148 +}
 1.59149 +
 1.59150 +/*
 1.59151 +** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
 1.59152 +** btree as the argument handle holds an exclusive lock on the 
 1.59153 +** sqlite_master table. Otherwise SQLITE_OK.
 1.59154 +*/
 1.59155 +SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
 1.59156 +  int rc;
 1.59157 +  assert( sqlite3_mutex_held(p->db->mutex) );
 1.59158 +  sqlite3BtreeEnter(p);
 1.59159 +  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
 1.59160 +  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
 1.59161 +  sqlite3BtreeLeave(p);
 1.59162 +  return rc;
 1.59163 +}
 1.59164 +
 1.59165 +
 1.59166 +#ifndef SQLITE_OMIT_SHARED_CACHE
 1.59167 +/*
 1.59168 +** Obtain a lock on the table whose root page is iTab.  The
 1.59169 +** lock is a write lock if isWritelock is true or a read lock
 1.59170 +** if it is false.
 1.59171 +*/
 1.59172 +SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
 1.59173 +  int rc = SQLITE_OK;
 1.59174 +  assert( p->inTrans!=TRANS_NONE );
 1.59175 +  if( p->sharable ){
 1.59176 +    u8 lockType = READ_LOCK + isWriteLock;
 1.59177 +    assert( READ_LOCK+1==WRITE_LOCK );
 1.59178 +    assert( isWriteLock==0 || isWriteLock==1 );
 1.59179 +
 1.59180 +    sqlite3BtreeEnter(p);
 1.59181 +    rc = querySharedCacheTableLock(p, iTab, lockType);
 1.59182 +    if( rc==SQLITE_OK ){
 1.59183 +      rc = setSharedCacheTableLock(p, iTab, lockType);
 1.59184 +    }
 1.59185 +    sqlite3BtreeLeave(p);
 1.59186 +  }
 1.59187 +  return rc;
 1.59188 +}
 1.59189 +#endif
 1.59190 +
 1.59191 +#ifndef SQLITE_OMIT_INCRBLOB
 1.59192 +/*
 1.59193 +** Argument pCsr must be a cursor opened for writing on an 
 1.59194 +** INTKEY table currently pointing at a valid table entry. 
 1.59195 +** This function modifies the data stored as part of that entry.
 1.59196 +**
 1.59197 +** Only the data content may only be modified, it is not possible to 
 1.59198 +** change the length of the data stored. If this function is called with
 1.59199 +** parameters that attempt to write past the end of the existing data,
 1.59200 +** no modifications are made and SQLITE_CORRUPT is returned.
 1.59201 +*/
 1.59202 +SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
 1.59203 +  int rc;
 1.59204 +  assert( cursorHoldsMutex(pCsr) );
 1.59205 +  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
 1.59206 +  assert( pCsr->isIncrblobHandle );
 1.59207 +
 1.59208 +  rc = restoreCursorPosition(pCsr);
 1.59209 +  if( rc!=SQLITE_OK ){
 1.59210 +    return rc;
 1.59211 +  }
 1.59212 +  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
 1.59213 +  if( pCsr->eState!=CURSOR_VALID ){
 1.59214 +    return SQLITE_ABORT;
 1.59215 +  }
 1.59216 +
 1.59217 +  /* Save the positions of all other cursors open on this table. This is
 1.59218 +  ** required in case any of them are holding references to an xFetch
 1.59219 +  ** version of the b-tree page modified by the accessPayload call below.
 1.59220 +  **
 1.59221 +  ** Note that pCsr must be open on a BTREE_INTKEY table and saveCursorPosition()
 1.59222 +  ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
 1.59223 +  ** saveAllCursors can only return SQLITE_OK.
 1.59224 +  */
 1.59225 +  VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
 1.59226 +  assert( rc==SQLITE_OK );
 1.59227 +
 1.59228 +  /* Check some assumptions: 
 1.59229 +  **   (a) the cursor is open for writing,
 1.59230 +  **   (b) there is a read/write transaction open,
 1.59231 +  **   (c) the connection holds a write-lock on the table (if required),
 1.59232 +  **   (d) there are no conflicting read-locks, and
 1.59233 +  **   (e) the cursor points at a valid row of an intKey table.
 1.59234 +  */
 1.59235 +  if( !pCsr->wrFlag ){
 1.59236 +    return SQLITE_READONLY;
 1.59237 +  }
 1.59238 +  assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
 1.59239 +              && pCsr->pBt->inTransaction==TRANS_WRITE );
 1.59240 +  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
 1.59241 +  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
 1.59242 +  assert( pCsr->apPage[pCsr->iPage]->intKey );
 1.59243 +
 1.59244 +  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
 1.59245 +}
 1.59246 +
 1.59247 +/* 
 1.59248 +** Set a flag on this cursor to cache the locations of pages from the 
 1.59249 +** overflow list for the current row. This is used by cursors opened
 1.59250 +** for incremental blob IO only.
 1.59251 +**
 1.59252 +** This function sets a flag only. The actual page location cache
 1.59253 +** (stored in BtCursor.aOverflow[]) is allocated and used by function
 1.59254 +** accessPayload() (the worker function for sqlite3BtreeData() and
 1.59255 +** sqlite3BtreePutData()).
 1.59256 +*/
 1.59257 +SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
 1.59258 +  assert( cursorHoldsMutex(pCur) );
 1.59259 +  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
 1.59260 +  invalidateOverflowCache(pCur);
 1.59261 +  pCur->isIncrblobHandle = 1;
 1.59262 +}
 1.59263 +#endif
 1.59264 +
 1.59265 +/*
 1.59266 +** Set both the "read version" (single byte at byte offset 18) and 
 1.59267 +** "write version" (single byte at byte offset 19) fields in the database
 1.59268 +** header to iVersion.
 1.59269 +*/
 1.59270 +SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
 1.59271 +  BtShared *pBt = pBtree->pBt;
 1.59272 +  int rc;                         /* Return code */
 1.59273 + 
 1.59274 +  assert( iVersion==1 || iVersion==2 );
 1.59275 +
 1.59276 +  /* If setting the version fields to 1, do not automatically open the
 1.59277 +  ** WAL connection, even if the version fields are currently set to 2.
 1.59278 +  */
 1.59279 +  pBt->btsFlags &= ~BTS_NO_WAL;
 1.59280 +  if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
 1.59281 +
 1.59282 +  rc = sqlite3BtreeBeginTrans(pBtree, 0);
 1.59283 +  if( rc==SQLITE_OK ){
 1.59284 +    u8 *aData = pBt->pPage1->aData;
 1.59285 +    if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
 1.59286 +      rc = sqlite3BtreeBeginTrans(pBtree, 2);
 1.59287 +      if( rc==SQLITE_OK ){
 1.59288 +        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
 1.59289 +        if( rc==SQLITE_OK ){
 1.59290 +          aData[18] = (u8)iVersion;
 1.59291 +          aData[19] = (u8)iVersion;
 1.59292 +        }
 1.59293 +      }
 1.59294 +    }
 1.59295 +  }
 1.59296 +
 1.59297 +  pBt->btsFlags &= ~BTS_NO_WAL;
 1.59298 +  return rc;
 1.59299 +}
 1.59300 +
 1.59301 +/*
 1.59302 +** set the mask of hint flags for cursor pCsr. Currently the only valid
 1.59303 +** values are 0 and BTREE_BULKLOAD.
 1.59304 +*/
 1.59305 +SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
 1.59306 +  assert( mask==BTREE_BULKLOAD || mask==0 );
 1.59307 +  pCsr->hints = mask;
 1.59308 +}
 1.59309 +
 1.59310 +/************** End of btree.c ***********************************************/
 1.59311 +/************** Begin file backup.c ******************************************/
 1.59312 +/*
 1.59313 +** 2009 January 28
 1.59314 +**
 1.59315 +** The author disclaims copyright to this source code.  In place of
 1.59316 +** a legal notice, here is a blessing:
 1.59317 +**
 1.59318 +**    May you do good and not evil.
 1.59319 +**    May you find forgiveness for yourself and forgive others.
 1.59320 +**    May you share freely, never taking more than you give.
 1.59321 +**
 1.59322 +*************************************************************************
 1.59323 +** This file contains the implementation of the sqlite3_backup_XXX() 
 1.59324 +** API functions and the related features.
 1.59325 +*/
 1.59326 +
 1.59327 +/*
 1.59328 +** Structure allocated for each backup operation.
 1.59329 +*/
 1.59330 +struct sqlite3_backup {
 1.59331 +  sqlite3* pDestDb;        /* Destination database handle */
 1.59332 +  Btree *pDest;            /* Destination b-tree file */
 1.59333 +  u32 iDestSchema;         /* Original schema cookie in destination */
 1.59334 +  int bDestLocked;         /* True once a write-transaction is open on pDest */
 1.59335 +
 1.59336 +  Pgno iNext;              /* Page number of the next source page to copy */
 1.59337 +  sqlite3* pSrcDb;         /* Source database handle */
 1.59338 +  Btree *pSrc;             /* Source b-tree file */
 1.59339 +
 1.59340 +  int rc;                  /* Backup process error code */
 1.59341 +
 1.59342 +  /* These two variables are set by every call to backup_step(). They are
 1.59343 +  ** read by calls to backup_remaining() and backup_pagecount().
 1.59344 +  */
 1.59345 +  Pgno nRemaining;         /* Number of pages left to copy */
 1.59346 +  Pgno nPagecount;         /* Total number of pages to copy */
 1.59347 +
 1.59348 +  int isAttached;          /* True once backup has been registered with pager */
 1.59349 +  sqlite3_backup *pNext;   /* Next backup associated with source pager */
 1.59350 +};
 1.59351 +
 1.59352 +/*
 1.59353 +** THREAD SAFETY NOTES:
 1.59354 +**
 1.59355 +**   Once it has been created using backup_init(), a single sqlite3_backup
 1.59356 +**   structure may be accessed via two groups of thread-safe entry points:
 1.59357 +**
 1.59358 +**     * Via the sqlite3_backup_XXX() API function backup_step() and 
 1.59359 +**       backup_finish(). Both these functions obtain the source database
 1.59360 +**       handle mutex and the mutex associated with the source BtShared 
 1.59361 +**       structure, in that order.
 1.59362 +**
 1.59363 +**     * Via the BackupUpdate() and BackupRestart() functions, which are
 1.59364 +**       invoked by the pager layer to report various state changes in
 1.59365 +**       the page cache associated with the source database. The mutex
 1.59366 +**       associated with the source database BtShared structure will always 
 1.59367 +**       be held when either of these functions are invoked.
 1.59368 +**
 1.59369 +**   The other sqlite3_backup_XXX() API functions, backup_remaining() and
 1.59370 +**   backup_pagecount() are not thread-safe functions. If they are called
 1.59371 +**   while some other thread is calling backup_step() or backup_finish(),
 1.59372 +**   the values returned may be invalid. There is no way for a call to
 1.59373 +**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
 1.59374 +**   or backup_pagecount().
 1.59375 +**
 1.59376 +**   Depending on the SQLite configuration, the database handles and/or
 1.59377 +**   the Btree objects may have their own mutexes that require locking.
 1.59378 +**   Non-sharable Btrees (in-memory databases for example), do not have
 1.59379 +**   associated mutexes.
 1.59380 +*/
 1.59381 +
 1.59382 +/*
 1.59383 +** Return a pointer corresponding to database zDb (i.e. "main", "temp")
 1.59384 +** in connection handle pDb. If such a database cannot be found, return
 1.59385 +** a NULL pointer and write an error message to pErrorDb.
 1.59386 +**
 1.59387 +** If the "temp" database is requested, it may need to be opened by this 
 1.59388 +** function. If an error occurs while doing so, return 0 and write an 
 1.59389 +** error message to pErrorDb.
 1.59390 +*/
 1.59391 +static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
 1.59392 +  int i = sqlite3FindDbName(pDb, zDb);
 1.59393 +
 1.59394 +  if( i==1 ){
 1.59395 +    Parse *pParse;
 1.59396 +    int rc = 0;
 1.59397 +    pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
 1.59398 +    if( pParse==0 ){
 1.59399 +      sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
 1.59400 +      rc = SQLITE_NOMEM;
 1.59401 +    }else{
 1.59402 +      pParse->db = pDb;
 1.59403 +      if( sqlite3OpenTempDatabase(pParse) ){
 1.59404 +        sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
 1.59405 +        rc = SQLITE_ERROR;
 1.59406 +      }
 1.59407 +      sqlite3DbFree(pErrorDb, pParse->zErrMsg);
 1.59408 +      sqlite3ParserReset(pParse);
 1.59409 +      sqlite3StackFree(pErrorDb, pParse);
 1.59410 +    }
 1.59411 +    if( rc ){
 1.59412 +      return 0;
 1.59413 +    }
 1.59414 +  }
 1.59415 +
 1.59416 +  if( i<0 ){
 1.59417 +    sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
 1.59418 +    return 0;
 1.59419 +  }
 1.59420 +
 1.59421 +  return pDb->aDb[i].pBt;
 1.59422 +}
 1.59423 +
 1.59424 +/*
 1.59425 +** Attempt to set the page size of the destination to match the page size
 1.59426 +** of the source.
 1.59427 +*/
 1.59428 +static int setDestPgsz(sqlite3_backup *p){
 1.59429 +  int rc;
 1.59430 +  rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
 1.59431 +  return rc;
 1.59432 +}
 1.59433 +
 1.59434 +/*
 1.59435 +** Create an sqlite3_backup process to copy the contents of zSrcDb from
 1.59436 +** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
 1.59437 +** a pointer to the new sqlite3_backup object.
 1.59438 +**
 1.59439 +** If an error occurs, NULL is returned and an error code and error message
 1.59440 +** stored in database handle pDestDb.
 1.59441 +*/
 1.59442 +SQLITE_API sqlite3_backup *sqlite3_backup_init(
 1.59443 +  sqlite3* pDestDb,                     /* Database to write to */
 1.59444 +  const char *zDestDb,                  /* Name of database within pDestDb */
 1.59445 +  sqlite3* pSrcDb,                      /* Database connection to read from */
 1.59446 +  const char *zSrcDb                    /* Name of database within pSrcDb */
 1.59447 +){
 1.59448 +  sqlite3_backup *p;                    /* Value to return */
 1.59449 +
 1.59450 +  /* Lock the source database handle. The destination database
 1.59451 +  ** handle is not locked in this routine, but it is locked in
 1.59452 +  ** sqlite3_backup_step(). The user is required to ensure that no
 1.59453 +  ** other thread accesses the destination handle for the duration
 1.59454 +  ** of the backup operation.  Any attempt to use the destination
 1.59455 +  ** database connection while a backup is in progress may cause
 1.59456 +  ** a malfunction or a deadlock.
 1.59457 +  */
 1.59458 +  sqlite3_mutex_enter(pSrcDb->mutex);
 1.59459 +  sqlite3_mutex_enter(pDestDb->mutex);
 1.59460 +
 1.59461 +  if( pSrcDb==pDestDb ){
 1.59462 +    sqlite3Error(
 1.59463 +        pDestDb, SQLITE_ERROR, "source and destination must be distinct"
 1.59464 +    );
 1.59465 +    p = 0;
 1.59466 +  }else {
 1.59467 +    /* Allocate space for a new sqlite3_backup object...
 1.59468 +    ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
 1.59469 +    ** call to sqlite3_backup_init() and is destroyed by a call to
 1.59470 +    ** sqlite3_backup_finish(). */
 1.59471 +    p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
 1.59472 +    if( !p ){
 1.59473 +      sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
 1.59474 +    }
 1.59475 +  }
 1.59476 +
 1.59477 +  /* If the allocation succeeded, populate the new object. */
 1.59478 +  if( p ){
 1.59479 +    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
 1.59480 +    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
 1.59481 +    p->pDestDb = pDestDb;
 1.59482 +    p->pSrcDb = pSrcDb;
 1.59483 +    p->iNext = 1;
 1.59484 +    p->isAttached = 0;
 1.59485 +
 1.59486 +    if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
 1.59487 +      /* One (or both) of the named databases did not exist or an OOM
 1.59488 +      ** error was hit.  The error has already been written into the
 1.59489 +      ** pDestDb handle.  All that is left to do here is free the
 1.59490 +      ** sqlite3_backup structure.
 1.59491 +      */
 1.59492 +      sqlite3_free(p);
 1.59493 +      p = 0;
 1.59494 +    }
 1.59495 +  }
 1.59496 +  if( p ){
 1.59497 +    p->pSrc->nBackup++;
 1.59498 +  }
 1.59499 +
 1.59500 +  sqlite3_mutex_leave(pDestDb->mutex);
 1.59501 +  sqlite3_mutex_leave(pSrcDb->mutex);
 1.59502 +  return p;
 1.59503 +}
 1.59504 +
 1.59505 +/*
 1.59506 +** Argument rc is an SQLite error code. Return true if this error is 
 1.59507 +** considered fatal if encountered during a backup operation. All errors
 1.59508 +** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
 1.59509 +*/
 1.59510 +static int isFatalError(int rc){
 1.59511 +  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
 1.59512 +}
 1.59513 +
 1.59514 +/*
 1.59515 +** Parameter zSrcData points to a buffer containing the data for 
 1.59516 +** page iSrcPg from the source database. Copy this data into the 
 1.59517 +** destination database.
 1.59518 +*/
 1.59519 +static int backupOnePage(
 1.59520 +  sqlite3_backup *p,              /* Backup handle */
 1.59521 +  Pgno iSrcPg,                    /* Source database page to backup */
 1.59522 +  const u8 *zSrcData,             /* Source database page data */
 1.59523 +  int bUpdate                     /* True for an update, false otherwise */
 1.59524 +){
 1.59525 +  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
 1.59526 +  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
 1.59527 +  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
 1.59528 +  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
 1.59529 +  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
 1.59530 +#ifdef SQLITE_HAS_CODEC
 1.59531 +  /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
 1.59532 +  ** guaranteed that the shared-mutex is held by this thread, handle
 1.59533 +  ** p->pSrc may not actually be the owner.  */
 1.59534 +  int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
 1.59535 +  int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
 1.59536 +#endif
 1.59537 +  int rc = SQLITE_OK;
 1.59538 +  i64 iOff;
 1.59539 +
 1.59540 +  assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
 1.59541 +  assert( p->bDestLocked );
 1.59542 +  assert( !isFatalError(p->rc) );
 1.59543 +  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
 1.59544 +  assert( zSrcData );
 1.59545 +
 1.59546 +  /* Catch the case where the destination is an in-memory database and the
 1.59547 +  ** page sizes of the source and destination differ. 
 1.59548 +  */
 1.59549 +  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
 1.59550 +    rc = SQLITE_READONLY;
 1.59551 +  }
 1.59552 +
 1.59553 +#ifdef SQLITE_HAS_CODEC
 1.59554 +  /* Backup is not possible if the page size of the destination is changing
 1.59555 +  ** and a codec is in use.
 1.59556 +  */
 1.59557 +  if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
 1.59558 +    rc = SQLITE_READONLY;
 1.59559 +  }
 1.59560 +
 1.59561 +  /* Backup is not possible if the number of bytes of reserve space differ
 1.59562 +  ** between source and destination.  If there is a difference, try to
 1.59563 +  ** fix the destination to agree with the source.  If that is not possible,
 1.59564 +  ** then the backup cannot proceed.
 1.59565 +  */
 1.59566 +  if( nSrcReserve!=nDestReserve ){
 1.59567 +    u32 newPgsz = nSrcPgsz;
 1.59568 +    rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
 1.59569 +    if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
 1.59570 +  }
 1.59571 +#endif
 1.59572 +
 1.59573 +  /* This loop runs once for each destination page spanned by the source 
 1.59574 +  ** page. For each iteration, variable iOff is set to the byte offset
 1.59575 +  ** of the destination page.
 1.59576 +  */
 1.59577 +  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
 1.59578 +    DbPage *pDestPg = 0;
 1.59579 +    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
 1.59580 +    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
 1.59581 +    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
 1.59582 +     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
 1.59583 +    ){
 1.59584 +      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
 1.59585 +      u8 *zDestData = sqlite3PagerGetData(pDestPg);
 1.59586 +      u8 *zOut = &zDestData[iOff%nDestPgsz];
 1.59587 +
 1.59588 +      /* Copy the data from the source page into the destination page.
 1.59589 +      ** Then clear the Btree layer MemPage.isInit flag. Both this module
 1.59590 +      ** and the pager code use this trick (clearing the first byte
 1.59591 +      ** of the page 'extra' space to invalidate the Btree layers
 1.59592 +      ** cached parse of the page). MemPage.isInit is marked 
 1.59593 +      ** "MUST BE FIRST" for this purpose.
 1.59594 +      */
 1.59595 +      memcpy(zOut, zIn, nCopy);
 1.59596 +      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
 1.59597 +      if( iOff==0 && bUpdate==0 ){
 1.59598 +        sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
 1.59599 +      }
 1.59600 +    }
 1.59601 +    sqlite3PagerUnref(pDestPg);
 1.59602 +  }
 1.59603 +
 1.59604 +  return rc;
 1.59605 +}
 1.59606 +
 1.59607 +/*
 1.59608 +** If pFile is currently larger than iSize bytes, then truncate it to
 1.59609 +** exactly iSize bytes. If pFile is not larger than iSize bytes, then
 1.59610 +** this function is a no-op.
 1.59611 +**
 1.59612 +** Return SQLITE_OK if everything is successful, or an SQLite error 
 1.59613 +** code if an error occurs.
 1.59614 +*/
 1.59615 +static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
 1.59616 +  i64 iCurrent;
 1.59617 +  int rc = sqlite3OsFileSize(pFile, &iCurrent);
 1.59618 +  if( rc==SQLITE_OK && iCurrent>iSize ){
 1.59619 +    rc = sqlite3OsTruncate(pFile, iSize);
 1.59620 +  }
 1.59621 +  return rc;
 1.59622 +}
 1.59623 +
 1.59624 +/*
 1.59625 +** Register this backup object with the associated source pager for
 1.59626 +** callbacks when pages are changed or the cache invalidated.
 1.59627 +*/
 1.59628 +static void attachBackupObject(sqlite3_backup *p){
 1.59629 +  sqlite3_backup **pp;
 1.59630 +  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
 1.59631 +  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
 1.59632 +  p->pNext = *pp;
 1.59633 +  *pp = p;
 1.59634 +  p->isAttached = 1;
 1.59635 +}
 1.59636 +
 1.59637 +/*
 1.59638 +** Copy nPage pages from the source b-tree to the destination.
 1.59639 +*/
 1.59640 +SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
 1.59641 +  int rc;
 1.59642 +  int destMode;       /* Destination journal mode */
 1.59643 +  int pgszSrc = 0;    /* Source page size */
 1.59644 +  int pgszDest = 0;   /* Destination page size */
 1.59645 +
 1.59646 +  sqlite3_mutex_enter(p->pSrcDb->mutex);
 1.59647 +  sqlite3BtreeEnter(p->pSrc);
 1.59648 +  if( p->pDestDb ){
 1.59649 +    sqlite3_mutex_enter(p->pDestDb->mutex);
 1.59650 +  }
 1.59651 +
 1.59652 +  rc = p->rc;
 1.59653 +  if( !isFatalError(rc) ){
 1.59654 +    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
 1.59655 +    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
 1.59656 +    int ii;                            /* Iterator variable */
 1.59657 +    int nSrcPage = -1;                 /* Size of source db in pages */
 1.59658 +    int bCloseTrans = 0;               /* True if src db requires unlocking */
 1.59659 +
 1.59660 +    /* If the source pager is currently in a write-transaction, return
 1.59661 +    ** SQLITE_BUSY immediately.
 1.59662 +    */
 1.59663 +    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
 1.59664 +      rc = SQLITE_BUSY;
 1.59665 +    }else{
 1.59666 +      rc = SQLITE_OK;
 1.59667 +    }
 1.59668 +
 1.59669 +    /* Lock the destination database, if it is not locked already. */
 1.59670 +    if( SQLITE_OK==rc && p->bDestLocked==0
 1.59671 +     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
 1.59672 +    ){
 1.59673 +      p->bDestLocked = 1;
 1.59674 +      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
 1.59675 +    }
 1.59676 +
 1.59677 +    /* If there is no open read-transaction on the source database, open
 1.59678 +    ** one now. If a transaction is opened here, then it will be closed
 1.59679 +    ** before this function exits.
 1.59680 +    */
 1.59681 +    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
 1.59682 +      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
 1.59683 +      bCloseTrans = 1;
 1.59684 +    }
 1.59685 +
 1.59686 +    /* Do not allow backup if the destination database is in WAL mode
 1.59687 +    ** and the page sizes are different between source and destination */
 1.59688 +    pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
 1.59689 +    pgszDest = sqlite3BtreeGetPageSize(p->pDest);
 1.59690 +    destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
 1.59691 +    if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
 1.59692 +      rc = SQLITE_READONLY;
 1.59693 +    }
 1.59694 +  
 1.59695 +    /* Now that there is a read-lock on the source database, query the
 1.59696 +    ** source pager for the number of pages in the database.
 1.59697 +    */
 1.59698 +    nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
 1.59699 +    assert( nSrcPage>=0 );
 1.59700 +    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
 1.59701 +      const Pgno iSrcPg = p->iNext;                 /* Source page number */
 1.59702 +      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
 1.59703 +        DbPage *pSrcPg;                             /* Source page object */
 1.59704 +        rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
 1.59705 +                                 PAGER_GET_READONLY);
 1.59706 +        if( rc==SQLITE_OK ){
 1.59707 +          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
 1.59708 +          sqlite3PagerUnref(pSrcPg);
 1.59709 +        }
 1.59710 +      }
 1.59711 +      p->iNext++;
 1.59712 +    }
 1.59713 +    if( rc==SQLITE_OK ){
 1.59714 +      p->nPagecount = nSrcPage;
 1.59715 +      p->nRemaining = nSrcPage+1-p->iNext;
 1.59716 +      if( p->iNext>(Pgno)nSrcPage ){
 1.59717 +        rc = SQLITE_DONE;
 1.59718 +      }else if( !p->isAttached ){
 1.59719 +        attachBackupObject(p);
 1.59720 +      }
 1.59721 +    }
 1.59722 +  
 1.59723 +    /* Update the schema version field in the destination database. This
 1.59724 +    ** is to make sure that the schema-version really does change in
 1.59725 +    ** the case where the source and destination databases have the
 1.59726 +    ** same schema version.
 1.59727 +    */
 1.59728 +    if( rc==SQLITE_DONE ){
 1.59729 +      if( nSrcPage==0 ){
 1.59730 +        rc = sqlite3BtreeNewDb(p->pDest);
 1.59731 +        nSrcPage = 1;
 1.59732 +      }
 1.59733 +      if( rc==SQLITE_OK || rc==SQLITE_DONE ){
 1.59734 +        rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
 1.59735 +      }
 1.59736 +      if( rc==SQLITE_OK ){
 1.59737 +        if( p->pDestDb ){
 1.59738 +          sqlite3ResetAllSchemasOfConnection(p->pDestDb);
 1.59739 +        }
 1.59740 +        if( destMode==PAGER_JOURNALMODE_WAL ){
 1.59741 +          rc = sqlite3BtreeSetVersion(p->pDest, 2);
 1.59742 +        }
 1.59743 +      }
 1.59744 +      if( rc==SQLITE_OK ){
 1.59745 +        int nDestTruncate;
 1.59746 +        /* Set nDestTruncate to the final number of pages in the destination
 1.59747 +        ** database. The complication here is that the destination page
 1.59748 +        ** size may be different to the source page size. 
 1.59749 +        **
 1.59750 +        ** If the source page size is smaller than the destination page size, 
 1.59751 +        ** round up. In this case the call to sqlite3OsTruncate() below will
 1.59752 +        ** fix the size of the file. However it is important to call
 1.59753 +        ** sqlite3PagerTruncateImage() here so that any pages in the 
 1.59754 +        ** destination file that lie beyond the nDestTruncate page mark are
 1.59755 +        ** journalled by PagerCommitPhaseOne() before they are destroyed
 1.59756 +        ** by the file truncation.
 1.59757 +        */
 1.59758 +        assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
 1.59759 +        assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
 1.59760 +        if( pgszSrc<pgszDest ){
 1.59761 +          int ratio = pgszDest/pgszSrc;
 1.59762 +          nDestTruncate = (nSrcPage+ratio-1)/ratio;
 1.59763 +          if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
 1.59764 +            nDestTruncate--;
 1.59765 +          }
 1.59766 +        }else{
 1.59767 +          nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
 1.59768 +        }
 1.59769 +        assert( nDestTruncate>0 );
 1.59770 +
 1.59771 +        if( pgszSrc<pgszDest ){
 1.59772 +          /* If the source page-size is smaller than the destination page-size,
 1.59773 +          ** two extra things may need to happen:
 1.59774 +          **
 1.59775 +          **   * The destination may need to be truncated, and
 1.59776 +          **
 1.59777 +          **   * Data stored on the pages immediately following the 
 1.59778 +          **     pending-byte page in the source database may need to be
 1.59779 +          **     copied into the destination database.
 1.59780 +          */
 1.59781 +          const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
 1.59782 +          sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
 1.59783 +          Pgno iPg;
 1.59784 +          int nDstPage;
 1.59785 +          i64 iOff;
 1.59786 +          i64 iEnd;
 1.59787 +
 1.59788 +          assert( pFile );
 1.59789 +          assert( nDestTruncate==0 
 1.59790 +              || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
 1.59791 +                nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
 1.59792 +             && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
 1.59793 +          ));
 1.59794 +
 1.59795 +          /* This block ensures that all data required to recreate the original
 1.59796 +          ** database has been stored in the journal for pDestPager and the
 1.59797 +          ** journal synced to disk. So at this point we may safely modify
 1.59798 +          ** the database file in any way, knowing that if a power failure
 1.59799 +          ** occurs, the original database will be reconstructed from the 
 1.59800 +          ** journal file.  */
 1.59801 +          sqlite3PagerPagecount(pDestPager, &nDstPage);
 1.59802 +          for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
 1.59803 +            if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
 1.59804 +              DbPage *pPg;
 1.59805 +              rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
 1.59806 +              if( rc==SQLITE_OK ){
 1.59807 +                rc = sqlite3PagerWrite(pPg);
 1.59808 +                sqlite3PagerUnref(pPg);
 1.59809 +              }
 1.59810 +            }
 1.59811 +          }
 1.59812 +          if( rc==SQLITE_OK ){
 1.59813 +            rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
 1.59814 +          }
 1.59815 +
 1.59816 +          /* Write the extra pages and truncate the database file as required */
 1.59817 +          iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
 1.59818 +          for(
 1.59819 +            iOff=PENDING_BYTE+pgszSrc; 
 1.59820 +            rc==SQLITE_OK && iOff<iEnd; 
 1.59821 +            iOff+=pgszSrc
 1.59822 +          ){
 1.59823 +            PgHdr *pSrcPg = 0;
 1.59824 +            const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
 1.59825 +            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
 1.59826 +            if( rc==SQLITE_OK ){
 1.59827 +              u8 *zData = sqlite3PagerGetData(pSrcPg);
 1.59828 +              rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
 1.59829 +            }
 1.59830 +            sqlite3PagerUnref(pSrcPg);
 1.59831 +          }
 1.59832 +          if( rc==SQLITE_OK ){
 1.59833 +            rc = backupTruncateFile(pFile, iSize);
 1.59834 +          }
 1.59835 +
 1.59836 +          /* Sync the database file to disk. */
 1.59837 +          if( rc==SQLITE_OK ){
 1.59838 +            rc = sqlite3PagerSync(pDestPager, 0);
 1.59839 +          }
 1.59840 +        }else{
 1.59841 +          sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
 1.59842 +          rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
 1.59843 +        }
 1.59844 +    
 1.59845 +        /* Finish committing the transaction to the destination database. */
 1.59846 +        if( SQLITE_OK==rc
 1.59847 +         && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
 1.59848 +        ){
 1.59849 +          rc = SQLITE_DONE;
 1.59850 +        }
 1.59851 +      }
 1.59852 +    }
 1.59853 +  
 1.59854 +    /* If bCloseTrans is true, then this function opened a read transaction
 1.59855 +    ** on the source database. Close the read transaction here. There is
 1.59856 +    ** no need to check the return values of the btree methods here, as
 1.59857 +    ** "committing" a read-only transaction cannot fail.
 1.59858 +    */
 1.59859 +    if( bCloseTrans ){
 1.59860 +      TESTONLY( int rc2 );
 1.59861 +      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
 1.59862 +      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
 1.59863 +      assert( rc2==SQLITE_OK );
 1.59864 +    }
 1.59865 +  
 1.59866 +    if( rc==SQLITE_IOERR_NOMEM ){
 1.59867 +      rc = SQLITE_NOMEM;
 1.59868 +    }
 1.59869 +    p->rc = rc;
 1.59870 +  }
 1.59871 +  if( p->pDestDb ){
 1.59872 +    sqlite3_mutex_leave(p->pDestDb->mutex);
 1.59873 +  }
 1.59874 +  sqlite3BtreeLeave(p->pSrc);
 1.59875 +  sqlite3_mutex_leave(p->pSrcDb->mutex);
 1.59876 +  return rc;
 1.59877 +}
 1.59878 +
 1.59879 +/*
 1.59880 +** Release all resources associated with an sqlite3_backup* handle.
 1.59881 +*/
 1.59882 +SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
 1.59883 +  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
 1.59884 +  sqlite3 *pSrcDb;                     /* Source database connection */
 1.59885 +  int rc;                              /* Value to return */
 1.59886 +
 1.59887 +  /* Enter the mutexes */
 1.59888 +  if( p==0 ) return SQLITE_OK;
 1.59889 +  pSrcDb = p->pSrcDb;
 1.59890 +  sqlite3_mutex_enter(pSrcDb->mutex);
 1.59891 +  sqlite3BtreeEnter(p->pSrc);
 1.59892 +  if( p->pDestDb ){
 1.59893 +    sqlite3_mutex_enter(p->pDestDb->mutex);
 1.59894 +  }
 1.59895 +
 1.59896 +  /* Detach this backup from the source pager. */
 1.59897 +  if( p->pDestDb ){
 1.59898 +    p->pSrc->nBackup--;
 1.59899 +  }
 1.59900 +  if( p->isAttached ){
 1.59901 +    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
 1.59902 +    while( *pp!=p ){
 1.59903 +      pp = &(*pp)->pNext;
 1.59904 +    }
 1.59905 +    *pp = p->pNext;
 1.59906 +  }
 1.59907 +
 1.59908 +  /* If a transaction is still open on the Btree, roll it back. */
 1.59909 +  sqlite3BtreeRollback(p->pDest, SQLITE_OK);
 1.59910 +
 1.59911 +  /* Set the error code of the destination database handle. */
 1.59912 +  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
 1.59913 +  if( p->pDestDb ){
 1.59914 +    sqlite3Error(p->pDestDb, rc, 0);
 1.59915 +
 1.59916 +    /* Exit the mutexes and free the backup context structure. */
 1.59917 +    sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
 1.59918 +  }
 1.59919 +  sqlite3BtreeLeave(p->pSrc);
 1.59920 +  if( p->pDestDb ){
 1.59921 +    /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
 1.59922 +    ** call to sqlite3_backup_init() and is destroyed by a call to
 1.59923 +    ** sqlite3_backup_finish(). */
 1.59924 +    sqlite3_free(p);
 1.59925 +  }
 1.59926 +  sqlite3LeaveMutexAndCloseZombie(pSrcDb);
 1.59927 +  return rc;
 1.59928 +}
 1.59929 +
 1.59930 +/*
 1.59931 +** Return the number of pages still to be backed up as of the most recent
 1.59932 +** call to sqlite3_backup_step().
 1.59933 +*/
 1.59934 +SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
 1.59935 +  return p->nRemaining;
 1.59936 +}
 1.59937 +
 1.59938 +/*
 1.59939 +** Return the total number of pages in the source database as of the most 
 1.59940 +** recent call to sqlite3_backup_step().
 1.59941 +*/
 1.59942 +SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
 1.59943 +  return p->nPagecount;
 1.59944 +}
 1.59945 +
 1.59946 +/*
 1.59947 +** This function is called after the contents of page iPage of the
 1.59948 +** source database have been modified. If page iPage has already been 
 1.59949 +** copied into the destination database, then the data written to the
 1.59950 +** destination is now invalidated. The destination copy of iPage needs
 1.59951 +** to be updated with the new data before the backup operation is
 1.59952 +** complete.
 1.59953 +**
 1.59954 +** It is assumed that the mutex associated with the BtShared object
 1.59955 +** corresponding to the source database is held when this function is
 1.59956 +** called.
 1.59957 +*/
 1.59958 +SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
 1.59959 +  sqlite3_backup *p;                   /* Iterator variable */
 1.59960 +  for(p=pBackup; p; p=p->pNext){
 1.59961 +    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
 1.59962 +    if( !isFatalError(p->rc) && iPage<p->iNext ){
 1.59963 +      /* The backup process p has already copied page iPage. But now it
 1.59964 +      ** has been modified by a transaction on the source pager. Copy
 1.59965 +      ** the new data into the backup.
 1.59966 +      */
 1.59967 +      int rc;
 1.59968 +      assert( p->pDestDb );
 1.59969 +      sqlite3_mutex_enter(p->pDestDb->mutex);
 1.59970 +      rc = backupOnePage(p, iPage, aData, 1);
 1.59971 +      sqlite3_mutex_leave(p->pDestDb->mutex);
 1.59972 +      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
 1.59973 +      if( rc!=SQLITE_OK ){
 1.59974 +        p->rc = rc;
 1.59975 +      }
 1.59976 +    }
 1.59977 +  }
 1.59978 +}
 1.59979 +
 1.59980 +/*
 1.59981 +** Restart the backup process. This is called when the pager layer
 1.59982 +** detects that the database has been modified by an external database
 1.59983 +** connection. In this case there is no way of knowing which of the
 1.59984 +** pages that have been copied into the destination database are still 
 1.59985 +** valid and which are not, so the entire process needs to be restarted.
 1.59986 +**
 1.59987 +** It is assumed that the mutex associated with the BtShared object
 1.59988 +** corresponding to the source database is held when this function is
 1.59989 +** called.
 1.59990 +*/
 1.59991 +SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
 1.59992 +  sqlite3_backup *p;                   /* Iterator variable */
 1.59993 +  for(p=pBackup; p; p=p->pNext){
 1.59994 +    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
 1.59995 +    p->iNext = 1;
 1.59996 +  }
 1.59997 +}
 1.59998 +
 1.59999 +#ifndef SQLITE_OMIT_VACUUM
 1.60000 +/*
 1.60001 +** Copy the complete content of pBtFrom into pBtTo.  A transaction
 1.60002 +** must be active for both files.
 1.60003 +**
 1.60004 +** The size of file pTo may be reduced by this operation. If anything 
 1.60005 +** goes wrong, the transaction on pTo is rolled back. If successful, the 
 1.60006 +** transaction is committed before returning.
 1.60007 +*/
 1.60008 +SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
 1.60009 +  int rc;
 1.60010 +  sqlite3_file *pFd;              /* File descriptor for database pTo */
 1.60011 +  sqlite3_backup b;
 1.60012 +  sqlite3BtreeEnter(pTo);
 1.60013 +  sqlite3BtreeEnter(pFrom);
 1.60014 +
 1.60015 +  assert( sqlite3BtreeIsInTrans(pTo) );
 1.60016 +  pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
 1.60017 +  if( pFd->pMethods ){
 1.60018 +    i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
 1.60019 +    rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
 1.60020 +    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
 1.60021 +    if( rc ) goto copy_finished;
 1.60022 +  }
 1.60023 +
 1.60024 +  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
 1.60025 +  ** to 0. This is used by the implementations of sqlite3_backup_step()
 1.60026 +  ** and sqlite3_backup_finish() to detect that they are being called
 1.60027 +  ** from this function, not directly by the user.
 1.60028 +  */
 1.60029 +  memset(&b, 0, sizeof(b));
 1.60030 +  b.pSrcDb = pFrom->db;
 1.60031 +  b.pSrc = pFrom;
 1.60032 +  b.pDest = pTo;
 1.60033 +  b.iNext = 1;
 1.60034 +
 1.60035 +  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
 1.60036 +  ** file. By passing this as the number of pages to copy to
 1.60037 +  ** sqlite3_backup_step(), we can guarantee that the copy finishes 
 1.60038 +  ** within a single call (unless an error occurs). The assert() statement
 1.60039 +  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
 1.60040 +  ** or an error code.
 1.60041 +  */
 1.60042 +  sqlite3_backup_step(&b, 0x7FFFFFFF);
 1.60043 +  assert( b.rc!=SQLITE_OK );
 1.60044 +  rc = sqlite3_backup_finish(&b);
 1.60045 +  if( rc==SQLITE_OK ){
 1.60046 +    pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
 1.60047 +  }else{
 1.60048 +    sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
 1.60049 +  }
 1.60050 +
 1.60051 +  assert( sqlite3BtreeIsInTrans(pTo)==0 );
 1.60052 +copy_finished:
 1.60053 +  sqlite3BtreeLeave(pFrom);
 1.60054 +  sqlite3BtreeLeave(pTo);
 1.60055 +  return rc;
 1.60056 +}
 1.60057 +#endif /* SQLITE_OMIT_VACUUM */
 1.60058 +
 1.60059 +/************** End of backup.c **********************************************/
 1.60060 +/************** Begin file vdbemem.c *****************************************/
 1.60061 +/*
 1.60062 +** 2004 May 26
 1.60063 +**
 1.60064 +** The author disclaims copyright to this source code.  In place of
 1.60065 +** a legal notice, here is a blessing:
 1.60066 +**
 1.60067 +**    May you do good and not evil.
 1.60068 +**    May you find forgiveness for yourself and forgive others.
 1.60069 +**    May you share freely, never taking more than you give.
 1.60070 +**
 1.60071 +*************************************************************************
 1.60072 +**
 1.60073 +** This file contains code use to manipulate "Mem" structure.  A "Mem"
 1.60074 +** stores a single value in the VDBE.  Mem is an opaque structure visible
 1.60075 +** only within the VDBE.  Interface routines refer to a Mem using the
 1.60076 +** name sqlite_value
 1.60077 +*/
 1.60078 +
 1.60079 +#ifdef SQLITE_DEBUG
 1.60080 +/*
 1.60081 +** Check invariants on a Mem object.
 1.60082 +**
 1.60083 +** This routine is intended for use inside of assert() statements, like
 1.60084 +** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
 1.60085 +*/
 1.60086 +SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
 1.60087 +  /* The MEM_Dyn bit is set if and only if Mem.xDel is a non-NULL destructor
 1.60088 +  ** function for Mem.z 
 1.60089 +  */
 1.60090 +  assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
 1.60091 +  assert( (p->flags & MEM_Dyn)!=0 || p->xDel==0 );
 1.60092 +
 1.60093 +  /* If p holds a string or blob, the Mem.z must point to exactly
 1.60094 +  ** one of the following:
 1.60095 +  **
 1.60096 +  **   (1) Memory in Mem.zMalloc and managed by the Mem object
 1.60097 +  **   (2) Memory to be freed using Mem.xDel
 1.60098 +  **   (3) An ephermal string or blob
 1.60099 +  **   (4) A static string or blob
 1.60100 +  */
 1.60101 +  if( (p->flags & (MEM_Str|MEM_Blob)) && p->z!=0 ){
 1.60102 +    assert( 
 1.60103 +      ((p->z==p->zMalloc)? 1 : 0) +
 1.60104 +      ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
 1.60105 +      ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
 1.60106 +      ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
 1.60107 +    );
 1.60108 +  }
 1.60109 +
 1.60110 +  return 1;
 1.60111 +}
 1.60112 +#endif
 1.60113 +
 1.60114 +
 1.60115 +/*
 1.60116 +** If pMem is an object with a valid string representation, this routine
 1.60117 +** ensures the internal encoding for the string representation is
 1.60118 +** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
 1.60119 +**
 1.60120 +** If pMem is not a string object, or the encoding of the string
 1.60121 +** representation is already stored using the requested encoding, then this
 1.60122 +** routine is a no-op.
 1.60123 +**
 1.60124 +** SQLITE_OK is returned if the conversion is successful (or not required).
 1.60125 +** SQLITE_NOMEM may be returned if a malloc() fails during conversion
 1.60126 +** between formats.
 1.60127 +*/
 1.60128 +SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
 1.60129 +#ifndef SQLITE_OMIT_UTF16
 1.60130 +  int rc;
 1.60131 +#endif
 1.60132 +  assert( (pMem->flags&MEM_RowSet)==0 );
 1.60133 +  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
 1.60134 +           || desiredEnc==SQLITE_UTF16BE );
 1.60135 +  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
 1.60136 +    return SQLITE_OK;
 1.60137 +  }
 1.60138 +  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 1.60139 +#ifdef SQLITE_OMIT_UTF16
 1.60140 +  return SQLITE_ERROR;
 1.60141 +#else
 1.60142 +
 1.60143 +  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
 1.60144 +  ** then the encoding of the value may not have changed.
 1.60145 +  */
 1.60146 +  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
 1.60147 +  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
 1.60148 +  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
 1.60149 +  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
 1.60150 +  return rc;
 1.60151 +#endif
 1.60152 +}
 1.60153 +
 1.60154 +/*
 1.60155 +** Make sure pMem->z points to a writable allocation of at least 
 1.60156 +** min(n,32) bytes.
 1.60157 +**
 1.60158 +** If the bPreserve argument is true, then copy of the content of
 1.60159 +** pMem->z into the new allocation.  pMem must be either a string or
 1.60160 +** blob if bPreserve is true.  If bPreserve is false, any prior content
 1.60161 +** in pMem->z is discarded.
 1.60162 +*/
 1.60163 +SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
 1.60164 +  assert( sqlite3VdbeCheckMemInvariants(pMem) );
 1.60165 +  assert( (pMem->flags&MEM_RowSet)==0 );
 1.60166 +
 1.60167 +  /* If the bPreserve flag is set to true, then the memory cell must already
 1.60168 +  ** contain a valid string or blob value.  */
 1.60169 +  assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
 1.60170 +  testcase( bPreserve && pMem->z==0 );
 1.60171 +
 1.60172 +  if( pMem->zMalloc==0 || sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
 1.60173 +    if( n<32 ) n = 32;
 1.60174 +    if( bPreserve && pMem->z==pMem->zMalloc ){
 1.60175 +      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
 1.60176 +      bPreserve = 0;
 1.60177 +    }else{
 1.60178 +      sqlite3DbFree(pMem->db, pMem->zMalloc);
 1.60179 +      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
 1.60180 +    }
 1.60181 +    if( pMem->zMalloc==0 ){
 1.60182 +      VdbeMemRelease(pMem);
 1.60183 +      pMem->z = 0;
 1.60184 +      pMem->flags = MEM_Null;  
 1.60185 +      return SQLITE_NOMEM;
 1.60186 +    }
 1.60187 +  }
 1.60188 +
 1.60189 +  if( pMem->z && bPreserve && pMem->z!=pMem->zMalloc ){
 1.60190 +    memcpy(pMem->zMalloc, pMem->z, pMem->n);
 1.60191 +  }
 1.60192 +  if( (pMem->flags&MEM_Dyn)!=0 ){
 1.60193 +    assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
 1.60194 +    pMem->xDel((void *)(pMem->z));
 1.60195 +  }
 1.60196 +
 1.60197 +  pMem->z = pMem->zMalloc;
 1.60198 +  pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
 1.60199 +  pMem->xDel = 0;
 1.60200 +  return SQLITE_OK;
 1.60201 +}
 1.60202 +
 1.60203 +/*
 1.60204 +** Make the given Mem object MEM_Dyn.  In other words, make it so
 1.60205 +** that any TEXT or BLOB content is stored in memory obtained from
 1.60206 +** malloc().  In this way, we know that the memory is safe to be
 1.60207 +** overwritten or altered.
 1.60208 +**
 1.60209 +** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
 1.60210 +*/
 1.60211 +SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
 1.60212 +  int f;
 1.60213 +  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 1.60214 +  assert( (pMem->flags&MEM_RowSet)==0 );
 1.60215 +  ExpandBlob(pMem);
 1.60216 +  f = pMem->flags;
 1.60217 +  if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
 1.60218 +    if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
 1.60219 +      return SQLITE_NOMEM;
 1.60220 +    }
 1.60221 +    pMem->z[pMem->n] = 0;
 1.60222 +    pMem->z[pMem->n+1] = 0;
 1.60223 +    pMem->flags |= MEM_Term;
 1.60224 +#ifdef SQLITE_DEBUG
 1.60225 +    pMem->pScopyFrom = 0;
 1.60226 +#endif
 1.60227 +  }
 1.60228 +
 1.60229 +  return SQLITE_OK;
 1.60230 +}
 1.60231 +
 1.60232 +/*
 1.60233 +** If the given Mem* has a zero-filled tail, turn it into an ordinary
 1.60234 +** blob stored in dynamically allocated space.
 1.60235 +*/
 1.60236 +#ifndef SQLITE_OMIT_INCRBLOB
 1.60237 +SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
 1.60238 +  if( pMem->flags & MEM_Zero ){
 1.60239 +    int nByte;
 1.60240 +    assert( pMem->flags&MEM_Blob );
 1.60241 +    assert( (pMem->flags&MEM_RowSet)==0 );
 1.60242 +    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 1.60243 +
 1.60244 +    /* Set nByte to the number of bytes required to store the expanded blob. */
 1.60245 +    nByte = pMem->n + pMem->u.nZero;
 1.60246 +    if( nByte<=0 ){
 1.60247 +      nByte = 1;
 1.60248 +    }
 1.60249 +    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
 1.60250 +      return SQLITE_NOMEM;
 1.60251 +    }
 1.60252 +
 1.60253 +    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
 1.60254 +    pMem->n += pMem->u.nZero;
 1.60255 +    pMem->flags &= ~(MEM_Zero|MEM_Term);
 1.60256 +  }
 1.60257 +  return SQLITE_OK;
 1.60258 +}
 1.60259 +#endif
 1.60260 +
 1.60261 +
 1.60262 +/*
 1.60263 +** Make sure the given Mem is \u0000 terminated.
 1.60264 +*/
 1.60265 +SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
 1.60266 +  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 1.60267 +  if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
 1.60268 +    return SQLITE_OK;   /* Nothing to do */
 1.60269 +  }
 1.60270 +  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
 1.60271 +    return SQLITE_NOMEM;
 1.60272 +  }
 1.60273 +  pMem->z[pMem->n] = 0;
 1.60274 +  pMem->z[pMem->n+1] = 0;
 1.60275 +  pMem->flags |= MEM_Term;
 1.60276 +  return SQLITE_OK;
 1.60277 +}
 1.60278 +
 1.60279 +/*
 1.60280 +** Add MEM_Str to the set of representations for the given Mem.  Numbers
 1.60281 +** are converted using sqlite3_snprintf().  Converting a BLOB to a string
 1.60282 +** is a no-op.
 1.60283 +**
 1.60284 +** Existing representations MEM_Int and MEM_Real are *not* invalidated.
 1.60285 +**
 1.60286 +** A MEM_Null value will never be passed to this function. This function is
 1.60287 +** used for converting values to text for returning to the user (i.e. via
 1.60288 +** sqlite3_value_text()), or for ensuring that values to be used as btree
 1.60289 +** keys are strings. In the former case a NULL pointer is returned the
 1.60290 +** user and the later is an internal programming error.
 1.60291 +*/
 1.60292 +SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
 1.60293 +  int rc = SQLITE_OK;
 1.60294 +  int fg = pMem->flags;
 1.60295 +  const int nByte = 32;
 1.60296 +
 1.60297 +  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 1.60298 +  assert( !(fg&MEM_Zero) );
 1.60299 +  assert( !(fg&(MEM_Str|MEM_Blob)) );
 1.60300 +  assert( fg&(MEM_Int|MEM_Real) );
 1.60301 +  assert( (pMem->flags&MEM_RowSet)==0 );
 1.60302 +  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 1.60303 +
 1.60304 +
 1.60305 +  if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
 1.60306 +    return SQLITE_NOMEM;
 1.60307 +  }
 1.60308 +
 1.60309 +  /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
 1.60310 +  ** string representation of the value. Then, if the required encoding
 1.60311 +  ** is UTF-16le or UTF-16be do a translation.
 1.60312 +  ** 
 1.60313 +  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
 1.60314 +  */
 1.60315 +  if( fg & MEM_Int ){
 1.60316 +    sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
 1.60317 +  }else{
 1.60318 +    assert( fg & MEM_Real );
 1.60319 +    sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
 1.60320 +  }
 1.60321 +  pMem->n = sqlite3Strlen30(pMem->z);
 1.60322 +  pMem->enc = SQLITE_UTF8;
 1.60323 +  pMem->flags |= MEM_Str|MEM_Term;
 1.60324 +  sqlite3VdbeChangeEncoding(pMem, enc);
 1.60325 +  return rc;
 1.60326 +}
 1.60327 +
 1.60328 +/*
 1.60329 +** Memory cell pMem contains the context of an aggregate function.
 1.60330 +** This routine calls the finalize method for that function.  The
 1.60331 +** result of the aggregate is stored back into pMem.
 1.60332 +**
 1.60333 +** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
 1.60334 +** otherwise.
 1.60335 +*/
 1.60336 +SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
 1.60337 +  int rc = SQLITE_OK;
 1.60338 +  if( ALWAYS(pFunc && pFunc->xFinalize) ){
 1.60339 +    sqlite3_context ctx;
 1.60340 +    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
 1.60341 +    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 1.60342 +    memset(&ctx, 0, sizeof(ctx));
 1.60343 +    ctx.s.flags = MEM_Null;
 1.60344 +    ctx.s.db = pMem->db;
 1.60345 +    ctx.pMem = pMem;
 1.60346 +    ctx.pFunc = pFunc;
 1.60347 +    pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
 1.60348 +    assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
 1.60349 +    sqlite3DbFree(pMem->db, pMem->zMalloc);
 1.60350 +    memcpy(pMem, &ctx.s, sizeof(ctx.s));
 1.60351 +    rc = ctx.isError;
 1.60352 +  }
 1.60353 +  return rc;
 1.60354 +}
 1.60355 +
 1.60356 +/*
 1.60357 +** If the memory cell contains a string value that must be freed by
 1.60358 +** invoking an external callback, free it now. Calling this function
 1.60359 +** does not free any Mem.zMalloc buffer.
 1.60360 +*/
 1.60361 +SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
 1.60362 +  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
 1.60363 +  if( p->flags&MEM_Agg ){
 1.60364 +    sqlite3VdbeMemFinalize(p, p->u.pDef);
 1.60365 +    assert( (p->flags & MEM_Agg)==0 );
 1.60366 +    sqlite3VdbeMemRelease(p);
 1.60367 +  }else if( p->flags&MEM_Dyn ){
 1.60368 +    assert( (p->flags&MEM_RowSet)==0 );
 1.60369 +    assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
 1.60370 +    p->xDel((void *)p->z);
 1.60371 +    p->xDel = 0;
 1.60372 +  }else if( p->flags&MEM_RowSet ){
 1.60373 +    sqlite3RowSetClear(p->u.pRowSet);
 1.60374 +  }else if( p->flags&MEM_Frame ){
 1.60375 +    sqlite3VdbeMemSetNull(p);
 1.60376 +  }
 1.60377 +}
 1.60378 +
 1.60379 +/*
 1.60380 +** Release any memory held by the Mem. This may leave the Mem in an
 1.60381 +** inconsistent state, for example with (Mem.z==0) and
 1.60382 +** (Mem.flags==MEM_Str).
 1.60383 +*/
 1.60384 +SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
 1.60385 +  assert( sqlite3VdbeCheckMemInvariants(p) );
 1.60386 +  VdbeMemRelease(p);
 1.60387 +  if( p->zMalloc ){
 1.60388 +    sqlite3DbFree(p->db, p->zMalloc);
 1.60389 +    p->zMalloc = 0;
 1.60390 +  }
 1.60391 +  p->z = 0;
 1.60392 +  assert( p->xDel==0 );  /* Zeroed by VdbeMemRelease() above */
 1.60393 +}
 1.60394 +
 1.60395 +/*
 1.60396 +** Convert a 64-bit IEEE double into a 64-bit signed integer.
 1.60397 +** If the double is out of range of a 64-bit signed integer then
 1.60398 +** return the closest available 64-bit signed integer.
 1.60399 +*/
 1.60400 +static i64 doubleToInt64(double r){
 1.60401 +#ifdef SQLITE_OMIT_FLOATING_POINT
 1.60402 +  /* When floating-point is omitted, double and int64 are the same thing */
 1.60403 +  return r;
 1.60404 +#else
 1.60405 +  /*
 1.60406 +  ** Many compilers we encounter do not define constants for the
 1.60407 +  ** minimum and maximum 64-bit integers, or they define them
 1.60408 +  ** inconsistently.  And many do not understand the "LL" notation.
 1.60409 +  ** So we define our own static constants here using nothing
 1.60410 +  ** larger than a 32-bit integer constant.
 1.60411 +  */
 1.60412 +  static const i64 maxInt = LARGEST_INT64;
 1.60413 +  static const i64 minInt = SMALLEST_INT64;
 1.60414 +
 1.60415 +  if( r<=(double)minInt ){
 1.60416 +    return minInt;
 1.60417 +  }else if( r>=(double)maxInt ){
 1.60418 +    return maxInt;
 1.60419 +  }else{
 1.60420 +    return (i64)r;
 1.60421 +  }
 1.60422 +#endif
 1.60423 +}
 1.60424 +
 1.60425 +/*
 1.60426 +** Return some kind of integer value which is the best we can do
 1.60427 +** at representing the value that *pMem describes as an integer.
 1.60428 +** If pMem is an integer, then the value is exact.  If pMem is
 1.60429 +** a floating-point then the value returned is the integer part.
 1.60430 +** If pMem is a string or blob, then we make an attempt to convert
 1.60431 +** it into a integer and return that.  If pMem represents an
 1.60432 +** an SQL-NULL value, return 0.
 1.60433 +**
 1.60434 +** If pMem represents a string value, its encoding might be changed.
 1.60435 +*/
 1.60436 +SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
 1.60437 +  int flags;
 1.60438 +  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 1.60439 +  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 1.60440 +  flags = pMem->flags;
 1.60441 +  if( flags & MEM_Int ){
 1.60442 +    return pMem->u.i;
 1.60443 +  }else if( flags & MEM_Real ){
 1.60444 +    return doubleToInt64(pMem->r);
 1.60445 +  }else if( flags & (MEM_Str|MEM_Blob) ){
 1.60446 +    i64 value = 0;
 1.60447 +    assert( pMem->z || pMem->n==0 );
 1.60448 +    testcase( pMem->z==0 );
 1.60449 +    sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
 1.60450 +    return value;
 1.60451 +  }else{
 1.60452 +    return 0;
 1.60453 +  }
 1.60454 +}
 1.60455 +
 1.60456 +/*
 1.60457 +** Return the best representation of pMem that we can get into a
 1.60458 +** double.  If pMem is already a double or an integer, return its
 1.60459 +** value.  If it is a string or blob, try to convert it to a double.
 1.60460 +** If it is a NULL, return 0.0.
 1.60461 +*/
 1.60462 +SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
 1.60463 +  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 1.60464 +  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 1.60465 +  if( pMem->flags & MEM_Real ){
 1.60466 +    return pMem->r;
 1.60467 +  }else if( pMem->flags & MEM_Int ){
 1.60468 +    return (double)pMem->u.i;
 1.60469 +  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
 1.60470 +    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
 1.60471 +    double val = (double)0;
 1.60472 +    sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
 1.60473 +    return val;
 1.60474 +  }else{
 1.60475 +    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
 1.60476 +    return (double)0;
 1.60477 +  }
 1.60478 +}
 1.60479 +
 1.60480 +/*
 1.60481 +** The MEM structure is already a MEM_Real.  Try to also make it a
 1.60482 +** MEM_Int if we can.
 1.60483 +*/
 1.60484 +SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
 1.60485 +  assert( pMem->flags & MEM_Real );
 1.60486 +  assert( (pMem->flags & MEM_RowSet)==0 );
 1.60487 +  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 1.60488 +  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 1.60489 +
 1.60490 +  pMem->u.i = doubleToInt64(pMem->r);
 1.60491 +
 1.60492 +  /* Only mark the value as an integer if
 1.60493 +  **
 1.60494 +  **    (1) the round-trip conversion real->int->real is a no-op, and
 1.60495 +  **    (2) The integer is neither the largest nor the smallest
 1.60496 +  **        possible integer (ticket #3922)
 1.60497 +  **
 1.60498 +  ** The second and third terms in the following conditional enforces
 1.60499 +  ** the second condition under the assumption that addition overflow causes
 1.60500 +  ** values to wrap around.
 1.60501 +  */
 1.60502 +  if( pMem->r==(double)pMem->u.i
 1.60503 +   && pMem->u.i>SMALLEST_INT64
 1.60504 +   && pMem->u.i<LARGEST_INT64
 1.60505 +  ){
 1.60506 +    pMem->flags |= MEM_Int;
 1.60507 +  }
 1.60508 +}
 1.60509 +
 1.60510 +/*
 1.60511 +** Convert pMem to type integer.  Invalidate any prior representations.
 1.60512 +*/
 1.60513 +SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
 1.60514 +  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 1.60515 +  assert( (pMem->flags & MEM_RowSet)==0 );
 1.60516 +  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 1.60517 +
 1.60518 +  pMem->u.i = sqlite3VdbeIntValue(pMem);
 1.60519 +  MemSetTypeFlag(pMem, MEM_Int);
 1.60520 +  return SQLITE_OK;
 1.60521 +}
 1.60522 +
 1.60523 +/*
 1.60524 +** Convert pMem so that it is of type MEM_Real.
 1.60525 +** Invalidate any prior representations.
 1.60526 +*/
 1.60527 +SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
 1.60528 +  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 1.60529 +  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 1.60530 +
 1.60531 +  pMem->r = sqlite3VdbeRealValue(pMem);
 1.60532 +  MemSetTypeFlag(pMem, MEM_Real);
 1.60533 +  return SQLITE_OK;
 1.60534 +}
 1.60535 +
 1.60536 +/*
 1.60537 +** Convert pMem so that it has types MEM_Real or MEM_Int or both.
 1.60538 +** Invalidate any prior representations.
 1.60539 +**
 1.60540 +** Every effort is made to force the conversion, even if the input
 1.60541 +** is a string that does not look completely like a number.  Convert
 1.60542 +** as much of the string as we can and ignore the rest.
 1.60543 +*/
 1.60544 +SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
 1.60545 +  if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
 1.60546 +    assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
 1.60547 +    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 1.60548 +    if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
 1.60549 +      MemSetTypeFlag(pMem, MEM_Int);
 1.60550 +    }else{
 1.60551 +      pMem->r = sqlite3VdbeRealValue(pMem);
 1.60552 +      MemSetTypeFlag(pMem, MEM_Real);
 1.60553 +      sqlite3VdbeIntegerAffinity(pMem);
 1.60554 +    }
 1.60555 +  }
 1.60556 +  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
 1.60557 +  pMem->flags &= ~(MEM_Str|MEM_Blob);
 1.60558 +  return SQLITE_OK;
 1.60559 +}
 1.60560 +
 1.60561 +/*
 1.60562 +** Delete any previous value and set the value stored in *pMem to NULL.
 1.60563 +*/
 1.60564 +SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
 1.60565 +  if( pMem->flags & MEM_Frame ){
 1.60566 +    VdbeFrame *pFrame = pMem->u.pFrame;
 1.60567 +    pFrame->pParent = pFrame->v->pDelFrame;
 1.60568 +    pFrame->v->pDelFrame = pFrame;
 1.60569 +  }
 1.60570 +  if( pMem->flags & MEM_RowSet ){
 1.60571 +    sqlite3RowSetClear(pMem->u.pRowSet);
 1.60572 +  }
 1.60573 +  MemSetTypeFlag(pMem, MEM_Null);
 1.60574 +}
 1.60575 +SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
 1.60576 +  sqlite3VdbeMemSetNull((Mem*)p); 
 1.60577 +}
 1.60578 +
 1.60579 +/*
 1.60580 +** Delete any previous value and set the value to be a BLOB of length
 1.60581 +** n containing all zeros.
 1.60582 +*/
 1.60583 +SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
 1.60584 +  sqlite3VdbeMemRelease(pMem);
 1.60585 +  pMem->flags = MEM_Blob|MEM_Zero;
 1.60586 +  pMem->n = 0;
 1.60587 +  if( n<0 ) n = 0;
 1.60588 +  pMem->u.nZero = n;
 1.60589 +  pMem->enc = SQLITE_UTF8;
 1.60590 +
 1.60591 +#ifdef SQLITE_OMIT_INCRBLOB
 1.60592 +  sqlite3VdbeMemGrow(pMem, n, 0);
 1.60593 +  if( pMem->z ){
 1.60594 +    pMem->n = n;
 1.60595 +    memset(pMem->z, 0, n);
 1.60596 +  }
 1.60597 +#endif
 1.60598 +}
 1.60599 +
 1.60600 +/*
 1.60601 +** Delete any previous value and set the value stored in *pMem to val,
 1.60602 +** manifest type INTEGER.
 1.60603 +*/
 1.60604 +SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
 1.60605 +  sqlite3VdbeMemRelease(pMem);
 1.60606 +  pMem->u.i = val;
 1.60607 +  pMem->flags = MEM_Int;
 1.60608 +}
 1.60609 +
 1.60610 +#ifndef SQLITE_OMIT_FLOATING_POINT
 1.60611 +/*
 1.60612 +** Delete any previous value and set the value stored in *pMem to val,
 1.60613 +** manifest type REAL.
 1.60614 +*/
 1.60615 +SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
 1.60616 +  if( sqlite3IsNaN(val) ){
 1.60617 +    sqlite3VdbeMemSetNull(pMem);
 1.60618 +  }else{
 1.60619 +    sqlite3VdbeMemRelease(pMem);
 1.60620 +    pMem->r = val;
 1.60621 +    pMem->flags = MEM_Real;
 1.60622 +  }
 1.60623 +}
 1.60624 +#endif
 1.60625 +
 1.60626 +/*
 1.60627 +** Delete any previous value and set the value of pMem to be an
 1.60628 +** empty boolean index.
 1.60629 +*/
 1.60630 +SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
 1.60631 +  sqlite3 *db = pMem->db;
 1.60632 +  assert( db!=0 );
 1.60633 +  assert( (pMem->flags & MEM_RowSet)==0 );
 1.60634 +  sqlite3VdbeMemRelease(pMem);
 1.60635 +  pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
 1.60636 +  if( db->mallocFailed ){
 1.60637 +    pMem->flags = MEM_Null;
 1.60638 +  }else{
 1.60639 +    assert( pMem->zMalloc );
 1.60640 +    pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, 
 1.60641 +                                       sqlite3DbMallocSize(db, pMem->zMalloc));
 1.60642 +    assert( pMem->u.pRowSet!=0 );
 1.60643 +    pMem->flags = MEM_RowSet;
 1.60644 +  }
 1.60645 +}
 1.60646 +
 1.60647 +/*
 1.60648 +** Return true if the Mem object contains a TEXT or BLOB that is
 1.60649 +** too large - whose size exceeds SQLITE_MAX_LENGTH.
 1.60650 +*/
 1.60651 +SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
 1.60652 +  assert( p->db!=0 );
 1.60653 +  if( p->flags & (MEM_Str|MEM_Blob) ){
 1.60654 +    int n = p->n;
 1.60655 +    if( p->flags & MEM_Zero ){
 1.60656 +      n += p->u.nZero;
 1.60657 +    }
 1.60658 +    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
 1.60659 +  }
 1.60660 +  return 0; 
 1.60661 +}
 1.60662 +
 1.60663 +#ifdef SQLITE_DEBUG
 1.60664 +/*
 1.60665 +** This routine prepares a memory cell for modication by breaking
 1.60666 +** its link to a shallow copy and by marking any current shallow
 1.60667 +** copies of this cell as invalid.
 1.60668 +**
 1.60669 +** This is used for testing and debugging only - to make sure shallow
 1.60670 +** copies are not misused.
 1.60671 +*/
 1.60672 +SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
 1.60673 +  int i;
 1.60674 +  Mem *pX;
 1.60675 +  for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
 1.60676 +    if( pX->pScopyFrom==pMem ){
 1.60677 +      pX->flags |= MEM_Undefined;
 1.60678 +      pX->pScopyFrom = 0;
 1.60679 +    }
 1.60680 +  }
 1.60681 +  pMem->pScopyFrom = 0;
 1.60682 +}
 1.60683 +#endif /* SQLITE_DEBUG */
 1.60684 +
 1.60685 +/*
 1.60686 +** Size of struct Mem not including the Mem.zMalloc member.
 1.60687 +*/
 1.60688 +#define MEMCELLSIZE offsetof(Mem,zMalloc)
 1.60689 +
 1.60690 +/*
 1.60691 +** Make an shallow copy of pFrom into pTo.  Prior contents of
 1.60692 +** pTo are freed.  The pFrom->z field is not duplicated.  If
 1.60693 +** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
 1.60694 +** and flags gets srcType (either MEM_Ephem or MEM_Static).
 1.60695 +*/
 1.60696 +SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
 1.60697 +  assert( (pFrom->flags & MEM_RowSet)==0 );
 1.60698 +  VdbeMemRelease(pTo);
 1.60699 +  memcpy(pTo, pFrom, MEMCELLSIZE);
 1.60700 +  pTo->xDel = 0;
 1.60701 +  if( (pFrom->flags&MEM_Static)==0 ){
 1.60702 +    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
 1.60703 +    assert( srcType==MEM_Ephem || srcType==MEM_Static );
 1.60704 +    pTo->flags |= srcType;
 1.60705 +  }
 1.60706 +}
 1.60707 +
 1.60708 +/*
 1.60709 +** Make a full copy of pFrom into pTo.  Prior contents of pTo are
 1.60710 +** freed before the copy is made.
 1.60711 +*/
 1.60712 +SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
 1.60713 +  int rc = SQLITE_OK;
 1.60714 +
 1.60715 +  assert( (pFrom->flags & MEM_RowSet)==0 );
 1.60716 +  VdbeMemRelease(pTo);
 1.60717 +  memcpy(pTo, pFrom, MEMCELLSIZE);
 1.60718 +  pTo->flags &= ~MEM_Dyn;
 1.60719 +  pTo->xDel = 0;
 1.60720 +
 1.60721 +  if( pTo->flags&(MEM_Str|MEM_Blob) ){
 1.60722 +    if( 0==(pFrom->flags&MEM_Static) ){
 1.60723 +      pTo->flags |= MEM_Ephem;
 1.60724 +      rc = sqlite3VdbeMemMakeWriteable(pTo);
 1.60725 +    }
 1.60726 +  }
 1.60727 +
 1.60728 +  return rc;
 1.60729 +}
 1.60730 +
 1.60731 +/*
 1.60732 +** Transfer the contents of pFrom to pTo. Any existing value in pTo is
 1.60733 +** freed. If pFrom contains ephemeral data, a copy is made.
 1.60734 +**
 1.60735 +** pFrom contains an SQL NULL when this routine returns.
 1.60736 +*/
 1.60737 +SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
 1.60738 +  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
 1.60739 +  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
 1.60740 +  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
 1.60741 +
 1.60742 +  sqlite3VdbeMemRelease(pTo);
 1.60743 +  memcpy(pTo, pFrom, sizeof(Mem));
 1.60744 +  pFrom->flags = MEM_Null;
 1.60745 +  pFrom->xDel = 0;
 1.60746 +  pFrom->zMalloc = 0;
 1.60747 +}
 1.60748 +
 1.60749 +/*
 1.60750 +** Change the value of a Mem to be a string or a BLOB.
 1.60751 +**
 1.60752 +** The memory management strategy depends on the value of the xDel
 1.60753 +** parameter. If the value passed is SQLITE_TRANSIENT, then the 
 1.60754 +** string is copied into a (possibly existing) buffer managed by the 
 1.60755 +** Mem structure. Otherwise, any existing buffer is freed and the
 1.60756 +** pointer copied.
 1.60757 +**
 1.60758 +** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
 1.60759 +** size limit) then no memory allocation occurs.  If the string can be
 1.60760 +** stored without allocating memory, then it is.  If a memory allocation
 1.60761 +** is required to store the string, then value of pMem is unchanged.  In
 1.60762 +** either case, SQLITE_TOOBIG is returned.
 1.60763 +*/
 1.60764 +SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
 1.60765 +  Mem *pMem,          /* Memory cell to set to string value */
 1.60766 +  const char *z,      /* String pointer */
 1.60767 +  int n,              /* Bytes in string, or negative */
 1.60768 +  u8 enc,             /* Encoding of z.  0 for BLOBs */
 1.60769 +  void (*xDel)(void*) /* Destructor function */
 1.60770 +){
 1.60771 +  int nByte = n;      /* New value for pMem->n */
 1.60772 +  int iLimit;         /* Maximum allowed string or blob size */
 1.60773 +  u16 flags = 0;      /* New value for pMem->flags */
 1.60774 +
 1.60775 +  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 1.60776 +  assert( (pMem->flags & MEM_RowSet)==0 );
 1.60777 +
 1.60778 +  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
 1.60779 +  if( !z ){
 1.60780 +    sqlite3VdbeMemSetNull(pMem);
 1.60781 +    return SQLITE_OK;
 1.60782 +  }
 1.60783 +
 1.60784 +  if( pMem->db ){
 1.60785 +    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
 1.60786 +  }else{
 1.60787 +    iLimit = SQLITE_MAX_LENGTH;
 1.60788 +  }
 1.60789 +  flags = (enc==0?MEM_Blob:MEM_Str);
 1.60790 +  if( nByte<0 ){
 1.60791 +    assert( enc!=0 );
 1.60792 +    if( enc==SQLITE_UTF8 ){
 1.60793 +      for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
 1.60794 +    }else{
 1.60795 +      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
 1.60796 +    }
 1.60797 +    flags |= MEM_Term;
 1.60798 +  }
 1.60799 +
 1.60800 +  /* The following block sets the new values of Mem.z and Mem.xDel. It
 1.60801 +  ** also sets a flag in local variable "flags" to indicate the memory
 1.60802 +  ** management (one of MEM_Dyn or MEM_Static).
 1.60803 +  */
 1.60804 +  if( xDel==SQLITE_TRANSIENT ){
 1.60805 +    int nAlloc = nByte;
 1.60806 +    if( flags&MEM_Term ){
 1.60807 +      nAlloc += (enc==SQLITE_UTF8?1:2);
 1.60808 +    }
 1.60809 +    if( nByte>iLimit ){
 1.60810 +      return SQLITE_TOOBIG;
 1.60811 +    }
 1.60812 +    if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
 1.60813 +      return SQLITE_NOMEM;
 1.60814 +    }
 1.60815 +    memcpy(pMem->z, z, nAlloc);
 1.60816 +  }else if( xDel==SQLITE_DYNAMIC ){
 1.60817 +    sqlite3VdbeMemRelease(pMem);
 1.60818 +    pMem->zMalloc = pMem->z = (char *)z;
 1.60819 +    pMem->xDel = 0;
 1.60820 +  }else{
 1.60821 +    sqlite3VdbeMemRelease(pMem);
 1.60822 +    pMem->z = (char *)z;
 1.60823 +    pMem->xDel = xDel;
 1.60824 +    flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
 1.60825 +  }
 1.60826 +
 1.60827 +  pMem->n = nByte;
 1.60828 +  pMem->flags = flags;
 1.60829 +  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
 1.60830 +
 1.60831 +#ifndef SQLITE_OMIT_UTF16
 1.60832 +  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
 1.60833 +    return SQLITE_NOMEM;
 1.60834 +  }
 1.60835 +#endif
 1.60836 +
 1.60837 +  if( nByte>iLimit ){
 1.60838 +    return SQLITE_TOOBIG;
 1.60839 +  }
 1.60840 +
 1.60841 +  return SQLITE_OK;
 1.60842 +}
 1.60843 +
 1.60844 +/*
 1.60845 +** Move data out of a btree key or data field and into a Mem structure.
 1.60846 +** The data or key is taken from the entry that pCur is currently pointing
 1.60847 +** to.  offset and amt determine what portion of the data or key to retrieve.
 1.60848 +** key is true to get the key or false to get data.  The result is written
 1.60849 +** into the pMem element.
 1.60850 +**
 1.60851 +** The pMem structure is assumed to be uninitialized.  Any prior content
 1.60852 +** is overwritten without being freed.
 1.60853 +**
 1.60854 +** If this routine fails for any reason (malloc returns NULL or unable
 1.60855 +** to read from the disk) then the pMem is left in an inconsistent state.
 1.60856 +*/
 1.60857 +SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
 1.60858 +  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
 1.60859 +  u32 offset,       /* Offset from the start of data to return bytes from. */
 1.60860 +  u32 amt,          /* Number of bytes to return. */
 1.60861 +  int key,          /* If true, retrieve from the btree key, not data. */
 1.60862 +  Mem *pMem         /* OUT: Return data in this Mem structure. */
 1.60863 +){
 1.60864 +  char *zData;        /* Data from the btree layer */
 1.60865 +  u32 available = 0;  /* Number of bytes available on the local btree page */
 1.60866 +  int rc = SQLITE_OK; /* Return code */
 1.60867 +
 1.60868 +  assert( sqlite3BtreeCursorIsValid(pCur) );
 1.60869 +
 1.60870 +  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
 1.60871 +  ** that both the BtShared and database handle mutexes are held. */
 1.60872 +  assert( (pMem->flags & MEM_RowSet)==0 );
 1.60873 +  if( key ){
 1.60874 +    zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
 1.60875 +  }else{
 1.60876 +    zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
 1.60877 +  }
 1.60878 +  assert( zData!=0 );
 1.60879 +
 1.60880 +  if( offset+amt<=available ){
 1.60881 +    sqlite3VdbeMemRelease(pMem);
 1.60882 +    pMem->z = &zData[offset];
 1.60883 +    pMem->flags = MEM_Blob|MEM_Ephem;
 1.60884 +    pMem->n = (int)amt;
 1.60885 +  }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
 1.60886 +    if( key ){
 1.60887 +      rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
 1.60888 +    }else{
 1.60889 +      rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
 1.60890 +    }
 1.60891 +    if( rc==SQLITE_OK ){
 1.60892 +      pMem->z[amt] = 0;
 1.60893 +      pMem->z[amt+1] = 0;
 1.60894 +      pMem->flags = MEM_Blob|MEM_Term;
 1.60895 +      pMem->n = (int)amt;
 1.60896 +    }else{
 1.60897 +      sqlite3VdbeMemRelease(pMem);
 1.60898 +    }
 1.60899 +  }
 1.60900 +
 1.60901 +  return rc;
 1.60902 +}
 1.60903 +
 1.60904 +/* This function is only available internally, it is not part of the
 1.60905 +** external API. It works in a similar way to sqlite3_value_text(),
 1.60906 +** except the data returned is in the encoding specified by the second
 1.60907 +** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
 1.60908 +** SQLITE_UTF8.
 1.60909 +**
 1.60910 +** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
 1.60911 +** If that is the case, then the result must be aligned on an even byte
 1.60912 +** boundary.
 1.60913 +*/
 1.60914 +SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
 1.60915 +  if( !pVal ) return 0;
 1.60916 +
 1.60917 +  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
 1.60918 +  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
 1.60919 +  assert( (pVal->flags & MEM_RowSet)==0 );
 1.60920 +
 1.60921 +  if( pVal->flags&MEM_Null ){
 1.60922 +    return 0;
 1.60923 +  }
 1.60924 +  assert( (MEM_Blob>>3) == MEM_Str );
 1.60925 +  pVal->flags |= (pVal->flags & MEM_Blob)>>3;
 1.60926 +  ExpandBlob(pVal);
 1.60927 +  if( pVal->flags&MEM_Str ){
 1.60928 +    sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
 1.60929 +    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
 1.60930 +      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
 1.60931 +      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
 1.60932 +        return 0;
 1.60933 +      }
 1.60934 +    }
 1.60935 +    sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
 1.60936 +  }else{
 1.60937 +    assert( (pVal->flags&MEM_Blob)==0 );
 1.60938 +    sqlite3VdbeMemStringify(pVal, enc);
 1.60939 +    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
 1.60940 +  }
 1.60941 +  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
 1.60942 +              || pVal->db->mallocFailed );
 1.60943 +  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
 1.60944 +    return pVal->z;
 1.60945 +  }else{
 1.60946 +    return 0;
 1.60947 +  }
 1.60948 +}
 1.60949 +
 1.60950 +/*
 1.60951 +** Create a new sqlite3_value object.
 1.60952 +*/
 1.60953 +SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
 1.60954 +  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
 1.60955 +  if( p ){
 1.60956 +    p->flags = MEM_Null;
 1.60957 +    p->db = db;
 1.60958 +  }
 1.60959 +  return p;
 1.60960 +}
 1.60961 +
 1.60962 +/*
 1.60963 +** Context object passed by sqlite3Stat4ProbeSetValue() through to 
 1.60964 +** valueNew(). See comments above valueNew() for details.
 1.60965 +*/
 1.60966 +struct ValueNewStat4Ctx {
 1.60967 +  Parse *pParse;
 1.60968 +  Index *pIdx;
 1.60969 +  UnpackedRecord **ppRec;
 1.60970 +  int iVal;
 1.60971 +};
 1.60972 +
 1.60973 +/*
 1.60974 +** Allocate and return a pointer to a new sqlite3_value object. If
 1.60975 +** the second argument to this function is NULL, the object is allocated
 1.60976 +** by calling sqlite3ValueNew().
 1.60977 +**
 1.60978 +** Otherwise, if the second argument is non-zero, then this function is 
 1.60979 +** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
 1.60980 +** already been allocated, allocate the UnpackedRecord structure that 
 1.60981 +** that function will return to its caller here. Then return a pointer 
 1.60982 +** an sqlite3_value within the UnpackedRecord.a[] array.
 1.60983 +*/
 1.60984 +static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
 1.60985 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.60986 +  if( p ){
 1.60987 +    UnpackedRecord *pRec = p->ppRec[0];
 1.60988 +
 1.60989 +    if( pRec==0 ){
 1.60990 +      Index *pIdx = p->pIdx;      /* Index being probed */
 1.60991 +      int nByte;                  /* Bytes of space to allocate */
 1.60992 +      int i;                      /* Counter variable */
 1.60993 +      int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
 1.60994 +  
 1.60995 +      nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
 1.60996 +      pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
 1.60997 +      if( pRec ){
 1.60998 +        pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
 1.60999 +        if( pRec->pKeyInfo ){
 1.61000 +          assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
 1.61001 +          assert( pRec->pKeyInfo->enc==ENC(db) );
 1.61002 +          pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
 1.61003 +          for(i=0; i<nCol; i++){
 1.61004 +            pRec->aMem[i].flags = MEM_Null;
 1.61005 +            pRec->aMem[i].db = db;
 1.61006 +          }
 1.61007 +        }else{
 1.61008 +          sqlite3DbFree(db, pRec);
 1.61009 +          pRec = 0;
 1.61010 +        }
 1.61011 +      }
 1.61012 +      if( pRec==0 ) return 0;
 1.61013 +      p->ppRec[0] = pRec;
 1.61014 +    }
 1.61015 +  
 1.61016 +    pRec->nField = p->iVal+1;
 1.61017 +    return &pRec->aMem[p->iVal];
 1.61018 +  }
 1.61019 +#else
 1.61020 +  UNUSED_PARAMETER(p);
 1.61021 +#endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
 1.61022 +  return sqlite3ValueNew(db);
 1.61023 +}
 1.61024 +
 1.61025 +/*
 1.61026 +** Extract a value from the supplied expression in the manner described
 1.61027 +** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
 1.61028 +** using valueNew().
 1.61029 +**
 1.61030 +** If pCtx is NULL and an error occurs after the sqlite3_value object
 1.61031 +** has been allocated, it is freed before returning. Or, if pCtx is not
 1.61032 +** NULL, it is assumed that the caller will free any allocated object
 1.61033 +** in all cases.
 1.61034 +*/
 1.61035 +static int valueFromExpr(
 1.61036 +  sqlite3 *db,                    /* The database connection */
 1.61037 +  Expr *pExpr,                    /* The expression to evaluate */
 1.61038 +  u8 enc,                         /* Encoding to use */
 1.61039 +  u8 affinity,                    /* Affinity to use */
 1.61040 +  sqlite3_value **ppVal,          /* Write the new value here */
 1.61041 +  struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
 1.61042 +){
 1.61043 +  int op;
 1.61044 +  char *zVal = 0;
 1.61045 +  sqlite3_value *pVal = 0;
 1.61046 +  int negInt = 1;
 1.61047 +  const char *zNeg = "";
 1.61048 +  int rc = SQLITE_OK;
 1.61049 +
 1.61050 +  if( !pExpr ){
 1.61051 +    *ppVal = 0;
 1.61052 +    return SQLITE_OK;
 1.61053 +  }
 1.61054 +  op = pExpr->op;
 1.61055 +  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
 1.61056 +
 1.61057 +  /* Handle negative integers in a single step.  This is needed in the
 1.61058 +  ** case when the value is -9223372036854775808.
 1.61059 +  */
 1.61060 +  if( op==TK_UMINUS
 1.61061 +   && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
 1.61062 +    pExpr = pExpr->pLeft;
 1.61063 +    op = pExpr->op;
 1.61064 +    negInt = -1;
 1.61065 +    zNeg = "-";
 1.61066 +  }
 1.61067 +
 1.61068 +  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
 1.61069 +    pVal = valueNew(db, pCtx);
 1.61070 +    if( pVal==0 ) goto no_mem;
 1.61071 +    if( ExprHasProperty(pExpr, EP_IntValue) ){
 1.61072 +      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
 1.61073 +    }else{
 1.61074 +      zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
 1.61075 +      if( zVal==0 ) goto no_mem;
 1.61076 +      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
 1.61077 +    }
 1.61078 +    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
 1.61079 +      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
 1.61080 +    }else{
 1.61081 +      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
 1.61082 +    }
 1.61083 +    if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
 1.61084 +    if( enc!=SQLITE_UTF8 ){
 1.61085 +      rc = sqlite3VdbeChangeEncoding(pVal, enc);
 1.61086 +    }
 1.61087 +  }else if( op==TK_UMINUS ) {
 1.61088 +    /* This branch happens for multiple negative signs.  Ex: -(-5) */
 1.61089 +    if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) 
 1.61090 +     && pVal!=0
 1.61091 +    ){
 1.61092 +      sqlite3VdbeMemNumerify(pVal);
 1.61093 +      if( pVal->u.i==SMALLEST_INT64 ){
 1.61094 +        pVal->flags &= ~MEM_Int;
 1.61095 +        pVal->flags |= MEM_Real;
 1.61096 +        pVal->r = (double)SMALLEST_INT64;
 1.61097 +      }else{
 1.61098 +        pVal->u.i = -pVal->u.i;
 1.61099 +      }
 1.61100 +      pVal->r = -pVal->r;
 1.61101 +      sqlite3ValueApplyAffinity(pVal, affinity, enc);
 1.61102 +    }
 1.61103 +  }else if( op==TK_NULL ){
 1.61104 +    pVal = valueNew(db, pCtx);
 1.61105 +    if( pVal==0 ) goto no_mem;
 1.61106 +  }
 1.61107 +#ifndef SQLITE_OMIT_BLOB_LITERAL
 1.61108 +  else if( op==TK_BLOB ){
 1.61109 +    int nVal;
 1.61110 +    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
 1.61111 +    assert( pExpr->u.zToken[1]=='\'' );
 1.61112 +    pVal = valueNew(db, pCtx);
 1.61113 +    if( !pVal ) goto no_mem;
 1.61114 +    zVal = &pExpr->u.zToken[2];
 1.61115 +    nVal = sqlite3Strlen30(zVal)-1;
 1.61116 +    assert( zVal[nVal]=='\'' );
 1.61117 +    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
 1.61118 +                         0, SQLITE_DYNAMIC);
 1.61119 +  }
 1.61120 +#endif
 1.61121 +
 1.61122 +  *ppVal = pVal;
 1.61123 +  return rc;
 1.61124 +
 1.61125 +no_mem:
 1.61126 +  db->mallocFailed = 1;
 1.61127 +  sqlite3DbFree(db, zVal);
 1.61128 +  assert( *ppVal==0 );
 1.61129 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.61130 +  if( pCtx==0 ) sqlite3ValueFree(pVal);
 1.61131 +#else
 1.61132 +  assert( pCtx==0 ); sqlite3ValueFree(pVal);
 1.61133 +#endif
 1.61134 +  return SQLITE_NOMEM;
 1.61135 +}
 1.61136 +
 1.61137 +/*
 1.61138 +** Create a new sqlite3_value object, containing the value of pExpr.
 1.61139 +**
 1.61140 +** This only works for very simple expressions that consist of one constant
 1.61141 +** token (i.e. "5", "5.1", "'a string'"). If the expression can
 1.61142 +** be converted directly into a value, then the value is allocated and
 1.61143 +** a pointer written to *ppVal. The caller is responsible for deallocating
 1.61144 +** the value by passing it to sqlite3ValueFree() later on. If the expression
 1.61145 +** cannot be converted to a value, then *ppVal is set to NULL.
 1.61146 +*/
 1.61147 +SQLITE_PRIVATE int sqlite3ValueFromExpr(
 1.61148 +  sqlite3 *db,              /* The database connection */
 1.61149 +  Expr *pExpr,              /* The expression to evaluate */
 1.61150 +  u8 enc,                   /* Encoding to use */
 1.61151 +  u8 affinity,              /* Affinity to use */
 1.61152 +  sqlite3_value **ppVal     /* Write the new value here */
 1.61153 +){
 1.61154 +  return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
 1.61155 +}
 1.61156 +
 1.61157 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.61158 +/*
 1.61159 +** The implementation of the sqlite_record() function. This function accepts
 1.61160 +** a single argument of any type. The return value is a formatted database 
 1.61161 +** record (a blob) containing the argument value.
 1.61162 +**
 1.61163 +** This is used to convert the value stored in the 'sample' column of the
 1.61164 +** sqlite_stat3 table to the record format SQLite uses internally.
 1.61165 +*/
 1.61166 +static void recordFunc(
 1.61167 +  sqlite3_context *context,
 1.61168 +  int argc,
 1.61169 +  sqlite3_value **argv
 1.61170 +){
 1.61171 +  const int file_format = 1;
 1.61172 +  int iSerial;                    /* Serial type */
 1.61173 +  int nSerial;                    /* Bytes of space for iSerial as varint */
 1.61174 +  int nVal;                       /* Bytes of space required for argv[0] */
 1.61175 +  int nRet;
 1.61176 +  sqlite3 *db;
 1.61177 +  u8 *aRet;
 1.61178 +
 1.61179 +  UNUSED_PARAMETER( argc );
 1.61180 +  iSerial = sqlite3VdbeSerialType(argv[0], file_format);
 1.61181 +  nSerial = sqlite3VarintLen(iSerial);
 1.61182 +  nVal = sqlite3VdbeSerialTypeLen(iSerial);
 1.61183 +  db = sqlite3_context_db_handle(context);
 1.61184 +
 1.61185 +  nRet = 1 + nSerial + nVal;
 1.61186 +  aRet = sqlite3DbMallocRaw(db, nRet);
 1.61187 +  if( aRet==0 ){
 1.61188 +    sqlite3_result_error_nomem(context);
 1.61189 +  }else{
 1.61190 +    aRet[0] = nSerial+1;
 1.61191 +    sqlite3PutVarint(&aRet[1], iSerial);
 1.61192 +    sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
 1.61193 +    sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
 1.61194 +    sqlite3DbFree(db, aRet);
 1.61195 +  }
 1.61196 +}
 1.61197 +
 1.61198 +/*
 1.61199 +** Register built-in functions used to help read ANALYZE data.
 1.61200 +*/
 1.61201 +SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
 1.61202 +  static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
 1.61203 +    FUNCTION(sqlite_record,   1, 0, 0, recordFunc),
 1.61204 +  };
 1.61205 +  int i;
 1.61206 +  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
 1.61207 +  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
 1.61208 +  for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
 1.61209 +    sqlite3FuncDefInsert(pHash, &aFunc[i]);
 1.61210 +  }
 1.61211 +}
 1.61212 +
 1.61213 +/*
 1.61214 +** This function is used to allocate and populate UnpackedRecord 
 1.61215 +** structures intended to be compared against sample index keys stored 
 1.61216 +** in the sqlite_stat4 table.
 1.61217 +**
 1.61218 +** A single call to this function attempts to populates field iVal (leftmost 
 1.61219 +** is 0 etc.) of the unpacked record with a value extracted from expression
 1.61220 +** pExpr. Extraction of values is possible if:
 1.61221 +**
 1.61222 +**  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
 1.61223 +**
 1.61224 +**  * The expression is a bound variable, and this is a reprepare, or
 1.61225 +**
 1.61226 +**  * The sqlite3ValueFromExpr() function is able to extract a value 
 1.61227 +**    from the expression (i.e. the expression is a literal value).
 1.61228 +**
 1.61229 +** If a value can be extracted, the affinity passed as the 5th argument
 1.61230 +** is applied to it before it is copied into the UnpackedRecord. Output
 1.61231 +** parameter *pbOk is set to true if a value is extracted, or false 
 1.61232 +** otherwise.
 1.61233 +**
 1.61234 +** When this function is called, *ppRec must either point to an object
 1.61235 +** allocated by an earlier call to this function, or must be NULL. If it
 1.61236 +** is NULL and a value can be successfully extracted, a new UnpackedRecord
 1.61237 +** is allocated (and *ppRec set to point to it) before returning.
 1.61238 +**
 1.61239 +** Unless an error is encountered, SQLITE_OK is returned. It is not an
 1.61240 +** error if a value cannot be extracted from pExpr. If an error does
 1.61241 +** occur, an SQLite error code is returned.
 1.61242 +*/
 1.61243 +SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
 1.61244 +  Parse *pParse,                  /* Parse context */
 1.61245 +  Index *pIdx,                    /* Index being probed */
 1.61246 +  UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
 1.61247 +  Expr *pExpr,                    /* The expression to extract a value from */
 1.61248 +  u8 affinity,                    /* Affinity to use */
 1.61249 +  int iVal,                       /* Array element to populate */
 1.61250 +  int *pbOk                       /* OUT: True if value was extracted */
 1.61251 +){
 1.61252 +  int rc = SQLITE_OK;
 1.61253 +  sqlite3_value *pVal = 0;
 1.61254 +  sqlite3 *db = pParse->db;
 1.61255 +
 1.61256 +
 1.61257 +  struct ValueNewStat4Ctx alloc;
 1.61258 +  alloc.pParse = pParse;
 1.61259 +  alloc.pIdx = pIdx;
 1.61260 +  alloc.ppRec = ppRec;
 1.61261 +  alloc.iVal = iVal;
 1.61262 +
 1.61263 +  /* Skip over any TK_COLLATE nodes */
 1.61264 +  pExpr = sqlite3ExprSkipCollate(pExpr);
 1.61265 +
 1.61266 +  if( !pExpr ){
 1.61267 +    pVal = valueNew(db, &alloc);
 1.61268 +    if( pVal ){
 1.61269 +      sqlite3VdbeMemSetNull((Mem*)pVal);
 1.61270 +    }
 1.61271 +  }else if( pExpr->op==TK_VARIABLE
 1.61272 +        || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
 1.61273 +  ){
 1.61274 +    Vdbe *v;
 1.61275 +    int iBindVar = pExpr->iColumn;
 1.61276 +    sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
 1.61277 +    if( (v = pParse->pReprepare)!=0 ){
 1.61278 +      pVal = valueNew(db, &alloc);
 1.61279 +      if( pVal ){
 1.61280 +        rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
 1.61281 +        if( rc==SQLITE_OK ){
 1.61282 +          sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
 1.61283 +        }
 1.61284 +        pVal->db = pParse->db;
 1.61285 +      }
 1.61286 +    }
 1.61287 +  }else{
 1.61288 +    rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, &alloc);
 1.61289 +  }
 1.61290 +  *pbOk = (pVal!=0);
 1.61291 +
 1.61292 +  assert( pVal==0 || pVal->db==db );
 1.61293 +  return rc;
 1.61294 +}
 1.61295 +
 1.61296 +/*
 1.61297 +** Unless it is NULL, the argument must be an UnpackedRecord object returned
 1.61298 +** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
 1.61299 +** the object.
 1.61300 +*/
 1.61301 +SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
 1.61302 +  if( pRec ){
 1.61303 +    int i;
 1.61304 +    int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
 1.61305 +    Mem *aMem = pRec->aMem;
 1.61306 +    sqlite3 *db = aMem[0].db;
 1.61307 +    for(i=0; i<nCol; i++){
 1.61308 +      sqlite3DbFree(db, aMem[i].zMalloc);
 1.61309 +    }
 1.61310 +    sqlite3KeyInfoUnref(pRec->pKeyInfo);
 1.61311 +    sqlite3DbFree(db, pRec);
 1.61312 +  }
 1.61313 +}
 1.61314 +#endif /* ifdef SQLITE_ENABLE_STAT4 */
 1.61315 +
 1.61316 +/*
 1.61317 +** Change the string value of an sqlite3_value object
 1.61318 +*/
 1.61319 +SQLITE_PRIVATE void sqlite3ValueSetStr(
 1.61320 +  sqlite3_value *v,     /* Value to be set */
 1.61321 +  int n,                /* Length of string z */
 1.61322 +  const void *z,        /* Text of the new string */
 1.61323 +  u8 enc,               /* Encoding to use */
 1.61324 +  void (*xDel)(void*)   /* Destructor for the string */
 1.61325 +){
 1.61326 +  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
 1.61327 +}
 1.61328 +
 1.61329 +/*
 1.61330 +** Free an sqlite3_value object
 1.61331 +*/
 1.61332 +SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
 1.61333 +  if( !v ) return;
 1.61334 +  sqlite3VdbeMemRelease((Mem *)v);
 1.61335 +  sqlite3DbFree(((Mem*)v)->db, v);
 1.61336 +}
 1.61337 +
 1.61338 +/*
 1.61339 +** Return the number of bytes in the sqlite3_value object assuming
 1.61340 +** that it uses the encoding "enc"
 1.61341 +*/
 1.61342 +SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
 1.61343 +  Mem *p = (Mem*)pVal;
 1.61344 +  if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
 1.61345 +    if( p->flags & MEM_Zero ){
 1.61346 +      return p->n + p->u.nZero;
 1.61347 +    }else{
 1.61348 +      return p->n;
 1.61349 +    }
 1.61350 +  }
 1.61351 +  return 0;
 1.61352 +}
 1.61353 +
 1.61354 +/************** End of vdbemem.c *********************************************/
 1.61355 +/************** Begin file vdbeaux.c *****************************************/
 1.61356 +/*
 1.61357 +** 2003 September 6
 1.61358 +**
 1.61359 +** The author disclaims copyright to this source code.  In place of
 1.61360 +** a legal notice, here is a blessing:
 1.61361 +**
 1.61362 +**    May you do good and not evil.
 1.61363 +**    May you find forgiveness for yourself and forgive others.
 1.61364 +**    May you share freely, never taking more than you give.
 1.61365 +**
 1.61366 +*************************************************************************
 1.61367 +** This file contains code used for creating, destroying, and populating
 1.61368 +** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
 1.61369 +** to version 2.8.7, all this code was combined into the vdbe.c source file.
 1.61370 +** But that file was getting too big so this subroutines were split out.
 1.61371 +*/
 1.61372 +
 1.61373 +/*
 1.61374 +** Create a new virtual database engine.
 1.61375 +*/
 1.61376 +SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
 1.61377 +  sqlite3 *db = pParse->db;
 1.61378 +  Vdbe *p;
 1.61379 +  p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
 1.61380 +  if( p==0 ) return 0;
 1.61381 +  p->db = db;
 1.61382 +  if( db->pVdbe ){
 1.61383 +    db->pVdbe->pPrev = p;
 1.61384 +  }
 1.61385 +  p->pNext = db->pVdbe;
 1.61386 +  p->pPrev = 0;
 1.61387 +  db->pVdbe = p;
 1.61388 +  p->magic = VDBE_MAGIC_INIT;
 1.61389 +  p->pParse = pParse;
 1.61390 +  assert( pParse->aLabel==0 );
 1.61391 +  assert( pParse->nLabel==0 );
 1.61392 +  assert( pParse->nOpAlloc==0 );
 1.61393 +  return p;
 1.61394 +}
 1.61395 +
 1.61396 +/*
 1.61397 +** Remember the SQL string for a prepared statement.
 1.61398 +*/
 1.61399 +SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
 1.61400 +  assert( isPrepareV2==1 || isPrepareV2==0 );
 1.61401 +  if( p==0 ) return;
 1.61402 +#if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
 1.61403 +  if( !isPrepareV2 ) return;
 1.61404 +#endif
 1.61405 +  assert( p->zSql==0 );
 1.61406 +  p->zSql = sqlite3DbStrNDup(p->db, z, n);
 1.61407 +  p->isPrepareV2 = (u8)isPrepareV2;
 1.61408 +}
 1.61409 +
 1.61410 +/*
 1.61411 +** Return the SQL associated with a prepared statement
 1.61412 +*/
 1.61413 +SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
 1.61414 +  Vdbe *p = (Vdbe *)pStmt;
 1.61415 +  return (p && p->isPrepareV2) ? p->zSql : 0;
 1.61416 +}
 1.61417 +
 1.61418 +/*
 1.61419 +** Swap all content between two VDBE structures.
 1.61420 +*/
 1.61421 +SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
 1.61422 +  Vdbe tmp, *pTmp;
 1.61423 +  char *zTmp;
 1.61424 +  tmp = *pA;
 1.61425 +  *pA = *pB;
 1.61426 +  *pB = tmp;
 1.61427 +  pTmp = pA->pNext;
 1.61428 +  pA->pNext = pB->pNext;
 1.61429 +  pB->pNext = pTmp;
 1.61430 +  pTmp = pA->pPrev;
 1.61431 +  pA->pPrev = pB->pPrev;
 1.61432 +  pB->pPrev = pTmp;
 1.61433 +  zTmp = pA->zSql;
 1.61434 +  pA->zSql = pB->zSql;
 1.61435 +  pB->zSql = zTmp;
 1.61436 +  pB->isPrepareV2 = pA->isPrepareV2;
 1.61437 +}
 1.61438 +
 1.61439 +/*
 1.61440 +** Resize the Vdbe.aOp array so that it is at least one op larger than 
 1.61441 +** it was.
 1.61442 +**
 1.61443 +** If an out-of-memory error occurs while resizing the array, return
 1.61444 +** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
 1.61445 +** unchanged (this is so that any opcodes already allocated can be 
 1.61446 +** correctly deallocated along with the rest of the Vdbe).
 1.61447 +*/
 1.61448 +static int growOpArray(Vdbe *v){
 1.61449 +  VdbeOp *pNew;
 1.61450 +  Parse *p = v->pParse;
 1.61451 +  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
 1.61452 +  pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
 1.61453 +  if( pNew ){
 1.61454 +    p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
 1.61455 +    v->aOp = pNew;
 1.61456 +  }
 1.61457 +  return (pNew ? SQLITE_OK : SQLITE_NOMEM);
 1.61458 +}
 1.61459 +
 1.61460 +#ifdef SQLITE_DEBUG
 1.61461 +/* This routine is just a convenient place to set a breakpoint that will
 1.61462 +** fire after each opcode is inserted and displayed using
 1.61463 +** "PRAGMA vdbe_addoptrace=on".
 1.61464 +*/
 1.61465 +static void test_addop_breakpoint(void){
 1.61466 +  static int n = 0;
 1.61467 +  n++;
 1.61468 +}
 1.61469 +#endif
 1.61470 +
 1.61471 +/*
 1.61472 +** Add a new instruction to the list of instructions current in the
 1.61473 +** VDBE.  Return the address of the new instruction.
 1.61474 +**
 1.61475 +** Parameters:
 1.61476 +**
 1.61477 +**    p               Pointer to the VDBE
 1.61478 +**
 1.61479 +**    op              The opcode for this instruction
 1.61480 +**
 1.61481 +**    p1, p2, p3      Operands
 1.61482 +**
 1.61483 +** Use the sqlite3VdbeResolveLabel() function to fix an address and
 1.61484 +** the sqlite3VdbeChangeP4() function to change the value of the P4
 1.61485 +** operand.
 1.61486 +*/
 1.61487 +SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
 1.61488 +  int i;
 1.61489 +  VdbeOp *pOp;
 1.61490 +
 1.61491 +  i = p->nOp;
 1.61492 +  assert( p->magic==VDBE_MAGIC_INIT );
 1.61493 +  assert( op>0 && op<0xff );
 1.61494 +  if( p->pParse->nOpAlloc<=i ){
 1.61495 +    if( growOpArray(p) ){
 1.61496 +      return 1;
 1.61497 +    }
 1.61498 +  }
 1.61499 +  p->nOp++;
 1.61500 +  pOp = &p->aOp[i];
 1.61501 +  pOp->opcode = (u8)op;
 1.61502 +  pOp->p5 = 0;
 1.61503 +  pOp->p1 = p1;
 1.61504 +  pOp->p2 = p2;
 1.61505 +  pOp->p3 = p3;
 1.61506 +  pOp->p4.p = 0;
 1.61507 +  pOp->p4type = P4_NOTUSED;
 1.61508 +#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 1.61509 +  pOp->zComment = 0;
 1.61510 +#endif
 1.61511 +#ifdef SQLITE_DEBUG
 1.61512 +  if( p->db->flags & SQLITE_VdbeAddopTrace ){
 1.61513 +    int jj, kk;
 1.61514 +    Parse *pParse = p->pParse;
 1.61515 +    for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
 1.61516 +      struct yColCache *x = pParse->aColCache + jj;
 1.61517 +      if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
 1.61518 +      printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
 1.61519 +      kk++;
 1.61520 +    }
 1.61521 +    if( kk ) printf("\n");
 1.61522 +    sqlite3VdbePrintOp(0, i, &p->aOp[i]);
 1.61523 +    test_addop_breakpoint();
 1.61524 +  }
 1.61525 +#endif
 1.61526 +#ifdef VDBE_PROFILE
 1.61527 +  pOp->cycles = 0;
 1.61528 +  pOp->cnt = 0;
 1.61529 +#endif
 1.61530 +#ifdef SQLITE_VDBE_COVERAGE
 1.61531 +  pOp->iSrcLine = 0;
 1.61532 +#endif
 1.61533 +  return i;
 1.61534 +}
 1.61535 +SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
 1.61536 +  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
 1.61537 +}
 1.61538 +SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
 1.61539 +  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
 1.61540 +}
 1.61541 +SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
 1.61542 +  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
 1.61543 +}
 1.61544 +
 1.61545 +
 1.61546 +/*
 1.61547 +** Add an opcode that includes the p4 value as a pointer.
 1.61548 +*/
 1.61549 +SQLITE_PRIVATE int sqlite3VdbeAddOp4(
 1.61550 +  Vdbe *p,            /* Add the opcode to this VM */
 1.61551 +  int op,             /* The new opcode */
 1.61552 +  int p1,             /* The P1 operand */
 1.61553 +  int p2,             /* The P2 operand */
 1.61554 +  int p3,             /* The P3 operand */
 1.61555 +  const char *zP4,    /* The P4 operand */
 1.61556 +  int p4type          /* P4 operand type */
 1.61557 +){
 1.61558 +  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
 1.61559 +  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
 1.61560 +  return addr;
 1.61561 +}
 1.61562 +
 1.61563 +/*
 1.61564 +** Add an OP_ParseSchema opcode.  This routine is broken out from
 1.61565 +** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
 1.61566 +** as having been used.
 1.61567 +**
 1.61568 +** The zWhere string must have been obtained from sqlite3_malloc().
 1.61569 +** This routine will take ownership of the allocated memory.
 1.61570 +*/
 1.61571 +SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
 1.61572 +  int j;
 1.61573 +  int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
 1.61574 +  sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
 1.61575 +  for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
 1.61576 +}
 1.61577 +
 1.61578 +/*
 1.61579 +** Add an opcode that includes the p4 value as an integer.
 1.61580 +*/
 1.61581 +SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
 1.61582 +  Vdbe *p,            /* Add the opcode to this VM */
 1.61583 +  int op,             /* The new opcode */
 1.61584 +  int p1,             /* The P1 operand */
 1.61585 +  int p2,             /* The P2 operand */
 1.61586 +  int p3,             /* The P3 operand */
 1.61587 +  int p4              /* The P4 operand as an integer */
 1.61588 +){
 1.61589 +  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
 1.61590 +  sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
 1.61591 +  return addr;
 1.61592 +}
 1.61593 +
 1.61594 +/*
 1.61595 +** Create a new symbolic label for an instruction that has yet to be
 1.61596 +** coded.  The symbolic label is really just a negative number.  The
 1.61597 +** label can be used as the P2 value of an operation.  Later, when
 1.61598 +** the label is resolved to a specific address, the VDBE will scan
 1.61599 +** through its operation list and change all values of P2 which match
 1.61600 +** the label into the resolved address.
 1.61601 +**
 1.61602 +** The VDBE knows that a P2 value is a label because labels are
 1.61603 +** always negative and P2 values are suppose to be non-negative.
 1.61604 +** Hence, a negative P2 value is a label that has yet to be resolved.
 1.61605 +**
 1.61606 +** Zero is returned if a malloc() fails.
 1.61607 +*/
 1.61608 +SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
 1.61609 +  Parse *p = v->pParse;
 1.61610 +  int i = p->nLabel++;
 1.61611 +  assert( v->magic==VDBE_MAGIC_INIT );
 1.61612 +  if( (i & (i-1))==0 ){
 1.61613 +    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel, 
 1.61614 +                                       (i*2+1)*sizeof(p->aLabel[0]));
 1.61615 +  }
 1.61616 +  if( p->aLabel ){
 1.61617 +    p->aLabel[i] = -1;
 1.61618 +  }
 1.61619 +  return -1-i;
 1.61620 +}
 1.61621 +
 1.61622 +/*
 1.61623 +** Resolve label "x" to be the address of the next instruction to
 1.61624 +** be inserted.  The parameter "x" must have been obtained from
 1.61625 +** a prior call to sqlite3VdbeMakeLabel().
 1.61626 +*/
 1.61627 +SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
 1.61628 +  Parse *p = v->pParse;
 1.61629 +  int j = -1-x;
 1.61630 +  assert( v->magic==VDBE_MAGIC_INIT );
 1.61631 +  assert( j<p->nLabel );
 1.61632 +  if( j>=0 && p->aLabel ){
 1.61633 +    p->aLabel[j] = v->nOp;
 1.61634 +  }
 1.61635 +  p->iFixedOp = v->nOp - 1;
 1.61636 +}
 1.61637 +
 1.61638 +/*
 1.61639 +** Mark the VDBE as one that can only be run one time.
 1.61640 +*/
 1.61641 +SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
 1.61642 +  p->runOnlyOnce = 1;
 1.61643 +}
 1.61644 +
 1.61645 +#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
 1.61646 +
 1.61647 +/*
 1.61648 +** The following type and function are used to iterate through all opcodes
 1.61649 +** in a Vdbe main program and each of the sub-programs (triggers) it may 
 1.61650 +** invoke directly or indirectly. It should be used as follows:
 1.61651 +**
 1.61652 +**   Op *pOp;
 1.61653 +**   VdbeOpIter sIter;
 1.61654 +**
 1.61655 +**   memset(&sIter, 0, sizeof(sIter));
 1.61656 +**   sIter.v = v;                            // v is of type Vdbe* 
 1.61657 +**   while( (pOp = opIterNext(&sIter)) ){
 1.61658 +**     // Do something with pOp
 1.61659 +**   }
 1.61660 +**   sqlite3DbFree(v->db, sIter.apSub);
 1.61661 +** 
 1.61662 +*/
 1.61663 +typedef struct VdbeOpIter VdbeOpIter;
 1.61664 +struct VdbeOpIter {
 1.61665 +  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
 1.61666 +  SubProgram **apSub;        /* Array of subprograms */
 1.61667 +  int nSub;                  /* Number of entries in apSub */
 1.61668 +  int iAddr;                 /* Address of next instruction to return */
 1.61669 +  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
 1.61670 +};
 1.61671 +static Op *opIterNext(VdbeOpIter *p){
 1.61672 +  Vdbe *v = p->v;
 1.61673 +  Op *pRet = 0;
 1.61674 +  Op *aOp;
 1.61675 +  int nOp;
 1.61676 +
 1.61677 +  if( p->iSub<=p->nSub ){
 1.61678 +
 1.61679 +    if( p->iSub==0 ){
 1.61680 +      aOp = v->aOp;
 1.61681 +      nOp = v->nOp;
 1.61682 +    }else{
 1.61683 +      aOp = p->apSub[p->iSub-1]->aOp;
 1.61684 +      nOp = p->apSub[p->iSub-1]->nOp;
 1.61685 +    }
 1.61686 +    assert( p->iAddr<nOp );
 1.61687 +
 1.61688 +    pRet = &aOp[p->iAddr];
 1.61689 +    p->iAddr++;
 1.61690 +    if( p->iAddr==nOp ){
 1.61691 +      p->iSub++;
 1.61692 +      p->iAddr = 0;
 1.61693 +    }
 1.61694 +  
 1.61695 +    if( pRet->p4type==P4_SUBPROGRAM ){
 1.61696 +      int nByte = (p->nSub+1)*sizeof(SubProgram*);
 1.61697 +      int j;
 1.61698 +      for(j=0; j<p->nSub; j++){
 1.61699 +        if( p->apSub[j]==pRet->p4.pProgram ) break;
 1.61700 +      }
 1.61701 +      if( j==p->nSub ){
 1.61702 +        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
 1.61703 +        if( !p->apSub ){
 1.61704 +          pRet = 0;
 1.61705 +        }else{
 1.61706 +          p->apSub[p->nSub++] = pRet->p4.pProgram;
 1.61707 +        }
 1.61708 +      }
 1.61709 +    }
 1.61710 +  }
 1.61711 +
 1.61712 +  return pRet;
 1.61713 +}
 1.61714 +
 1.61715 +/*
 1.61716 +** Check if the program stored in the VM associated with pParse may
 1.61717 +** throw an ABORT exception (causing the statement, but not entire transaction
 1.61718 +** to be rolled back). This condition is true if the main program or any
 1.61719 +** sub-programs contains any of the following:
 1.61720 +**
 1.61721 +**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
 1.61722 +**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
 1.61723 +**   *  OP_Destroy
 1.61724 +**   *  OP_VUpdate
 1.61725 +**   *  OP_VRename
 1.61726 +**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
 1.61727 +**
 1.61728 +** Then check that the value of Parse.mayAbort is true if an
 1.61729 +** ABORT may be thrown, or false otherwise. Return true if it does
 1.61730 +** match, or false otherwise. This function is intended to be used as
 1.61731 +** part of an assert statement in the compiler. Similar to:
 1.61732 +**
 1.61733 +**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
 1.61734 +*/
 1.61735 +SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
 1.61736 +  int hasAbort = 0;
 1.61737 +  Op *pOp;
 1.61738 +  VdbeOpIter sIter;
 1.61739 +  memset(&sIter, 0, sizeof(sIter));
 1.61740 +  sIter.v = v;
 1.61741 +
 1.61742 +  while( (pOp = opIterNext(&sIter))!=0 ){
 1.61743 +    int opcode = pOp->opcode;
 1.61744 +    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
 1.61745 +#ifndef SQLITE_OMIT_FOREIGN_KEY
 1.61746 +     || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) 
 1.61747 +#endif
 1.61748 +     || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
 1.61749 +      && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
 1.61750 +    ){
 1.61751 +      hasAbort = 1;
 1.61752 +      break;
 1.61753 +    }
 1.61754 +  }
 1.61755 +  sqlite3DbFree(v->db, sIter.apSub);
 1.61756 +
 1.61757 +  /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
 1.61758 +  ** If malloc failed, then the while() loop above may not have iterated
 1.61759 +  ** through all opcodes and hasAbort may be set incorrectly. Return
 1.61760 +  ** true for this case to prevent the assert() in the callers frame
 1.61761 +  ** from failing.  */
 1.61762 +  return ( v->db->mallocFailed || hasAbort==mayAbort );
 1.61763 +}
 1.61764 +#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
 1.61765 +
 1.61766 +/*
 1.61767 +** Loop through the program looking for P2 values that are negative
 1.61768 +** on jump instructions.  Each such value is a label.  Resolve the
 1.61769 +** label by setting the P2 value to its correct non-zero value.
 1.61770 +**
 1.61771 +** This routine is called once after all opcodes have been inserted.
 1.61772 +**
 1.61773 +** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
 1.61774 +** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
 1.61775 +** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
 1.61776 +**
 1.61777 +** The Op.opflags field is set on all opcodes.
 1.61778 +*/
 1.61779 +static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
 1.61780 +  int i;
 1.61781 +  int nMaxArgs = *pMaxFuncArgs;
 1.61782 +  Op *pOp;
 1.61783 +  Parse *pParse = p->pParse;
 1.61784 +  int *aLabel = pParse->aLabel;
 1.61785 +  p->readOnly = 1;
 1.61786 +  p->bIsReader = 0;
 1.61787 +  for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
 1.61788 +    u8 opcode = pOp->opcode;
 1.61789 +
 1.61790 +    /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
 1.61791 +    ** cases from this switch! */
 1.61792 +    switch( opcode ){
 1.61793 +      case OP_Function:
 1.61794 +      case OP_AggStep: {
 1.61795 +        if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
 1.61796 +        break;
 1.61797 +      }
 1.61798 +      case OP_Transaction: {
 1.61799 +        if( pOp->p2!=0 ) p->readOnly = 0;
 1.61800 +        /* fall thru */
 1.61801 +      }
 1.61802 +      case OP_AutoCommit:
 1.61803 +      case OP_Savepoint: {
 1.61804 +        p->bIsReader = 1;
 1.61805 +        break;
 1.61806 +      }
 1.61807 +#ifndef SQLITE_OMIT_WAL
 1.61808 +      case OP_Checkpoint:
 1.61809 +#endif
 1.61810 +      case OP_Vacuum:
 1.61811 +      case OP_JournalMode: {
 1.61812 +        p->readOnly = 0;
 1.61813 +        p->bIsReader = 1;
 1.61814 +        break;
 1.61815 +      }
 1.61816 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.61817 +      case OP_VUpdate: {
 1.61818 +        if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
 1.61819 +        break;
 1.61820 +      }
 1.61821 +      case OP_VFilter: {
 1.61822 +        int n;
 1.61823 +        assert( p->nOp - i >= 3 );
 1.61824 +        assert( pOp[-1].opcode==OP_Integer );
 1.61825 +        n = pOp[-1].p1;
 1.61826 +        if( n>nMaxArgs ) nMaxArgs = n;
 1.61827 +        break;
 1.61828 +      }
 1.61829 +#endif
 1.61830 +      case OP_Next:
 1.61831 +      case OP_NextIfOpen:
 1.61832 +      case OP_SorterNext: {
 1.61833 +        pOp->p4.xAdvance = sqlite3BtreeNext;
 1.61834 +        pOp->p4type = P4_ADVANCE;
 1.61835 +        break;
 1.61836 +      }
 1.61837 +      case OP_Prev:
 1.61838 +      case OP_PrevIfOpen: {
 1.61839 +        pOp->p4.xAdvance = sqlite3BtreePrevious;
 1.61840 +        pOp->p4type = P4_ADVANCE;
 1.61841 +        break;
 1.61842 +      }
 1.61843 +    }
 1.61844 +
 1.61845 +    pOp->opflags = sqlite3OpcodeProperty[opcode];
 1.61846 +    if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
 1.61847 +      assert( -1-pOp->p2<pParse->nLabel );
 1.61848 +      pOp->p2 = aLabel[-1-pOp->p2];
 1.61849 +    }
 1.61850 +  }
 1.61851 +  sqlite3DbFree(p->db, pParse->aLabel);
 1.61852 +  pParse->aLabel = 0;
 1.61853 +  pParse->nLabel = 0;
 1.61854 +  *pMaxFuncArgs = nMaxArgs;
 1.61855 +  assert( p->bIsReader!=0 || p->btreeMask==0 );
 1.61856 +}
 1.61857 +
 1.61858 +/*
 1.61859 +** Return the address of the next instruction to be inserted.
 1.61860 +*/
 1.61861 +SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
 1.61862 +  assert( p->magic==VDBE_MAGIC_INIT );
 1.61863 +  return p->nOp;
 1.61864 +}
 1.61865 +
 1.61866 +/*
 1.61867 +** This function returns a pointer to the array of opcodes associated with
 1.61868 +** the Vdbe passed as the first argument. It is the callers responsibility
 1.61869 +** to arrange for the returned array to be eventually freed using the 
 1.61870 +** vdbeFreeOpArray() function.
 1.61871 +**
 1.61872 +** Before returning, *pnOp is set to the number of entries in the returned
 1.61873 +** array. Also, *pnMaxArg is set to the larger of its current value and 
 1.61874 +** the number of entries in the Vdbe.apArg[] array required to execute the 
 1.61875 +** returned program.
 1.61876 +*/
 1.61877 +SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
 1.61878 +  VdbeOp *aOp = p->aOp;
 1.61879 +  assert( aOp && !p->db->mallocFailed );
 1.61880 +
 1.61881 +  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
 1.61882 +  assert( p->btreeMask==0 );
 1.61883 +
 1.61884 +  resolveP2Values(p, pnMaxArg);
 1.61885 +  *pnOp = p->nOp;
 1.61886 +  p->aOp = 0;
 1.61887 +  return aOp;
 1.61888 +}
 1.61889 +
 1.61890 +/*
 1.61891 +** Add a whole list of operations to the operation stack.  Return the
 1.61892 +** address of the first operation added.
 1.61893 +*/
 1.61894 +SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
 1.61895 +  int addr;
 1.61896 +  assert( p->magic==VDBE_MAGIC_INIT );
 1.61897 +  if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p) ){
 1.61898 +    return 0;
 1.61899 +  }
 1.61900 +  addr = p->nOp;
 1.61901 +  if( ALWAYS(nOp>0) ){
 1.61902 +    int i;
 1.61903 +    VdbeOpList const *pIn = aOp;
 1.61904 +    for(i=0; i<nOp; i++, pIn++){
 1.61905 +      int p2 = pIn->p2;
 1.61906 +      VdbeOp *pOut = &p->aOp[i+addr];
 1.61907 +      pOut->opcode = pIn->opcode;
 1.61908 +      pOut->p1 = pIn->p1;
 1.61909 +      if( p2<0 ){
 1.61910 +        assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
 1.61911 +        pOut->p2 = addr + ADDR(p2);
 1.61912 +      }else{
 1.61913 +        pOut->p2 = p2;
 1.61914 +      }
 1.61915 +      pOut->p3 = pIn->p3;
 1.61916 +      pOut->p4type = P4_NOTUSED;
 1.61917 +      pOut->p4.p = 0;
 1.61918 +      pOut->p5 = 0;
 1.61919 +#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 1.61920 +      pOut->zComment = 0;
 1.61921 +#endif
 1.61922 +#ifdef SQLITE_VDBE_COVERAGE
 1.61923 +      pOut->iSrcLine = iLineno+i;
 1.61924 +#else
 1.61925 +      (void)iLineno;
 1.61926 +#endif
 1.61927 +#ifdef SQLITE_DEBUG
 1.61928 +      if( p->db->flags & SQLITE_VdbeAddopTrace ){
 1.61929 +        sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
 1.61930 +      }
 1.61931 +#endif
 1.61932 +    }
 1.61933 +    p->nOp += nOp;
 1.61934 +  }
 1.61935 +  return addr;
 1.61936 +}
 1.61937 +
 1.61938 +/*
 1.61939 +** Change the value of the P1 operand for a specific instruction.
 1.61940 +** This routine is useful when a large program is loaded from a
 1.61941 +** static array using sqlite3VdbeAddOpList but we want to make a
 1.61942 +** few minor changes to the program.
 1.61943 +*/
 1.61944 +SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
 1.61945 +  assert( p!=0 );
 1.61946 +  if( ((u32)p->nOp)>addr ){
 1.61947 +    p->aOp[addr].p1 = val;
 1.61948 +  }
 1.61949 +}
 1.61950 +
 1.61951 +/*
 1.61952 +** Change the value of the P2 operand for a specific instruction.
 1.61953 +** This routine is useful for setting a jump destination.
 1.61954 +*/
 1.61955 +SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
 1.61956 +  assert( p!=0 );
 1.61957 +  if( ((u32)p->nOp)>addr ){
 1.61958 +    p->aOp[addr].p2 = val;
 1.61959 +  }
 1.61960 +}
 1.61961 +
 1.61962 +/*
 1.61963 +** Change the value of the P3 operand for a specific instruction.
 1.61964 +*/
 1.61965 +SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
 1.61966 +  assert( p!=0 );
 1.61967 +  if( ((u32)p->nOp)>addr ){
 1.61968 +    p->aOp[addr].p3 = val;
 1.61969 +  }
 1.61970 +}
 1.61971 +
 1.61972 +/*
 1.61973 +** Change the value of the P5 operand for the most recently
 1.61974 +** added operation.
 1.61975 +*/
 1.61976 +SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
 1.61977 +  assert( p!=0 );
 1.61978 +  if( p->aOp ){
 1.61979 +    assert( p->nOp>0 );
 1.61980 +    p->aOp[p->nOp-1].p5 = val;
 1.61981 +  }
 1.61982 +}
 1.61983 +
 1.61984 +/*
 1.61985 +** Change the P2 operand of instruction addr so that it points to
 1.61986 +** the address of the next instruction to be coded.
 1.61987 +*/
 1.61988 +SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
 1.61989 +  sqlite3VdbeChangeP2(p, addr, p->nOp);
 1.61990 +  p->pParse->iFixedOp = p->nOp - 1;
 1.61991 +}
 1.61992 +
 1.61993 +
 1.61994 +/*
 1.61995 +** If the input FuncDef structure is ephemeral, then free it.  If
 1.61996 +** the FuncDef is not ephermal, then do nothing.
 1.61997 +*/
 1.61998 +static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
 1.61999 +  if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
 1.62000 +    sqlite3DbFree(db, pDef);
 1.62001 +  }
 1.62002 +}
 1.62003 +
 1.62004 +static void vdbeFreeOpArray(sqlite3 *, Op *, int);
 1.62005 +
 1.62006 +/*
 1.62007 +** Delete a P4 value if necessary.
 1.62008 +*/
 1.62009 +static void freeP4(sqlite3 *db, int p4type, void *p4){
 1.62010 +  if( p4 ){
 1.62011 +    assert( db );
 1.62012 +    switch( p4type ){
 1.62013 +      case P4_REAL:
 1.62014 +      case P4_INT64:
 1.62015 +      case P4_DYNAMIC:
 1.62016 +      case P4_INTARRAY: {
 1.62017 +        sqlite3DbFree(db, p4);
 1.62018 +        break;
 1.62019 +      }
 1.62020 +      case P4_KEYINFO: {
 1.62021 +        if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
 1.62022 +        break;
 1.62023 +      }
 1.62024 +      case P4_MPRINTF: {
 1.62025 +        if( db->pnBytesFreed==0 ) sqlite3_free(p4);
 1.62026 +        break;
 1.62027 +      }
 1.62028 +      case P4_FUNCDEF: {
 1.62029 +        freeEphemeralFunction(db, (FuncDef*)p4);
 1.62030 +        break;
 1.62031 +      }
 1.62032 +      case P4_MEM: {
 1.62033 +        if( db->pnBytesFreed==0 ){
 1.62034 +          sqlite3ValueFree((sqlite3_value*)p4);
 1.62035 +        }else{
 1.62036 +          Mem *p = (Mem*)p4;
 1.62037 +          sqlite3DbFree(db, p->zMalloc);
 1.62038 +          sqlite3DbFree(db, p);
 1.62039 +        }
 1.62040 +        break;
 1.62041 +      }
 1.62042 +      case P4_VTAB : {
 1.62043 +        if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
 1.62044 +        break;
 1.62045 +      }
 1.62046 +    }
 1.62047 +  }
 1.62048 +}
 1.62049 +
 1.62050 +/*
 1.62051 +** Free the space allocated for aOp and any p4 values allocated for the
 1.62052 +** opcodes contained within. If aOp is not NULL it is assumed to contain 
 1.62053 +** nOp entries. 
 1.62054 +*/
 1.62055 +static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
 1.62056 +  if( aOp ){
 1.62057 +    Op *pOp;
 1.62058 +    for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
 1.62059 +      freeP4(db, pOp->p4type, pOp->p4.p);
 1.62060 +#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 1.62061 +      sqlite3DbFree(db, pOp->zComment);
 1.62062 +#endif     
 1.62063 +    }
 1.62064 +  }
 1.62065 +  sqlite3DbFree(db, aOp);
 1.62066 +}
 1.62067 +
 1.62068 +/*
 1.62069 +** Link the SubProgram object passed as the second argument into the linked
 1.62070 +** list at Vdbe.pSubProgram. This list is used to delete all sub-program
 1.62071 +** objects when the VM is no longer required.
 1.62072 +*/
 1.62073 +SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
 1.62074 +  p->pNext = pVdbe->pProgram;
 1.62075 +  pVdbe->pProgram = p;
 1.62076 +}
 1.62077 +
 1.62078 +/*
 1.62079 +** Change the opcode at addr into OP_Noop
 1.62080 +*/
 1.62081 +SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
 1.62082 +  if( p->aOp ){
 1.62083 +    VdbeOp *pOp = &p->aOp[addr];
 1.62084 +    sqlite3 *db = p->db;
 1.62085 +    freeP4(db, pOp->p4type, pOp->p4.p);
 1.62086 +    memset(pOp, 0, sizeof(pOp[0]));
 1.62087 +    pOp->opcode = OP_Noop;
 1.62088 +    if( addr==p->nOp-1 ) p->nOp--;
 1.62089 +  }
 1.62090 +}
 1.62091 +
 1.62092 +/*
 1.62093 +** Remove the last opcode inserted
 1.62094 +*/
 1.62095 +SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
 1.62096 +  if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
 1.62097 +    sqlite3VdbeChangeToNoop(p, p->nOp-1);
 1.62098 +    return 1;
 1.62099 +  }else{
 1.62100 +    return 0;
 1.62101 +  }
 1.62102 +}
 1.62103 +
 1.62104 +/*
 1.62105 +** Change the value of the P4 operand for a specific instruction.
 1.62106 +** This routine is useful when a large program is loaded from a
 1.62107 +** static array using sqlite3VdbeAddOpList but we want to make a
 1.62108 +** few minor changes to the program.
 1.62109 +**
 1.62110 +** If n>=0 then the P4 operand is dynamic, meaning that a copy of
 1.62111 +** the string is made into memory obtained from sqlite3_malloc().
 1.62112 +** A value of n==0 means copy bytes of zP4 up to and including the
 1.62113 +** first null byte.  If n>0 then copy n+1 bytes of zP4.
 1.62114 +** 
 1.62115 +** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
 1.62116 +** to a string or structure that is guaranteed to exist for the lifetime of
 1.62117 +** the Vdbe. In these cases we can just copy the pointer.
 1.62118 +**
 1.62119 +** If addr<0 then change P4 on the most recently inserted instruction.
 1.62120 +*/
 1.62121 +SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
 1.62122 +  Op *pOp;
 1.62123 +  sqlite3 *db;
 1.62124 +  assert( p!=0 );
 1.62125 +  db = p->db;
 1.62126 +  assert( p->magic==VDBE_MAGIC_INIT );
 1.62127 +  if( p->aOp==0 || db->mallocFailed ){
 1.62128 +    if( n!=P4_VTAB ){
 1.62129 +      freeP4(db, n, (void*)*(char**)&zP4);
 1.62130 +    }
 1.62131 +    return;
 1.62132 +  }
 1.62133 +  assert( p->nOp>0 );
 1.62134 +  assert( addr<p->nOp );
 1.62135 +  if( addr<0 ){
 1.62136 +    addr = p->nOp - 1;
 1.62137 +  }
 1.62138 +  pOp = &p->aOp[addr];
 1.62139 +  assert( pOp->p4type==P4_NOTUSED || pOp->p4type==P4_INT32 );
 1.62140 +  freeP4(db, pOp->p4type, pOp->p4.p);
 1.62141 +  pOp->p4.p = 0;
 1.62142 +  if( n==P4_INT32 ){
 1.62143 +    /* Note: this cast is safe, because the origin data point was an int
 1.62144 +    ** that was cast to a (const char *). */
 1.62145 +    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
 1.62146 +    pOp->p4type = P4_INT32;
 1.62147 +  }else if( zP4==0 ){
 1.62148 +    pOp->p4.p = 0;
 1.62149 +    pOp->p4type = P4_NOTUSED;
 1.62150 +  }else if( n==P4_KEYINFO ){
 1.62151 +    pOp->p4.p = (void*)zP4;
 1.62152 +    pOp->p4type = P4_KEYINFO;
 1.62153 +  }else if( n==P4_VTAB ){
 1.62154 +    pOp->p4.p = (void*)zP4;
 1.62155 +    pOp->p4type = P4_VTAB;
 1.62156 +    sqlite3VtabLock((VTable *)zP4);
 1.62157 +    assert( ((VTable *)zP4)->db==p->db );
 1.62158 +  }else if( n<0 ){
 1.62159 +    pOp->p4.p = (void*)zP4;
 1.62160 +    pOp->p4type = (signed char)n;
 1.62161 +  }else{
 1.62162 +    if( n==0 ) n = sqlite3Strlen30(zP4);
 1.62163 +    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
 1.62164 +    pOp->p4type = P4_DYNAMIC;
 1.62165 +  }
 1.62166 +}
 1.62167 +
 1.62168 +/*
 1.62169 +** Set the P4 on the most recently added opcode to the KeyInfo for the
 1.62170 +** index given.
 1.62171 +*/
 1.62172 +SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
 1.62173 +  Vdbe *v = pParse->pVdbe;
 1.62174 +  assert( v!=0 );
 1.62175 +  assert( pIdx!=0 );
 1.62176 +  sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
 1.62177 +                      P4_KEYINFO);
 1.62178 +}
 1.62179 +
 1.62180 +#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 1.62181 +/*
 1.62182 +** Change the comment on the most recently coded instruction.  Or
 1.62183 +** insert a No-op and add the comment to that new instruction.  This
 1.62184 +** makes the code easier to read during debugging.  None of this happens
 1.62185 +** in a production build.
 1.62186 +*/
 1.62187 +static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
 1.62188 +  assert( p->nOp>0 || p->aOp==0 );
 1.62189 +  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
 1.62190 +  if( p->nOp ){
 1.62191 +    assert( p->aOp );
 1.62192 +    sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
 1.62193 +    p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
 1.62194 +  }
 1.62195 +}
 1.62196 +SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
 1.62197 +  va_list ap;
 1.62198 +  if( p ){
 1.62199 +    va_start(ap, zFormat);
 1.62200 +    vdbeVComment(p, zFormat, ap);
 1.62201 +    va_end(ap);
 1.62202 +  }
 1.62203 +}
 1.62204 +SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
 1.62205 +  va_list ap;
 1.62206 +  if( p ){
 1.62207 +    sqlite3VdbeAddOp0(p, OP_Noop);
 1.62208 +    va_start(ap, zFormat);
 1.62209 +    vdbeVComment(p, zFormat, ap);
 1.62210 +    va_end(ap);
 1.62211 +  }
 1.62212 +}
 1.62213 +#endif  /* NDEBUG */
 1.62214 +
 1.62215 +#ifdef SQLITE_VDBE_COVERAGE
 1.62216 +/*
 1.62217 +** Set the value if the iSrcLine field for the previously coded instruction.
 1.62218 +*/
 1.62219 +SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
 1.62220 +  sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
 1.62221 +}
 1.62222 +#endif /* SQLITE_VDBE_COVERAGE */
 1.62223 +
 1.62224 +/*
 1.62225 +** Return the opcode for a given address.  If the address is -1, then
 1.62226 +** return the most recently inserted opcode.
 1.62227 +**
 1.62228 +** If a memory allocation error has occurred prior to the calling of this
 1.62229 +** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
 1.62230 +** is readable but not writable, though it is cast to a writable value.
 1.62231 +** The return of a dummy opcode allows the call to continue functioning
 1.62232 +** after a OOM fault without having to check to see if the return from 
 1.62233 +** this routine is a valid pointer.  But because the dummy.opcode is 0,
 1.62234 +** dummy will never be written to.  This is verified by code inspection and
 1.62235 +** by running with Valgrind.
 1.62236 +*/
 1.62237 +SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
 1.62238 +  /* C89 specifies that the constant "dummy" will be initialized to all
 1.62239 +  ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
 1.62240 +  static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
 1.62241 +  assert( p->magic==VDBE_MAGIC_INIT );
 1.62242 +  if( addr<0 ){
 1.62243 +    addr = p->nOp - 1;
 1.62244 +  }
 1.62245 +  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
 1.62246 +  if( p->db->mallocFailed ){
 1.62247 +    return (VdbeOp*)&dummy;
 1.62248 +  }else{
 1.62249 +    return &p->aOp[addr];
 1.62250 +  }
 1.62251 +}
 1.62252 +
 1.62253 +#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
 1.62254 +/*
 1.62255 +** Return an integer value for one of the parameters to the opcode pOp
 1.62256 +** determined by character c.
 1.62257 +*/
 1.62258 +static int translateP(char c, const Op *pOp){
 1.62259 +  if( c=='1' ) return pOp->p1;
 1.62260 +  if( c=='2' ) return pOp->p2;
 1.62261 +  if( c=='3' ) return pOp->p3;
 1.62262 +  if( c=='4' ) return pOp->p4.i;
 1.62263 +  return pOp->p5;
 1.62264 +}
 1.62265 +
 1.62266 +/*
 1.62267 +** Compute a string for the "comment" field of a VDBE opcode listing.
 1.62268 +**
 1.62269 +** The Synopsis: field in comments in the vdbe.c source file gets converted
 1.62270 +** to an extra string that is appended to the sqlite3OpcodeName().  In the
 1.62271 +** absence of other comments, this synopsis becomes the comment on the opcode.
 1.62272 +** Some translation occurs:
 1.62273 +**
 1.62274 +**       "PX"      ->  "r[X]"
 1.62275 +**       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
 1.62276 +**       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
 1.62277 +**       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
 1.62278 +*/
 1.62279 +static int displayComment(
 1.62280 +  const Op *pOp,     /* The opcode to be commented */
 1.62281 +  const char *zP4,   /* Previously obtained value for P4 */
 1.62282 +  char *zTemp,       /* Write result here */
 1.62283 +  int nTemp          /* Space available in zTemp[] */
 1.62284 +){
 1.62285 +  const char *zOpName;
 1.62286 +  const char *zSynopsis;
 1.62287 +  int nOpName;
 1.62288 +  int ii, jj;
 1.62289 +  zOpName = sqlite3OpcodeName(pOp->opcode);
 1.62290 +  nOpName = sqlite3Strlen30(zOpName);
 1.62291 +  if( zOpName[nOpName+1] ){
 1.62292 +    int seenCom = 0;
 1.62293 +    char c;
 1.62294 +    zSynopsis = zOpName += nOpName + 1;
 1.62295 +    for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
 1.62296 +      if( c=='P' ){
 1.62297 +        c = zSynopsis[++ii];
 1.62298 +        if( c=='4' ){
 1.62299 +          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
 1.62300 +        }else if( c=='X' ){
 1.62301 +          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
 1.62302 +          seenCom = 1;
 1.62303 +        }else{
 1.62304 +          int v1 = translateP(c, pOp);
 1.62305 +          int v2;
 1.62306 +          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
 1.62307 +          if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
 1.62308 +            ii += 3;
 1.62309 +            jj += sqlite3Strlen30(zTemp+jj);
 1.62310 +            v2 = translateP(zSynopsis[ii], pOp);
 1.62311 +            if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
 1.62312 +              ii += 2;
 1.62313 +              v2++;
 1.62314 +            }
 1.62315 +            if( v2>1 ){
 1.62316 +              sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
 1.62317 +            }
 1.62318 +          }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
 1.62319 +            ii += 4;
 1.62320 +          }
 1.62321 +        }
 1.62322 +        jj += sqlite3Strlen30(zTemp+jj);
 1.62323 +      }else{
 1.62324 +        zTemp[jj++] = c;
 1.62325 +      }
 1.62326 +    }
 1.62327 +    if( !seenCom && jj<nTemp-5 && pOp->zComment ){
 1.62328 +      sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
 1.62329 +      jj += sqlite3Strlen30(zTemp+jj);
 1.62330 +    }
 1.62331 +    if( jj<nTemp ) zTemp[jj] = 0;
 1.62332 +  }else if( pOp->zComment ){
 1.62333 +    sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
 1.62334 +    jj = sqlite3Strlen30(zTemp);
 1.62335 +  }else{
 1.62336 +    zTemp[0] = 0;
 1.62337 +    jj = 0;
 1.62338 +  }
 1.62339 +  return jj;
 1.62340 +}
 1.62341 +#endif /* SQLITE_DEBUG */
 1.62342 +
 1.62343 +
 1.62344 +#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
 1.62345 +     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
 1.62346 +/*
 1.62347 +** Compute a string that describes the P4 parameter for an opcode.
 1.62348 +** Use zTemp for any required temporary buffer space.
 1.62349 +*/
 1.62350 +static char *displayP4(Op *pOp, char *zTemp, int nTemp){
 1.62351 +  char *zP4 = zTemp;
 1.62352 +  assert( nTemp>=20 );
 1.62353 +  switch( pOp->p4type ){
 1.62354 +    case P4_KEYINFO: {
 1.62355 +      int i, j;
 1.62356 +      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
 1.62357 +      assert( pKeyInfo->aSortOrder!=0 );
 1.62358 +      sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
 1.62359 +      i = sqlite3Strlen30(zTemp);
 1.62360 +      for(j=0; j<pKeyInfo->nField; j++){
 1.62361 +        CollSeq *pColl = pKeyInfo->aColl[j];
 1.62362 +        const char *zColl = pColl ? pColl->zName : "nil";
 1.62363 +        int n = sqlite3Strlen30(zColl);
 1.62364 +        if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
 1.62365 +          zColl = "B";
 1.62366 +          n = 1;
 1.62367 +        }
 1.62368 +        if( i+n>nTemp-6 ){
 1.62369 +          memcpy(&zTemp[i],",...",4);
 1.62370 +          break;
 1.62371 +        }
 1.62372 +        zTemp[i++] = ',';
 1.62373 +        if( pKeyInfo->aSortOrder[j] ){
 1.62374 +          zTemp[i++] = '-';
 1.62375 +        }
 1.62376 +        memcpy(&zTemp[i], zColl, n+1);
 1.62377 +        i += n;
 1.62378 +      }
 1.62379 +      zTemp[i++] = ')';
 1.62380 +      zTemp[i] = 0;
 1.62381 +      assert( i<nTemp );
 1.62382 +      break;
 1.62383 +    }
 1.62384 +    case P4_COLLSEQ: {
 1.62385 +      CollSeq *pColl = pOp->p4.pColl;
 1.62386 +      sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
 1.62387 +      break;
 1.62388 +    }
 1.62389 +    case P4_FUNCDEF: {
 1.62390 +      FuncDef *pDef = pOp->p4.pFunc;
 1.62391 +      sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
 1.62392 +      break;
 1.62393 +    }
 1.62394 +    case P4_INT64: {
 1.62395 +      sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
 1.62396 +      break;
 1.62397 +    }
 1.62398 +    case P4_INT32: {
 1.62399 +      sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
 1.62400 +      break;
 1.62401 +    }
 1.62402 +    case P4_REAL: {
 1.62403 +      sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
 1.62404 +      break;
 1.62405 +    }
 1.62406 +    case P4_MEM: {
 1.62407 +      Mem *pMem = pOp->p4.pMem;
 1.62408 +      if( pMem->flags & MEM_Str ){
 1.62409 +        zP4 = pMem->z;
 1.62410 +      }else if( pMem->flags & MEM_Int ){
 1.62411 +        sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
 1.62412 +      }else if( pMem->flags & MEM_Real ){
 1.62413 +        sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
 1.62414 +      }else if( pMem->flags & MEM_Null ){
 1.62415 +        sqlite3_snprintf(nTemp, zTemp, "NULL");
 1.62416 +      }else{
 1.62417 +        assert( pMem->flags & MEM_Blob );
 1.62418 +        zP4 = "(blob)";
 1.62419 +      }
 1.62420 +      break;
 1.62421 +    }
 1.62422 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.62423 +    case P4_VTAB: {
 1.62424 +      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
 1.62425 +      sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
 1.62426 +      break;
 1.62427 +    }
 1.62428 +#endif
 1.62429 +    case P4_INTARRAY: {
 1.62430 +      sqlite3_snprintf(nTemp, zTemp, "intarray");
 1.62431 +      break;
 1.62432 +    }
 1.62433 +    case P4_SUBPROGRAM: {
 1.62434 +      sqlite3_snprintf(nTemp, zTemp, "program");
 1.62435 +      break;
 1.62436 +    }
 1.62437 +    case P4_ADVANCE: {
 1.62438 +      zTemp[0] = 0;
 1.62439 +      break;
 1.62440 +    }
 1.62441 +    default: {
 1.62442 +      zP4 = pOp->p4.z;
 1.62443 +      if( zP4==0 ){
 1.62444 +        zP4 = zTemp;
 1.62445 +        zTemp[0] = 0;
 1.62446 +      }
 1.62447 +    }
 1.62448 +  }
 1.62449 +  assert( zP4!=0 );
 1.62450 +  return zP4;
 1.62451 +}
 1.62452 +#endif
 1.62453 +
 1.62454 +/*
 1.62455 +** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
 1.62456 +**
 1.62457 +** The prepared statements need to know in advance the complete set of
 1.62458 +** attached databases that will be use.  A mask of these databases
 1.62459 +** is maintained in p->btreeMask.  The p->lockMask value is the subset of
 1.62460 +** p->btreeMask of databases that will require a lock.
 1.62461 +*/
 1.62462 +SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
 1.62463 +  assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
 1.62464 +  assert( i<(int)sizeof(p->btreeMask)*8 );
 1.62465 +  p->btreeMask |= ((yDbMask)1)<<i;
 1.62466 +  if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
 1.62467 +    p->lockMask |= ((yDbMask)1)<<i;
 1.62468 +  }
 1.62469 +}
 1.62470 +
 1.62471 +#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
 1.62472 +/*
 1.62473 +** If SQLite is compiled to support shared-cache mode and to be threadsafe,
 1.62474 +** this routine obtains the mutex associated with each BtShared structure
 1.62475 +** that may be accessed by the VM passed as an argument. In doing so it also
 1.62476 +** sets the BtShared.db member of each of the BtShared structures, ensuring
 1.62477 +** that the correct busy-handler callback is invoked if required.
 1.62478 +**
 1.62479 +** If SQLite is not threadsafe but does support shared-cache mode, then
 1.62480 +** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
 1.62481 +** of all of BtShared structures accessible via the database handle 
 1.62482 +** associated with the VM.
 1.62483 +**
 1.62484 +** If SQLite is not threadsafe and does not support shared-cache mode, this
 1.62485 +** function is a no-op.
 1.62486 +**
 1.62487 +** The p->btreeMask field is a bitmask of all btrees that the prepared 
 1.62488 +** statement p will ever use.  Let N be the number of bits in p->btreeMask
 1.62489 +** corresponding to btrees that use shared cache.  Then the runtime of
 1.62490 +** this routine is N*N.  But as N is rarely more than 1, this should not
 1.62491 +** be a problem.
 1.62492 +*/
 1.62493 +SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
 1.62494 +  int i;
 1.62495 +  yDbMask mask;
 1.62496 +  sqlite3 *db;
 1.62497 +  Db *aDb;
 1.62498 +  int nDb;
 1.62499 +  if( p->lockMask==0 ) return;  /* The common case */
 1.62500 +  db = p->db;
 1.62501 +  aDb = db->aDb;
 1.62502 +  nDb = db->nDb;
 1.62503 +  for(i=0, mask=1; i<nDb; i++, mask += mask){
 1.62504 +    if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
 1.62505 +      sqlite3BtreeEnter(aDb[i].pBt);
 1.62506 +    }
 1.62507 +  }
 1.62508 +}
 1.62509 +#endif
 1.62510 +
 1.62511 +#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
 1.62512 +/*
 1.62513 +** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
 1.62514 +*/
 1.62515 +SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
 1.62516 +  int i;
 1.62517 +  yDbMask mask;
 1.62518 +  sqlite3 *db;
 1.62519 +  Db *aDb;
 1.62520 +  int nDb;
 1.62521 +  if( p->lockMask==0 ) return;  /* The common case */
 1.62522 +  db = p->db;
 1.62523 +  aDb = db->aDb;
 1.62524 +  nDb = db->nDb;
 1.62525 +  for(i=0, mask=1; i<nDb; i++, mask += mask){
 1.62526 +    if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
 1.62527 +      sqlite3BtreeLeave(aDb[i].pBt);
 1.62528 +    }
 1.62529 +  }
 1.62530 +}
 1.62531 +#endif
 1.62532 +
 1.62533 +#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
 1.62534 +/*
 1.62535 +** Print a single opcode.  This routine is used for debugging only.
 1.62536 +*/
 1.62537 +SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
 1.62538 +  char *zP4;
 1.62539 +  char zPtr[50];
 1.62540 +  char zCom[100];
 1.62541 +  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
 1.62542 +  if( pOut==0 ) pOut = stdout;
 1.62543 +  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
 1.62544 +#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 1.62545 +  displayComment(pOp, zP4, zCom, sizeof(zCom));
 1.62546 +#else
 1.62547 +  zCom[0] = 0;
 1.62548 +#endif
 1.62549 +  /* NB:  The sqlite3OpcodeName() function is implemented by code created
 1.62550 +  ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
 1.62551 +  ** information from the vdbe.c source text */
 1.62552 +  fprintf(pOut, zFormat1, pc, 
 1.62553 +      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
 1.62554 +      zCom
 1.62555 +  );
 1.62556 +  fflush(pOut);
 1.62557 +}
 1.62558 +#endif
 1.62559 +
 1.62560 +/*
 1.62561 +** Release an array of N Mem elements
 1.62562 +*/
 1.62563 +static void releaseMemArray(Mem *p, int N){
 1.62564 +  if( p && N ){
 1.62565 +    Mem *pEnd;
 1.62566 +    sqlite3 *db = p->db;
 1.62567 +    u8 malloc_failed = db->mallocFailed;
 1.62568 +    if( db->pnBytesFreed ){
 1.62569 +      for(pEnd=&p[N]; p<pEnd; p++){
 1.62570 +        sqlite3DbFree(db, p->zMalloc);
 1.62571 +      }
 1.62572 +      return;
 1.62573 +    }
 1.62574 +    for(pEnd=&p[N]; p<pEnd; p++){
 1.62575 +      assert( (&p[1])==pEnd || p[0].db==p[1].db );
 1.62576 +      assert( sqlite3VdbeCheckMemInvariants(p) );
 1.62577 +
 1.62578 +      /* This block is really an inlined version of sqlite3VdbeMemRelease()
 1.62579 +      ** that takes advantage of the fact that the memory cell value is 
 1.62580 +      ** being set to NULL after releasing any dynamic resources.
 1.62581 +      **
 1.62582 +      ** The justification for duplicating code is that according to 
 1.62583 +      ** callgrind, this causes a certain test case to hit the CPU 4.7 
 1.62584 +      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
 1.62585 +      ** sqlite3MemRelease() were called from here. With -O2, this jumps
 1.62586 +      ** to 6.6 percent. The test case is inserting 1000 rows into a table 
 1.62587 +      ** with no indexes using a single prepared INSERT statement, bind() 
 1.62588 +      ** and reset(). Inserts are grouped into a transaction.
 1.62589 +      */
 1.62590 +      testcase( p->flags & MEM_Agg );
 1.62591 +      testcase( p->flags & MEM_Dyn );
 1.62592 +      testcase( p->flags & MEM_Frame );
 1.62593 +      testcase( p->flags & MEM_RowSet );
 1.62594 +      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
 1.62595 +        sqlite3VdbeMemRelease(p);
 1.62596 +      }else if( p->zMalloc ){
 1.62597 +        sqlite3DbFree(db, p->zMalloc);
 1.62598 +        p->zMalloc = 0;
 1.62599 +      }
 1.62600 +
 1.62601 +      p->flags = MEM_Undefined;
 1.62602 +    }
 1.62603 +    db->mallocFailed = malloc_failed;
 1.62604 +  }
 1.62605 +}
 1.62606 +
 1.62607 +/*
 1.62608 +** Delete a VdbeFrame object and its contents. VdbeFrame objects are
 1.62609 +** allocated by the OP_Program opcode in sqlite3VdbeExec().
 1.62610 +*/
 1.62611 +SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
 1.62612 +  int i;
 1.62613 +  Mem *aMem = VdbeFrameMem(p);
 1.62614 +  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
 1.62615 +  for(i=0; i<p->nChildCsr; i++){
 1.62616 +    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
 1.62617 +  }
 1.62618 +  releaseMemArray(aMem, p->nChildMem);
 1.62619 +  sqlite3DbFree(p->v->db, p);
 1.62620 +}
 1.62621 +
 1.62622 +#ifndef SQLITE_OMIT_EXPLAIN
 1.62623 +/*
 1.62624 +** Give a listing of the program in the virtual machine.
 1.62625 +**
 1.62626 +** The interface is the same as sqlite3VdbeExec().  But instead of
 1.62627 +** running the code, it invokes the callback once for each instruction.
 1.62628 +** This feature is used to implement "EXPLAIN".
 1.62629 +**
 1.62630 +** When p->explain==1, each instruction is listed.  When
 1.62631 +** p->explain==2, only OP_Explain instructions are listed and these
 1.62632 +** are shown in a different format.  p->explain==2 is used to implement
 1.62633 +** EXPLAIN QUERY PLAN.
 1.62634 +**
 1.62635 +** When p->explain==1, first the main program is listed, then each of
 1.62636 +** the trigger subprograms are listed one by one.
 1.62637 +*/
 1.62638 +SQLITE_PRIVATE int sqlite3VdbeList(
 1.62639 +  Vdbe *p                   /* The VDBE */
 1.62640 +){
 1.62641 +  int nRow;                            /* Stop when row count reaches this */
 1.62642 +  int nSub = 0;                        /* Number of sub-vdbes seen so far */
 1.62643 +  SubProgram **apSub = 0;              /* Array of sub-vdbes */
 1.62644 +  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
 1.62645 +  sqlite3 *db = p->db;                 /* The database connection */
 1.62646 +  int i;                               /* Loop counter */
 1.62647 +  int rc = SQLITE_OK;                  /* Return code */
 1.62648 +  Mem *pMem = &p->aMem[1];             /* First Mem of result set */
 1.62649 +
 1.62650 +  assert( p->explain );
 1.62651 +  assert( p->magic==VDBE_MAGIC_RUN );
 1.62652 +  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
 1.62653 +
 1.62654 +  /* Even though this opcode does not use dynamic strings for
 1.62655 +  ** the result, result columns may become dynamic if the user calls
 1.62656 +  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
 1.62657 +  */
 1.62658 +  releaseMemArray(pMem, 8);
 1.62659 +  p->pResultSet = 0;
 1.62660 +
 1.62661 +  if( p->rc==SQLITE_NOMEM ){
 1.62662 +    /* This happens if a malloc() inside a call to sqlite3_column_text() or
 1.62663 +    ** sqlite3_column_text16() failed.  */
 1.62664 +    db->mallocFailed = 1;
 1.62665 +    return SQLITE_ERROR;
 1.62666 +  }
 1.62667 +
 1.62668 +  /* When the number of output rows reaches nRow, that means the
 1.62669 +  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
 1.62670 +  ** nRow is the sum of the number of rows in the main program, plus
 1.62671 +  ** the sum of the number of rows in all trigger subprograms encountered
 1.62672 +  ** so far.  The nRow value will increase as new trigger subprograms are
 1.62673 +  ** encountered, but p->pc will eventually catch up to nRow.
 1.62674 +  */
 1.62675 +  nRow = p->nOp;
 1.62676 +  if( p->explain==1 ){
 1.62677 +    /* The first 8 memory cells are used for the result set.  So we will
 1.62678 +    ** commandeer the 9th cell to use as storage for an array of pointers
 1.62679 +    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
 1.62680 +    ** cells.  */
 1.62681 +    assert( p->nMem>9 );
 1.62682 +    pSub = &p->aMem[9];
 1.62683 +    if( pSub->flags&MEM_Blob ){
 1.62684 +      /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
 1.62685 +      ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
 1.62686 +      nSub = pSub->n/sizeof(Vdbe*);
 1.62687 +      apSub = (SubProgram **)pSub->z;
 1.62688 +    }
 1.62689 +    for(i=0; i<nSub; i++){
 1.62690 +      nRow += apSub[i]->nOp;
 1.62691 +    }
 1.62692 +  }
 1.62693 +
 1.62694 +  do{
 1.62695 +    i = p->pc++;
 1.62696 +  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
 1.62697 +  if( i>=nRow ){
 1.62698 +    p->rc = SQLITE_OK;
 1.62699 +    rc = SQLITE_DONE;
 1.62700 +  }else if( db->u1.isInterrupted ){
 1.62701 +    p->rc = SQLITE_INTERRUPT;
 1.62702 +    rc = SQLITE_ERROR;
 1.62703 +    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
 1.62704 +  }else{
 1.62705 +    char *zP4;
 1.62706 +    Op *pOp;
 1.62707 +    if( i<p->nOp ){
 1.62708 +      /* The output line number is small enough that we are still in the
 1.62709 +      ** main program. */
 1.62710 +      pOp = &p->aOp[i];
 1.62711 +    }else{
 1.62712 +      /* We are currently listing subprograms.  Figure out which one and
 1.62713 +      ** pick up the appropriate opcode. */
 1.62714 +      int j;
 1.62715 +      i -= p->nOp;
 1.62716 +      for(j=0; i>=apSub[j]->nOp; j++){
 1.62717 +        i -= apSub[j]->nOp;
 1.62718 +      }
 1.62719 +      pOp = &apSub[j]->aOp[i];
 1.62720 +    }
 1.62721 +    if( p->explain==1 ){
 1.62722 +      pMem->flags = MEM_Int;
 1.62723 +      pMem->u.i = i;                                /* Program counter */
 1.62724 +      pMem++;
 1.62725 +  
 1.62726 +      pMem->flags = MEM_Static|MEM_Str|MEM_Term;
 1.62727 +      pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
 1.62728 +      assert( pMem->z!=0 );
 1.62729 +      pMem->n = sqlite3Strlen30(pMem->z);
 1.62730 +      pMem->enc = SQLITE_UTF8;
 1.62731 +      pMem++;
 1.62732 +
 1.62733 +      /* When an OP_Program opcode is encounter (the only opcode that has
 1.62734 +      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
 1.62735 +      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
 1.62736 +      ** has not already been seen.
 1.62737 +      */
 1.62738 +      if( pOp->p4type==P4_SUBPROGRAM ){
 1.62739 +        int nByte = (nSub+1)*sizeof(SubProgram*);
 1.62740 +        int j;
 1.62741 +        for(j=0; j<nSub; j++){
 1.62742 +          if( apSub[j]==pOp->p4.pProgram ) break;
 1.62743 +        }
 1.62744 +        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
 1.62745 +          apSub = (SubProgram **)pSub->z;
 1.62746 +          apSub[nSub++] = pOp->p4.pProgram;
 1.62747 +          pSub->flags |= MEM_Blob;
 1.62748 +          pSub->n = nSub*sizeof(SubProgram*);
 1.62749 +        }
 1.62750 +      }
 1.62751 +    }
 1.62752 +
 1.62753 +    pMem->flags = MEM_Int;
 1.62754 +    pMem->u.i = pOp->p1;                          /* P1 */
 1.62755 +    pMem++;
 1.62756 +
 1.62757 +    pMem->flags = MEM_Int;
 1.62758 +    pMem->u.i = pOp->p2;                          /* P2 */
 1.62759 +    pMem++;
 1.62760 +
 1.62761 +    pMem->flags = MEM_Int;
 1.62762 +    pMem->u.i = pOp->p3;                          /* P3 */
 1.62763 +    pMem++;
 1.62764 +
 1.62765 +    if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
 1.62766 +      assert( p->db->mallocFailed );
 1.62767 +      return SQLITE_ERROR;
 1.62768 +    }
 1.62769 +    pMem->flags = MEM_Str|MEM_Term;
 1.62770 +    zP4 = displayP4(pOp, pMem->z, 32);
 1.62771 +    if( zP4!=pMem->z ){
 1.62772 +      sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
 1.62773 +    }else{
 1.62774 +      assert( pMem->z!=0 );
 1.62775 +      pMem->n = sqlite3Strlen30(pMem->z);
 1.62776 +      pMem->enc = SQLITE_UTF8;
 1.62777 +    }
 1.62778 +    pMem++;
 1.62779 +
 1.62780 +    if( p->explain==1 ){
 1.62781 +      if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
 1.62782 +        assert( p->db->mallocFailed );
 1.62783 +        return SQLITE_ERROR;
 1.62784 +      }
 1.62785 +      pMem->flags = MEM_Str|MEM_Term;
 1.62786 +      pMem->n = 2;
 1.62787 +      sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
 1.62788 +      pMem->enc = SQLITE_UTF8;
 1.62789 +      pMem++;
 1.62790 +  
 1.62791 +#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 1.62792 +      if( sqlite3VdbeMemGrow(pMem, 500, 0) ){
 1.62793 +        assert( p->db->mallocFailed );
 1.62794 +        return SQLITE_ERROR;
 1.62795 +      }
 1.62796 +      pMem->flags = MEM_Str|MEM_Term;
 1.62797 +      pMem->n = displayComment(pOp, zP4, pMem->z, 500);
 1.62798 +      pMem->enc = SQLITE_UTF8;
 1.62799 +#else
 1.62800 +      pMem->flags = MEM_Null;                       /* Comment */
 1.62801 +#endif
 1.62802 +    }
 1.62803 +
 1.62804 +    p->nResColumn = 8 - 4*(p->explain-1);
 1.62805 +    p->pResultSet = &p->aMem[1];
 1.62806 +    p->rc = SQLITE_OK;
 1.62807 +    rc = SQLITE_ROW;
 1.62808 +  }
 1.62809 +  return rc;
 1.62810 +}
 1.62811 +#endif /* SQLITE_OMIT_EXPLAIN */
 1.62812 +
 1.62813 +#ifdef SQLITE_DEBUG
 1.62814 +/*
 1.62815 +** Print the SQL that was used to generate a VDBE program.
 1.62816 +*/
 1.62817 +SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
 1.62818 +  const char *z = 0;
 1.62819 +  if( p->zSql ){
 1.62820 +    z = p->zSql;
 1.62821 +  }else if( p->nOp>=1 ){
 1.62822 +    const VdbeOp *pOp = &p->aOp[0];
 1.62823 +    if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
 1.62824 +      z = pOp->p4.z;
 1.62825 +      while( sqlite3Isspace(*z) ) z++;
 1.62826 +    }
 1.62827 +  }
 1.62828 +  if( z ) printf("SQL: [%s]\n", z);
 1.62829 +}
 1.62830 +#endif
 1.62831 +
 1.62832 +#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
 1.62833 +/*
 1.62834 +** Print an IOTRACE message showing SQL content.
 1.62835 +*/
 1.62836 +SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
 1.62837 +  int nOp = p->nOp;
 1.62838 +  VdbeOp *pOp;
 1.62839 +  if( sqlite3IoTrace==0 ) return;
 1.62840 +  if( nOp<1 ) return;
 1.62841 +  pOp = &p->aOp[0];
 1.62842 +  if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
 1.62843 +    int i, j;
 1.62844 +    char z[1000];
 1.62845 +    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
 1.62846 +    for(i=0; sqlite3Isspace(z[i]); i++){}
 1.62847 +    for(j=0; z[i]; i++){
 1.62848 +      if( sqlite3Isspace(z[i]) ){
 1.62849 +        if( z[i-1]!=' ' ){
 1.62850 +          z[j++] = ' ';
 1.62851 +        }
 1.62852 +      }else{
 1.62853 +        z[j++] = z[i];
 1.62854 +      }
 1.62855 +    }
 1.62856 +    z[j] = 0;
 1.62857 +    sqlite3IoTrace("SQL %s\n", z);
 1.62858 +  }
 1.62859 +}
 1.62860 +#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
 1.62861 +
 1.62862 +/*
 1.62863 +** Allocate space from a fixed size buffer and return a pointer to
 1.62864 +** that space.  If insufficient space is available, return NULL.
 1.62865 +**
 1.62866 +** The pBuf parameter is the initial value of a pointer which will
 1.62867 +** receive the new memory.  pBuf is normally NULL.  If pBuf is not
 1.62868 +** NULL, it means that memory space has already been allocated and that
 1.62869 +** this routine should not allocate any new memory.  When pBuf is not
 1.62870 +** NULL simply return pBuf.  Only allocate new memory space when pBuf
 1.62871 +** is NULL.
 1.62872 +**
 1.62873 +** nByte is the number of bytes of space needed.
 1.62874 +**
 1.62875 +** *ppFrom points to available space and pEnd points to the end of the
 1.62876 +** available space.  When space is allocated, *ppFrom is advanced past
 1.62877 +** the end of the allocated space.
 1.62878 +**
 1.62879 +** *pnByte is a counter of the number of bytes of space that have failed
 1.62880 +** to allocate.  If there is insufficient space in *ppFrom to satisfy the
 1.62881 +** request, then increment *pnByte by the amount of the request.
 1.62882 +*/
 1.62883 +static void *allocSpace(
 1.62884 +  void *pBuf,          /* Where return pointer will be stored */
 1.62885 +  int nByte,           /* Number of bytes to allocate */
 1.62886 +  u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
 1.62887 +  u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
 1.62888 +  int *pnByte          /* If allocation cannot be made, increment *pnByte */
 1.62889 +){
 1.62890 +  assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
 1.62891 +  if( pBuf ) return pBuf;
 1.62892 +  nByte = ROUND8(nByte);
 1.62893 +  if( &(*ppFrom)[nByte] <= pEnd ){
 1.62894 +    pBuf = (void*)*ppFrom;
 1.62895 +    *ppFrom += nByte;
 1.62896 +  }else{
 1.62897 +    *pnByte += nByte;
 1.62898 +  }
 1.62899 +  return pBuf;
 1.62900 +}
 1.62901 +
 1.62902 +/*
 1.62903 +** Rewind the VDBE back to the beginning in preparation for
 1.62904 +** running it.
 1.62905 +*/
 1.62906 +SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
 1.62907 +#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
 1.62908 +  int i;
 1.62909 +#endif
 1.62910 +  assert( p!=0 );
 1.62911 +  assert( p->magic==VDBE_MAGIC_INIT );
 1.62912 +
 1.62913 +  /* There should be at least one opcode.
 1.62914 +  */
 1.62915 +  assert( p->nOp>0 );
 1.62916 +
 1.62917 +  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
 1.62918 +  p->magic = VDBE_MAGIC_RUN;
 1.62919 +
 1.62920 +#ifdef SQLITE_DEBUG
 1.62921 +  for(i=1; i<p->nMem; i++){
 1.62922 +    assert( p->aMem[i].db==p->db );
 1.62923 +  }
 1.62924 +#endif
 1.62925 +  p->pc = -1;
 1.62926 +  p->rc = SQLITE_OK;
 1.62927 +  p->errorAction = OE_Abort;
 1.62928 +  p->magic = VDBE_MAGIC_RUN;
 1.62929 +  p->nChange = 0;
 1.62930 +  p->cacheCtr = 1;
 1.62931 +  p->minWriteFileFormat = 255;
 1.62932 +  p->iStatement = 0;
 1.62933 +  p->nFkConstraint = 0;
 1.62934 +#ifdef VDBE_PROFILE
 1.62935 +  for(i=0; i<p->nOp; i++){
 1.62936 +    p->aOp[i].cnt = 0;
 1.62937 +    p->aOp[i].cycles = 0;
 1.62938 +  }
 1.62939 +#endif
 1.62940 +}
 1.62941 +
 1.62942 +/*
 1.62943 +** Prepare a virtual machine for execution for the first time after
 1.62944 +** creating the virtual machine.  This involves things such
 1.62945 +** as allocating stack space and initializing the program counter.
 1.62946 +** After the VDBE has be prepped, it can be executed by one or more
 1.62947 +** calls to sqlite3VdbeExec().  
 1.62948 +**
 1.62949 +** This function may be called exact once on a each virtual machine.
 1.62950 +** After this routine is called the VM has been "packaged" and is ready
 1.62951 +** to run.  After this routine is called, futher calls to 
 1.62952 +** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
 1.62953 +** the Vdbe from the Parse object that helped generate it so that the
 1.62954 +** the Vdbe becomes an independent entity and the Parse object can be
 1.62955 +** destroyed.
 1.62956 +**
 1.62957 +** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
 1.62958 +** to its initial state after it has been run.
 1.62959 +*/
 1.62960 +SQLITE_PRIVATE void sqlite3VdbeMakeReady(
 1.62961 +  Vdbe *p,                       /* The VDBE */
 1.62962 +  Parse *pParse                  /* Parsing context */
 1.62963 +){
 1.62964 +  sqlite3 *db;                   /* The database connection */
 1.62965 +  int nVar;                      /* Number of parameters */
 1.62966 +  int nMem;                      /* Number of VM memory registers */
 1.62967 +  int nCursor;                   /* Number of cursors required */
 1.62968 +  int nArg;                      /* Number of arguments in subprograms */
 1.62969 +  int nOnce;                     /* Number of OP_Once instructions */
 1.62970 +  int n;                         /* Loop counter */
 1.62971 +  u8 *zCsr;                      /* Memory available for allocation */
 1.62972 +  u8 *zEnd;                      /* First byte past allocated memory */
 1.62973 +  int nByte;                     /* How much extra memory is needed */
 1.62974 +
 1.62975 +  assert( p!=0 );
 1.62976 +  assert( p->nOp>0 );
 1.62977 +  assert( pParse!=0 );
 1.62978 +  assert( p->magic==VDBE_MAGIC_INIT );
 1.62979 +  assert( pParse==p->pParse );
 1.62980 +  db = p->db;
 1.62981 +  assert( db->mallocFailed==0 );
 1.62982 +  nVar = pParse->nVar;
 1.62983 +  nMem = pParse->nMem;
 1.62984 +  nCursor = pParse->nTab;
 1.62985 +  nArg = pParse->nMaxArg;
 1.62986 +  nOnce = pParse->nOnce;
 1.62987 +  if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
 1.62988 +  
 1.62989 +  /* For each cursor required, also allocate a memory cell. Memory
 1.62990 +  ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
 1.62991 +  ** the vdbe program. Instead they are used to allocate space for
 1.62992 +  ** VdbeCursor/BtCursor structures. The blob of memory associated with 
 1.62993 +  ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
 1.62994 +  ** stores the blob of memory associated with cursor 1, etc.
 1.62995 +  **
 1.62996 +  ** See also: allocateCursor().
 1.62997 +  */
 1.62998 +  nMem += nCursor;
 1.62999 +
 1.63000 +  /* Allocate space for memory registers, SQL variables, VDBE cursors and 
 1.63001 +  ** an array to marshal SQL function arguments in.
 1.63002 +  */
 1.63003 +  zCsr = (u8*)&p->aOp[p->nOp];            /* Memory avaliable for allocation */
 1.63004 +  zEnd = (u8*)&p->aOp[pParse->nOpAlloc];  /* First byte past end of zCsr[] */
 1.63005 +
 1.63006 +  resolveP2Values(p, &nArg);
 1.63007 +  p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
 1.63008 +  if( pParse->explain && nMem<10 ){
 1.63009 +    nMem = 10;
 1.63010 +  }
 1.63011 +  memset(zCsr, 0, zEnd-zCsr);
 1.63012 +  zCsr += (zCsr - (u8*)0)&7;
 1.63013 +  assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
 1.63014 +  p->expired = 0;
 1.63015 +
 1.63016 +  /* Memory for registers, parameters, cursor, etc, is allocated in two
 1.63017 +  ** passes.  On the first pass, we try to reuse unused space at the 
 1.63018 +  ** end of the opcode array.  If we are unable to satisfy all memory
 1.63019 +  ** requirements by reusing the opcode array tail, then the second
 1.63020 +  ** pass will fill in the rest using a fresh allocation.  
 1.63021 +  **
 1.63022 +  ** This two-pass approach that reuses as much memory as possible from
 1.63023 +  ** the leftover space at the end of the opcode array can significantly
 1.63024 +  ** reduce the amount of memory held by a prepared statement.
 1.63025 +  */
 1.63026 +  do {
 1.63027 +    nByte = 0;
 1.63028 +    p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
 1.63029 +    p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
 1.63030 +    p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
 1.63031 +    p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
 1.63032 +    p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
 1.63033 +                          &zCsr, zEnd, &nByte);
 1.63034 +    p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
 1.63035 +    if( nByte ){
 1.63036 +      p->pFree = sqlite3DbMallocZero(db, nByte);
 1.63037 +    }
 1.63038 +    zCsr = p->pFree;
 1.63039 +    zEnd = &zCsr[nByte];
 1.63040 +  }while( nByte && !db->mallocFailed );
 1.63041 +
 1.63042 +  p->nCursor = nCursor;
 1.63043 +  p->nOnceFlag = nOnce;
 1.63044 +  if( p->aVar ){
 1.63045 +    p->nVar = (ynVar)nVar;
 1.63046 +    for(n=0; n<nVar; n++){
 1.63047 +      p->aVar[n].flags = MEM_Null;
 1.63048 +      p->aVar[n].db = db;
 1.63049 +    }
 1.63050 +  }
 1.63051 +  if( p->azVar ){
 1.63052 +    p->nzVar = pParse->nzVar;
 1.63053 +    memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
 1.63054 +    memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
 1.63055 +  }
 1.63056 +  if( p->aMem ){
 1.63057 +    p->aMem--;                      /* aMem[] goes from 1..nMem */
 1.63058 +    p->nMem = nMem;                 /*       not from 0..nMem-1 */
 1.63059 +    for(n=1; n<=nMem; n++){
 1.63060 +      p->aMem[n].flags = MEM_Undefined;
 1.63061 +      p->aMem[n].db = db;
 1.63062 +    }
 1.63063 +  }
 1.63064 +  p->explain = pParse->explain;
 1.63065 +  sqlite3VdbeRewind(p);
 1.63066 +}
 1.63067 +
 1.63068 +/*
 1.63069 +** Close a VDBE cursor and release all the resources that cursor 
 1.63070 +** happens to hold.
 1.63071 +*/
 1.63072 +SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
 1.63073 +  if( pCx==0 ){
 1.63074 +    return;
 1.63075 +  }
 1.63076 +  sqlite3VdbeSorterClose(p->db, pCx);
 1.63077 +  if( pCx->pBt ){
 1.63078 +    sqlite3BtreeClose(pCx->pBt);
 1.63079 +    /* The pCx->pCursor will be close automatically, if it exists, by
 1.63080 +    ** the call above. */
 1.63081 +  }else if( pCx->pCursor ){
 1.63082 +    sqlite3BtreeCloseCursor(pCx->pCursor);
 1.63083 +  }
 1.63084 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.63085 +  if( pCx->pVtabCursor ){
 1.63086 +    sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
 1.63087 +    const sqlite3_module *pModule = pVtabCursor->pVtab->pModule;
 1.63088 +    p->inVtabMethod = 1;
 1.63089 +    pModule->xClose(pVtabCursor);
 1.63090 +    p->inVtabMethod = 0;
 1.63091 +  }
 1.63092 +#endif
 1.63093 +}
 1.63094 +
 1.63095 +/*
 1.63096 +** Copy the values stored in the VdbeFrame structure to its Vdbe. This
 1.63097 +** is used, for example, when a trigger sub-program is halted to restore
 1.63098 +** control to the main program.
 1.63099 +*/
 1.63100 +SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
 1.63101 +  Vdbe *v = pFrame->v;
 1.63102 +  v->aOnceFlag = pFrame->aOnceFlag;
 1.63103 +  v->nOnceFlag = pFrame->nOnceFlag;
 1.63104 +  v->aOp = pFrame->aOp;
 1.63105 +  v->nOp = pFrame->nOp;
 1.63106 +  v->aMem = pFrame->aMem;
 1.63107 +  v->nMem = pFrame->nMem;
 1.63108 +  v->apCsr = pFrame->apCsr;
 1.63109 +  v->nCursor = pFrame->nCursor;
 1.63110 +  v->db->lastRowid = pFrame->lastRowid;
 1.63111 +  v->nChange = pFrame->nChange;
 1.63112 +  return pFrame->pc;
 1.63113 +}
 1.63114 +
 1.63115 +/*
 1.63116 +** Close all cursors.
 1.63117 +**
 1.63118 +** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
 1.63119 +** cell array. This is necessary as the memory cell array may contain
 1.63120 +** pointers to VdbeFrame objects, which may in turn contain pointers to
 1.63121 +** open cursors.
 1.63122 +*/
 1.63123 +static void closeAllCursors(Vdbe *p){
 1.63124 +  if( p->pFrame ){
 1.63125 +    VdbeFrame *pFrame;
 1.63126 +    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
 1.63127 +    sqlite3VdbeFrameRestore(pFrame);
 1.63128 +  }
 1.63129 +  p->pFrame = 0;
 1.63130 +  p->nFrame = 0;
 1.63131 +
 1.63132 +  if( p->apCsr ){
 1.63133 +    int i;
 1.63134 +    for(i=0; i<p->nCursor; i++){
 1.63135 +      VdbeCursor *pC = p->apCsr[i];
 1.63136 +      if( pC ){
 1.63137 +        sqlite3VdbeFreeCursor(p, pC);
 1.63138 +        p->apCsr[i] = 0;
 1.63139 +      }
 1.63140 +    }
 1.63141 +  }
 1.63142 +  if( p->aMem ){
 1.63143 +    releaseMemArray(&p->aMem[1], p->nMem);
 1.63144 +  }
 1.63145 +  while( p->pDelFrame ){
 1.63146 +    VdbeFrame *pDel = p->pDelFrame;
 1.63147 +    p->pDelFrame = pDel->pParent;
 1.63148 +    sqlite3VdbeFrameDelete(pDel);
 1.63149 +  }
 1.63150 +
 1.63151 +  /* Delete any auxdata allocations made by the VM */
 1.63152 +  sqlite3VdbeDeleteAuxData(p, -1, 0);
 1.63153 +  assert( p->pAuxData==0 );
 1.63154 +}
 1.63155 +
 1.63156 +/*
 1.63157 +** Clean up the VM after execution.
 1.63158 +**
 1.63159 +** This routine will automatically close any cursors, lists, and/or
 1.63160 +** sorters that were left open.  It also deletes the values of
 1.63161 +** variables in the aVar[] array.
 1.63162 +*/
 1.63163 +static void Cleanup(Vdbe *p){
 1.63164 +  sqlite3 *db = p->db;
 1.63165 +
 1.63166 +#ifdef SQLITE_DEBUG
 1.63167 +  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
 1.63168 +  ** Vdbe.aMem[] arrays have already been cleaned up.  */
 1.63169 +  int i;
 1.63170 +  if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
 1.63171 +  if( p->aMem ){
 1.63172 +    for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
 1.63173 +  }
 1.63174 +#endif
 1.63175 +
 1.63176 +  sqlite3DbFree(db, p->zErrMsg);
 1.63177 +  p->zErrMsg = 0;
 1.63178 +  p->pResultSet = 0;
 1.63179 +}
 1.63180 +
 1.63181 +/*
 1.63182 +** Set the number of result columns that will be returned by this SQL
 1.63183 +** statement. This is now set at compile time, rather than during
 1.63184 +** execution of the vdbe program so that sqlite3_column_count() can
 1.63185 +** be called on an SQL statement before sqlite3_step().
 1.63186 +*/
 1.63187 +SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
 1.63188 +  Mem *pColName;
 1.63189 +  int n;
 1.63190 +  sqlite3 *db = p->db;
 1.63191 +
 1.63192 +  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
 1.63193 +  sqlite3DbFree(db, p->aColName);
 1.63194 +  n = nResColumn*COLNAME_N;
 1.63195 +  p->nResColumn = (u16)nResColumn;
 1.63196 +  p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
 1.63197 +  if( p->aColName==0 ) return;
 1.63198 +  while( n-- > 0 ){
 1.63199 +    pColName->flags = MEM_Null;
 1.63200 +    pColName->db = p->db;
 1.63201 +    pColName++;
 1.63202 +  }
 1.63203 +}
 1.63204 +
 1.63205 +/*
 1.63206 +** Set the name of the idx'th column to be returned by the SQL statement.
 1.63207 +** zName must be a pointer to a nul terminated string.
 1.63208 +**
 1.63209 +** This call must be made after a call to sqlite3VdbeSetNumCols().
 1.63210 +**
 1.63211 +** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
 1.63212 +** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
 1.63213 +** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
 1.63214 +*/
 1.63215 +SQLITE_PRIVATE int sqlite3VdbeSetColName(
 1.63216 +  Vdbe *p,                         /* Vdbe being configured */
 1.63217 +  int idx,                         /* Index of column zName applies to */
 1.63218 +  int var,                         /* One of the COLNAME_* constants */
 1.63219 +  const char *zName,               /* Pointer to buffer containing name */
 1.63220 +  void (*xDel)(void*)              /* Memory management strategy for zName */
 1.63221 +){
 1.63222 +  int rc;
 1.63223 +  Mem *pColName;
 1.63224 +  assert( idx<p->nResColumn );
 1.63225 +  assert( var<COLNAME_N );
 1.63226 +  if( p->db->mallocFailed ){
 1.63227 +    assert( !zName || xDel!=SQLITE_DYNAMIC );
 1.63228 +    return SQLITE_NOMEM;
 1.63229 +  }
 1.63230 +  assert( p->aColName!=0 );
 1.63231 +  pColName = &(p->aColName[idx+var*p->nResColumn]);
 1.63232 +  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
 1.63233 +  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
 1.63234 +  return rc;
 1.63235 +}
 1.63236 +
 1.63237 +/*
 1.63238 +** A read or write transaction may or may not be active on database handle
 1.63239 +** db. If a transaction is active, commit it. If there is a
 1.63240 +** write-transaction spanning more than one database file, this routine
 1.63241 +** takes care of the master journal trickery.
 1.63242 +*/
 1.63243 +static int vdbeCommit(sqlite3 *db, Vdbe *p){
 1.63244 +  int i;
 1.63245 +  int nTrans = 0;  /* Number of databases with an active write-transaction */
 1.63246 +  int rc = SQLITE_OK;
 1.63247 +  int needXcommit = 0;
 1.63248 +
 1.63249 +#ifdef SQLITE_OMIT_VIRTUALTABLE
 1.63250 +  /* With this option, sqlite3VtabSync() is defined to be simply 
 1.63251 +  ** SQLITE_OK so p is not used. 
 1.63252 +  */
 1.63253 +  UNUSED_PARAMETER(p);
 1.63254 +#endif
 1.63255 +
 1.63256 +  /* Before doing anything else, call the xSync() callback for any
 1.63257 +  ** virtual module tables written in this transaction. This has to
 1.63258 +  ** be done before determining whether a master journal file is 
 1.63259 +  ** required, as an xSync() callback may add an attached database
 1.63260 +  ** to the transaction.
 1.63261 +  */
 1.63262 +  rc = sqlite3VtabSync(db, p);
 1.63263 +
 1.63264 +  /* This loop determines (a) if the commit hook should be invoked and
 1.63265 +  ** (b) how many database files have open write transactions, not 
 1.63266 +  ** including the temp database. (b) is important because if more than 
 1.63267 +  ** one database file has an open write transaction, a master journal
 1.63268 +  ** file is required for an atomic commit.
 1.63269 +  */ 
 1.63270 +  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
 1.63271 +    Btree *pBt = db->aDb[i].pBt;
 1.63272 +    if( sqlite3BtreeIsInTrans(pBt) ){
 1.63273 +      needXcommit = 1;
 1.63274 +      if( i!=1 ) nTrans++;
 1.63275 +      sqlite3BtreeEnter(pBt);
 1.63276 +      rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
 1.63277 +      sqlite3BtreeLeave(pBt);
 1.63278 +    }
 1.63279 +  }
 1.63280 +  if( rc!=SQLITE_OK ){
 1.63281 +    return rc;
 1.63282 +  }
 1.63283 +
 1.63284 +  /* If there are any write-transactions at all, invoke the commit hook */
 1.63285 +  if( needXcommit && db->xCommitCallback ){
 1.63286 +    rc = db->xCommitCallback(db->pCommitArg);
 1.63287 +    if( rc ){
 1.63288 +      return SQLITE_CONSTRAINT_COMMITHOOK;
 1.63289 +    }
 1.63290 +  }
 1.63291 +
 1.63292 +  /* The simple case - no more than one database file (not counting the
 1.63293 +  ** TEMP database) has a transaction active.   There is no need for the
 1.63294 +  ** master-journal.
 1.63295 +  **
 1.63296 +  ** If the return value of sqlite3BtreeGetFilename() is a zero length
 1.63297 +  ** string, it means the main database is :memory: or a temp file.  In 
 1.63298 +  ** that case we do not support atomic multi-file commits, so use the 
 1.63299 +  ** simple case then too.
 1.63300 +  */
 1.63301 +  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
 1.63302 +   || nTrans<=1
 1.63303 +  ){
 1.63304 +    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
 1.63305 +      Btree *pBt = db->aDb[i].pBt;
 1.63306 +      if( pBt ){
 1.63307 +        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
 1.63308 +      }
 1.63309 +    }
 1.63310 +
 1.63311 +    /* Do the commit only if all databases successfully complete phase 1. 
 1.63312 +    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
 1.63313 +    ** IO error while deleting or truncating a journal file. It is unlikely,
 1.63314 +    ** but could happen. In this case abandon processing and return the error.
 1.63315 +    */
 1.63316 +    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
 1.63317 +      Btree *pBt = db->aDb[i].pBt;
 1.63318 +      if( pBt ){
 1.63319 +        rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
 1.63320 +      }
 1.63321 +    }
 1.63322 +    if( rc==SQLITE_OK ){
 1.63323 +      sqlite3VtabCommit(db);
 1.63324 +    }
 1.63325 +  }
 1.63326 +
 1.63327 +  /* The complex case - There is a multi-file write-transaction active.
 1.63328 +  ** This requires a master journal file to ensure the transaction is
 1.63329 +  ** committed atomicly.
 1.63330 +  */
 1.63331 +#ifndef SQLITE_OMIT_DISKIO
 1.63332 +  else{
 1.63333 +    sqlite3_vfs *pVfs = db->pVfs;
 1.63334 +    int needSync = 0;
 1.63335 +    char *zMaster = 0;   /* File-name for the master journal */
 1.63336 +    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
 1.63337 +    sqlite3_file *pMaster = 0;
 1.63338 +    i64 offset = 0;
 1.63339 +    int res;
 1.63340 +    int retryCount = 0;
 1.63341 +    int nMainFile;
 1.63342 +
 1.63343 +    /* Select a master journal file name */
 1.63344 +    nMainFile = sqlite3Strlen30(zMainFile);
 1.63345 +    zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
 1.63346 +    if( zMaster==0 ) return SQLITE_NOMEM;
 1.63347 +    do {
 1.63348 +      u32 iRandom;
 1.63349 +      if( retryCount ){
 1.63350 +        if( retryCount>100 ){
 1.63351 +          sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
 1.63352 +          sqlite3OsDelete(pVfs, zMaster, 0);
 1.63353 +          break;
 1.63354 +        }else if( retryCount==1 ){
 1.63355 +          sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
 1.63356 +        }
 1.63357 +      }
 1.63358 +      retryCount++;
 1.63359 +      sqlite3_randomness(sizeof(iRandom), &iRandom);
 1.63360 +      sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
 1.63361 +                               (iRandom>>8)&0xffffff, iRandom&0xff);
 1.63362 +      /* The antipenultimate character of the master journal name must
 1.63363 +      ** be "9" to avoid name collisions when using 8+3 filenames. */
 1.63364 +      assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
 1.63365 +      sqlite3FileSuffix3(zMainFile, zMaster);
 1.63366 +      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
 1.63367 +    }while( rc==SQLITE_OK && res );
 1.63368 +    if( rc==SQLITE_OK ){
 1.63369 +      /* Open the master journal. */
 1.63370 +      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
 1.63371 +          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
 1.63372 +          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
 1.63373 +      );
 1.63374 +    }
 1.63375 +    if( rc!=SQLITE_OK ){
 1.63376 +      sqlite3DbFree(db, zMaster);
 1.63377 +      return rc;
 1.63378 +    }
 1.63379 + 
 1.63380 +    /* Write the name of each database file in the transaction into the new
 1.63381 +    ** master journal file. If an error occurs at this point close
 1.63382 +    ** and delete the master journal file. All the individual journal files
 1.63383 +    ** still have 'null' as the master journal pointer, so they will roll
 1.63384 +    ** back independently if a failure occurs.
 1.63385 +    */
 1.63386 +    for(i=0; i<db->nDb; i++){
 1.63387 +      Btree *pBt = db->aDb[i].pBt;
 1.63388 +      if( sqlite3BtreeIsInTrans(pBt) ){
 1.63389 +        char const *zFile = sqlite3BtreeGetJournalname(pBt);
 1.63390 +        if( zFile==0 ){
 1.63391 +          continue;  /* Ignore TEMP and :memory: databases */
 1.63392 +        }
 1.63393 +        assert( zFile[0]!=0 );
 1.63394 +        if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
 1.63395 +          needSync = 1;
 1.63396 +        }
 1.63397 +        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
 1.63398 +        offset += sqlite3Strlen30(zFile)+1;
 1.63399 +        if( rc!=SQLITE_OK ){
 1.63400 +          sqlite3OsCloseFree(pMaster);
 1.63401 +          sqlite3OsDelete(pVfs, zMaster, 0);
 1.63402 +          sqlite3DbFree(db, zMaster);
 1.63403 +          return rc;
 1.63404 +        }
 1.63405 +      }
 1.63406 +    }
 1.63407 +
 1.63408 +    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
 1.63409 +    ** flag is set this is not required.
 1.63410 +    */
 1.63411 +    if( needSync 
 1.63412 +     && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
 1.63413 +     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
 1.63414 +    ){
 1.63415 +      sqlite3OsCloseFree(pMaster);
 1.63416 +      sqlite3OsDelete(pVfs, zMaster, 0);
 1.63417 +      sqlite3DbFree(db, zMaster);
 1.63418 +      return rc;
 1.63419 +    }
 1.63420 +
 1.63421 +    /* Sync all the db files involved in the transaction. The same call
 1.63422 +    ** sets the master journal pointer in each individual journal. If
 1.63423 +    ** an error occurs here, do not delete the master journal file.
 1.63424 +    **
 1.63425 +    ** If the error occurs during the first call to
 1.63426 +    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
 1.63427 +    ** master journal file will be orphaned. But we cannot delete it,
 1.63428 +    ** in case the master journal file name was written into the journal
 1.63429 +    ** file before the failure occurred.
 1.63430 +    */
 1.63431 +    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
 1.63432 +      Btree *pBt = db->aDb[i].pBt;
 1.63433 +      if( pBt ){
 1.63434 +        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
 1.63435 +      }
 1.63436 +    }
 1.63437 +    sqlite3OsCloseFree(pMaster);
 1.63438 +    assert( rc!=SQLITE_BUSY );
 1.63439 +    if( rc!=SQLITE_OK ){
 1.63440 +      sqlite3DbFree(db, zMaster);
 1.63441 +      return rc;
 1.63442 +    }
 1.63443 +
 1.63444 +    /* Delete the master journal file. This commits the transaction. After
 1.63445 +    ** doing this the directory is synced again before any individual
 1.63446 +    ** transaction files are deleted.
 1.63447 +    */
 1.63448 +    rc = sqlite3OsDelete(pVfs, zMaster, 1);
 1.63449 +    sqlite3DbFree(db, zMaster);
 1.63450 +    zMaster = 0;
 1.63451 +    if( rc ){
 1.63452 +      return rc;
 1.63453 +    }
 1.63454 +
 1.63455 +    /* All files and directories have already been synced, so the following
 1.63456 +    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
 1.63457 +    ** deleting or truncating journals. If something goes wrong while
 1.63458 +    ** this is happening we don't really care. The integrity of the
 1.63459 +    ** transaction is already guaranteed, but some stray 'cold' journals
 1.63460 +    ** may be lying around. Returning an error code won't help matters.
 1.63461 +    */
 1.63462 +    disable_simulated_io_errors();
 1.63463 +    sqlite3BeginBenignMalloc();
 1.63464 +    for(i=0; i<db->nDb; i++){ 
 1.63465 +      Btree *pBt = db->aDb[i].pBt;
 1.63466 +      if( pBt ){
 1.63467 +        sqlite3BtreeCommitPhaseTwo(pBt, 1);
 1.63468 +      }
 1.63469 +    }
 1.63470 +    sqlite3EndBenignMalloc();
 1.63471 +    enable_simulated_io_errors();
 1.63472 +
 1.63473 +    sqlite3VtabCommit(db);
 1.63474 +  }
 1.63475 +#endif
 1.63476 +
 1.63477 +  return rc;
 1.63478 +}
 1.63479 +
 1.63480 +/* 
 1.63481 +** This routine checks that the sqlite3.nVdbeActive count variable
 1.63482 +** matches the number of vdbe's in the list sqlite3.pVdbe that are
 1.63483 +** currently active. An assertion fails if the two counts do not match.
 1.63484 +** This is an internal self-check only - it is not an essential processing
 1.63485 +** step.
 1.63486 +**
 1.63487 +** This is a no-op if NDEBUG is defined.
 1.63488 +*/
 1.63489 +#ifndef NDEBUG
 1.63490 +static void checkActiveVdbeCnt(sqlite3 *db){
 1.63491 +  Vdbe *p;
 1.63492 +  int cnt = 0;
 1.63493 +  int nWrite = 0;
 1.63494 +  int nRead = 0;
 1.63495 +  p = db->pVdbe;
 1.63496 +  while( p ){
 1.63497 +    if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
 1.63498 +      cnt++;
 1.63499 +      if( p->readOnly==0 ) nWrite++;
 1.63500 +      if( p->bIsReader ) nRead++;
 1.63501 +    }
 1.63502 +    p = p->pNext;
 1.63503 +  }
 1.63504 +  assert( cnt==db->nVdbeActive );
 1.63505 +  assert( nWrite==db->nVdbeWrite );
 1.63506 +  assert( nRead==db->nVdbeRead );
 1.63507 +}
 1.63508 +#else
 1.63509 +#define checkActiveVdbeCnt(x)
 1.63510 +#endif
 1.63511 +
 1.63512 +/*
 1.63513 +** If the Vdbe passed as the first argument opened a statement-transaction,
 1.63514 +** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
 1.63515 +** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
 1.63516 +** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
 1.63517 +** statement transaction is committed.
 1.63518 +**
 1.63519 +** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
 1.63520 +** Otherwise SQLITE_OK.
 1.63521 +*/
 1.63522 +SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
 1.63523 +  sqlite3 *const db = p->db;
 1.63524 +  int rc = SQLITE_OK;
 1.63525 +
 1.63526 +  /* If p->iStatement is greater than zero, then this Vdbe opened a 
 1.63527 +  ** statement transaction that should be closed here. The only exception
 1.63528 +  ** is that an IO error may have occurred, causing an emergency rollback.
 1.63529 +  ** In this case (db->nStatement==0), and there is nothing to do.
 1.63530 +  */
 1.63531 +  if( db->nStatement && p->iStatement ){
 1.63532 +    int i;
 1.63533 +    const int iSavepoint = p->iStatement-1;
 1.63534 +
 1.63535 +    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
 1.63536 +    assert( db->nStatement>0 );
 1.63537 +    assert( p->iStatement==(db->nStatement+db->nSavepoint) );
 1.63538 +
 1.63539 +    for(i=0; i<db->nDb; i++){ 
 1.63540 +      int rc2 = SQLITE_OK;
 1.63541 +      Btree *pBt = db->aDb[i].pBt;
 1.63542 +      if( pBt ){
 1.63543 +        if( eOp==SAVEPOINT_ROLLBACK ){
 1.63544 +          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
 1.63545 +        }
 1.63546 +        if( rc2==SQLITE_OK ){
 1.63547 +          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
 1.63548 +        }
 1.63549 +        if( rc==SQLITE_OK ){
 1.63550 +          rc = rc2;
 1.63551 +        }
 1.63552 +      }
 1.63553 +    }
 1.63554 +    db->nStatement--;
 1.63555 +    p->iStatement = 0;
 1.63556 +
 1.63557 +    if( rc==SQLITE_OK ){
 1.63558 +      if( eOp==SAVEPOINT_ROLLBACK ){
 1.63559 +        rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
 1.63560 +      }
 1.63561 +      if( rc==SQLITE_OK ){
 1.63562 +        rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
 1.63563 +      }
 1.63564 +    }
 1.63565 +
 1.63566 +    /* If the statement transaction is being rolled back, also restore the 
 1.63567 +    ** database handles deferred constraint counter to the value it had when 
 1.63568 +    ** the statement transaction was opened.  */
 1.63569 +    if( eOp==SAVEPOINT_ROLLBACK ){
 1.63570 +      db->nDeferredCons = p->nStmtDefCons;
 1.63571 +      db->nDeferredImmCons = p->nStmtDefImmCons;
 1.63572 +    }
 1.63573 +  }
 1.63574 +  return rc;
 1.63575 +}
 1.63576 +
 1.63577 +/*
 1.63578 +** This function is called when a transaction opened by the database 
 1.63579 +** handle associated with the VM passed as an argument is about to be 
 1.63580 +** committed. If there are outstanding deferred foreign key constraint
 1.63581 +** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
 1.63582 +**
 1.63583 +** If there are outstanding FK violations and this function returns 
 1.63584 +** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
 1.63585 +** and write an error message to it. Then return SQLITE_ERROR.
 1.63586 +*/
 1.63587 +#ifndef SQLITE_OMIT_FOREIGN_KEY
 1.63588 +SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
 1.63589 +  sqlite3 *db = p->db;
 1.63590 +  if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0) 
 1.63591 +   || (!deferred && p->nFkConstraint>0) 
 1.63592 +  ){
 1.63593 +    p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
 1.63594 +    p->errorAction = OE_Abort;
 1.63595 +    sqlite3SetString(&p->zErrMsg, db, "FOREIGN KEY constraint failed");
 1.63596 +    return SQLITE_ERROR;
 1.63597 +  }
 1.63598 +  return SQLITE_OK;
 1.63599 +}
 1.63600 +#endif
 1.63601 +
 1.63602 +/*
 1.63603 +** This routine is called the when a VDBE tries to halt.  If the VDBE
 1.63604 +** has made changes and is in autocommit mode, then commit those
 1.63605 +** changes.  If a rollback is needed, then do the rollback.
 1.63606 +**
 1.63607 +** This routine is the only way to move the state of a VM from
 1.63608 +** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
 1.63609 +** call this on a VM that is in the SQLITE_MAGIC_HALT state.
 1.63610 +**
 1.63611 +** Return an error code.  If the commit could not complete because of
 1.63612 +** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
 1.63613 +** means the close did not happen and needs to be repeated.
 1.63614 +*/
 1.63615 +SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
 1.63616 +  int rc;                         /* Used to store transient return codes */
 1.63617 +  sqlite3 *db = p->db;
 1.63618 +
 1.63619 +  /* This function contains the logic that determines if a statement or
 1.63620 +  ** transaction will be committed or rolled back as a result of the
 1.63621 +  ** execution of this virtual machine. 
 1.63622 +  **
 1.63623 +  ** If any of the following errors occur:
 1.63624 +  **
 1.63625 +  **     SQLITE_NOMEM
 1.63626 +  **     SQLITE_IOERR
 1.63627 +  **     SQLITE_FULL
 1.63628 +  **     SQLITE_INTERRUPT
 1.63629 +  **
 1.63630 +  ** Then the internal cache might have been left in an inconsistent
 1.63631 +  ** state.  We need to rollback the statement transaction, if there is
 1.63632 +  ** one, or the complete transaction if there is no statement transaction.
 1.63633 +  */
 1.63634 +
 1.63635 +  if( p->db->mallocFailed ){
 1.63636 +    p->rc = SQLITE_NOMEM;
 1.63637 +  }
 1.63638 +  if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
 1.63639 +  closeAllCursors(p);
 1.63640 +  if( p->magic!=VDBE_MAGIC_RUN ){
 1.63641 +    return SQLITE_OK;
 1.63642 +  }
 1.63643 +  checkActiveVdbeCnt(db);
 1.63644 +
 1.63645 +  /* No commit or rollback needed if the program never started or if the
 1.63646 +  ** SQL statement does not read or write a database file.  */
 1.63647 +  if( p->pc>=0 && p->bIsReader ){
 1.63648 +    int mrc;   /* Primary error code from p->rc */
 1.63649 +    int eStatementOp = 0;
 1.63650 +    int isSpecialError;            /* Set to true if a 'special' error */
 1.63651 +
 1.63652 +    /* Lock all btrees used by the statement */
 1.63653 +    sqlite3VdbeEnter(p);
 1.63654 +
 1.63655 +    /* Check for one of the special errors */
 1.63656 +    mrc = p->rc & 0xff;
 1.63657 +    assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
 1.63658 +    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
 1.63659 +                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
 1.63660 +    if( isSpecialError ){
 1.63661 +      /* If the query was read-only and the error code is SQLITE_INTERRUPT, 
 1.63662 +      ** no rollback is necessary. Otherwise, at least a savepoint 
 1.63663 +      ** transaction must be rolled back to restore the database to a 
 1.63664 +      ** consistent state.
 1.63665 +      **
 1.63666 +      ** Even if the statement is read-only, it is important to perform
 1.63667 +      ** a statement or transaction rollback operation. If the error 
 1.63668 +      ** occurred while writing to the journal, sub-journal or database
 1.63669 +      ** file as part of an effort to free up cache space (see function
 1.63670 +      ** pagerStress() in pager.c), the rollback is required to restore 
 1.63671 +      ** the pager to a consistent state.
 1.63672 +      */
 1.63673 +      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
 1.63674 +        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
 1.63675 +          eStatementOp = SAVEPOINT_ROLLBACK;
 1.63676 +        }else{
 1.63677 +          /* We are forced to roll back the active transaction. Before doing
 1.63678 +          ** so, abort any other statements this handle currently has active.
 1.63679 +          */
 1.63680 +          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
 1.63681 +          sqlite3CloseSavepoints(db);
 1.63682 +          db->autoCommit = 1;
 1.63683 +        }
 1.63684 +      }
 1.63685 +    }
 1.63686 +
 1.63687 +    /* Check for immediate foreign key violations. */
 1.63688 +    if( p->rc==SQLITE_OK ){
 1.63689 +      sqlite3VdbeCheckFk(p, 0);
 1.63690 +    }
 1.63691 +  
 1.63692 +    /* If the auto-commit flag is set and this is the only active writer 
 1.63693 +    ** VM, then we do either a commit or rollback of the current transaction. 
 1.63694 +    **
 1.63695 +    ** Note: This block also runs if one of the special errors handled 
 1.63696 +    ** above has occurred. 
 1.63697 +    */
 1.63698 +    if( !sqlite3VtabInSync(db) 
 1.63699 +     && db->autoCommit 
 1.63700 +     && db->nVdbeWrite==(p->readOnly==0) 
 1.63701 +    ){
 1.63702 +      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
 1.63703 +        rc = sqlite3VdbeCheckFk(p, 1);
 1.63704 +        if( rc!=SQLITE_OK ){
 1.63705 +          if( NEVER(p->readOnly) ){
 1.63706 +            sqlite3VdbeLeave(p);
 1.63707 +            return SQLITE_ERROR;
 1.63708 +          }
 1.63709 +          rc = SQLITE_CONSTRAINT_FOREIGNKEY;
 1.63710 +        }else{ 
 1.63711 +          /* The auto-commit flag is true, the vdbe program was successful 
 1.63712 +          ** or hit an 'OR FAIL' constraint and there are no deferred foreign
 1.63713 +          ** key constraints to hold up the transaction. This means a commit 
 1.63714 +          ** is required. */
 1.63715 +          rc = vdbeCommit(db, p);
 1.63716 +        }
 1.63717 +        if( rc==SQLITE_BUSY && p->readOnly ){
 1.63718 +          sqlite3VdbeLeave(p);
 1.63719 +          return SQLITE_BUSY;
 1.63720 +        }else if( rc!=SQLITE_OK ){
 1.63721 +          p->rc = rc;
 1.63722 +          sqlite3RollbackAll(db, SQLITE_OK);
 1.63723 +        }else{
 1.63724 +          db->nDeferredCons = 0;
 1.63725 +          db->nDeferredImmCons = 0;
 1.63726 +          db->flags &= ~SQLITE_DeferFKs;
 1.63727 +          sqlite3CommitInternalChanges(db);
 1.63728 +        }
 1.63729 +      }else{
 1.63730 +        sqlite3RollbackAll(db, SQLITE_OK);
 1.63731 +      }
 1.63732 +      db->nStatement = 0;
 1.63733 +    }else if( eStatementOp==0 ){
 1.63734 +      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
 1.63735 +        eStatementOp = SAVEPOINT_RELEASE;
 1.63736 +      }else if( p->errorAction==OE_Abort ){
 1.63737 +        eStatementOp = SAVEPOINT_ROLLBACK;
 1.63738 +      }else{
 1.63739 +        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
 1.63740 +        sqlite3CloseSavepoints(db);
 1.63741 +        db->autoCommit = 1;
 1.63742 +      }
 1.63743 +    }
 1.63744 +  
 1.63745 +    /* If eStatementOp is non-zero, then a statement transaction needs to
 1.63746 +    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
 1.63747 +    ** do so. If this operation returns an error, and the current statement
 1.63748 +    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
 1.63749 +    ** current statement error code.
 1.63750 +    */
 1.63751 +    if( eStatementOp ){
 1.63752 +      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
 1.63753 +      if( rc ){
 1.63754 +        if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
 1.63755 +          p->rc = rc;
 1.63756 +          sqlite3DbFree(db, p->zErrMsg);
 1.63757 +          p->zErrMsg = 0;
 1.63758 +        }
 1.63759 +        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
 1.63760 +        sqlite3CloseSavepoints(db);
 1.63761 +        db->autoCommit = 1;
 1.63762 +      }
 1.63763 +    }
 1.63764 +  
 1.63765 +    /* If this was an INSERT, UPDATE or DELETE and no statement transaction
 1.63766 +    ** has been rolled back, update the database connection change-counter. 
 1.63767 +    */
 1.63768 +    if( p->changeCntOn ){
 1.63769 +      if( eStatementOp!=SAVEPOINT_ROLLBACK ){
 1.63770 +        sqlite3VdbeSetChanges(db, p->nChange);
 1.63771 +      }else{
 1.63772 +        sqlite3VdbeSetChanges(db, 0);
 1.63773 +      }
 1.63774 +      p->nChange = 0;
 1.63775 +    }
 1.63776 +
 1.63777 +    /* Release the locks */
 1.63778 +    sqlite3VdbeLeave(p);
 1.63779 +  }
 1.63780 +
 1.63781 +  /* We have successfully halted and closed the VM.  Record this fact. */
 1.63782 +  if( p->pc>=0 ){
 1.63783 +    db->nVdbeActive--;
 1.63784 +    if( !p->readOnly ) db->nVdbeWrite--;
 1.63785 +    if( p->bIsReader ) db->nVdbeRead--;
 1.63786 +    assert( db->nVdbeActive>=db->nVdbeRead );
 1.63787 +    assert( db->nVdbeRead>=db->nVdbeWrite );
 1.63788 +    assert( db->nVdbeWrite>=0 );
 1.63789 +  }
 1.63790 +  p->magic = VDBE_MAGIC_HALT;
 1.63791 +  checkActiveVdbeCnt(db);
 1.63792 +  if( p->db->mallocFailed ){
 1.63793 +    p->rc = SQLITE_NOMEM;
 1.63794 +  }
 1.63795 +
 1.63796 +  /* If the auto-commit flag is set to true, then any locks that were held
 1.63797 +  ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
 1.63798 +  ** to invoke any required unlock-notify callbacks.
 1.63799 +  */
 1.63800 +  if( db->autoCommit ){
 1.63801 +    sqlite3ConnectionUnlocked(db);
 1.63802 +  }
 1.63803 +
 1.63804 +  assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
 1.63805 +  return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
 1.63806 +}
 1.63807 +
 1.63808 +
 1.63809 +/*
 1.63810 +** Each VDBE holds the result of the most recent sqlite3_step() call
 1.63811 +** in p->rc.  This routine sets that result back to SQLITE_OK.
 1.63812 +*/
 1.63813 +SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
 1.63814 +  p->rc = SQLITE_OK;
 1.63815 +}
 1.63816 +
 1.63817 +/*
 1.63818 +** Copy the error code and error message belonging to the VDBE passed
 1.63819 +** as the first argument to its database handle (so that they will be 
 1.63820 +** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
 1.63821 +**
 1.63822 +** This function does not clear the VDBE error code or message, just
 1.63823 +** copies them to the database handle.
 1.63824 +*/
 1.63825 +SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
 1.63826 +  sqlite3 *db = p->db;
 1.63827 +  int rc = p->rc;
 1.63828 +  if( p->zErrMsg ){
 1.63829 +    u8 mallocFailed = db->mallocFailed;
 1.63830 +    sqlite3BeginBenignMalloc();
 1.63831 +    if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
 1.63832 +    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
 1.63833 +    sqlite3EndBenignMalloc();
 1.63834 +    db->mallocFailed = mallocFailed;
 1.63835 +    db->errCode = rc;
 1.63836 +  }else{
 1.63837 +    sqlite3Error(db, rc, 0);
 1.63838 +  }
 1.63839 +  return rc;
 1.63840 +}
 1.63841 +
 1.63842 +#ifdef SQLITE_ENABLE_SQLLOG
 1.63843 +/*
 1.63844 +** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run, 
 1.63845 +** invoke it.
 1.63846 +*/
 1.63847 +static void vdbeInvokeSqllog(Vdbe *v){
 1.63848 +  if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
 1.63849 +    char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
 1.63850 +    assert( v->db->init.busy==0 );
 1.63851 +    if( zExpanded ){
 1.63852 +      sqlite3GlobalConfig.xSqllog(
 1.63853 +          sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
 1.63854 +      );
 1.63855 +      sqlite3DbFree(v->db, zExpanded);
 1.63856 +    }
 1.63857 +  }
 1.63858 +}
 1.63859 +#else
 1.63860 +# define vdbeInvokeSqllog(x)
 1.63861 +#endif
 1.63862 +
 1.63863 +/*
 1.63864 +** Clean up a VDBE after execution but do not delete the VDBE just yet.
 1.63865 +** Write any error messages into *pzErrMsg.  Return the result code.
 1.63866 +**
 1.63867 +** After this routine is run, the VDBE should be ready to be executed
 1.63868 +** again.
 1.63869 +**
 1.63870 +** To look at it another way, this routine resets the state of the
 1.63871 +** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
 1.63872 +** VDBE_MAGIC_INIT.
 1.63873 +*/
 1.63874 +SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
 1.63875 +  sqlite3 *db;
 1.63876 +  db = p->db;
 1.63877 +
 1.63878 +  /* If the VM did not run to completion or if it encountered an
 1.63879 +  ** error, then it might not have been halted properly.  So halt
 1.63880 +  ** it now.
 1.63881 +  */
 1.63882 +  sqlite3VdbeHalt(p);
 1.63883 +
 1.63884 +  /* If the VDBE has be run even partially, then transfer the error code
 1.63885 +  ** and error message from the VDBE into the main database structure.  But
 1.63886 +  ** if the VDBE has just been set to run but has not actually executed any
 1.63887 +  ** instructions yet, leave the main database error information unchanged.
 1.63888 +  */
 1.63889 +  if( p->pc>=0 ){
 1.63890 +    vdbeInvokeSqllog(p);
 1.63891 +    sqlite3VdbeTransferError(p);
 1.63892 +    sqlite3DbFree(db, p->zErrMsg);
 1.63893 +    p->zErrMsg = 0;
 1.63894 +    if( p->runOnlyOnce ) p->expired = 1;
 1.63895 +  }else if( p->rc && p->expired ){
 1.63896 +    /* The expired flag was set on the VDBE before the first call
 1.63897 +    ** to sqlite3_step(). For consistency (since sqlite3_step() was
 1.63898 +    ** called), set the database error in this case as well.
 1.63899 +    */
 1.63900 +    sqlite3Error(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
 1.63901 +    sqlite3DbFree(db, p->zErrMsg);
 1.63902 +    p->zErrMsg = 0;
 1.63903 +  }
 1.63904 +
 1.63905 +  /* Reclaim all memory used by the VDBE
 1.63906 +  */
 1.63907 +  Cleanup(p);
 1.63908 +
 1.63909 +  /* Save profiling information from this VDBE run.
 1.63910 +  */
 1.63911 +#ifdef VDBE_PROFILE
 1.63912 +  {
 1.63913 +    FILE *out = fopen("vdbe_profile.out", "a");
 1.63914 +    if( out ){
 1.63915 +      int i;
 1.63916 +      fprintf(out, "---- ");
 1.63917 +      for(i=0; i<p->nOp; i++){
 1.63918 +        fprintf(out, "%02x", p->aOp[i].opcode);
 1.63919 +      }
 1.63920 +      fprintf(out, "\n");
 1.63921 +      if( p->zSql ){
 1.63922 +        char c, pc = 0;
 1.63923 +        fprintf(out, "-- ");
 1.63924 +        for(i=0; (c = p->zSql[i])!=0; i++){
 1.63925 +          if( pc=='\n' ) fprintf(out, "-- ");
 1.63926 +          putc(c, out);
 1.63927 +          pc = c;
 1.63928 +        }
 1.63929 +        if( pc!='\n' ) fprintf(out, "\n");
 1.63930 +      }
 1.63931 +      for(i=0; i<p->nOp; i++){
 1.63932 +        char zHdr[100];
 1.63933 +        sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
 1.63934 +           p->aOp[i].cnt,
 1.63935 +           p->aOp[i].cycles,
 1.63936 +           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
 1.63937 +        );
 1.63938 +        fprintf(out, "%s", zHdr);
 1.63939 +        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
 1.63940 +      }
 1.63941 +      fclose(out);
 1.63942 +    }
 1.63943 +  }
 1.63944 +#endif
 1.63945 +  p->iCurrentTime = 0;
 1.63946 +  p->magic = VDBE_MAGIC_INIT;
 1.63947 +  return p->rc & db->errMask;
 1.63948 +}
 1.63949 + 
 1.63950 +/*
 1.63951 +** Clean up and delete a VDBE after execution.  Return an integer which is
 1.63952 +** the result code.  Write any error message text into *pzErrMsg.
 1.63953 +*/
 1.63954 +SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
 1.63955 +  int rc = SQLITE_OK;
 1.63956 +  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
 1.63957 +    rc = sqlite3VdbeReset(p);
 1.63958 +    assert( (rc & p->db->errMask)==rc );
 1.63959 +  }
 1.63960 +  sqlite3VdbeDelete(p);
 1.63961 +  return rc;
 1.63962 +}
 1.63963 +
 1.63964 +/*
 1.63965 +** If parameter iOp is less than zero, then invoke the destructor for
 1.63966 +** all auxiliary data pointers currently cached by the VM passed as
 1.63967 +** the first argument.
 1.63968 +**
 1.63969 +** Or, if iOp is greater than or equal to zero, then the destructor is
 1.63970 +** only invoked for those auxiliary data pointers created by the user 
 1.63971 +** function invoked by the OP_Function opcode at instruction iOp of 
 1.63972 +** VM pVdbe, and only then if:
 1.63973 +**
 1.63974 +**    * the associated function parameter is the 32nd or later (counting
 1.63975 +**      from left to right), or
 1.63976 +**
 1.63977 +**    * the corresponding bit in argument mask is clear (where the first
 1.63978 +**      function parameter corrsponds to bit 0 etc.).
 1.63979 +*/
 1.63980 +SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
 1.63981 +  AuxData **pp = &pVdbe->pAuxData;
 1.63982 +  while( *pp ){
 1.63983 +    AuxData *pAux = *pp;
 1.63984 +    if( (iOp<0)
 1.63985 +     || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
 1.63986 +    ){
 1.63987 +      testcase( pAux->iArg==31 );
 1.63988 +      if( pAux->xDelete ){
 1.63989 +        pAux->xDelete(pAux->pAux);
 1.63990 +      }
 1.63991 +      *pp = pAux->pNext;
 1.63992 +      sqlite3DbFree(pVdbe->db, pAux);
 1.63993 +    }else{
 1.63994 +      pp= &pAux->pNext;
 1.63995 +    }
 1.63996 +  }
 1.63997 +}
 1.63998 +
 1.63999 +/*
 1.64000 +** Free all memory associated with the Vdbe passed as the second argument,
 1.64001 +** except for object itself, which is preserved.
 1.64002 +**
 1.64003 +** The difference between this function and sqlite3VdbeDelete() is that
 1.64004 +** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
 1.64005 +** the database connection and frees the object itself.
 1.64006 +*/
 1.64007 +SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
 1.64008 +  SubProgram *pSub, *pNext;
 1.64009 +  int i;
 1.64010 +  assert( p->db==0 || p->db==db );
 1.64011 +  releaseMemArray(p->aVar, p->nVar);
 1.64012 +  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
 1.64013 +  for(pSub=p->pProgram; pSub; pSub=pNext){
 1.64014 +    pNext = pSub->pNext;
 1.64015 +    vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
 1.64016 +    sqlite3DbFree(db, pSub);
 1.64017 +  }
 1.64018 +  for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
 1.64019 +  vdbeFreeOpArray(db, p->aOp, p->nOp);
 1.64020 +  sqlite3DbFree(db, p->aColName);
 1.64021 +  sqlite3DbFree(db, p->zSql);
 1.64022 +  sqlite3DbFree(db, p->pFree);
 1.64023 +#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
 1.64024 +  sqlite3DbFree(db, p->zExplain);
 1.64025 +  sqlite3DbFree(db, p->pExplain);
 1.64026 +#endif
 1.64027 +}
 1.64028 +
 1.64029 +/*
 1.64030 +** Delete an entire VDBE.
 1.64031 +*/
 1.64032 +SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
 1.64033 +  sqlite3 *db;
 1.64034 +
 1.64035 +  if( NEVER(p==0) ) return;
 1.64036 +  db = p->db;
 1.64037 +  assert( sqlite3_mutex_held(db->mutex) );
 1.64038 +  sqlite3VdbeClearObject(db, p);
 1.64039 +  if( p->pPrev ){
 1.64040 +    p->pPrev->pNext = p->pNext;
 1.64041 +  }else{
 1.64042 +    assert( db->pVdbe==p );
 1.64043 +    db->pVdbe = p->pNext;
 1.64044 +  }
 1.64045 +  if( p->pNext ){
 1.64046 +    p->pNext->pPrev = p->pPrev;
 1.64047 +  }
 1.64048 +  p->magic = VDBE_MAGIC_DEAD;
 1.64049 +  p->db = 0;
 1.64050 +  sqlite3DbFree(db, p);
 1.64051 +}
 1.64052 +
 1.64053 +/*
 1.64054 +** Make sure the cursor p is ready to read or write the row to which it
 1.64055 +** was last positioned.  Return an error code if an OOM fault or I/O error
 1.64056 +** prevents us from positioning the cursor to its correct position.
 1.64057 +**
 1.64058 +** If a MoveTo operation is pending on the given cursor, then do that
 1.64059 +** MoveTo now.  If no move is pending, check to see if the row has been
 1.64060 +** deleted out from under the cursor and if it has, mark the row as
 1.64061 +** a NULL row.
 1.64062 +**
 1.64063 +** If the cursor is already pointing to the correct row and that row has
 1.64064 +** not been deleted out from under the cursor, then this routine is a no-op.
 1.64065 +*/
 1.64066 +SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
 1.64067 +  if( p->deferredMoveto ){
 1.64068 +    int res, rc;
 1.64069 +#ifdef SQLITE_TEST
 1.64070 +    extern int sqlite3_search_count;
 1.64071 +#endif
 1.64072 +    assert( p->isTable );
 1.64073 +    rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
 1.64074 +    if( rc ) return rc;
 1.64075 +    p->lastRowid = p->movetoTarget;
 1.64076 +    if( res!=0 ) return SQLITE_CORRUPT_BKPT;
 1.64077 +    p->rowidIsValid = 1;
 1.64078 +#ifdef SQLITE_TEST
 1.64079 +    sqlite3_search_count++;
 1.64080 +#endif
 1.64081 +    p->deferredMoveto = 0;
 1.64082 +    p->cacheStatus = CACHE_STALE;
 1.64083 +  }else if( p->pCursor ){
 1.64084 +    int hasMoved;
 1.64085 +    int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
 1.64086 +    if( rc ) return rc;
 1.64087 +    if( hasMoved ){
 1.64088 +      p->cacheStatus = CACHE_STALE;
 1.64089 +      p->nullRow = 1;
 1.64090 +    }
 1.64091 +  }
 1.64092 +  return SQLITE_OK;
 1.64093 +}
 1.64094 +
 1.64095 +/*
 1.64096 +** The following functions:
 1.64097 +**
 1.64098 +** sqlite3VdbeSerialType()
 1.64099 +** sqlite3VdbeSerialTypeLen()
 1.64100 +** sqlite3VdbeSerialLen()
 1.64101 +** sqlite3VdbeSerialPut()
 1.64102 +** sqlite3VdbeSerialGet()
 1.64103 +**
 1.64104 +** encapsulate the code that serializes values for storage in SQLite
 1.64105 +** data and index records. Each serialized value consists of a
 1.64106 +** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
 1.64107 +** integer, stored as a varint.
 1.64108 +**
 1.64109 +** In an SQLite index record, the serial type is stored directly before
 1.64110 +** the blob of data that it corresponds to. In a table record, all serial
 1.64111 +** types are stored at the start of the record, and the blobs of data at
 1.64112 +** the end. Hence these functions allow the caller to handle the
 1.64113 +** serial-type and data blob separately.
 1.64114 +**
 1.64115 +** The following table describes the various storage classes for data:
 1.64116 +**
 1.64117 +**   serial type        bytes of data      type
 1.64118 +**   --------------     ---------------    ---------------
 1.64119 +**      0                     0            NULL
 1.64120 +**      1                     1            signed integer
 1.64121 +**      2                     2            signed integer
 1.64122 +**      3                     3            signed integer
 1.64123 +**      4                     4            signed integer
 1.64124 +**      5                     6            signed integer
 1.64125 +**      6                     8            signed integer
 1.64126 +**      7                     8            IEEE float
 1.64127 +**      8                     0            Integer constant 0
 1.64128 +**      9                     0            Integer constant 1
 1.64129 +**     10,11                               reserved for expansion
 1.64130 +**    N>=12 and even       (N-12)/2        BLOB
 1.64131 +**    N>=13 and odd        (N-13)/2        text
 1.64132 +**
 1.64133 +** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
 1.64134 +** of SQLite will not understand those serial types.
 1.64135 +*/
 1.64136 +
 1.64137 +/*
 1.64138 +** Return the serial-type for the value stored in pMem.
 1.64139 +*/
 1.64140 +SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
 1.64141 +  int flags = pMem->flags;
 1.64142 +  int n;
 1.64143 +
 1.64144 +  if( flags&MEM_Null ){
 1.64145 +    return 0;
 1.64146 +  }
 1.64147 +  if( flags&MEM_Int ){
 1.64148 +    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
 1.64149 +#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
 1.64150 +    i64 i = pMem->u.i;
 1.64151 +    u64 u;
 1.64152 +    if( i<0 ){
 1.64153 +      if( i<(-MAX_6BYTE) ) return 6;
 1.64154 +      /* Previous test prevents:  u = -(-9223372036854775808) */
 1.64155 +      u = -i;
 1.64156 +    }else{
 1.64157 +      u = i;
 1.64158 +    }
 1.64159 +    if( u<=127 ){
 1.64160 +      return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
 1.64161 +    }
 1.64162 +    if( u<=32767 ) return 2;
 1.64163 +    if( u<=8388607 ) return 3;
 1.64164 +    if( u<=2147483647 ) return 4;
 1.64165 +    if( u<=MAX_6BYTE ) return 5;
 1.64166 +    return 6;
 1.64167 +  }
 1.64168 +  if( flags&MEM_Real ){
 1.64169 +    return 7;
 1.64170 +  }
 1.64171 +  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
 1.64172 +  n = pMem->n;
 1.64173 +  if( flags & MEM_Zero ){
 1.64174 +    n += pMem->u.nZero;
 1.64175 +  }
 1.64176 +  assert( n>=0 );
 1.64177 +  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
 1.64178 +}
 1.64179 +
 1.64180 +/*
 1.64181 +** Return the length of the data corresponding to the supplied serial-type.
 1.64182 +*/
 1.64183 +SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
 1.64184 +  if( serial_type>=12 ){
 1.64185 +    return (serial_type-12)/2;
 1.64186 +  }else{
 1.64187 +    static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
 1.64188 +    return aSize[serial_type];
 1.64189 +  }
 1.64190 +}
 1.64191 +
 1.64192 +/*
 1.64193 +** If we are on an architecture with mixed-endian floating 
 1.64194 +** points (ex: ARM7) then swap the lower 4 bytes with the 
 1.64195 +** upper 4 bytes.  Return the result.
 1.64196 +**
 1.64197 +** For most architectures, this is a no-op.
 1.64198 +**
 1.64199 +** (later):  It is reported to me that the mixed-endian problem
 1.64200 +** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
 1.64201 +** that early versions of GCC stored the two words of a 64-bit
 1.64202 +** float in the wrong order.  And that error has been propagated
 1.64203 +** ever since.  The blame is not necessarily with GCC, though.
 1.64204 +** GCC might have just copying the problem from a prior compiler.
 1.64205 +** I am also told that newer versions of GCC that follow a different
 1.64206 +** ABI get the byte order right.
 1.64207 +**
 1.64208 +** Developers using SQLite on an ARM7 should compile and run their
 1.64209 +** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
 1.64210 +** enabled, some asserts below will ensure that the byte order of
 1.64211 +** floating point values is correct.
 1.64212 +**
 1.64213 +** (2007-08-30)  Frank van Vugt has studied this problem closely
 1.64214 +** and has send his findings to the SQLite developers.  Frank
 1.64215 +** writes that some Linux kernels offer floating point hardware
 1.64216 +** emulation that uses only 32-bit mantissas instead of a full 
 1.64217 +** 48-bits as required by the IEEE standard.  (This is the
 1.64218 +** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
 1.64219 +** byte swapping becomes very complicated.  To avoid problems,
 1.64220 +** the necessary byte swapping is carried out using a 64-bit integer
 1.64221 +** rather than a 64-bit float.  Frank assures us that the code here
 1.64222 +** works for him.  We, the developers, have no way to independently
 1.64223 +** verify this, but Frank seems to know what he is talking about
 1.64224 +** so we trust him.
 1.64225 +*/
 1.64226 +#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
 1.64227 +static u64 floatSwap(u64 in){
 1.64228 +  union {
 1.64229 +    u64 r;
 1.64230 +    u32 i[2];
 1.64231 +  } u;
 1.64232 +  u32 t;
 1.64233 +
 1.64234 +  u.r = in;
 1.64235 +  t = u.i[0];
 1.64236 +  u.i[0] = u.i[1];
 1.64237 +  u.i[1] = t;
 1.64238 +  return u.r;
 1.64239 +}
 1.64240 +# define swapMixedEndianFloat(X)  X = floatSwap(X)
 1.64241 +#else
 1.64242 +# define swapMixedEndianFloat(X)
 1.64243 +#endif
 1.64244 +
 1.64245 +/*
 1.64246 +** Write the serialized data blob for the value stored in pMem into 
 1.64247 +** buf. It is assumed that the caller has allocated sufficient space.
 1.64248 +** Return the number of bytes written.
 1.64249 +**
 1.64250 +** nBuf is the amount of space left in buf[].  The caller is responsible
 1.64251 +** for allocating enough space to buf[] to hold the entire field, exclusive
 1.64252 +** of the pMem->u.nZero bytes for a MEM_Zero value.
 1.64253 +**
 1.64254 +** Return the number of bytes actually written into buf[].  The number
 1.64255 +** of bytes in the zero-filled tail is included in the return value only
 1.64256 +** if those bytes were zeroed in buf[].
 1.64257 +*/ 
 1.64258 +SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
 1.64259 +  u32 len;
 1.64260 +
 1.64261 +  /* Integer and Real */
 1.64262 +  if( serial_type<=7 && serial_type>0 ){
 1.64263 +    u64 v;
 1.64264 +    u32 i;
 1.64265 +    if( serial_type==7 ){
 1.64266 +      assert( sizeof(v)==sizeof(pMem->r) );
 1.64267 +      memcpy(&v, &pMem->r, sizeof(v));
 1.64268 +      swapMixedEndianFloat(v);
 1.64269 +    }else{
 1.64270 +      v = pMem->u.i;
 1.64271 +    }
 1.64272 +    len = i = sqlite3VdbeSerialTypeLen(serial_type);
 1.64273 +    while( i-- ){
 1.64274 +      buf[i] = (u8)(v&0xFF);
 1.64275 +      v >>= 8;
 1.64276 +    }
 1.64277 +    return len;
 1.64278 +  }
 1.64279 +
 1.64280 +  /* String or blob */
 1.64281 +  if( serial_type>=12 ){
 1.64282 +    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
 1.64283 +             == (int)sqlite3VdbeSerialTypeLen(serial_type) );
 1.64284 +    len = pMem->n;
 1.64285 +    memcpy(buf, pMem->z, len);
 1.64286 +    return len;
 1.64287 +  }
 1.64288 +
 1.64289 +  /* NULL or constants 0 or 1 */
 1.64290 +  return 0;
 1.64291 +}
 1.64292 +
 1.64293 +/* Input "x" is a sequence of unsigned characters that represent a
 1.64294 +** big-endian integer.  Return the equivalent native integer
 1.64295 +*/
 1.64296 +#define ONE_BYTE_INT(x)    ((i8)(x)[0])
 1.64297 +#define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
 1.64298 +#define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
 1.64299 +#define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
 1.64300 +
 1.64301 +/*
 1.64302 +** Deserialize the data blob pointed to by buf as serial type serial_type
 1.64303 +** and store the result in pMem.  Return the number of bytes read.
 1.64304 +*/ 
 1.64305 +SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
 1.64306 +  const unsigned char *buf,     /* Buffer to deserialize from */
 1.64307 +  u32 serial_type,              /* Serial type to deserialize */
 1.64308 +  Mem *pMem                     /* Memory cell to write value into */
 1.64309 +){
 1.64310 +  u64 x;
 1.64311 +  u32 y;
 1.64312 +  switch( serial_type ){
 1.64313 +    case 10:   /* Reserved for future use */
 1.64314 +    case 11:   /* Reserved for future use */
 1.64315 +    case 0: {  /* NULL */
 1.64316 +      pMem->flags = MEM_Null;
 1.64317 +      break;
 1.64318 +    }
 1.64319 +    case 1: { /* 1-byte signed integer */
 1.64320 +      pMem->u.i = ONE_BYTE_INT(buf);
 1.64321 +      pMem->flags = MEM_Int;
 1.64322 +      testcase( pMem->u.i<0 );
 1.64323 +      return 1;
 1.64324 +    }
 1.64325 +    case 2: { /* 2-byte signed integer */
 1.64326 +      pMem->u.i = TWO_BYTE_INT(buf);
 1.64327 +      pMem->flags = MEM_Int;
 1.64328 +      testcase( pMem->u.i<0 );
 1.64329 +      return 2;
 1.64330 +    }
 1.64331 +    case 3: { /* 3-byte signed integer */
 1.64332 +      pMem->u.i = THREE_BYTE_INT(buf);
 1.64333 +      pMem->flags = MEM_Int;
 1.64334 +      testcase( pMem->u.i<0 );
 1.64335 +      return 3;
 1.64336 +    }
 1.64337 +    case 4: { /* 4-byte signed integer */
 1.64338 +      y = FOUR_BYTE_UINT(buf);
 1.64339 +      pMem->u.i = (i64)*(int*)&y;
 1.64340 +      pMem->flags = MEM_Int;
 1.64341 +      testcase( pMem->u.i<0 );
 1.64342 +      return 4;
 1.64343 +    }
 1.64344 +    case 5: { /* 6-byte signed integer */
 1.64345 +      pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
 1.64346 +      pMem->flags = MEM_Int;
 1.64347 +      testcase( pMem->u.i<0 );
 1.64348 +      return 6;
 1.64349 +    }
 1.64350 +    case 6:   /* 8-byte signed integer */
 1.64351 +    case 7: { /* IEEE floating point */
 1.64352 +#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
 1.64353 +      /* Verify that integers and floating point values use the same
 1.64354 +      ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
 1.64355 +      ** defined that 64-bit floating point values really are mixed
 1.64356 +      ** endian.
 1.64357 +      */
 1.64358 +      static const u64 t1 = ((u64)0x3ff00000)<<32;
 1.64359 +      static const double r1 = 1.0;
 1.64360 +      u64 t2 = t1;
 1.64361 +      swapMixedEndianFloat(t2);
 1.64362 +      assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
 1.64363 +#endif
 1.64364 +      x = FOUR_BYTE_UINT(buf);
 1.64365 +      y = FOUR_BYTE_UINT(buf+4);
 1.64366 +      x = (x<<32) | y;
 1.64367 +      if( serial_type==6 ){
 1.64368 +        pMem->u.i = *(i64*)&x;
 1.64369 +        pMem->flags = MEM_Int;
 1.64370 +        testcase( pMem->u.i<0 );
 1.64371 +      }else{
 1.64372 +        assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
 1.64373 +        swapMixedEndianFloat(x);
 1.64374 +        memcpy(&pMem->r, &x, sizeof(x));
 1.64375 +        pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
 1.64376 +      }
 1.64377 +      return 8;
 1.64378 +    }
 1.64379 +    case 8:    /* Integer 0 */
 1.64380 +    case 9: {  /* Integer 1 */
 1.64381 +      pMem->u.i = serial_type-8;
 1.64382 +      pMem->flags = MEM_Int;
 1.64383 +      return 0;
 1.64384 +    }
 1.64385 +    default: {
 1.64386 +      static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
 1.64387 +      u32 len = (serial_type-12)/2;
 1.64388 +      pMem->z = (char *)buf;
 1.64389 +      pMem->n = len;
 1.64390 +      pMem->xDel = 0;
 1.64391 +      pMem->flags = aFlag[serial_type&1];
 1.64392 +      return len;
 1.64393 +    }
 1.64394 +  }
 1.64395 +  return 0;
 1.64396 +}
 1.64397 +
 1.64398 +/*
 1.64399 +** This routine is used to allocate sufficient space for an UnpackedRecord
 1.64400 +** structure large enough to be used with sqlite3VdbeRecordUnpack() if
 1.64401 +** the first argument is a pointer to KeyInfo structure pKeyInfo.
 1.64402 +**
 1.64403 +** The space is either allocated using sqlite3DbMallocRaw() or from within
 1.64404 +** the unaligned buffer passed via the second and third arguments (presumably
 1.64405 +** stack space). If the former, then *ppFree is set to a pointer that should
 1.64406 +** be eventually freed by the caller using sqlite3DbFree(). Or, if the 
 1.64407 +** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
 1.64408 +** before returning.
 1.64409 +**
 1.64410 +** If an OOM error occurs, NULL is returned.
 1.64411 +*/
 1.64412 +SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
 1.64413 +  KeyInfo *pKeyInfo,              /* Description of the record */
 1.64414 +  char *pSpace,                   /* Unaligned space available */
 1.64415 +  int szSpace,                    /* Size of pSpace[] in bytes */
 1.64416 +  char **ppFree                   /* OUT: Caller should free this pointer */
 1.64417 +){
 1.64418 +  UnpackedRecord *p;              /* Unpacked record to return */
 1.64419 +  int nOff;                       /* Increment pSpace by nOff to align it */
 1.64420 +  int nByte;                      /* Number of bytes required for *p */
 1.64421 +
 1.64422 +  /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
 1.64423 +  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
 1.64424 +  ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
 1.64425 +  */
 1.64426 +  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
 1.64427 +  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
 1.64428 +  if( nByte>szSpace+nOff ){
 1.64429 +    p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
 1.64430 +    *ppFree = (char *)p;
 1.64431 +    if( !p ) return 0;
 1.64432 +  }else{
 1.64433 +    p = (UnpackedRecord*)&pSpace[nOff];
 1.64434 +    *ppFree = 0;
 1.64435 +  }
 1.64436 +
 1.64437 +  p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
 1.64438 +  assert( pKeyInfo->aSortOrder!=0 );
 1.64439 +  p->pKeyInfo = pKeyInfo;
 1.64440 +  p->nField = pKeyInfo->nField + 1;
 1.64441 +  return p;
 1.64442 +}
 1.64443 +
 1.64444 +/*
 1.64445 +** Given the nKey-byte encoding of a record in pKey[], populate the 
 1.64446 +** UnpackedRecord structure indicated by the fourth argument with the
 1.64447 +** contents of the decoded record.
 1.64448 +*/ 
 1.64449 +SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
 1.64450 +  KeyInfo *pKeyInfo,     /* Information about the record format */
 1.64451 +  int nKey,              /* Size of the binary record */
 1.64452 +  const void *pKey,      /* The binary record */
 1.64453 +  UnpackedRecord *p      /* Populate this structure before returning. */
 1.64454 +){
 1.64455 +  const unsigned char *aKey = (const unsigned char *)pKey;
 1.64456 +  int d; 
 1.64457 +  u32 idx;                        /* Offset in aKey[] to read from */
 1.64458 +  u16 u;                          /* Unsigned loop counter */
 1.64459 +  u32 szHdr;
 1.64460 +  Mem *pMem = p->aMem;
 1.64461 +
 1.64462 +  p->default_rc = 0;
 1.64463 +  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 1.64464 +  idx = getVarint32(aKey, szHdr);
 1.64465 +  d = szHdr;
 1.64466 +  u = 0;
 1.64467 +  while( idx<szHdr && u<p->nField && d<=nKey ){
 1.64468 +    u32 serial_type;
 1.64469 +
 1.64470 +    idx += getVarint32(&aKey[idx], serial_type);
 1.64471 +    pMem->enc = pKeyInfo->enc;
 1.64472 +    pMem->db = pKeyInfo->db;
 1.64473 +    /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
 1.64474 +    pMem->zMalloc = 0;
 1.64475 +    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
 1.64476 +    pMem++;
 1.64477 +    u++;
 1.64478 +  }
 1.64479 +  assert( u<=pKeyInfo->nField + 1 );
 1.64480 +  p->nField = u;
 1.64481 +}
 1.64482 +
 1.64483 +#if SQLITE_DEBUG
 1.64484 +/*
 1.64485 +** This function compares two index or table record keys in the same way
 1.64486 +** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
 1.64487 +** this function deserializes and compares values using the
 1.64488 +** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
 1.64489 +** in assert() statements to ensure that the optimized code in
 1.64490 +** sqlite3VdbeRecordCompare() returns results with these two primitives.
 1.64491 +*/
 1.64492 +static int vdbeRecordCompareDebug(
 1.64493 +  int nKey1, const void *pKey1, /* Left key */
 1.64494 +  const UnpackedRecord *pPKey2  /* Right key */
 1.64495 +){
 1.64496 +  u32 d1;            /* Offset into aKey[] of next data element */
 1.64497 +  u32 idx1;          /* Offset into aKey[] of next header element */
 1.64498 +  u32 szHdr1;        /* Number of bytes in header */
 1.64499 +  int i = 0;
 1.64500 +  int rc = 0;
 1.64501 +  const unsigned char *aKey1 = (const unsigned char *)pKey1;
 1.64502 +  KeyInfo *pKeyInfo;
 1.64503 +  Mem mem1;
 1.64504 +
 1.64505 +  pKeyInfo = pPKey2->pKeyInfo;
 1.64506 +  mem1.enc = pKeyInfo->enc;
 1.64507 +  mem1.db = pKeyInfo->db;
 1.64508 +  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
 1.64509 +  VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
 1.64510 +
 1.64511 +  /* Compilers may complain that mem1.u.i is potentially uninitialized.
 1.64512 +  ** We could initialize it, as shown here, to silence those complaints.
 1.64513 +  ** But in fact, mem1.u.i will never actually be used uninitialized, and doing 
 1.64514 +  ** the unnecessary initialization has a measurable negative performance
 1.64515 +  ** impact, since this routine is a very high runner.  And so, we choose
 1.64516 +  ** to ignore the compiler warnings and leave this variable uninitialized.
 1.64517 +  */
 1.64518 +  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
 1.64519 +  
 1.64520 +  idx1 = getVarint32(aKey1, szHdr1);
 1.64521 +  d1 = szHdr1;
 1.64522 +  assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
 1.64523 +  assert( pKeyInfo->aSortOrder!=0 );
 1.64524 +  assert( pKeyInfo->nField>0 );
 1.64525 +  assert( idx1<=szHdr1 || CORRUPT_DB );
 1.64526 +  do{
 1.64527 +    u32 serial_type1;
 1.64528 +
 1.64529 +    /* Read the serial types for the next element in each key. */
 1.64530 +    idx1 += getVarint32( aKey1+idx1, serial_type1 );
 1.64531 +
 1.64532 +    /* Verify that there is enough key space remaining to avoid
 1.64533 +    ** a buffer overread.  The "d1+serial_type1+2" subexpression will
 1.64534 +    ** always be greater than or equal to the amount of required key space.
 1.64535 +    ** Use that approximation to avoid the more expensive call to
 1.64536 +    ** sqlite3VdbeSerialTypeLen() in the common case.
 1.64537 +    */
 1.64538 +    if( d1+serial_type1+2>(u32)nKey1
 1.64539 +     && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1 
 1.64540 +    ){
 1.64541 +      break;
 1.64542 +    }
 1.64543 +
 1.64544 +    /* Extract the values to be compared.
 1.64545 +    */
 1.64546 +    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
 1.64547 +
 1.64548 +    /* Do the comparison
 1.64549 +    */
 1.64550 +    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
 1.64551 +    if( rc!=0 ){
 1.64552 +      assert( mem1.zMalloc==0 );  /* See comment below */
 1.64553 +      if( pKeyInfo->aSortOrder[i] ){
 1.64554 +        rc = -rc;  /* Invert the result for DESC sort order. */
 1.64555 +      }
 1.64556 +      return rc;
 1.64557 +    }
 1.64558 +    i++;
 1.64559 +  }while( idx1<szHdr1 && i<pPKey2->nField );
 1.64560 +
 1.64561 +  /* No memory allocation is ever used on mem1.  Prove this using
 1.64562 +  ** the following assert().  If the assert() fails, it indicates a
 1.64563 +  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
 1.64564 +  */
 1.64565 +  assert( mem1.zMalloc==0 );
 1.64566 +
 1.64567 +  /* rc==0 here means that one of the keys ran out of fields and
 1.64568 +  ** all the fields up to that point were equal. Return the the default_rc
 1.64569 +  ** value.  */
 1.64570 +  return pPKey2->default_rc;
 1.64571 +}
 1.64572 +#endif
 1.64573 +
 1.64574 +/*
 1.64575 +** Both *pMem1 and *pMem2 contain string values. Compare the two values
 1.64576 +** using the collation sequence pColl. As usual, return a negative , zero
 1.64577 +** or positive value if *pMem1 is less than, equal to or greater than 
 1.64578 +** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
 1.64579 +*/
 1.64580 +static int vdbeCompareMemString(
 1.64581 +  const Mem *pMem1,
 1.64582 +  const Mem *pMem2,
 1.64583 +  const CollSeq *pColl
 1.64584 +){
 1.64585 +  if( pMem1->enc==pColl->enc ){
 1.64586 +    /* The strings are already in the correct encoding.  Call the
 1.64587 +     ** comparison function directly */
 1.64588 +    return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
 1.64589 +  }else{
 1.64590 +    int rc;
 1.64591 +    const void *v1, *v2;
 1.64592 +    int n1, n2;
 1.64593 +    Mem c1;
 1.64594 +    Mem c2;
 1.64595 +    memset(&c1, 0, sizeof(c1));
 1.64596 +    memset(&c2, 0, sizeof(c2));
 1.64597 +    sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
 1.64598 +    sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
 1.64599 +    v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
 1.64600 +    n1 = v1==0 ? 0 : c1.n;
 1.64601 +    v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
 1.64602 +    n2 = v2==0 ? 0 : c2.n;
 1.64603 +    rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
 1.64604 +    sqlite3VdbeMemRelease(&c1);
 1.64605 +    sqlite3VdbeMemRelease(&c2);
 1.64606 +    return rc;
 1.64607 +  }
 1.64608 +}
 1.64609 +
 1.64610 +/*
 1.64611 +** Compare the values contained by the two memory cells, returning
 1.64612 +** negative, zero or positive if pMem1 is less than, equal to, or greater
 1.64613 +** than pMem2. Sorting order is NULL's first, followed by numbers (integers
 1.64614 +** and reals) sorted numerically, followed by text ordered by the collating
 1.64615 +** sequence pColl and finally blob's ordered by memcmp().
 1.64616 +**
 1.64617 +** Two NULL values are considered equal by this function.
 1.64618 +*/
 1.64619 +SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
 1.64620 +  int rc;
 1.64621 +  int f1, f2;
 1.64622 +  int combined_flags;
 1.64623 +
 1.64624 +  f1 = pMem1->flags;
 1.64625 +  f2 = pMem2->flags;
 1.64626 +  combined_flags = f1|f2;
 1.64627 +  assert( (combined_flags & MEM_RowSet)==0 );
 1.64628 + 
 1.64629 +  /* If one value is NULL, it is less than the other. If both values
 1.64630 +  ** are NULL, return 0.
 1.64631 +  */
 1.64632 +  if( combined_flags&MEM_Null ){
 1.64633 +    return (f2&MEM_Null) - (f1&MEM_Null);
 1.64634 +  }
 1.64635 +
 1.64636 +  /* If one value is a number and the other is not, the number is less.
 1.64637 +  ** If both are numbers, compare as reals if one is a real, or as integers
 1.64638 +  ** if both values are integers.
 1.64639 +  */
 1.64640 +  if( combined_flags&(MEM_Int|MEM_Real) ){
 1.64641 +    double r1, r2;
 1.64642 +    if( (f1 & f2 & MEM_Int)!=0 ){
 1.64643 +      if( pMem1->u.i < pMem2->u.i ) return -1;
 1.64644 +      if( pMem1->u.i > pMem2->u.i ) return 1;
 1.64645 +      return 0;
 1.64646 +    }
 1.64647 +    if( (f1&MEM_Real)!=0 ){
 1.64648 +      r1 = pMem1->r;
 1.64649 +    }else if( (f1&MEM_Int)!=0 ){
 1.64650 +      r1 = (double)pMem1->u.i;
 1.64651 +    }else{
 1.64652 +      return 1;
 1.64653 +    }
 1.64654 +    if( (f2&MEM_Real)!=0 ){
 1.64655 +      r2 = pMem2->r;
 1.64656 +    }else if( (f2&MEM_Int)!=0 ){
 1.64657 +      r2 = (double)pMem2->u.i;
 1.64658 +    }else{
 1.64659 +      return -1;
 1.64660 +    }
 1.64661 +    if( r1<r2 ) return -1;
 1.64662 +    if( r1>r2 ) return 1;
 1.64663 +    return 0;
 1.64664 +  }
 1.64665 +
 1.64666 +  /* If one value is a string and the other is a blob, the string is less.
 1.64667 +  ** If both are strings, compare using the collating functions.
 1.64668 +  */
 1.64669 +  if( combined_flags&MEM_Str ){
 1.64670 +    if( (f1 & MEM_Str)==0 ){
 1.64671 +      return 1;
 1.64672 +    }
 1.64673 +    if( (f2 & MEM_Str)==0 ){
 1.64674 +      return -1;
 1.64675 +    }
 1.64676 +
 1.64677 +    assert( pMem1->enc==pMem2->enc );
 1.64678 +    assert( pMem1->enc==SQLITE_UTF8 || 
 1.64679 +            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
 1.64680 +
 1.64681 +    /* The collation sequence must be defined at this point, even if
 1.64682 +    ** the user deletes the collation sequence after the vdbe program is
 1.64683 +    ** compiled (this was not always the case).
 1.64684 +    */
 1.64685 +    assert( !pColl || pColl->xCmp );
 1.64686 +
 1.64687 +    if( pColl ){
 1.64688 +      return vdbeCompareMemString(pMem1, pMem2, pColl);
 1.64689 +    }
 1.64690 +    /* If a NULL pointer was passed as the collate function, fall through
 1.64691 +    ** to the blob case and use memcmp().  */
 1.64692 +  }
 1.64693 + 
 1.64694 +  /* Both values must be blobs.  Compare using memcmp().  */
 1.64695 +  rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
 1.64696 +  if( rc==0 ){
 1.64697 +    rc = pMem1->n - pMem2->n;
 1.64698 +  }
 1.64699 +  return rc;
 1.64700 +}
 1.64701 +
 1.64702 +
 1.64703 +/*
 1.64704 +** The first argument passed to this function is a serial-type that
 1.64705 +** corresponds to an integer - all values between 1 and 9 inclusive 
 1.64706 +** except 7. The second points to a buffer containing an integer value
 1.64707 +** serialized according to serial_type. This function deserializes
 1.64708 +** and returns the value.
 1.64709 +*/
 1.64710 +static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
 1.64711 +  u32 y;
 1.64712 +  assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
 1.64713 +  switch( serial_type ){
 1.64714 +    case 0:
 1.64715 +    case 1:
 1.64716 +      testcase( aKey[0]&0x80 );
 1.64717 +      return ONE_BYTE_INT(aKey);
 1.64718 +    case 2:
 1.64719 +      testcase( aKey[0]&0x80 );
 1.64720 +      return TWO_BYTE_INT(aKey);
 1.64721 +    case 3:
 1.64722 +      testcase( aKey[0]&0x80 );
 1.64723 +      return THREE_BYTE_INT(aKey);
 1.64724 +    case 4: {
 1.64725 +      testcase( aKey[0]&0x80 );
 1.64726 +      y = FOUR_BYTE_UINT(aKey);
 1.64727 +      return (i64)*(int*)&y;
 1.64728 +    }
 1.64729 +    case 5: {
 1.64730 +      testcase( aKey[0]&0x80 );
 1.64731 +      return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
 1.64732 +    }
 1.64733 +    case 6: {
 1.64734 +      u64 x = FOUR_BYTE_UINT(aKey);
 1.64735 +      testcase( aKey[0]&0x80 );
 1.64736 +      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
 1.64737 +      return (i64)*(i64*)&x;
 1.64738 +    }
 1.64739 +  }
 1.64740 +
 1.64741 +  return (serial_type - 8);
 1.64742 +}
 1.64743 +
 1.64744 +/*
 1.64745 +** This function compares the two table rows or index records
 1.64746 +** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
 1.64747 +** or positive integer if key1 is less than, equal to or 
 1.64748 +** greater than key2.  The {nKey1, pKey1} key must be a blob
 1.64749 +** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
 1.64750 +** key must be a parsed key such as obtained from
 1.64751 +** sqlite3VdbeParseRecord.
 1.64752 +**
 1.64753 +** If argument bSkip is non-zero, it is assumed that the caller has already
 1.64754 +** determined that the first fields of the keys are equal.
 1.64755 +**
 1.64756 +** Key1 and Key2 do not have to contain the same number of fields. If all 
 1.64757 +** fields that appear in both keys are equal, then pPKey2->default_rc is 
 1.64758 +** returned.
 1.64759 +*/
 1.64760 +SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
 1.64761 +  int nKey1, const void *pKey1,   /* Left key */
 1.64762 +  const UnpackedRecord *pPKey2,   /* Right key */
 1.64763 +  int bSkip                       /* If true, skip the first field */
 1.64764 +){
 1.64765 +  u32 d1;                         /* Offset into aKey[] of next data element */
 1.64766 +  int i;                          /* Index of next field to compare */
 1.64767 +  u32 szHdr1;                     /* Size of record header in bytes */
 1.64768 +  u32 idx1;                       /* Offset of first type in header */
 1.64769 +  int rc = 0;                     /* Return value */
 1.64770 +  Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
 1.64771 +  KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
 1.64772 +  const unsigned char *aKey1 = (const unsigned char *)pKey1;
 1.64773 +  Mem mem1;
 1.64774 +
 1.64775 +  /* If bSkip is true, then the caller has already determined that the first
 1.64776 +  ** two elements in the keys are equal. Fix the various stack variables so
 1.64777 +  ** that this routine begins comparing at the second field. */
 1.64778 +  if( bSkip ){
 1.64779 +    u32 s1;
 1.64780 +    idx1 = 1 + getVarint32(&aKey1[1], s1);
 1.64781 +    szHdr1 = aKey1[0];
 1.64782 +    d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
 1.64783 +    i = 1;
 1.64784 +    pRhs++;
 1.64785 +  }else{
 1.64786 +    idx1 = getVarint32(aKey1, szHdr1);
 1.64787 +    d1 = szHdr1;
 1.64788 +    if( d1>(unsigned)nKey1 ) return 1;  /* Corruption */
 1.64789 +    i = 0;
 1.64790 +  }
 1.64791 +
 1.64792 +  VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
 1.64793 +  assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField 
 1.64794 +       || CORRUPT_DB );
 1.64795 +  assert( pPKey2->pKeyInfo->aSortOrder!=0 );
 1.64796 +  assert( pPKey2->pKeyInfo->nField>0 );
 1.64797 +  assert( idx1<=szHdr1 || CORRUPT_DB );
 1.64798 +  do{
 1.64799 +    u32 serial_type;
 1.64800 +
 1.64801 +    /* RHS is an integer */
 1.64802 +    if( pRhs->flags & MEM_Int ){
 1.64803 +      serial_type = aKey1[idx1];
 1.64804 +      testcase( serial_type==12 );
 1.64805 +      if( serial_type>=12 ){
 1.64806 +        rc = +1;
 1.64807 +      }else if( serial_type==0 ){
 1.64808 +        rc = -1;
 1.64809 +      }else if( serial_type==7 ){
 1.64810 +        double rhs = (double)pRhs->u.i;
 1.64811 +        sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
 1.64812 +        if( mem1.r<rhs ){
 1.64813 +          rc = -1;
 1.64814 +        }else if( mem1.r>rhs ){
 1.64815 +          rc = +1;
 1.64816 +        }
 1.64817 +      }else{
 1.64818 +        i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
 1.64819 +        i64 rhs = pRhs->u.i;
 1.64820 +        if( lhs<rhs ){
 1.64821 +          rc = -1;
 1.64822 +        }else if( lhs>rhs ){
 1.64823 +          rc = +1;
 1.64824 +        }
 1.64825 +      }
 1.64826 +    }
 1.64827 +
 1.64828 +    /* RHS is real */
 1.64829 +    else if( pRhs->flags & MEM_Real ){
 1.64830 +      serial_type = aKey1[idx1];
 1.64831 +      if( serial_type>=12 ){
 1.64832 +        rc = +1;
 1.64833 +      }else if( serial_type==0 ){
 1.64834 +        rc = -1;
 1.64835 +      }else{
 1.64836 +        double rhs = pRhs->r;
 1.64837 +        double lhs;
 1.64838 +        sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
 1.64839 +        if( serial_type==7 ){
 1.64840 +          lhs = mem1.r;
 1.64841 +        }else{
 1.64842 +          lhs = (double)mem1.u.i;
 1.64843 +        }
 1.64844 +        if( lhs<rhs ){
 1.64845 +          rc = -1;
 1.64846 +        }else if( lhs>rhs ){
 1.64847 +          rc = +1;
 1.64848 +        }
 1.64849 +      }
 1.64850 +    }
 1.64851 +
 1.64852 +    /* RHS is a string */
 1.64853 +    else if( pRhs->flags & MEM_Str ){
 1.64854 +      getVarint32(&aKey1[idx1], serial_type);
 1.64855 +      testcase( serial_type==12 );
 1.64856 +      if( serial_type<12 ){
 1.64857 +        rc = -1;
 1.64858 +      }else if( !(serial_type & 0x01) ){
 1.64859 +        rc = +1;
 1.64860 +      }else{
 1.64861 +        mem1.n = (serial_type - 12) / 2;
 1.64862 +        testcase( (d1+mem1.n)==(unsigned)nKey1 );
 1.64863 +        testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
 1.64864 +        if( (d1+mem1.n) > (unsigned)nKey1 ){
 1.64865 +          rc = 1;                /* Corruption */
 1.64866 +        }else if( pKeyInfo->aColl[i] ){
 1.64867 +          mem1.enc = pKeyInfo->enc;
 1.64868 +          mem1.db = pKeyInfo->db;
 1.64869 +          mem1.flags = MEM_Str;
 1.64870 +          mem1.z = (char*)&aKey1[d1];
 1.64871 +          rc = vdbeCompareMemString(&mem1, pRhs, pKeyInfo->aColl[i]);
 1.64872 +        }else{
 1.64873 +          int nCmp = MIN(mem1.n, pRhs->n);
 1.64874 +          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
 1.64875 +          if( rc==0 ) rc = mem1.n - pRhs->n; 
 1.64876 +        }
 1.64877 +      }
 1.64878 +    }
 1.64879 +
 1.64880 +    /* RHS is a blob */
 1.64881 +    else if( pRhs->flags & MEM_Blob ){
 1.64882 +      getVarint32(&aKey1[idx1], serial_type);
 1.64883 +      testcase( serial_type==12 );
 1.64884 +      if( serial_type<12 || (serial_type & 0x01) ){
 1.64885 +        rc = -1;
 1.64886 +      }else{
 1.64887 +        int nStr = (serial_type - 12) / 2;
 1.64888 +        testcase( (d1+nStr)==(unsigned)nKey1 );
 1.64889 +        testcase( (d1+nStr+1)==(unsigned)nKey1 );
 1.64890 +        if( (d1+nStr) > (unsigned)nKey1 ){
 1.64891 +          rc = 1;                /* Corruption */
 1.64892 +        }else{
 1.64893 +          int nCmp = MIN(nStr, pRhs->n);
 1.64894 +          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
 1.64895 +          if( rc==0 ) rc = nStr - pRhs->n;
 1.64896 +        }
 1.64897 +      }
 1.64898 +    }
 1.64899 +
 1.64900 +    /* RHS is null */
 1.64901 +    else{
 1.64902 +      serial_type = aKey1[idx1];
 1.64903 +      rc = (serial_type!=0);
 1.64904 +    }
 1.64905 +
 1.64906 +    if( rc!=0 ){
 1.64907 +      if( pKeyInfo->aSortOrder[i] ){
 1.64908 +        rc = -rc;
 1.64909 +      }
 1.64910 +      assert( CORRUPT_DB
 1.64911 +          || (rc<0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)<0)
 1.64912 +          || (rc>0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)>0)
 1.64913 +          || pKeyInfo->db->mallocFailed
 1.64914 +      );
 1.64915 +      assert( mem1.zMalloc==0 );  /* See comment below */
 1.64916 +      return rc;
 1.64917 +    }
 1.64918 +
 1.64919 +    i++;
 1.64920 +    pRhs++;
 1.64921 +    d1 += sqlite3VdbeSerialTypeLen(serial_type);
 1.64922 +    idx1 += sqlite3VarintLen(serial_type);
 1.64923 +  }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
 1.64924 +
 1.64925 +  /* No memory allocation is ever used on mem1.  Prove this using
 1.64926 +  ** the following assert().  If the assert() fails, it indicates a
 1.64927 +  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
 1.64928 +  assert( mem1.zMalloc==0 );
 1.64929 +
 1.64930 +  /* rc==0 here means that one or both of the keys ran out of fields and
 1.64931 +  ** all the fields up to that point were equal. Return the the default_rc
 1.64932 +  ** value.  */
 1.64933 +  assert( CORRUPT_DB 
 1.64934 +       || pPKey2->default_rc==vdbeRecordCompareDebug(nKey1, pKey1, pPKey2) 
 1.64935 +  );
 1.64936 +  return pPKey2->default_rc;
 1.64937 +}
 1.64938 +
 1.64939 +/*
 1.64940 +** This function is an optimized version of sqlite3VdbeRecordCompare() 
 1.64941 +** that (a) the first field of pPKey2 is an integer, and (b) the 
 1.64942 +** size-of-header varint at the start of (pKey1/nKey1) fits in a single
 1.64943 +** byte (i.e. is less than 128).
 1.64944 +*/
 1.64945 +static int vdbeRecordCompareInt(
 1.64946 +  int nKey1, const void *pKey1, /* Left key */
 1.64947 +  const UnpackedRecord *pPKey2, /* Right key */
 1.64948 +  int bSkip                     /* Ignored */
 1.64949 +){
 1.64950 +  const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
 1.64951 +  int serial_type = ((const u8*)pKey1)[1];
 1.64952 +  int res;
 1.64953 +  u32 y;
 1.64954 +  u64 x;
 1.64955 +  i64 v = pPKey2->aMem[0].u.i;
 1.64956 +  i64 lhs;
 1.64957 +  UNUSED_PARAMETER(bSkip);
 1.64958 +
 1.64959 +  assert( bSkip==0 );
 1.64960 +  switch( serial_type ){
 1.64961 +    case 1: { /* 1-byte signed integer */
 1.64962 +      lhs = ONE_BYTE_INT(aKey);
 1.64963 +      testcase( lhs<0 );
 1.64964 +      break;
 1.64965 +    }
 1.64966 +    case 2: { /* 2-byte signed integer */
 1.64967 +      lhs = TWO_BYTE_INT(aKey);
 1.64968 +      testcase( lhs<0 );
 1.64969 +      break;
 1.64970 +    }
 1.64971 +    case 3: { /* 3-byte signed integer */
 1.64972 +      lhs = THREE_BYTE_INT(aKey);
 1.64973 +      testcase( lhs<0 );
 1.64974 +      break;
 1.64975 +    }
 1.64976 +    case 4: { /* 4-byte signed integer */
 1.64977 +      y = FOUR_BYTE_UINT(aKey);
 1.64978 +      lhs = (i64)*(int*)&y;
 1.64979 +      testcase( lhs<0 );
 1.64980 +      break;
 1.64981 +    }
 1.64982 +    case 5: { /* 6-byte signed integer */
 1.64983 +      lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
 1.64984 +      testcase( lhs<0 );
 1.64985 +      break;
 1.64986 +    }
 1.64987 +    case 6: { /* 8-byte signed integer */
 1.64988 +      x = FOUR_BYTE_UINT(aKey);
 1.64989 +      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
 1.64990 +      lhs = *(i64*)&x;
 1.64991 +      testcase( lhs<0 );
 1.64992 +      break;
 1.64993 +    }
 1.64994 +    case 8: 
 1.64995 +      lhs = 0;
 1.64996 +      break;
 1.64997 +    case 9:
 1.64998 +      lhs = 1;
 1.64999 +      break;
 1.65000 +
 1.65001 +    /* This case could be removed without changing the results of running
 1.65002 +    ** this code. Including it causes gcc to generate a faster switch 
 1.65003 +    ** statement (since the range of switch targets now starts at zero and
 1.65004 +    ** is contiguous) but does not cause any duplicate code to be generated
 1.65005 +    ** (as gcc is clever enough to combine the two like cases). Other 
 1.65006 +    ** compilers might be similar.  */ 
 1.65007 +    case 0: case 7:
 1.65008 +      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2, 0);
 1.65009 +
 1.65010 +    default:
 1.65011 +      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2, 0);
 1.65012 +  }
 1.65013 +
 1.65014 +  if( v>lhs ){
 1.65015 +    res = pPKey2->r1;
 1.65016 +  }else if( v<lhs ){
 1.65017 +    res = pPKey2->r2;
 1.65018 +  }else if( pPKey2->nField>1 ){
 1.65019 +    /* The first fields of the two keys are equal. Compare the trailing 
 1.65020 +    ** fields.  */
 1.65021 +    res = sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2, 1);
 1.65022 +  }else{
 1.65023 +    /* The first fields of the two keys are equal and there are no trailing
 1.65024 +    ** fields. Return pPKey2->default_rc in this case. */
 1.65025 +    res = pPKey2->default_rc;
 1.65026 +  }
 1.65027 +
 1.65028 +  assert( (res==0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)==0)
 1.65029 +       || (res<0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)<0)
 1.65030 +       || (res>0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)>0)
 1.65031 +       || CORRUPT_DB
 1.65032 +  );
 1.65033 +  return res;
 1.65034 +}
 1.65035 +
 1.65036 +/*
 1.65037 +** This function is an optimized version of sqlite3VdbeRecordCompare() 
 1.65038 +** that (a) the first field of pPKey2 is a string, that (b) the first field
 1.65039 +** uses the collation sequence BINARY and (c) that the size-of-header varint 
 1.65040 +** at the start of (pKey1/nKey1) fits in a single byte.
 1.65041 +*/
 1.65042 +static int vdbeRecordCompareString(
 1.65043 +  int nKey1, const void *pKey1, /* Left key */
 1.65044 +  const UnpackedRecord *pPKey2, /* Right key */
 1.65045 +  int bSkip
 1.65046 +){
 1.65047 +  const u8 *aKey1 = (const u8*)pKey1;
 1.65048 +  int serial_type;
 1.65049 +  int res;
 1.65050 +  UNUSED_PARAMETER(bSkip);
 1.65051 +
 1.65052 +  assert( bSkip==0 );
 1.65053 +  getVarint32(&aKey1[1], serial_type);
 1.65054 +
 1.65055 +  if( serial_type<12 ){
 1.65056 +    res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
 1.65057 +  }else if( !(serial_type & 0x01) ){ 
 1.65058 +    res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
 1.65059 +  }else{
 1.65060 +    int nCmp;
 1.65061 +    int nStr;
 1.65062 +    int szHdr = aKey1[0];
 1.65063 +
 1.65064 +    nStr = (serial_type-12) / 2;
 1.65065 +    if( (szHdr + nStr) > nKey1 ) return 0;    /* Corruption */
 1.65066 +    nCmp = MIN( pPKey2->aMem[0].n, nStr );
 1.65067 +    res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
 1.65068 +
 1.65069 +    if( res==0 ){
 1.65070 +      res = nStr - pPKey2->aMem[0].n;
 1.65071 +      if( res==0 ){
 1.65072 +        if( pPKey2->nField>1 ){
 1.65073 +          res = sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2, 1);
 1.65074 +        }else{
 1.65075 +          res = pPKey2->default_rc;
 1.65076 +        }
 1.65077 +      }else if( res>0 ){
 1.65078 +        res = pPKey2->r2;
 1.65079 +      }else{
 1.65080 +        res = pPKey2->r1;
 1.65081 +      }
 1.65082 +    }else if( res>0 ){
 1.65083 +      res = pPKey2->r2;
 1.65084 +    }else{
 1.65085 +      res = pPKey2->r1;
 1.65086 +    }
 1.65087 +  }
 1.65088 +
 1.65089 +  assert( (res==0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)==0)
 1.65090 +       || (res<0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)<0)
 1.65091 +       || (res>0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)>0)
 1.65092 +       || CORRUPT_DB
 1.65093 +  );
 1.65094 +  return res;
 1.65095 +}
 1.65096 +
 1.65097 +/*
 1.65098 +** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
 1.65099 +** suitable for comparing serialized records to the unpacked record passed
 1.65100 +** as the only argument.
 1.65101 +*/
 1.65102 +SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
 1.65103 +  /* varintRecordCompareInt() and varintRecordCompareString() both assume
 1.65104 +  ** that the size-of-header varint that occurs at the start of each record
 1.65105 +  ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
 1.65106 +  ** also assumes that it is safe to overread a buffer by at least the 
 1.65107 +  ** maximum possible legal header size plus 8 bytes. Because there is
 1.65108 +  ** guaranteed to be at least 74 (but not 136) bytes of padding following each
 1.65109 +  ** buffer passed to varintRecordCompareInt() this makes it convenient to
 1.65110 +  ** limit the size of the header to 64 bytes in cases where the first field
 1.65111 +  ** is an integer.
 1.65112 +  **
 1.65113 +  ** The easiest way to enforce this limit is to consider only records with
 1.65114 +  ** 13 fields or less. If the first field is an integer, the maximum legal
 1.65115 +  ** header size is (12*5 + 1 + 1) bytes.  */
 1.65116 +  if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
 1.65117 +    int flags = p->aMem[0].flags;
 1.65118 +    if( p->pKeyInfo->aSortOrder[0] ){
 1.65119 +      p->r1 = 1;
 1.65120 +      p->r2 = -1;
 1.65121 +    }else{
 1.65122 +      p->r1 = -1;
 1.65123 +      p->r2 = 1;
 1.65124 +    }
 1.65125 +    if( (flags & MEM_Int) ){
 1.65126 +      return vdbeRecordCompareInt;
 1.65127 +    }
 1.65128 +    testcase( flags & MEM_Real );
 1.65129 +    testcase( flags & MEM_Null );
 1.65130 +    testcase( flags & MEM_Blob );
 1.65131 +    if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
 1.65132 +      assert( flags & MEM_Str );
 1.65133 +      return vdbeRecordCompareString;
 1.65134 +    }
 1.65135 +  }
 1.65136 +
 1.65137 +  return sqlite3VdbeRecordCompare;
 1.65138 +}
 1.65139 +
 1.65140 +/*
 1.65141 +** pCur points at an index entry created using the OP_MakeRecord opcode.
 1.65142 +** Read the rowid (the last field in the record) and store it in *rowid.
 1.65143 +** Return SQLITE_OK if everything works, or an error code otherwise.
 1.65144 +**
 1.65145 +** pCur might be pointing to text obtained from a corrupt database file.
 1.65146 +** So the content cannot be trusted.  Do appropriate checks on the content.
 1.65147 +*/
 1.65148 +SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
 1.65149 +  i64 nCellKey = 0;
 1.65150 +  int rc;
 1.65151 +  u32 szHdr;        /* Size of the header */
 1.65152 +  u32 typeRowid;    /* Serial type of the rowid */
 1.65153 +  u32 lenRowid;     /* Size of the rowid */
 1.65154 +  Mem m, v;
 1.65155 +
 1.65156 +  UNUSED_PARAMETER(db);
 1.65157 +
 1.65158 +  /* Get the size of the index entry.  Only indices entries of less
 1.65159 +  ** than 2GiB are support - anything large must be database corruption.
 1.65160 +  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
 1.65161 +  ** this code can safely assume that nCellKey is 32-bits  
 1.65162 +  */
 1.65163 +  assert( sqlite3BtreeCursorIsValid(pCur) );
 1.65164 +  VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
 1.65165 +  assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
 1.65166 +  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
 1.65167 +
 1.65168 +  /* Read in the complete content of the index entry */
 1.65169 +  memset(&m, 0, sizeof(m));
 1.65170 +  rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
 1.65171 +  if( rc ){
 1.65172 +    return rc;
 1.65173 +  }
 1.65174 +
 1.65175 +  /* The index entry must begin with a header size */
 1.65176 +  (void)getVarint32((u8*)m.z, szHdr);
 1.65177 +  testcase( szHdr==3 );
 1.65178 +  testcase( szHdr==m.n );
 1.65179 +  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
 1.65180 +    goto idx_rowid_corruption;
 1.65181 +  }
 1.65182 +
 1.65183 +  /* The last field of the index should be an integer - the ROWID.
 1.65184 +  ** Verify that the last entry really is an integer. */
 1.65185 +  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
 1.65186 +  testcase( typeRowid==1 );
 1.65187 +  testcase( typeRowid==2 );
 1.65188 +  testcase( typeRowid==3 );
 1.65189 +  testcase( typeRowid==4 );
 1.65190 +  testcase( typeRowid==5 );
 1.65191 +  testcase( typeRowid==6 );
 1.65192 +  testcase( typeRowid==8 );
 1.65193 +  testcase( typeRowid==9 );
 1.65194 +  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
 1.65195 +    goto idx_rowid_corruption;
 1.65196 +  }
 1.65197 +  lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
 1.65198 +  testcase( (u32)m.n==szHdr+lenRowid );
 1.65199 +  if( unlikely((u32)m.n<szHdr+lenRowid) ){
 1.65200 +    goto idx_rowid_corruption;
 1.65201 +  }
 1.65202 +
 1.65203 +  /* Fetch the integer off the end of the index record */
 1.65204 +  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
 1.65205 +  *rowid = v.u.i;
 1.65206 +  sqlite3VdbeMemRelease(&m);
 1.65207 +  return SQLITE_OK;
 1.65208 +
 1.65209 +  /* Jump here if database corruption is detected after m has been
 1.65210 +  ** allocated.  Free the m object and return SQLITE_CORRUPT. */
 1.65211 +idx_rowid_corruption:
 1.65212 +  testcase( m.zMalloc!=0 );
 1.65213 +  sqlite3VdbeMemRelease(&m);
 1.65214 +  return SQLITE_CORRUPT_BKPT;
 1.65215 +}
 1.65216 +
 1.65217 +/*
 1.65218 +** Compare the key of the index entry that cursor pC is pointing to against
 1.65219 +** the key string in pUnpacked.  Write into *pRes a number
 1.65220 +** that is negative, zero, or positive if pC is less than, equal to,
 1.65221 +** or greater than pUnpacked.  Return SQLITE_OK on success.
 1.65222 +**
 1.65223 +** pUnpacked is either created without a rowid or is truncated so that it
 1.65224 +** omits the rowid at the end.  The rowid at the end of the index entry
 1.65225 +** is ignored as well.  Hence, this routine only compares the prefixes 
 1.65226 +** of the keys prior to the final rowid, not the entire key.
 1.65227 +*/
 1.65228 +SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
 1.65229 +  VdbeCursor *pC,                  /* The cursor to compare against */
 1.65230 +  const UnpackedRecord *pUnpacked, /* Unpacked version of key */
 1.65231 +  int *res                         /* Write the comparison result here */
 1.65232 +){
 1.65233 +  i64 nCellKey = 0;
 1.65234 +  int rc;
 1.65235 +  BtCursor *pCur = pC->pCursor;
 1.65236 +  Mem m;
 1.65237 +
 1.65238 +  assert( sqlite3BtreeCursorIsValid(pCur) );
 1.65239 +  VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
 1.65240 +  assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
 1.65241 +  /* nCellKey will always be between 0 and 0xffffffff because of the way
 1.65242 +  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
 1.65243 +  if( nCellKey<=0 || nCellKey>0x7fffffff ){
 1.65244 +    *res = 0;
 1.65245 +    return SQLITE_CORRUPT_BKPT;
 1.65246 +  }
 1.65247 +  memset(&m, 0, sizeof(m));
 1.65248 +  rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
 1.65249 +  if( rc ){
 1.65250 +    return rc;
 1.65251 +  }
 1.65252 +  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked, 0);
 1.65253 +  sqlite3VdbeMemRelease(&m);
 1.65254 +  return SQLITE_OK;
 1.65255 +}
 1.65256 +
 1.65257 +/*
 1.65258 +** This routine sets the value to be returned by subsequent calls to
 1.65259 +** sqlite3_changes() on the database handle 'db'. 
 1.65260 +*/
 1.65261 +SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
 1.65262 +  assert( sqlite3_mutex_held(db->mutex) );
 1.65263 +  db->nChange = nChange;
 1.65264 +  db->nTotalChange += nChange;
 1.65265 +}
 1.65266 +
 1.65267 +/*
 1.65268 +** Set a flag in the vdbe to update the change counter when it is finalised
 1.65269 +** or reset.
 1.65270 +*/
 1.65271 +SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
 1.65272 +  v->changeCntOn = 1;
 1.65273 +}
 1.65274 +
 1.65275 +/*
 1.65276 +** Mark every prepared statement associated with a database connection
 1.65277 +** as expired.
 1.65278 +**
 1.65279 +** An expired statement means that recompilation of the statement is
 1.65280 +** recommend.  Statements expire when things happen that make their
 1.65281 +** programs obsolete.  Removing user-defined functions or collating
 1.65282 +** sequences, or changing an authorization function are the types of
 1.65283 +** things that make prepared statements obsolete.
 1.65284 +*/
 1.65285 +SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
 1.65286 +  Vdbe *p;
 1.65287 +  for(p = db->pVdbe; p; p=p->pNext){
 1.65288 +    p->expired = 1;
 1.65289 +  }
 1.65290 +}
 1.65291 +
 1.65292 +/*
 1.65293 +** Return the database associated with the Vdbe.
 1.65294 +*/
 1.65295 +SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
 1.65296 +  return v->db;
 1.65297 +}
 1.65298 +
 1.65299 +/*
 1.65300 +** Return a pointer to an sqlite3_value structure containing the value bound
 1.65301 +** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
 1.65302 +** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
 1.65303 +** constants) to the value before returning it.
 1.65304 +**
 1.65305 +** The returned value must be freed by the caller using sqlite3ValueFree().
 1.65306 +*/
 1.65307 +SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
 1.65308 +  assert( iVar>0 );
 1.65309 +  if( v ){
 1.65310 +    Mem *pMem = &v->aVar[iVar-1];
 1.65311 +    if( 0==(pMem->flags & MEM_Null) ){
 1.65312 +      sqlite3_value *pRet = sqlite3ValueNew(v->db);
 1.65313 +      if( pRet ){
 1.65314 +        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
 1.65315 +        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
 1.65316 +      }
 1.65317 +      return pRet;
 1.65318 +    }
 1.65319 +  }
 1.65320 +  return 0;
 1.65321 +}
 1.65322 +
 1.65323 +/*
 1.65324 +** Configure SQL variable iVar so that binding a new value to it signals
 1.65325 +** to sqlite3_reoptimize() that re-preparing the statement may result
 1.65326 +** in a better query plan.
 1.65327 +*/
 1.65328 +SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
 1.65329 +  assert( iVar>0 );
 1.65330 +  if( iVar>32 ){
 1.65331 +    v->expmask = 0xffffffff;
 1.65332 +  }else{
 1.65333 +    v->expmask |= ((u32)1 << (iVar-1));
 1.65334 +  }
 1.65335 +}
 1.65336 +
 1.65337 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.65338 +/*
 1.65339 +** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
 1.65340 +** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
 1.65341 +** in memory obtained from sqlite3DbMalloc).
 1.65342 +*/
 1.65343 +SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
 1.65344 +  sqlite3 *db = p->db;
 1.65345 +  sqlite3DbFree(db, p->zErrMsg);
 1.65346 +  p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
 1.65347 +  sqlite3_free(pVtab->zErrMsg);
 1.65348 +  pVtab->zErrMsg = 0;
 1.65349 +}
 1.65350 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
 1.65351 +
 1.65352 +/************** End of vdbeaux.c *********************************************/
 1.65353 +/************** Begin file vdbeapi.c *****************************************/
 1.65354 +/*
 1.65355 +** 2004 May 26
 1.65356 +**
 1.65357 +** The author disclaims copyright to this source code.  In place of
 1.65358 +** a legal notice, here is a blessing:
 1.65359 +**
 1.65360 +**    May you do good and not evil.
 1.65361 +**    May you find forgiveness for yourself and forgive others.
 1.65362 +**    May you share freely, never taking more than you give.
 1.65363 +**
 1.65364 +*************************************************************************
 1.65365 +**
 1.65366 +** This file contains code use to implement APIs that are part of the
 1.65367 +** VDBE.
 1.65368 +*/
 1.65369 +
 1.65370 +#ifndef SQLITE_OMIT_DEPRECATED
 1.65371 +/*
 1.65372 +** Return TRUE (non-zero) of the statement supplied as an argument needs
 1.65373 +** to be recompiled.  A statement needs to be recompiled whenever the
 1.65374 +** execution environment changes in a way that would alter the program
 1.65375 +** that sqlite3_prepare() generates.  For example, if new functions or
 1.65376 +** collating sequences are registered or if an authorizer function is
 1.65377 +** added or changed.
 1.65378 +*/
 1.65379 +SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
 1.65380 +  Vdbe *p = (Vdbe*)pStmt;
 1.65381 +  return p==0 || p->expired;
 1.65382 +}
 1.65383 +#endif
 1.65384 +
 1.65385 +/*
 1.65386 +** Check on a Vdbe to make sure it has not been finalized.  Log
 1.65387 +** an error and return true if it has been finalized (or is otherwise
 1.65388 +** invalid).  Return false if it is ok.
 1.65389 +*/
 1.65390 +static int vdbeSafety(Vdbe *p){
 1.65391 +  if( p->db==0 ){
 1.65392 +    sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
 1.65393 +    return 1;
 1.65394 +  }else{
 1.65395 +    return 0;
 1.65396 +  }
 1.65397 +}
 1.65398 +static int vdbeSafetyNotNull(Vdbe *p){
 1.65399 +  if( p==0 ){
 1.65400 +    sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
 1.65401 +    return 1;
 1.65402 +  }else{
 1.65403 +    return vdbeSafety(p);
 1.65404 +  }
 1.65405 +}
 1.65406 +
 1.65407 +/*
 1.65408 +** The following routine destroys a virtual machine that is created by
 1.65409 +** the sqlite3_compile() routine. The integer returned is an SQLITE_
 1.65410 +** success/failure code that describes the result of executing the virtual
 1.65411 +** machine.
 1.65412 +**
 1.65413 +** This routine sets the error code and string returned by
 1.65414 +** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
 1.65415 +*/
 1.65416 +SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
 1.65417 +  int rc;
 1.65418 +  if( pStmt==0 ){
 1.65419 +    /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
 1.65420 +    ** pointer is a harmless no-op. */
 1.65421 +    rc = SQLITE_OK;
 1.65422 +  }else{
 1.65423 +    Vdbe *v = (Vdbe*)pStmt;
 1.65424 +    sqlite3 *db = v->db;
 1.65425 +    if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
 1.65426 +    sqlite3_mutex_enter(db->mutex);
 1.65427 +    rc = sqlite3VdbeFinalize(v);
 1.65428 +    rc = sqlite3ApiExit(db, rc);
 1.65429 +    sqlite3LeaveMutexAndCloseZombie(db);
 1.65430 +  }
 1.65431 +  return rc;
 1.65432 +}
 1.65433 +
 1.65434 +/*
 1.65435 +** Terminate the current execution of an SQL statement and reset it
 1.65436 +** back to its starting state so that it can be reused. A success code from
 1.65437 +** the prior execution is returned.
 1.65438 +**
 1.65439 +** This routine sets the error code and string returned by
 1.65440 +** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
 1.65441 +*/
 1.65442 +SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
 1.65443 +  int rc;
 1.65444 +  if( pStmt==0 ){
 1.65445 +    rc = SQLITE_OK;
 1.65446 +  }else{
 1.65447 +    Vdbe *v = (Vdbe*)pStmt;
 1.65448 +    sqlite3_mutex_enter(v->db->mutex);
 1.65449 +    rc = sqlite3VdbeReset(v);
 1.65450 +    sqlite3VdbeRewind(v);
 1.65451 +    assert( (rc & (v->db->errMask))==rc );
 1.65452 +    rc = sqlite3ApiExit(v->db, rc);
 1.65453 +    sqlite3_mutex_leave(v->db->mutex);
 1.65454 +  }
 1.65455 +  return rc;
 1.65456 +}
 1.65457 +
 1.65458 +/*
 1.65459 +** Set all the parameters in the compiled SQL statement to NULL.
 1.65460 +*/
 1.65461 +SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
 1.65462 +  int i;
 1.65463 +  int rc = SQLITE_OK;
 1.65464 +  Vdbe *p = (Vdbe*)pStmt;
 1.65465 +#if SQLITE_THREADSAFE
 1.65466 +  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
 1.65467 +#endif
 1.65468 +  sqlite3_mutex_enter(mutex);
 1.65469 +  for(i=0; i<p->nVar; i++){
 1.65470 +    sqlite3VdbeMemRelease(&p->aVar[i]);
 1.65471 +    p->aVar[i].flags = MEM_Null;
 1.65472 +  }
 1.65473 +  if( p->isPrepareV2 && p->expmask ){
 1.65474 +    p->expired = 1;
 1.65475 +  }
 1.65476 +  sqlite3_mutex_leave(mutex);
 1.65477 +  return rc;
 1.65478 +}
 1.65479 +
 1.65480 +
 1.65481 +/**************************** sqlite3_value_  *******************************
 1.65482 +** The following routines extract information from a Mem or sqlite3_value
 1.65483 +** structure.
 1.65484 +*/
 1.65485 +SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
 1.65486 +  Mem *p = (Mem*)pVal;
 1.65487 +  if( p->flags & (MEM_Blob|MEM_Str) ){
 1.65488 +    sqlite3VdbeMemExpandBlob(p);
 1.65489 +    p->flags |= MEM_Blob;
 1.65490 +    return p->n ? p->z : 0;
 1.65491 +  }else{
 1.65492 +    return sqlite3_value_text(pVal);
 1.65493 +  }
 1.65494 +}
 1.65495 +SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
 1.65496 +  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
 1.65497 +}
 1.65498 +SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
 1.65499 +  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
 1.65500 +}
 1.65501 +SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
 1.65502 +  return sqlite3VdbeRealValue((Mem*)pVal);
 1.65503 +}
 1.65504 +SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
 1.65505 +  return (int)sqlite3VdbeIntValue((Mem*)pVal);
 1.65506 +}
 1.65507 +SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
 1.65508 +  return sqlite3VdbeIntValue((Mem*)pVal);
 1.65509 +}
 1.65510 +SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
 1.65511 +  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
 1.65512 +}
 1.65513 +#ifndef SQLITE_OMIT_UTF16
 1.65514 +SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
 1.65515 +  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
 1.65516 +}
 1.65517 +SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
 1.65518 +  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
 1.65519 +}
 1.65520 +SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
 1.65521 +  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
 1.65522 +}
 1.65523 +#endif /* SQLITE_OMIT_UTF16 */
 1.65524 +SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
 1.65525 +  static const u8 aType[] = {
 1.65526 +     SQLITE_BLOB,     /* 0x00 */
 1.65527 +     SQLITE_NULL,     /* 0x01 */
 1.65528 +     SQLITE_TEXT,     /* 0x02 */
 1.65529 +     SQLITE_NULL,     /* 0x03 */
 1.65530 +     SQLITE_INTEGER,  /* 0x04 */
 1.65531 +     SQLITE_NULL,     /* 0x05 */
 1.65532 +     SQLITE_INTEGER,  /* 0x06 */
 1.65533 +     SQLITE_NULL,     /* 0x07 */
 1.65534 +     SQLITE_FLOAT,    /* 0x08 */
 1.65535 +     SQLITE_NULL,     /* 0x09 */
 1.65536 +     SQLITE_FLOAT,    /* 0x0a */
 1.65537 +     SQLITE_NULL,     /* 0x0b */
 1.65538 +     SQLITE_INTEGER,  /* 0x0c */
 1.65539 +     SQLITE_NULL,     /* 0x0d */
 1.65540 +     SQLITE_INTEGER,  /* 0x0e */
 1.65541 +     SQLITE_NULL,     /* 0x0f */
 1.65542 +     SQLITE_BLOB,     /* 0x10 */
 1.65543 +     SQLITE_NULL,     /* 0x11 */
 1.65544 +     SQLITE_TEXT,     /* 0x12 */
 1.65545 +     SQLITE_NULL,     /* 0x13 */
 1.65546 +     SQLITE_INTEGER,  /* 0x14 */
 1.65547 +     SQLITE_NULL,     /* 0x15 */
 1.65548 +     SQLITE_INTEGER,  /* 0x16 */
 1.65549 +     SQLITE_NULL,     /* 0x17 */
 1.65550 +     SQLITE_FLOAT,    /* 0x18 */
 1.65551 +     SQLITE_NULL,     /* 0x19 */
 1.65552 +     SQLITE_FLOAT,    /* 0x1a */
 1.65553 +     SQLITE_NULL,     /* 0x1b */
 1.65554 +     SQLITE_INTEGER,  /* 0x1c */
 1.65555 +     SQLITE_NULL,     /* 0x1d */
 1.65556 +     SQLITE_INTEGER,  /* 0x1e */
 1.65557 +     SQLITE_NULL,     /* 0x1f */
 1.65558 +  };
 1.65559 +  return aType[pVal->flags&MEM_AffMask];
 1.65560 +}
 1.65561 +
 1.65562 +/**************************** sqlite3_result_  *******************************
 1.65563 +** The following routines are used by user-defined functions to specify
 1.65564 +** the function result.
 1.65565 +**
 1.65566 +** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
 1.65567 +** result as a string or blob but if the string or blob is too large, it
 1.65568 +** then sets the error code to SQLITE_TOOBIG
 1.65569 +*/
 1.65570 +static void setResultStrOrError(
 1.65571 +  sqlite3_context *pCtx,  /* Function context */
 1.65572 +  const char *z,          /* String pointer */
 1.65573 +  int n,                  /* Bytes in string, or negative */
 1.65574 +  u8 enc,                 /* Encoding of z.  0 for BLOBs */
 1.65575 +  void (*xDel)(void*)     /* Destructor function */
 1.65576 +){
 1.65577 +  if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
 1.65578 +    sqlite3_result_error_toobig(pCtx);
 1.65579 +  }
 1.65580 +}
 1.65581 +SQLITE_API void sqlite3_result_blob(
 1.65582 +  sqlite3_context *pCtx, 
 1.65583 +  const void *z, 
 1.65584 +  int n, 
 1.65585 +  void (*xDel)(void *)
 1.65586 +){
 1.65587 +  assert( n>=0 );
 1.65588 +  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
 1.65589 +  setResultStrOrError(pCtx, z, n, 0, xDel);
 1.65590 +}
 1.65591 +SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
 1.65592 +  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
 1.65593 +  sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
 1.65594 +}
 1.65595 +SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
 1.65596 +  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
 1.65597 +  pCtx->isError = SQLITE_ERROR;
 1.65598 +  pCtx->fErrorOrAux = 1;
 1.65599 +  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
 1.65600 +}
 1.65601 +#ifndef SQLITE_OMIT_UTF16
 1.65602 +SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
 1.65603 +  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
 1.65604 +  pCtx->isError = SQLITE_ERROR;
 1.65605 +  pCtx->fErrorOrAux = 1;
 1.65606 +  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
 1.65607 +}
 1.65608 +#endif
 1.65609 +SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
 1.65610 +  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
 1.65611 +  sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
 1.65612 +}
 1.65613 +SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
 1.65614 +  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
 1.65615 +  sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
 1.65616 +}
 1.65617 +SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
 1.65618 +  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
 1.65619 +  sqlite3VdbeMemSetNull(&pCtx->s);
 1.65620 +}
 1.65621 +SQLITE_API void sqlite3_result_text(
 1.65622 +  sqlite3_context *pCtx, 
 1.65623 +  const char *z, 
 1.65624 +  int n,
 1.65625 +  void (*xDel)(void *)
 1.65626 +){
 1.65627 +  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
 1.65628 +  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
 1.65629 +}
 1.65630 +#ifndef SQLITE_OMIT_UTF16
 1.65631 +SQLITE_API void sqlite3_result_text16(
 1.65632 +  sqlite3_context *pCtx, 
 1.65633 +  const void *z, 
 1.65634 +  int n, 
 1.65635 +  void (*xDel)(void *)
 1.65636 +){
 1.65637 +  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
 1.65638 +  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
 1.65639 +}
 1.65640 +SQLITE_API void sqlite3_result_text16be(
 1.65641 +  sqlite3_context *pCtx, 
 1.65642 +  const void *z, 
 1.65643 +  int n, 
 1.65644 +  void (*xDel)(void *)
 1.65645 +){
 1.65646 +  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
 1.65647 +  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
 1.65648 +}
 1.65649 +SQLITE_API void sqlite3_result_text16le(
 1.65650 +  sqlite3_context *pCtx, 
 1.65651 +  const void *z, 
 1.65652 +  int n, 
 1.65653 +  void (*xDel)(void *)
 1.65654 +){
 1.65655 +  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
 1.65656 +  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
 1.65657 +}
 1.65658 +#endif /* SQLITE_OMIT_UTF16 */
 1.65659 +SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
 1.65660 +  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
 1.65661 +  sqlite3VdbeMemCopy(&pCtx->s, pValue);
 1.65662 +}
 1.65663 +SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
 1.65664 +  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
 1.65665 +  sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
 1.65666 +}
 1.65667 +SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
 1.65668 +  pCtx->isError = errCode;
 1.65669 +  pCtx->fErrorOrAux = 1;
 1.65670 +  if( pCtx->s.flags & MEM_Null ){
 1.65671 +    sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1, 
 1.65672 +                         SQLITE_UTF8, SQLITE_STATIC);
 1.65673 +  }
 1.65674 +}
 1.65675 +
 1.65676 +/* Force an SQLITE_TOOBIG error. */
 1.65677 +SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
 1.65678 +  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
 1.65679 +  pCtx->isError = SQLITE_TOOBIG;
 1.65680 +  pCtx->fErrorOrAux = 1;
 1.65681 +  sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
 1.65682 +                       SQLITE_UTF8, SQLITE_STATIC);
 1.65683 +}
 1.65684 +
 1.65685 +/* An SQLITE_NOMEM error. */
 1.65686 +SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
 1.65687 +  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
 1.65688 +  sqlite3VdbeMemSetNull(&pCtx->s);
 1.65689 +  pCtx->isError = SQLITE_NOMEM;
 1.65690 +  pCtx->fErrorOrAux = 1;
 1.65691 +  pCtx->s.db->mallocFailed = 1;
 1.65692 +}
 1.65693 +
 1.65694 +/*
 1.65695 +** This function is called after a transaction has been committed. It 
 1.65696 +** invokes callbacks registered with sqlite3_wal_hook() as required.
 1.65697 +*/
 1.65698 +static int doWalCallbacks(sqlite3 *db){
 1.65699 +  int rc = SQLITE_OK;
 1.65700 +#ifndef SQLITE_OMIT_WAL
 1.65701 +  int i;
 1.65702 +  for(i=0; i<db->nDb; i++){
 1.65703 +    Btree *pBt = db->aDb[i].pBt;
 1.65704 +    if( pBt ){
 1.65705 +      int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
 1.65706 +      if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
 1.65707 +        rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
 1.65708 +      }
 1.65709 +    }
 1.65710 +  }
 1.65711 +#endif
 1.65712 +  return rc;
 1.65713 +}
 1.65714 +
 1.65715 +/*
 1.65716 +** Execute the statement pStmt, either until a row of data is ready, the
 1.65717 +** statement is completely executed or an error occurs.
 1.65718 +**
 1.65719 +** This routine implements the bulk of the logic behind the sqlite_step()
 1.65720 +** API.  The only thing omitted is the automatic recompile if a 
 1.65721 +** schema change has occurred.  That detail is handled by the
 1.65722 +** outer sqlite3_step() wrapper procedure.
 1.65723 +*/
 1.65724 +static int sqlite3Step(Vdbe *p){
 1.65725 +  sqlite3 *db;
 1.65726 +  int rc;
 1.65727 +
 1.65728 +  assert(p);
 1.65729 +  if( p->magic!=VDBE_MAGIC_RUN ){
 1.65730 +    /* We used to require that sqlite3_reset() be called before retrying
 1.65731 +    ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
 1.65732 +    ** with version 3.7.0, we changed this so that sqlite3_reset() would
 1.65733 +    ** be called automatically instead of throwing the SQLITE_MISUSE error.
 1.65734 +    ** This "automatic-reset" change is not technically an incompatibility, 
 1.65735 +    ** since any application that receives an SQLITE_MISUSE is broken by
 1.65736 +    ** definition.
 1.65737 +    **
 1.65738 +    ** Nevertheless, some published applications that were originally written
 1.65739 +    ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE 
 1.65740 +    ** returns, and those were broken by the automatic-reset change.  As a
 1.65741 +    ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
 1.65742 +    ** legacy behavior of returning SQLITE_MISUSE for cases where the 
 1.65743 +    ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
 1.65744 +    ** or SQLITE_BUSY error.
 1.65745 +    */
 1.65746 +#ifdef SQLITE_OMIT_AUTORESET
 1.65747 +    if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
 1.65748 +      sqlite3_reset((sqlite3_stmt*)p);
 1.65749 +    }else{
 1.65750 +      return SQLITE_MISUSE_BKPT;
 1.65751 +    }
 1.65752 +#else
 1.65753 +    sqlite3_reset((sqlite3_stmt*)p);
 1.65754 +#endif
 1.65755 +  }
 1.65756 +
 1.65757 +  /* Check that malloc() has not failed. If it has, return early. */
 1.65758 +  db = p->db;
 1.65759 +  if( db->mallocFailed ){
 1.65760 +    p->rc = SQLITE_NOMEM;
 1.65761 +    return SQLITE_NOMEM;
 1.65762 +  }
 1.65763 +
 1.65764 +  if( p->pc<=0 && p->expired ){
 1.65765 +    p->rc = SQLITE_SCHEMA;
 1.65766 +    rc = SQLITE_ERROR;
 1.65767 +    goto end_of_step;
 1.65768 +  }
 1.65769 +  if( p->pc<0 ){
 1.65770 +    /* If there are no other statements currently running, then
 1.65771 +    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
 1.65772 +    ** from interrupting a statement that has not yet started.
 1.65773 +    */
 1.65774 +    if( db->nVdbeActive==0 ){
 1.65775 +      db->u1.isInterrupted = 0;
 1.65776 +    }
 1.65777 +
 1.65778 +    assert( db->nVdbeWrite>0 || db->autoCommit==0 
 1.65779 +        || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
 1.65780 +    );
 1.65781 +
 1.65782 +#ifndef SQLITE_OMIT_TRACE
 1.65783 +    if( db->xProfile && !db->init.busy ){
 1.65784 +      sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
 1.65785 +    }
 1.65786 +#endif
 1.65787 +
 1.65788 +    db->nVdbeActive++;
 1.65789 +    if( p->readOnly==0 ) db->nVdbeWrite++;
 1.65790 +    if( p->bIsReader ) db->nVdbeRead++;
 1.65791 +    p->pc = 0;
 1.65792 +  }
 1.65793 +#ifndef SQLITE_OMIT_EXPLAIN
 1.65794 +  if( p->explain ){
 1.65795 +    rc = sqlite3VdbeList(p);
 1.65796 +  }else
 1.65797 +#endif /* SQLITE_OMIT_EXPLAIN */
 1.65798 +  {
 1.65799 +    db->nVdbeExec++;
 1.65800 +    rc = sqlite3VdbeExec(p);
 1.65801 +    db->nVdbeExec--;
 1.65802 +  }
 1.65803 +
 1.65804 +#ifndef SQLITE_OMIT_TRACE
 1.65805 +  /* Invoke the profile callback if there is one
 1.65806 +  */
 1.65807 +  if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
 1.65808 +    sqlite3_int64 iNow;
 1.65809 +    sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
 1.65810 +    db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
 1.65811 +  }
 1.65812 +#endif
 1.65813 +
 1.65814 +  if( rc==SQLITE_DONE ){
 1.65815 +    assert( p->rc==SQLITE_OK );
 1.65816 +    p->rc = doWalCallbacks(db);
 1.65817 +    if( p->rc!=SQLITE_OK ){
 1.65818 +      rc = SQLITE_ERROR;
 1.65819 +    }
 1.65820 +  }
 1.65821 +
 1.65822 +  db->errCode = rc;
 1.65823 +  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
 1.65824 +    p->rc = SQLITE_NOMEM;
 1.65825 +  }
 1.65826 +end_of_step:
 1.65827 +  /* At this point local variable rc holds the value that should be 
 1.65828 +  ** returned if this statement was compiled using the legacy 
 1.65829 +  ** sqlite3_prepare() interface. According to the docs, this can only
 1.65830 +  ** be one of the values in the first assert() below. Variable p->rc 
 1.65831 +  ** contains the value that would be returned if sqlite3_finalize() 
 1.65832 +  ** were called on statement p.
 1.65833 +  */
 1.65834 +  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
 1.65835 +       || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
 1.65836 +  );
 1.65837 +  assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
 1.65838 +  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
 1.65839 +    /* If this statement was prepared using sqlite3_prepare_v2(), and an
 1.65840 +    ** error has occurred, then return the error code in p->rc to the
 1.65841 +    ** caller. Set the error code in the database handle to the same value.
 1.65842 +    */ 
 1.65843 +    rc = sqlite3VdbeTransferError(p);
 1.65844 +  }
 1.65845 +  return (rc&db->errMask);
 1.65846 +}
 1.65847 +
 1.65848 +/*
 1.65849 +** This is the top-level implementation of sqlite3_step().  Call
 1.65850 +** sqlite3Step() to do most of the work.  If a schema error occurs,
 1.65851 +** call sqlite3Reprepare() and try again.
 1.65852 +*/
 1.65853 +SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
 1.65854 +  int rc = SQLITE_OK;      /* Result from sqlite3Step() */
 1.65855 +  int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
 1.65856 +  Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
 1.65857 +  int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
 1.65858 +  sqlite3 *db;             /* The database connection */
 1.65859 +
 1.65860 +  if( vdbeSafetyNotNull(v) ){
 1.65861 +    return SQLITE_MISUSE_BKPT;
 1.65862 +  }
 1.65863 +  db = v->db;
 1.65864 +  sqlite3_mutex_enter(db->mutex);
 1.65865 +  v->doingRerun = 0;
 1.65866 +  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
 1.65867 +         && cnt++ < SQLITE_MAX_SCHEMA_RETRY
 1.65868 +         && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
 1.65869 +    sqlite3_reset(pStmt);
 1.65870 +    v->doingRerun = 1;
 1.65871 +    assert( v->expired==0 );
 1.65872 +  }
 1.65873 +  if( rc2!=SQLITE_OK ){
 1.65874 +    /* This case occurs after failing to recompile an sql statement. 
 1.65875 +    ** The error message from the SQL compiler has already been loaded 
 1.65876 +    ** into the database handle. This block copies the error message 
 1.65877 +    ** from the database handle into the statement and sets the statement
 1.65878 +    ** program counter to 0 to ensure that when the statement is 
 1.65879 +    ** finalized or reset the parser error message is available via
 1.65880 +    ** sqlite3_errmsg() and sqlite3_errcode().
 1.65881 +    */
 1.65882 +    const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
 1.65883 +    assert( zErr!=0 || db->mallocFailed );
 1.65884 +    sqlite3DbFree(db, v->zErrMsg);
 1.65885 +    if( !db->mallocFailed ){
 1.65886 +      v->zErrMsg = sqlite3DbStrDup(db, zErr);
 1.65887 +      v->rc = rc2;
 1.65888 +    } else {
 1.65889 +      v->zErrMsg = 0;
 1.65890 +      v->rc = rc = SQLITE_NOMEM;
 1.65891 +    }
 1.65892 +  }
 1.65893 +  rc = sqlite3ApiExit(db, rc);
 1.65894 +  sqlite3_mutex_leave(db->mutex);
 1.65895 +  return rc;
 1.65896 +}
 1.65897 +
 1.65898 +
 1.65899 +/*
 1.65900 +** Extract the user data from a sqlite3_context structure and return a
 1.65901 +** pointer to it.
 1.65902 +*/
 1.65903 +SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
 1.65904 +  assert( p && p->pFunc );
 1.65905 +  return p->pFunc->pUserData;
 1.65906 +}
 1.65907 +
 1.65908 +/*
 1.65909 +** Extract the user data from a sqlite3_context structure and return a
 1.65910 +** pointer to it.
 1.65911 +**
 1.65912 +** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
 1.65913 +** returns a copy of the pointer to the database connection (the 1st
 1.65914 +** parameter) of the sqlite3_create_function() and
 1.65915 +** sqlite3_create_function16() routines that originally registered the
 1.65916 +** application defined function.
 1.65917 +*/
 1.65918 +SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
 1.65919 +  assert( p && p->pFunc );
 1.65920 +  return p->s.db;
 1.65921 +}
 1.65922 +
 1.65923 +/*
 1.65924 +** Return the current time for a statement
 1.65925 +*/
 1.65926 +SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
 1.65927 +  Vdbe *v = p->pVdbe;
 1.65928 +  int rc;
 1.65929 +  if( v->iCurrentTime==0 ){
 1.65930 +    rc = sqlite3OsCurrentTimeInt64(p->s.db->pVfs, &v->iCurrentTime);
 1.65931 +    if( rc ) v->iCurrentTime = 0;
 1.65932 +  }
 1.65933 +  return v->iCurrentTime;
 1.65934 +}
 1.65935 +
 1.65936 +/*
 1.65937 +** The following is the implementation of an SQL function that always
 1.65938 +** fails with an error message stating that the function is used in the
 1.65939 +** wrong context.  The sqlite3_overload_function() API might construct
 1.65940 +** SQL function that use this routine so that the functions will exist
 1.65941 +** for name resolution but are actually overloaded by the xFindFunction
 1.65942 +** method of virtual tables.
 1.65943 +*/
 1.65944 +SQLITE_PRIVATE void sqlite3InvalidFunction(
 1.65945 +  sqlite3_context *context,  /* The function calling context */
 1.65946 +  int NotUsed,               /* Number of arguments to the function */
 1.65947 +  sqlite3_value **NotUsed2   /* Value of each argument */
 1.65948 +){
 1.65949 +  const char *zName = context->pFunc->zName;
 1.65950 +  char *zErr;
 1.65951 +  UNUSED_PARAMETER2(NotUsed, NotUsed2);
 1.65952 +  zErr = sqlite3_mprintf(
 1.65953 +      "unable to use function %s in the requested context", zName);
 1.65954 +  sqlite3_result_error(context, zErr, -1);
 1.65955 +  sqlite3_free(zErr);
 1.65956 +}
 1.65957 +
 1.65958 +/*
 1.65959 +** Allocate or return the aggregate context for a user function.  A new
 1.65960 +** context is allocated on the first call.  Subsequent calls return the
 1.65961 +** same context that was returned on prior calls.
 1.65962 +*/
 1.65963 +SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
 1.65964 +  Mem *pMem;
 1.65965 +  assert( p && p->pFunc && p->pFunc->xStep );
 1.65966 +  assert( sqlite3_mutex_held(p->s.db->mutex) );
 1.65967 +  pMem = p->pMem;
 1.65968 +  testcase( nByte<0 );
 1.65969 +  if( (pMem->flags & MEM_Agg)==0 ){
 1.65970 +    if( nByte<=0 ){
 1.65971 +      sqlite3VdbeMemReleaseExternal(pMem);
 1.65972 +      pMem->flags = MEM_Null;
 1.65973 +      pMem->z = 0;
 1.65974 +    }else{
 1.65975 +      sqlite3VdbeMemGrow(pMem, nByte, 0);
 1.65976 +      pMem->flags = MEM_Agg;
 1.65977 +      pMem->u.pDef = p->pFunc;
 1.65978 +      if( pMem->z ){
 1.65979 +        memset(pMem->z, 0, nByte);
 1.65980 +      }
 1.65981 +    }
 1.65982 +  }
 1.65983 +  return (void*)pMem->z;
 1.65984 +}
 1.65985 +
 1.65986 +/*
 1.65987 +** Return the auxilary data pointer, if any, for the iArg'th argument to
 1.65988 +** the user-function defined by pCtx.
 1.65989 +*/
 1.65990 +SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
 1.65991 +  AuxData *pAuxData;
 1.65992 +
 1.65993 +  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
 1.65994 +  for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
 1.65995 +    if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
 1.65996 +  }
 1.65997 +
 1.65998 +  return (pAuxData ? pAuxData->pAux : 0);
 1.65999 +}
 1.66000 +
 1.66001 +/*
 1.66002 +** Set the auxilary data pointer and delete function, for the iArg'th
 1.66003 +** argument to the user-function defined by pCtx. Any previous value is
 1.66004 +** deleted by calling the delete function specified when it was set.
 1.66005 +*/
 1.66006 +SQLITE_API void sqlite3_set_auxdata(
 1.66007 +  sqlite3_context *pCtx, 
 1.66008 +  int iArg, 
 1.66009 +  void *pAux, 
 1.66010 +  void (*xDelete)(void*)
 1.66011 +){
 1.66012 +  AuxData *pAuxData;
 1.66013 +  Vdbe *pVdbe = pCtx->pVdbe;
 1.66014 +
 1.66015 +  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
 1.66016 +  if( iArg<0 ) goto failed;
 1.66017 +
 1.66018 +  for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
 1.66019 +    if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
 1.66020 +  }
 1.66021 +  if( pAuxData==0 ){
 1.66022 +    pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
 1.66023 +    if( !pAuxData ) goto failed;
 1.66024 +    pAuxData->iOp = pCtx->iOp;
 1.66025 +    pAuxData->iArg = iArg;
 1.66026 +    pAuxData->pNext = pVdbe->pAuxData;
 1.66027 +    pVdbe->pAuxData = pAuxData;
 1.66028 +    if( pCtx->fErrorOrAux==0 ){
 1.66029 +      pCtx->isError = 0;
 1.66030 +      pCtx->fErrorOrAux = 1;
 1.66031 +    }
 1.66032 +  }else if( pAuxData->xDelete ){
 1.66033 +    pAuxData->xDelete(pAuxData->pAux);
 1.66034 +  }
 1.66035 +
 1.66036 +  pAuxData->pAux = pAux;
 1.66037 +  pAuxData->xDelete = xDelete;
 1.66038 +  return;
 1.66039 +
 1.66040 +failed:
 1.66041 +  if( xDelete ){
 1.66042 +    xDelete(pAux);
 1.66043 +  }
 1.66044 +}
 1.66045 +
 1.66046 +#ifndef SQLITE_OMIT_DEPRECATED
 1.66047 +/*
 1.66048 +** Return the number of times the Step function of a aggregate has been 
 1.66049 +** called.
 1.66050 +**
 1.66051 +** This function is deprecated.  Do not use it for new code.  It is
 1.66052 +** provide only to avoid breaking legacy code.  New aggregate function
 1.66053 +** implementations should keep their own counts within their aggregate
 1.66054 +** context.
 1.66055 +*/
 1.66056 +SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
 1.66057 +  assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
 1.66058 +  return p->pMem->n;
 1.66059 +}
 1.66060 +#endif
 1.66061 +
 1.66062 +/*
 1.66063 +** Return the number of columns in the result set for the statement pStmt.
 1.66064 +*/
 1.66065 +SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
 1.66066 +  Vdbe *pVm = (Vdbe *)pStmt;
 1.66067 +  return pVm ? pVm->nResColumn : 0;
 1.66068 +}
 1.66069 +
 1.66070 +/*
 1.66071 +** Return the number of values available from the current row of the
 1.66072 +** currently executing statement pStmt.
 1.66073 +*/
 1.66074 +SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
 1.66075 +  Vdbe *pVm = (Vdbe *)pStmt;
 1.66076 +  if( pVm==0 || pVm->pResultSet==0 ) return 0;
 1.66077 +  return pVm->nResColumn;
 1.66078 +}
 1.66079 +
 1.66080 +/*
 1.66081 +** Return a pointer to static memory containing an SQL NULL value.
 1.66082 +*/
 1.66083 +static const Mem *columnNullValue(void){
 1.66084 +  /* Even though the Mem structure contains an element
 1.66085 +  ** of type i64, on certain architectures (x86) with certain compiler
 1.66086 +  ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
 1.66087 +  ** instead of an 8-byte one. This all works fine, except that when
 1.66088 +  ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
 1.66089 +  ** that a Mem structure is located on an 8-byte boundary. To prevent
 1.66090 +  ** these assert()s from failing, when building with SQLITE_DEBUG defined
 1.66091 +  ** using gcc, we force nullMem to be 8-byte aligned using the magical
 1.66092 +  ** __attribute__((aligned(8))) macro.  */
 1.66093 +  static const Mem nullMem 
 1.66094 +#if defined(SQLITE_DEBUG) && defined(__GNUC__)
 1.66095 +    __attribute__((aligned(8))) 
 1.66096 +#endif
 1.66097 +    = {0, "", (double)0, {0}, 0, MEM_Null, 0,
 1.66098 +#ifdef SQLITE_DEBUG
 1.66099 +       0, 0,  /* pScopyFrom, pFiller */
 1.66100 +#endif
 1.66101 +       0, 0 };
 1.66102 +  return &nullMem;
 1.66103 +}
 1.66104 +
 1.66105 +/*
 1.66106 +** Check to see if column iCol of the given statement is valid.  If
 1.66107 +** it is, return a pointer to the Mem for the value of that column.
 1.66108 +** If iCol is not valid, return a pointer to a Mem which has a value
 1.66109 +** of NULL.
 1.66110 +*/
 1.66111 +static Mem *columnMem(sqlite3_stmt *pStmt, int i){
 1.66112 +  Vdbe *pVm;
 1.66113 +  Mem *pOut;
 1.66114 +
 1.66115 +  pVm = (Vdbe *)pStmt;
 1.66116 +  if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
 1.66117 +    sqlite3_mutex_enter(pVm->db->mutex);
 1.66118 +    pOut = &pVm->pResultSet[i];
 1.66119 +  }else{
 1.66120 +    if( pVm && ALWAYS(pVm->db) ){
 1.66121 +      sqlite3_mutex_enter(pVm->db->mutex);
 1.66122 +      sqlite3Error(pVm->db, SQLITE_RANGE, 0);
 1.66123 +    }
 1.66124 +    pOut = (Mem*)columnNullValue();
 1.66125 +  }
 1.66126 +  return pOut;
 1.66127 +}
 1.66128 +
 1.66129 +/*
 1.66130 +** This function is called after invoking an sqlite3_value_XXX function on a 
 1.66131 +** column value (i.e. a value returned by evaluating an SQL expression in the
 1.66132 +** select list of a SELECT statement) that may cause a malloc() failure. If 
 1.66133 +** malloc() has failed, the threads mallocFailed flag is cleared and the result
 1.66134 +** code of statement pStmt set to SQLITE_NOMEM.
 1.66135 +**
 1.66136 +** Specifically, this is called from within:
 1.66137 +**
 1.66138 +**     sqlite3_column_int()
 1.66139 +**     sqlite3_column_int64()
 1.66140 +**     sqlite3_column_text()
 1.66141 +**     sqlite3_column_text16()
 1.66142 +**     sqlite3_column_real()
 1.66143 +**     sqlite3_column_bytes()
 1.66144 +**     sqlite3_column_bytes16()
 1.66145 +**     sqiite3_column_blob()
 1.66146 +*/
 1.66147 +static void columnMallocFailure(sqlite3_stmt *pStmt)
 1.66148 +{
 1.66149 +  /* If malloc() failed during an encoding conversion within an
 1.66150 +  ** sqlite3_column_XXX API, then set the return code of the statement to
 1.66151 +  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
 1.66152 +  ** and _finalize() will return NOMEM.
 1.66153 +  */
 1.66154 +  Vdbe *p = (Vdbe *)pStmt;
 1.66155 +  if( p ){
 1.66156 +    p->rc = sqlite3ApiExit(p->db, p->rc);
 1.66157 +    sqlite3_mutex_leave(p->db->mutex);
 1.66158 +  }
 1.66159 +}
 1.66160 +
 1.66161 +/**************************** sqlite3_column_  *******************************
 1.66162 +** The following routines are used to access elements of the current row
 1.66163 +** in the result set.
 1.66164 +*/
 1.66165 +SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
 1.66166 +  const void *val;
 1.66167 +  val = sqlite3_value_blob( columnMem(pStmt,i) );
 1.66168 +  /* Even though there is no encoding conversion, value_blob() might
 1.66169 +  ** need to call malloc() to expand the result of a zeroblob() 
 1.66170 +  ** expression. 
 1.66171 +  */
 1.66172 +  columnMallocFailure(pStmt);
 1.66173 +  return val;
 1.66174 +}
 1.66175 +SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
 1.66176 +  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
 1.66177 +  columnMallocFailure(pStmt);
 1.66178 +  return val;
 1.66179 +}
 1.66180 +SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
 1.66181 +  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
 1.66182 +  columnMallocFailure(pStmt);
 1.66183 +  return val;
 1.66184 +}
 1.66185 +SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
 1.66186 +  double val = sqlite3_value_double( columnMem(pStmt,i) );
 1.66187 +  columnMallocFailure(pStmt);
 1.66188 +  return val;
 1.66189 +}
 1.66190 +SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
 1.66191 +  int val = sqlite3_value_int( columnMem(pStmt,i) );
 1.66192 +  columnMallocFailure(pStmt);
 1.66193 +  return val;
 1.66194 +}
 1.66195 +SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
 1.66196 +  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
 1.66197 +  columnMallocFailure(pStmt);
 1.66198 +  return val;
 1.66199 +}
 1.66200 +SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
 1.66201 +  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
 1.66202 +  columnMallocFailure(pStmt);
 1.66203 +  return val;
 1.66204 +}
 1.66205 +SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
 1.66206 +  Mem *pOut = columnMem(pStmt, i);
 1.66207 +  if( pOut->flags&MEM_Static ){
 1.66208 +    pOut->flags &= ~MEM_Static;
 1.66209 +    pOut->flags |= MEM_Ephem;
 1.66210 +  }
 1.66211 +  columnMallocFailure(pStmt);
 1.66212 +  return (sqlite3_value *)pOut;
 1.66213 +}
 1.66214 +#ifndef SQLITE_OMIT_UTF16
 1.66215 +SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
 1.66216 +  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
 1.66217 +  columnMallocFailure(pStmt);
 1.66218 +  return val;
 1.66219 +}
 1.66220 +#endif /* SQLITE_OMIT_UTF16 */
 1.66221 +SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
 1.66222 +  int iType = sqlite3_value_type( columnMem(pStmt,i) );
 1.66223 +  columnMallocFailure(pStmt);
 1.66224 +  return iType;
 1.66225 +}
 1.66226 +
 1.66227 +/*
 1.66228 +** Convert the N-th element of pStmt->pColName[] into a string using
 1.66229 +** xFunc() then return that string.  If N is out of range, return 0.
 1.66230 +**
 1.66231 +** There are up to 5 names for each column.  useType determines which
 1.66232 +** name is returned.  Here are the names:
 1.66233 +**
 1.66234 +**    0      The column name as it should be displayed for output
 1.66235 +**    1      The datatype name for the column
 1.66236 +**    2      The name of the database that the column derives from
 1.66237 +**    3      The name of the table that the column derives from
 1.66238 +**    4      The name of the table column that the result column derives from
 1.66239 +**
 1.66240 +** If the result is not a simple column reference (if it is an expression
 1.66241 +** or a constant) then useTypes 2, 3, and 4 return NULL.
 1.66242 +*/
 1.66243 +static const void *columnName(
 1.66244 +  sqlite3_stmt *pStmt,
 1.66245 +  int N,
 1.66246 +  const void *(*xFunc)(Mem*),
 1.66247 +  int useType
 1.66248 +){
 1.66249 +  const void *ret = 0;
 1.66250 +  Vdbe *p = (Vdbe *)pStmt;
 1.66251 +  int n;
 1.66252 +  sqlite3 *db = p->db;
 1.66253 +  
 1.66254 +  assert( db!=0 );
 1.66255 +  n = sqlite3_column_count(pStmt);
 1.66256 +  if( N<n && N>=0 ){
 1.66257 +    N += useType*n;
 1.66258 +    sqlite3_mutex_enter(db->mutex);
 1.66259 +    assert( db->mallocFailed==0 );
 1.66260 +    ret = xFunc(&p->aColName[N]);
 1.66261 +     /* A malloc may have failed inside of the xFunc() call. If this
 1.66262 +    ** is the case, clear the mallocFailed flag and return NULL.
 1.66263 +    */
 1.66264 +    if( db->mallocFailed ){
 1.66265 +      db->mallocFailed = 0;
 1.66266 +      ret = 0;
 1.66267 +    }
 1.66268 +    sqlite3_mutex_leave(db->mutex);
 1.66269 +  }
 1.66270 +  return ret;
 1.66271 +}
 1.66272 +
 1.66273 +/*
 1.66274 +** Return the name of the Nth column of the result set returned by SQL
 1.66275 +** statement pStmt.
 1.66276 +*/
 1.66277 +SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
 1.66278 +  return columnName(
 1.66279 +      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
 1.66280 +}
 1.66281 +#ifndef SQLITE_OMIT_UTF16
 1.66282 +SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
 1.66283 +  return columnName(
 1.66284 +      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
 1.66285 +}
 1.66286 +#endif
 1.66287 +
 1.66288 +/*
 1.66289 +** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
 1.66290 +** not define OMIT_DECLTYPE.
 1.66291 +*/
 1.66292 +#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
 1.66293 +# error "Must not define both SQLITE_OMIT_DECLTYPE \
 1.66294 +         and SQLITE_ENABLE_COLUMN_METADATA"
 1.66295 +#endif
 1.66296 +
 1.66297 +#ifndef SQLITE_OMIT_DECLTYPE
 1.66298 +/*
 1.66299 +** Return the column declaration type (if applicable) of the 'i'th column
 1.66300 +** of the result set of SQL statement pStmt.
 1.66301 +*/
 1.66302 +SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
 1.66303 +  return columnName(
 1.66304 +      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
 1.66305 +}
 1.66306 +#ifndef SQLITE_OMIT_UTF16
 1.66307 +SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
 1.66308 +  return columnName(
 1.66309 +      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
 1.66310 +}
 1.66311 +#endif /* SQLITE_OMIT_UTF16 */
 1.66312 +#endif /* SQLITE_OMIT_DECLTYPE */
 1.66313 +
 1.66314 +#ifdef SQLITE_ENABLE_COLUMN_METADATA
 1.66315 +/*
 1.66316 +** Return the name of the database from which a result column derives.
 1.66317 +** NULL is returned if the result column is an expression or constant or
 1.66318 +** anything else which is not an unabiguous reference to a database column.
 1.66319 +*/
 1.66320 +SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
 1.66321 +  return columnName(
 1.66322 +      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
 1.66323 +}
 1.66324 +#ifndef SQLITE_OMIT_UTF16
 1.66325 +SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
 1.66326 +  return columnName(
 1.66327 +      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
 1.66328 +}
 1.66329 +#endif /* SQLITE_OMIT_UTF16 */
 1.66330 +
 1.66331 +/*
 1.66332 +** Return the name of the table from which a result column derives.
 1.66333 +** NULL is returned if the result column is an expression or constant or
 1.66334 +** anything else which is not an unabiguous reference to a database column.
 1.66335 +*/
 1.66336 +SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
 1.66337 +  return columnName(
 1.66338 +      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
 1.66339 +}
 1.66340 +#ifndef SQLITE_OMIT_UTF16
 1.66341 +SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
 1.66342 +  return columnName(
 1.66343 +      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
 1.66344 +}
 1.66345 +#endif /* SQLITE_OMIT_UTF16 */
 1.66346 +
 1.66347 +/*
 1.66348 +** Return the name of the table column from which a result column derives.
 1.66349 +** NULL is returned if the result column is an expression or constant or
 1.66350 +** anything else which is not an unabiguous reference to a database column.
 1.66351 +*/
 1.66352 +SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
 1.66353 +  return columnName(
 1.66354 +      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
 1.66355 +}
 1.66356 +#ifndef SQLITE_OMIT_UTF16
 1.66357 +SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
 1.66358 +  return columnName(
 1.66359 +      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
 1.66360 +}
 1.66361 +#endif /* SQLITE_OMIT_UTF16 */
 1.66362 +#endif /* SQLITE_ENABLE_COLUMN_METADATA */
 1.66363 +
 1.66364 +
 1.66365 +/******************************* sqlite3_bind_  ***************************
 1.66366 +** 
 1.66367 +** Routines used to attach values to wildcards in a compiled SQL statement.
 1.66368 +*/
 1.66369 +/*
 1.66370 +** Unbind the value bound to variable i in virtual machine p. This is the 
 1.66371 +** the same as binding a NULL value to the column. If the "i" parameter is
 1.66372 +** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
 1.66373 +**
 1.66374 +** A successful evaluation of this routine acquires the mutex on p.
 1.66375 +** the mutex is released if any kind of error occurs.
 1.66376 +**
 1.66377 +** The error code stored in database p->db is overwritten with the return
 1.66378 +** value in any case.
 1.66379 +*/
 1.66380 +static int vdbeUnbind(Vdbe *p, int i){
 1.66381 +  Mem *pVar;
 1.66382 +  if( vdbeSafetyNotNull(p) ){
 1.66383 +    return SQLITE_MISUSE_BKPT;
 1.66384 +  }
 1.66385 +  sqlite3_mutex_enter(p->db->mutex);
 1.66386 +  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
 1.66387 +    sqlite3Error(p->db, SQLITE_MISUSE, 0);
 1.66388 +    sqlite3_mutex_leave(p->db->mutex);
 1.66389 +    sqlite3_log(SQLITE_MISUSE, 
 1.66390 +        "bind on a busy prepared statement: [%s]", p->zSql);
 1.66391 +    return SQLITE_MISUSE_BKPT;
 1.66392 +  }
 1.66393 +  if( i<1 || i>p->nVar ){
 1.66394 +    sqlite3Error(p->db, SQLITE_RANGE, 0);
 1.66395 +    sqlite3_mutex_leave(p->db->mutex);
 1.66396 +    return SQLITE_RANGE;
 1.66397 +  }
 1.66398 +  i--;
 1.66399 +  pVar = &p->aVar[i];
 1.66400 +  sqlite3VdbeMemRelease(pVar);
 1.66401 +  pVar->flags = MEM_Null;
 1.66402 +  sqlite3Error(p->db, SQLITE_OK, 0);
 1.66403 +
 1.66404 +  /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
 1.66405 +  ** binding a new value to this variable invalidates the current query plan.
 1.66406 +  **
 1.66407 +  ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
 1.66408 +  ** parameter in the WHERE clause might influence the choice of query plan
 1.66409 +  ** for a statement, then the statement will be automatically recompiled,
 1.66410 +  ** as if there had been a schema change, on the first sqlite3_step() call
 1.66411 +  ** following any change to the bindings of that parameter.
 1.66412 +  */
 1.66413 +  if( p->isPrepareV2 &&
 1.66414 +     ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
 1.66415 +  ){
 1.66416 +    p->expired = 1;
 1.66417 +  }
 1.66418 +  return SQLITE_OK;
 1.66419 +}
 1.66420 +
 1.66421 +/*
 1.66422 +** Bind a text or BLOB value.
 1.66423 +*/
 1.66424 +static int bindText(
 1.66425 +  sqlite3_stmt *pStmt,   /* The statement to bind against */
 1.66426 +  int i,                 /* Index of the parameter to bind */
 1.66427 +  const void *zData,     /* Pointer to the data to be bound */
 1.66428 +  int nData,             /* Number of bytes of data to be bound */
 1.66429 +  void (*xDel)(void*),   /* Destructor for the data */
 1.66430 +  u8 encoding            /* Encoding for the data */
 1.66431 +){
 1.66432 +  Vdbe *p = (Vdbe *)pStmt;
 1.66433 +  Mem *pVar;
 1.66434 +  int rc;
 1.66435 +
 1.66436 +  rc = vdbeUnbind(p, i);
 1.66437 +  if( rc==SQLITE_OK ){
 1.66438 +    if( zData!=0 ){
 1.66439 +      pVar = &p->aVar[i-1];
 1.66440 +      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
 1.66441 +      if( rc==SQLITE_OK && encoding!=0 ){
 1.66442 +        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
 1.66443 +      }
 1.66444 +      sqlite3Error(p->db, rc, 0);
 1.66445 +      rc = sqlite3ApiExit(p->db, rc);
 1.66446 +    }
 1.66447 +    sqlite3_mutex_leave(p->db->mutex);
 1.66448 +  }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
 1.66449 +    xDel((void*)zData);
 1.66450 +  }
 1.66451 +  return rc;
 1.66452 +}
 1.66453 +
 1.66454 +
 1.66455 +/*
 1.66456 +** Bind a blob value to an SQL statement variable.
 1.66457 +*/
 1.66458 +SQLITE_API int sqlite3_bind_blob(
 1.66459 +  sqlite3_stmt *pStmt, 
 1.66460 +  int i, 
 1.66461 +  const void *zData, 
 1.66462 +  int nData, 
 1.66463 +  void (*xDel)(void*)
 1.66464 +){
 1.66465 +  return bindText(pStmt, i, zData, nData, xDel, 0);
 1.66466 +}
 1.66467 +SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
 1.66468 +  int rc;
 1.66469 +  Vdbe *p = (Vdbe *)pStmt;
 1.66470 +  rc = vdbeUnbind(p, i);
 1.66471 +  if( rc==SQLITE_OK ){
 1.66472 +    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
 1.66473 +    sqlite3_mutex_leave(p->db->mutex);
 1.66474 +  }
 1.66475 +  return rc;
 1.66476 +}
 1.66477 +SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
 1.66478 +  return sqlite3_bind_int64(p, i, (i64)iValue);
 1.66479 +}
 1.66480 +SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
 1.66481 +  int rc;
 1.66482 +  Vdbe *p = (Vdbe *)pStmt;
 1.66483 +  rc = vdbeUnbind(p, i);
 1.66484 +  if( rc==SQLITE_OK ){
 1.66485 +    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
 1.66486 +    sqlite3_mutex_leave(p->db->mutex);
 1.66487 +  }
 1.66488 +  return rc;
 1.66489 +}
 1.66490 +SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
 1.66491 +  int rc;
 1.66492 +  Vdbe *p = (Vdbe*)pStmt;
 1.66493 +  rc = vdbeUnbind(p, i);
 1.66494 +  if( rc==SQLITE_OK ){
 1.66495 +    sqlite3_mutex_leave(p->db->mutex);
 1.66496 +  }
 1.66497 +  return rc;
 1.66498 +}
 1.66499 +SQLITE_API int sqlite3_bind_text( 
 1.66500 +  sqlite3_stmt *pStmt, 
 1.66501 +  int i, 
 1.66502 +  const char *zData, 
 1.66503 +  int nData, 
 1.66504 +  void (*xDel)(void*)
 1.66505 +){
 1.66506 +  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
 1.66507 +}
 1.66508 +#ifndef SQLITE_OMIT_UTF16
 1.66509 +SQLITE_API int sqlite3_bind_text16(
 1.66510 +  sqlite3_stmt *pStmt, 
 1.66511 +  int i, 
 1.66512 +  const void *zData, 
 1.66513 +  int nData, 
 1.66514 +  void (*xDel)(void*)
 1.66515 +){
 1.66516 +  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
 1.66517 +}
 1.66518 +#endif /* SQLITE_OMIT_UTF16 */
 1.66519 +SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
 1.66520 +  int rc;
 1.66521 +  switch( sqlite3_value_type((sqlite3_value*)pValue) ){
 1.66522 +    case SQLITE_INTEGER: {
 1.66523 +      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
 1.66524 +      break;
 1.66525 +    }
 1.66526 +    case SQLITE_FLOAT: {
 1.66527 +      rc = sqlite3_bind_double(pStmt, i, pValue->r);
 1.66528 +      break;
 1.66529 +    }
 1.66530 +    case SQLITE_BLOB: {
 1.66531 +      if( pValue->flags & MEM_Zero ){
 1.66532 +        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
 1.66533 +      }else{
 1.66534 +        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
 1.66535 +      }
 1.66536 +      break;
 1.66537 +    }
 1.66538 +    case SQLITE_TEXT: {
 1.66539 +      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
 1.66540 +                              pValue->enc);
 1.66541 +      break;
 1.66542 +    }
 1.66543 +    default: {
 1.66544 +      rc = sqlite3_bind_null(pStmt, i);
 1.66545 +      break;
 1.66546 +    }
 1.66547 +  }
 1.66548 +  return rc;
 1.66549 +}
 1.66550 +SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
 1.66551 +  int rc;
 1.66552 +  Vdbe *p = (Vdbe *)pStmt;
 1.66553 +  rc = vdbeUnbind(p, i);
 1.66554 +  if( rc==SQLITE_OK ){
 1.66555 +    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
 1.66556 +    sqlite3_mutex_leave(p->db->mutex);
 1.66557 +  }
 1.66558 +  return rc;
 1.66559 +}
 1.66560 +
 1.66561 +/*
 1.66562 +** Return the number of wildcards that can be potentially bound to.
 1.66563 +** This routine is added to support DBD::SQLite.  
 1.66564 +*/
 1.66565 +SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
 1.66566 +  Vdbe *p = (Vdbe*)pStmt;
 1.66567 +  return p ? p->nVar : 0;
 1.66568 +}
 1.66569 +
 1.66570 +/*
 1.66571 +** Return the name of a wildcard parameter.  Return NULL if the index
 1.66572 +** is out of range or if the wildcard is unnamed.
 1.66573 +**
 1.66574 +** The result is always UTF-8.
 1.66575 +*/
 1.66576 +SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
 1.66577 +  Vdbe *p = (Vdbe*)pStmt;
 1.66578 +  if( p==0 || i<1 || i>p->nzVar ){
 1.66579 +    return 0;
 1.66580 +  }
 1.66581 +  return p->azVar[i-1];
 1.66582 +}
 1.66583 +
 1.66584 +/*
 1.66585 +** Given a wildcard parameter name, return the index of the variable
 1.66586 +** with that name.  If there is no variable with the given name,
 1.66587 +** return 0.
 1.66588 +*/
 1.66589 +SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
 1.66590 +  int i;
 1.66591 +  if( p==0 ){
 1.66592 +    return 0;
 1.66593 +  }
 1.66594 +  if( zName ){
 1.66595 +    for(i=0; i<p->nzVar; i++){
 1.66596 +      const char *z = p->azVar[i];
 1.66597 +      if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
 1.66598 +        return i+1;
 1.66599 +      }
 1.66600 +    }
 1.66601 +  }
 1.66602 +  return 0;
 1.66603 +}
 1.66604 +SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
 1.66605 +  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
 1.66606 +}
 1.66607 +
 1.66608 +/*
 1.66609 +** Transfer all bindings from the first statement over to the second.
 1.66610 +*/
 1.66611 +SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
 1.66612 +  Vdbe *pFrom = (Vdbe*)pFromStmt;
 1.66613 +  Vdbe *pTo = (Vdbe*)pToStmt;
 1.66614 +  int i;
 1.66615 +  assert( pTo->db==pFrom->db );
 1.66616 +  assert( pTo->nVar==pFrom->nVar );
 1.66617 +  sqlite3_mutex_enter(pTo->db->mutex);
 1.66618 +  for(i=0; i<pFrom->nVar; i++){
 1.66619 +    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
 1.66620 +  }
 1.66621 +  sqlite3_mutex_leave(pTo->db->mutex);
 1.66622 +  return SQLITE_OK;
 1.66623 +}
 1.66624 +
 1.66625 +#ifndef SQLITE_OMIT_DEPRECATED
 1.66626 +/*
 1.66627 +** Deprecated external interface.  Internal/core SQLite code
 1.66628 +** should call sqlite3TransferBindings.
 1.66629 +**
 1.66630 +** Is is misuse to call this routine with statements from different
 1.66631 +** database connections.  But as this is a deprecated interface, we
 1.66632 +** will not bother to check for that condition.
 1.66633 +**
 1.66634 +** If the two statements contain a different number of bindings, then
 1.66635 +** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
 1.66636 +** SQLITE_OK is returned.
 1.66637 +*/
 1.66638 +SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
 1.66639 +  Vdbe *pFrom = (Vdbe*)pFromStmt;
 1.66640 +  Vdbe *pTo = (Vdbe*)pToStmt;
 1.66641 +  if( pFrom->nVar!=pTo->nVar ){
 1.66642 +    return SQLITE_ERROR;
 1.66643 +  }
 1.66644 +  if( pTo->isPrepareV2 && pTo->expmask ){
 1.66645 +    pTo->expired = 1;
 1.66646 +  }
 1.66647 +  if( pFrom->isPrepareV2 && pFrom->expmask ){
 1.66648 +    pFrom->expired = 1;
 1.66649 +  }
 1.66650 +  return sqlite3TransferBindings(pFromStmt, pToStmt);
 1.66651 +}
 1.66652 +#endif
 1.66653 +
 1.66654 +/*
 1.66655 +** Return the sqlite3* database handle to which the prepared statement given
 1.66656 +** in the argument belongs.  This is the same database handle that was
 1.66657 +** the first argument to the sqlite3_prepare() that was used to create
 1.66658 +** the statement in the first place.
 1.66659 +*/
 1.66660 +SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
 1.66661 +  return pStmt ? ((Vdbe*)pStmt)->db : 0;
 1.66662 +}
 1.66663 +
 1.66664 +/*
 1.66665 +** Return true if the prepared statement is guaranteed to not modify the
 1.66666 +** database.
 1.66667 +*/
 1.66668 +SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
 1.66669 +  return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
 1.66670 +}
 1.66671 +
 1.66672 +/*
 1.66673 +** Return true if the prepared statement is in need of being reset.
 1.66674 +*/
 1.66675 +SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
 1.66676 +  Vdbe *v = (Vdbe*)pStmt;
 1.66677 +  return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
 1.66678 +}
 1.66679 +
 1.66680 +/*
 1.66681 +** Return a pointer to the next prepared statement after pStmt associated
 1.66682 +** with database connection pDb.  If pStmt is NULL, return the first
 1.66683 +** prepared statement for the database connection.  Return NULL if there
 1.66684 +** are no more.
 1.66685 +*/
 1.66686 +SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
 1.66687 +  sqlite3_stmt *pNext;
 1.66688 +  sqlite3_mutex_enter(pDb->mutex);
 1.66689 +  if( pStmt==0 ){
 1.66690 +    pNext = (sqlite3_stmt*)pDb->pVdbe;
 1.66691 +  }else{
 1.66692 +    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
 1.66693 +  }
 1.66694 +  sqlite3_mutex_leave(pDb->mutex);
 1.66695 +  return pNext;
 1.66696 +}
 1.66697 +
 1.66698 +/*
 1.66699 +** Return the value of a status counter for a prepared statement
 1.66700 +*/
 1.66701 +SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
 1.66702 +  Vdbe *pVdbe = (Vdbe*)pStmt;
 1.66703 +  u32 v = pVdbe->aCounter[op];
 1.66704 +  if( resetFlag ) pVdbe->aCounter[op] = 0;
 1.66705 +  return (int)v;
 1.66706 +}
 1.66707 +
 1.66708 +/************** End of vdbeapi.c *********************************************/
 1.66709 +/************** Begin file vdbetrace.c ***************************************/
 1.66710 +/*
 1.66711 +** 2009 November 25
 1.66712 +**
 1.66713 +** The author disclaims copyright to this source code.  In place of
 1.66714 +** a legal notice, here is a blessing:
 1.66715 +**
 1.66716 +**    May you do good and not evil.
 1.66717 +**    May you find forgiveness for yourself and forgive others.
 1.66718 +**    May you share freely, never taking more than you give.
 1.66719 +**
 1.66720 +*************************************************************************
 1.66721 +**
 1.66722 +** This file contains code used to insert the values of host parameters
 1.66723 +** (aka "wildcards") into the SQL text output by sqlite3_trace().
 1.66724 +**
 1.66725 +** The Vdbe parse-tree explainer is also found here.
 1.66726 +*/
 1.66727 +
 1.66728 +#ifndef SQLITE_OMIT_TRACE
 1.66729 +
 1.66730 +/*
 1.66731 +** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
 1.66732 +** bytes in this text up to but excluding the first character in
 1.66733 +** a host parameter.  If the text contains no host parameters, return
 1.66734 +** the total number of bytes in the text.
 1.66735 +*/
 1.66736 +static int findNextHostParameter(const char *zSql, int *pnToken){
 1.66737 +  int tokenType;
 1.66738 +  int nTotal = 0;
 1.66739 +  int n;
 1.66740 +
 1.66741 +  *pnToken = 0;
 1.66742 +  while( zSql[0] ){
 1.66743 +    n = sqlite3GetToken((u8*)zSql, &tokenType);
 1.66744 +    assert( n>0 && tokenType!=TK_ILLEGAL );
 1.66745 +    if( tokenType==TK_VARIABLE ){
 1.66746 +      *pnToken = n;
 1.66747 +      break;
 1.66748 +    }
 1.66749 +    nTotal += n;
 1.66750 +    zSql += n;
 1.66751 +  }
 1.66752 +  return nTotal;
 1.66753 +}
 1.66754 +
 1.66755 +/*
 1.66756 +** This function returns a pointer to a nul-terminated string in memory
 1.66757 +** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
 1.66758 +** string contains a copy of zRawSql but with host parameters expanded to 
 1.66759 +** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1, 
 1.66760 +** then the returned string holds a copy of zRawSql with "-- " prepended
 1.66761 +** to each line of text.
 1.66762 +**
 1.66763 +** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
 1.66764 +** then long strings and blobs are truncated to that many bytes.  This
 1.66765 +** can be used to prevent unreasonably large trace strings when dealing
 1.66766 +** with large (multi-megabyte) strings and blobs.
 1.66767 +**
 1.66768 +** The calling function is responsible for making sure the memory returned
 1.66769 +** is eventually freed.
 1.66770 +**
 1.66771 +** ALGORITHM:  Scan the input string looking for host parameters in any of
 1.66772 +** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
 1.66773 +** string literals, quoted identifier names, and comments.  For text forms,
 1.66774 +** the host parameter index is found by scanning the perpared
 1.66775 +** statement for the corresponding OP_Variable opcode.  Once the host
 1.66776 +** parameter index is known, locate the value in p->aVar[].  Then render
 1.66777 +** the value as a literal in place of the host parameter name.
 1.66778 +*/
 1.66779 +SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
 1.66780 +  Vdbe *p,                 /* The prepared statement being evaluated */
 1.66781 +  const char *zRawSql      /* Raw text of the SQL statement */
 1.66782 +){
 1.66783 +  sqlite3 *db;             /* The database connection */
 1.66784 +  int idx = 0;             /* Index of a host parameter */
 1.66785 +  int nextIndex = 1;       /* Index of next ? host parameter */
 1.66786 +  int n;                   /* Length of a token prefix */
 1.66787 +  int nToken;              /* Length of the parameter token */
 1.66788 +  int i;                   /* Loop counter */
 1.66789 +  Mem *pVar;               /* Value of a host parameter */
 1.66790 +  StrAccum out;            /* Accumulate the output here */
 1.66791 +  char zBase[100];         /* Initial working space */
 1.66792 +
 1.66793 +  db = p->db;
 1.66794 +  sqlite3StrAccumInit(&out, zBase, sizeof(zBase), 
 1.66795 +                      db->aLimit[SQLITE_LIMIT_LENGTH]);
 1.66796 +  out.db = db;
 1.66797 +  if( db->nVdbeExec>1 ){
 1.66798 +    while( *zRawSql ){
 1.66799 +      const char *zStart = zRawSql;
 1.66800 +      while( *(zRawSql++)!='\n' && *zRawSql );
 1.66801 +      sqlite3StrAccumAppend(&out, "-- ", 3);
 1.66802 +      assert( (zRawSql - zStart) > 0 );
 1.66803 +      sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
 1.66804 +    }
 1.66805 +  }else{
 1.66806 +    while( zRawSql[0] ){
 1.66807 +      n = findNextHostParameter(zRawSql, &nToken);
 1.66808 +      assert( n>0 );
 1.66809 +      sqlite3StrAccumAppend(&out, zRawSql, n);
 1.66810 +      zRawSql += n;
 1.66811 +      assert( zRawSql[0] || nToken==0 );
 1.66812 +      if( nToken==0 ) break;
 1.66813 +      if( zRawSql[0]=='?' ){
 1.66814 +        if( nToken>1 ){
 1.66815 +          assert( sqlite3Isdigit(zRawSql[1]) );
 1.66816 +          sqlite3GetInt32(&zRawSql[1], &idx);
 1.66817 +        }else{
 1.66818 +          idx = nextIndex;
 1.66819 +        }
 1.66820 +      }else{
 1.66821 +        assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
 1.66822 +        testcase( zRawSql[0]==':' );
 1.66823 +        testcase( zRawSql[0]=='$' );
 1.66824 +        testcase( zRawSql[0]=='@' );
 1.66825 +        idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
 1.66826 +        assert( idx>0 );
 1.66827 +      }
 1.66828 +      zRawSql += nToken;
 1.66829 +      nextIndex = idx + 1;
 1.66830 +      assert( idx>0 && idx<=p->nVar );
 1.66831 +      pVar = &p->aVar[idx-1];
 1.66832 +      if( pVar->flags & MEM_Null ){
 1.66833 +        sqlite3StrAccumAppend(&out, "NULL", 4);
 1.66834 +      }else if( pVar->flags & MEM_Int ){
 1.66835 +        sqlite3XPrintf(&out, 0, "%lld", pVar->u.i);
 1.66836 +      }else if( pVar->flags & MEM_Real ){
 1.66837 +        sqlite3XPrintf(&out, 0, "%!.15g", pVar->r);
 1.66838 +      }else if( pVar->flags & MEM_Str ){
 1.66839 +        int nOut;  /* Number of bytes of the string text to include in output */
 1.66840 +#ifndef SQLITE_OMIT_UTF16
 1.66841 +        u8 enc = ENC(db);
 1.66842 +        Mem utf8;
 1.66843 +        if( enc!=SQLITE_UTF8 ){
 1.66844 +          memset(&utf8, 0, sizeof(utf8));
 1.66845 +          utf8.db = db;
 1.66846 +          sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
 1.66847 +          sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
 1.66848 +          pVar = &utf8;
 1.66849 +        }
 1.66850 +#endif
 1.66851 +        nOut = pVar->n;
 1.66852 +#ifdef SQLITE_TRACE_SIZE_LIMIT
 1.66853 +        if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
 1.66854 +          nOut = SQLITE_TRACE_SIZE_LIMIT;
 1.66855 +          while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
 1.66856 +        }
 1.66857 +#endif    
 1.66858 +        sqlite3XPrintf(&out, 0, "'%.*q'", nOut, pVar->z);
 1.66859 +#ifdef SQLITE_TRACE_SIZE_LIMIT
 1.66860 +        if( nOut<pVar->n ){
 1.66861 +          sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
 1.66862 +        }
 1.66863 +#endif
 1.66864 +#ifndef SQLITE_OMIT_UTF16
 1.66865 +        if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
 1.66866 +#endif
 1.66867 +      }else if( pVar->flags & MEM_Zero ){
 1.66868 +        sqlite3XPrintf(&out, 0, "zeroblob(%d)", pVar->u.nZero);
 1.66869 +      }else{
 1.66870 +        int nOut;  /* Number of bytes of the blob to include in output */
 1.66871 +        assert( pVar->flags & MEM_Blob );
 1.66872 +        sqlite3StrAccumAppend(&out, "x'", 2);
 1.66873 +        nOut = pVar->n;
 1.66874 +#ifdef SQLITE_TRACE_SIZE_LIMIT
 1.66875 +        if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
 1.66876 +#endif
 1.66877 +        for(i=0; i<nOut; i++){
 1.66878 +          sqlite3XPrintf(&out, 0, "%02x", pVar->z[i]&0xff);
 1.66879 +        }
 1.66880 +        sqlite3StrAccumAppend(&out, "'", 1);
 1.66881 +#ifdef SQLITE_TRACE_SIZE_LIMIT
 1.66882 +        if( nOut<pVar->n ){
 1.66883 +          sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
 1.66884 +        }
 1.66885 +#endif
 1.66886 +      }
 1.66887 +    }
 1.66888 +  }
 1.66889 +  return sqlite3StrAccumFinish(&out);
 1.66890 +}
 1.66891 +
 1.66892 +#endif /* #ifndef SQLITE_OMIT_TRACE */
 1.66893 +
 1.66894 +/*****************************************************************************
 1.66895 +** The following code implements the data-structure explaining logic
 1.66896 +** for the Vdbe.
 1.66897 +*/
 1.66898 +
 1.66899 +#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
 1.66900 +
 1.66901 +/*
 1.66902 +** Allocate a new Explain object
 1.66903 +*/
 1.66904 +SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
 1.66905 +  if( pVdbe ){
 1.66906 +    Explain *p;
 1.66907 +    sqlite3BeginBenignMalloc();
 1.66908 +    p = (Explain *)sqlite3MallocZero( sizeof(Explain) );
 1.66909 +    if( p ){
 1.66910 +      p->pVdbe = pVdbe;
 1.66911 +      sqlite3_free(pVdbe->pExplain);
 1.66912 +      pVdbe->pExplain = p;
 1.66913 +      sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
 1.66914 +                          SQLITE_MAX_LENGTH);
 1.66915 +      p->str.useMalloc = 2;
 1.66916 +    }else{
 1.66917 +      sqlite3EndBenignMalloc();
 1.66918 +    }
 1.66919 +  }
 1.66920 +}
 1.66921 +
 1.66922 +/*
 1.66923 +** Return true if the Explain ends with a new-line.
 1.66924 +*/
 1.66925 +static int endsWithNL(Explain *p){
 1.66926 +  return p && p->str.zText && p->str.nChar
 1.66927 +           && p->str.zText[p->str.nChar-1]=='\n';
 1.66928 +}
 1.66929 +    
 1.66930 +/*
 1.66931 +** Append text to the indentation
 1.66932 +*/
 1.66933 +SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
 1.66934 +  Explain *p;
 1.66935 +  if( pVdbe && (p = pVdbe->pExplain)!=0 ){
 1.66936 +    va_list ap;
 1.66937 +    if( p->nIndent && endsWithNL(p) ){
 1.66938 +      int n = p->nIndent;
 1.66939 +      if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
 1.66940 +      sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
 1.66941 +    }   
 1.66942 +    va_start(ap, zFormat);
 1.66943 +    sqlite3VXPrintf(&p->str, SQLITE_PRINTF_INTERNAL, zFormat, ap);
 1.66944 +    va_end(ap);
 1.66945 +  }
 1.66946 +}
 1.66947 +
 1.66948 +/*
 1.66949 +** Append a '\n' if there is not already one.
 1.66950 +*/
 1.66951 +SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
 1.66952 +  Explain *p;
 1.66953 +  if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
 1.66954 +    sqlite3StrAccumAppend(&p->str, "\n", 1);
 1.66955 +  }
 1.66956 +}
 1.66957 +
 1.66958 +/*
 1.66959 +** Push a new indentation level.  Subsequent lines will be indented
 1.66960 +** so that they begin at the current cursor position.
 1.66961 +*/
 1.66962 +SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
 1.66963 +  Explain *p;
 1.66964 +  if( pVdbe && (p = pVdbe->pExplain)!=0 ){
 1.66965 +    if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
 1.66966 +      const char *z = p->str.zText;
 1.66967 +      int i = p->str.nChar-1;
 1.66968 +      int x;
 1.66969 +      while( i>=0 && z[i]!='\n' ){ i--; }
 1.66970 +      x = (p->str.nChar - 1) - i;
 1.66971 +      if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
 1.66972 +        x = p->aIndent[p->nIndent-1];
 1.66973 +      }
 1.66974 +      p->aIndent[p->nIndent] = x;
 1.66975 +    }
 1.66976 +    p->nIndent++;
 1.66977 +  }
 1.66978 +}
 1.66979 +
 1.66980 +/*
 1.66981 +** Pop the indentation stack by one level.
 1.66982 +*/
 1.66983 +SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
 1.66984 +  if( p && p->pExplain ) p->pExplain->nIndent--;
 1.66985 +}
 1.66986 +
 1.66987 +/*
 1.66988 +** Free the indentation structure
 1.66989 +*/
 1.66990 +SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
 1.66991 +  if( pVdbe && pVdbe->pExplain ){
 1.66992 +    sqlite3_free(pVdbe->zExplain);
 1.66993 +    sqlite3ExplainNL(pVdbe);
 1.66994 +    pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
 1.66995 +    sqlite3_free(pVdbe->pExplain);
 1.66996 +    pVdbe->pExplain = 0;
 1.66997 +    sqlite3EndBenignMalloc();
 1.66998 +  }
 1.66999 +}
 1.67000 +
 1.67001 +/*
 1.67002 +** Return the explanation of a virtual machine.
 1.67003 +*/
 1.67004 +SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
 1.67005 +  return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
 1.67006 +}
 1.67007 +#endif /* defined(SQLITE_DEBUG) */
 1.67008 +
 1.67009 +/************** End of vdbetrace.c *******************************************/
 1.67010 +/************** Begin file vdbe.c ********************************************/
 1.67011 +/*
 1.67012 +** 2001 September 15
 1.67013 +**
 1.67014 +** The author disclaims copyright to this source code.  In place of
 1.67015 +** a legal notice, here is a blessing:
 1.67016 +**
 1.67017 +**    May you do good and not evil.
 1.67018 +**    May you find forgiveness for yourself and forgive others.
 1.67019 +**    May you share freely, never taking more than you give.
 1.67020 +**
 1.67021 +*************************************************************************
 1.67022 +** The code in this file implements the function that runs the
 1.67023 +** bytecode of a prepared statement.
 1.67024 +**
 1.67025 +** Various scripts scan this source file in order to generate HTML
 1.67026 +** documentation, headers files, or other derived files.  The formatting
 1.67027 +** of the code in this file is, therefore, important.  See other comments
 1.67028 +** in this file for details.  If in doubt, do not deviate from existing
 1.67029 +** commenting and indentation practices when changing or adding code.
 1.67030 +*/
 1.67031 +
 1.67032 +/*
 1.67033 +** Invoke this macro on memory cells just prior to changing the
 1.67034 +** value of the cell.  This macro verifies that shallow copies are
 1.67035 +** not misused.  A shallow copy of a string or blob just copies a
 1.67036 +** pointer to the string or blob, not the content.  If the original
 1.67037 +** is changed while the copy is still in use, the string or blob might
 1.67038 +** be changed out from under the copy.  This macro verifies that nothing
 1.67039 +** like that ever happens.
 1.67040 +*/
 1.67041 +#ifdef SQLITE_DEBUG
 1.67042 +# define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
 1.67043 +#else
 1.67044 +# define memAboutToChange(P,M)
 1.67045 +#endif
 1.67046 +
 1.67047 +/*
 1.67048 +** The following global variable is incremented every time a cursor
 1.67049 +** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
 1.67050 +** procedures use this information to make sure that indices are
 1.67051 +** working correctly.  This variable has no function other than to
 1.67052 +** help verify the correct operation of the library.
 1.67053 +*/
 1.67054 +#ifdef SQLITE_TEST
 1.67055 +SQLITE_API int sqlite3_search_count = 0;
 1.67056 +#endif
 1.67057 +
 1.67058 +/*
 1.67059 +** When this global variable is positive, it gets decremented once before
 1.67060 +** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
 1.67061 +** field of the sqlite3 structure is set in order to simulate an interrupt.
 1.67062 +**
 1.67063 +** This facility is used for testing purposes only.  It does not function
 1.67064 +** in an ordinary build.
 1.67065 +*/
 1.67066 +#ifdef SQLITE_TEST
 1.67067 +SQLITE_API int sqlite3_interrupt_count = 0;
 1.67068 +#endif
 1.67069 +
 1.67070 +/*
 1.67071 +** The next global variable is incremented each type the OP_Sort opcode
 1.67072 +** is executed.  The test procedures use this information to make sure that
 1.67073 +** sorting is occurring or not occurring at appropriate times.   This variable
 1.67074 +** has no function other than to help verify the correct operation of the
 1.67075 +** library.
 1.67076 +*/
 1.67077 +#ifdef SQLITE_TEST
 1.67078 +SQLITE_API int sqlite3_sort_count = 0;
 1.67079 +#endif
 1.67080 +
 1.67081 +/*
 1.67082 +** The next global variable records the size of the largest MEM_Blob
 1.67083 +** or MEM_Str that has been used by a VDBE opcode.  The test procedures
 1.67084 +** use this information to make sure that the zero-blob functionality
 1.67085 +** is working correctly.   This variable has no function other than to
 1.67086 +** help verify the correct operation of the library.
 1.67087 +*/
 1.67088 +#ifdef SQLITE_TEST
 1.67089 +SQLITE_API int sqlite3_max_blobsize = 0;
 1.67090 +static void updateMaxBlobsize(Mem *p){
 1.67091 +  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
 1.67092 +    sqlite3_max_blobsize = p->n;
 1.67093 +  }
 1.67094 +}
 1.67095 +#endif
 1.67096 +
 1.67097 +/*
 1.67098 +** The next global variable is incremented each time the OP_Found opcode
 1.67099 +** is executed. This is used to test whether or not the foreign key
 1.67100 +** operation implemented using OP_FkIsZero is working. This variable
 1.67101 +** has no function other than to help verify the correct operation of the
 1.67102 +** library.
 1.67103 +*/
 1.67104 +#ifdef SQLITE_TEST
 1.67105 +SQLITE_API int sqlite3_found_count = 0;
 1.67106 +#endif
 1.67107 +
 1.67108 +/*
 1.67109 +** Test a register to see if it exceeds the current maximum blob size.
 1.67110 +** If it does, record the new maximum blob size.
 1.67111 +*/
 1.67112 +#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
 1.67113 +# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
 1.67114 +#else
 1.67115 +# define UPDATE_MAX_BLOBSIZE(P)
 1.67116 +#endif
 1.67117 +
 1.67118 +/*
 1.67119 +** Invoke the VDBE coverage callback, if that callback is defined.  This
 1.67120 +** feature is used for test suite validation only and does not appear an
 1.67121 +** production builds.
 1.67122 +**
 1.67123 +** M is an integer, 2 or 3, that indices how many different ways the
 1.67124 +** branch can go.  It is usually 2.  "I" is the direction the branch
 1.67125 +** goes.  0 means falls through.  1 means branch is taken.  2 means the
 1.67126 +** second alternative branch is taken.
 1.67127 +*/
 1.67128 +#if !defined(SQLITE_VDBE_COVERAGE)
 1.67129 +# define VdbeBranchTaken(I,M)
 1.67130 +#else
 1.67131 +# define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
 1.67132 +  static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
 1.67133 +    if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
 1.67134 +      M = iSrcLine;
 1.67135 +      /* Assert the truth of VdbeCoverageAlwaysTaken() and 
 1.67136 +      ** VdbeCoverageNeverTaken() */
 1.67137 +      assert( (M & I)==I );
 1.67138 +    }else{
 1.67139 +      if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
 1.67140 +      sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
 1.67141 +                                      iSrcLine,I,M);
 1.67142 +    }
 1.67143 +  }
 1.67144 +#endif
 1.67145 +
 1.67146 +/*
 1.67147 +** Convert the given register into a string if it isn't one
 1.67148 +** already. Return non-zero if a malloc() fails.
 1.67149 +*/
 1.67150 +#define Stringify(P, enc) \
 1.67151 +   if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
 1.67152 +     { goto no_mem; }
 1.67153 +
 1.67154 +/*
 1.67155 +** An ephemeral string value (signified by the MEM_Ephem flag) contains
 1.67156 +** a pointer to a dynamically allocated string where some other entity
 1.67157 +** is responsible for deallocating that string.  Because the register
 1.67158 +** does not control the string, it might be deleted without the register
 1.67159 +** knowing it.
 1.67160 +**
 1.67161 +** This routine converts an ephemeral string into a dynamically allocated
 1.67162 +** string that the register itself controls.  In other words, it
 1.67163 +** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
 1.67164 +*/
 1.67165 +#define Deephemeralize(P) \
 1.67166 +   if( ((P)->flags&MEM_Ephem)!=0 \
 1.67167 +       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
 1.67168 +
 1.67169 +/* Return true if the cursor was opened using the OP_OpenSorter opcode. */
 1.67170 +#define isSorter(x) ((x)->pSorter!=0)
 1.67171 +
 1.67172 +/*
 1.67173 +** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
 1.67174 +** if we run out of memory.
 1.67175 +*/
 1.67176 +static VdbeCursor *allocateCursor(
 1.67177 +  Vdbe *p,              /* The virtual machine */
 1.67178 +  int iCur,             /* Index of the new VdbeCursor */
 1.67179 +  int nField,           /* Number of fields in the table or index */
 1.67180 +  int iDb,              /* Database the cursor belongs to, or -1 */
 1.67181 +  int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
 1.67182 +){
 1.67183 +  /* Find the memory cell that will be used to store the blob of memory
 1.67184 +  ** required for this VdbeCursor structure. It is convenient to use a 
 1.67185 +  ** vdbe memory cell to manage the memory allocation required for a
 1.67186 +  ** VdbeCursor structure for the following reasons:
 1.67187 +  **
 1.67188 +  **   * Sometimes cursor numbers are used for a couple of different
 1.67189 +  **     purposes in a vdbe program. The different uses might require
 1.67190 +  **     different sized allocations. Memory cells provide growable
 1.67191 +  **     allocations.
 1.67192 +  **
 1.67193 +  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
 1.67194 +  **     be freed lazily via the sqlite3_release_memory() API. This
 1.67195 +  **     minimizes the number of malloc calls made by the system.
 1.67196 +  **
 1.67197 +  ** Memory cells for cursors are allocated at the top of the address
 1.67198 +  ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
 1.67199 +  ** cursor 1 is managed by memory cell (p->nMem-1), etc.
 1.67200 +  */
 1.67201 +  Mem *pMem = &p->aMem[p->nMem-iCur];
 1.67202 +
 1.67203 +  int nByte;
 1.67204 +  VdbeCursor *pCx = 0;
 1.67205 +  nByte = 
 1.67206 +      ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField + 
 1.67207 +      (isBtreeCursor?sqlite3BtreeCursorSize():0);
 1.67208 +
 1.67209 +  assert( iCur<p->nCursor );
 1.67210 +  if( p->apCsr[iCur] ){
 1.67211 +    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
 1.67212 +    p->apCsr[iCur] = 0;
 1.67213 +  }
 1.67214 +  if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
 1.67215 +    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
 1.67216 +    memset(pCx, 0, sizeof(VdbeCursor));
 1.67217 +    pCx->iDb = iDb;
 1.67218 +    pCx->nField = nField;
 1.67219 +    if( isBtreeCursor ){
 1.67220 +      pCx->pCursor = (BtCursor*)
 1.67221 +          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
 1.67222 +      sqlite3BtreeCursorZero(pCx->pCursor);
 1.67223 +    }
 1.67224 +  }
 1.67225 +  return pCx;
 1.67226 +}
 1.67227 +
 1.67228 +/*
 1.67229 +** Try to convert a value into a numeric representation if we can
 1.67230 +** do so without loss of information.  In other words, if the string
 1.67231 +** looks like a number, convert it into a number.  If it does not
 1.67232 +** look like a number, leave it alone.
 1.67233 +*/
 1.67234 +static void applyNumericAffinity(Mem *pRec){
 1.67235 +  if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
 1.67236 +    double rValue;
 1.67237 +    i64 iValue;
 1.67238 +    u8 enc = pRec->enc;
 1.67239 +    if( (pRec->flags&MEM_Str)==0 ) return;
 1.67240 +    if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
 1.67241 +    if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
 1.67242 +      pRec->u.i = iValue;
 1.67243 +      pRec->flags |= MEM_Int;
 1.67244 +    }else{
 1.67245 +      pRec->r = rValue;
 1.67246 +      pRec->flags |= MEM_Real;
 1.67247 +    }
 1.67248 +  }
 1.67249 +}
 1.67250 +
 1.67251 +/*
 1.67252 +** Processing is determine by the affinity parameter:
 1.67253 +**
 1.67254 +** SQLITE_AFF_INTEGER:
 1.67255 +** SQLITE_AFF_REAL:
 1.67256 +** SQLITE_AFF_NUMERIC:
 1.67257 +**    Try to convert pRec to an integer representation or a 
 1.67258 +**    floating-point representation if an integer representation
 1.67259 +**    is not possible.  Note that the integer representation is
 1.67260 +**    always preferred, even if the affinity is REAL, because
 1.67261 +**    an integer representation is more space efficient on disk.
 1.67262 +**
 1.67263 +** SQLITE_AFF_TEXT:
 1.67264 +**    Convert pRec to a text representation.
 1.67265 +**
 1.67266 +** SQLITE_AFF_NONE:
 1.67267 +**    No-op.  pRec is unchanged.
 1.67268 +*/
 1.67269 +static void applyAffinity(
 1.67270 +  Mem *pRec,          /* The value to apply affinity to */
 1.67271 +  char affinity,      /* The affinity to be applied */
 1.67272 +  u8 enc              /* Use this text encoding */
 1.67273 +){
 1.67274 +  if( affinity==SQLITE_AFF_TEXT ){
 1.67275 +    /* Only attempt the conversion to TEXT if there is an integer or real
 1.67276 +    ** representation (blob and NULL do not get converted) but no string
 1.67277 +    ** representation.
 1.67278 +    */
 1.67279 +    if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
 1.67280 +      sqlite3VdbeMemStringify(pRec, enc);
 1.67281 +    }
 1.67282 +    pRec->flags &= ~(MEM_Real|MEM_Int);
 1.67283 +  }else if( affinity!=SQLITE_AFF_NONE ){
 1.67284 +    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
 1.67285 +             || affinity==SQLITE_AFF_NUMERIC );
 1.67286 +    applyNumericAffinity(pRec);
 1.67287 +    if( pRec->flags & MEM_Real ){
 1.67288 +      sqlite3VdbeIntegerAffinity(pRec);
 1.67289 +    }
 1.67290 +  }
 1.67291 +}
 1.67292 +
 1.67293 +/*
 1.67294 +** Try to convert the type of a function argument or a result column
 1.67295 +** into a numeric representation.  Use either INTEGER or REAL whichever
 1.67296 +** is appropriate.  But only do the conversion if it is possible without
 1.67297 +** loss of information and return the revised type of the argument.
 1.67298 +*/
 1.67299 +SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
 1.67300 +  int eType = sqlite3_value_type(pVal);
 1.67301 +  if( eType==SQLITE_TEXT ){
 1.67302 +    Mem *pMem = (Mem*)pVal;
 1.67303 +    applyNumericAffinity(pMem);
 1.67304 +    eType = sqlite3_value_type(pVal);
 1.67305 +  }
 1.67306 +  return eType;
 1.67307 +}
 1.67308 +
 1.67309 +/*
 1.67310 +** Exported version of applyAffinity(). This one works on sqlite3_value*, 
 1.67311 +** not the internal Mem* type.
 1.67312 +*/
 1.67313 +SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
 1.67314 +  sqlite3_value *pVal, 
 1.67315 +  u8 affinity, 
 1.67316 +  u8 enc
 1.67317 +){
 1.67318 +  applyAffinity((Mem *)pVal, affinity, enc);
 1.67319 +}
 1.67320 +
 1.67321 +#ifdef SQLITE_DEBUG
 1.67322 +/*
 1.67323 +** Write a nice string representation of the contents of cell pMem
 1.67324 +** into buffer zBuf, length nBuf.
 1.67325 +*/
 1.67326 +SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
 1.67327 +  char *zCsr = zBuf;
 1.67328 +  int f = pMem->flags;
 1.67329 +
 1.67330 +  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
 1.67331 +
 1.67332 +  if( f&MEM_Blob ){
 1.67333 +    int i;
 1.67334 +    char c;
 1.67335 +    if( f & MEM_Dyn ){
 1.67336 +      c = 'z';
 1.67337 +      assert( (f & (MEM_Static|MEM_Ephem))==0 );
 1.67338 +    }else if( f & MEM_Static ){
 1.67339 +      c = 't';
 1.67340 +      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
 1.67341 +    }else if( f & MEM_Ephem ){
 1.67342 +      c = 'e';
 1.67343 +      assert( (f & (MEM_Static|MEM_Dyn))==0 );
 1.67344 +    }else{
 1.67345 +      c = 's';
 1.67346 +    }
 1.67347 +
 1.67348 +    sqlite3_snprintf(100, zCsr, "%c", c);
 1.67349 +    zCsr += sqlite3Strlen30(zCsr);
 1.67350 +    sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
 1.67351 +    zCsr += sqlite3Strlen30(zCsr);
 1.67352 +    for(i=0; i<16 && i<pMem->n; i++){
 1.67353 +      sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
 1.67354 +      zCsr += sqlite3Strlen30(zCsr);
 1.67355 +    }
 1.67356 +    for(i=0; i<16 && i<pMem->n; i++){
 1.67357 +      char z = pMem->z[i];
 1.67358 +      if( z<32 || z>126 ) *zCsr++ = '.';
 1.67359 +      else *zCsr++ = z;
 1.67360 +    }
 1.67361 +
 1.67362 +    sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
 1.67363 +    zCsr += sqlite3Strlen30(zCsr);
 1.67364 +    if( f & MEM_Zero ){
 1.67365 +      sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
 1.67366 +      zCsr += sqlite3Strlen30(zCsr);
 1.67367 +    }
 1.67368 +    *zCsr = '\0';
 1.67369 +  }else if( f & MEM_Str ){
 1.67370 +    int j, k;
 1.67371 +    zBuf[0] = ' ';
 1.67372 +    if( f & MEM_Dyn ){
 1.67373 +      zBuf[1] = 'z';
 1.67374 +      assert( (f & (MEM_Static|MEM_Ephem))==0 );
 1.67375 +    }else if( f & MEM_Static ){
 1.67376 +      zBuf[1] = 't';
 1.67377 +      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
 1.67378 +    }else if( f & MEM_Ephem ){
 1.67379 +      zBuf[1] = 'e';
 1.67380 +      assert( (f & (MEM_Static|MEM_Dyn))==0 );
 1.67381 +    }else{
 1.67382 +      zBuf[1] = 's';
 1.67383 +    }
 1.67384 +    k = 2;
 1.67385 +    sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
 1.67386 +    k += sqlite3Strlen30(&zBuf[k]);
 1.67387 +    zBuf[k++] = '[';
 1.67388 +    for(j=0; j<15 && j<pMem->n; j++){
 1.67389 +      u8 c = pMem->z[j];
 1.67390 +      if( c>=0x20 && c<0x7f ){
 1.67391 +        zBuf[k++] = c;
 1.67392 +      }else{
 1.67393 +        zBuf[k++] = '.';
 1.67394 +      }
 1.67395 +    }
 1.67396 +    zBuf[k++] = ']';
 1.67397 +    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
 1.67398 +    k += sqlite3Strlen30(&zBuf[k]);
 1.67399 +    zBuf[k++] = 0;
 1.67400 +  }
 1.67401 +}
 1.67402 +#endif
 1.67403 +
 1.67404 +#ifdef SQLITE_DEBUG
 1.67405 +/*
 1.67406 +** Print the value of a register for tracing purposes:
 1.67407 +*/
 1.67408 +static void memTracePrint(Mem *p){
 1.67409 +  if( p->flags & MEM_Undefined ){
 1.67410 +    printf(" undefined");
 1.67411 +  }else if( p->flags & MEM_Null ){
 1.67412 +    printf(" NULL");
 1.67413 +  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
 1.67414 +    printf(" si:%lld", p->u.i);
 1.67415 +  }else if( p->flags & MEM_Int ){
 1.67416 +    printf(" i:%lld", p->u.i);
 1.67417 +#ifndef SQLITE_OMIT_FLOATING_POINT
 1.67418 +  }else if( p->flags & MEM_Real ){
 1.67419 +    printf(" r:%g", p->r);
 1.67420 +#endif
 1.67421 +  }else if( p->flags & MEM_RowSet ){
 1.67422 +    printf(" (rowset)");
 1.67423 +  }else{
 1.67424 +    char zBuf[200];
 1.67425 +    sqlite3VdbeMemPrettyPrint(p, zBuf);
 1.67426 +    printf(" %s", zBuf);
 1.67427 +  }
 1.67428 +}
 1.67429 +static void registerTrace(int iReg, Mem *p){
 1.67430 +  printf("REG[%d] = ", iReg);
 1.67431 +  memTracePrint(p);
 1.67432 +  printf("\n");
 1.67433 +}
 1.67434 +#endif
 1.67435 +
 1.67436 +#ifdef SQLITE_DEBUG
 1.67437 +#  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
 1.67438 +#else
 1.67439 +#  define REGISTER_TRACE(R,M)
 1.67440 +#endif
 1.67441 +
 1.67442 +
 1.67443 +#ifdef VDBE_PROFILE
 1.67444 +
 1.67445 +/* 
 1.67446 +** hwtime.h contains inline assembler code for implementing 
 1.67447 +** high-performance timing routines.
 1.67448 +*/
 1.67449 +/************** Include hwtime.h in the middle of vdbe.c *********************/
 1.67450 +/************** Begin file hwtime.h ******************************************/
 1.67451 +/*
 1.67452 +** 2008 May 27
 1.67453 +**
 1.67454 +** The author disclaims copyright to this source code.  In place of
 1.67455 +** a legal notice, here is a blessing:
 1.67456 +**
 1.67457 +**    May you do good and not evil.
 1.67458 +**    May you find forgiveness for yourself and forgive others.
 1.67459 +**    May you share freely, never taking more than you give.
 1.67460 +**
 1.67461 +******************************************************************************
 1.67462 +**
 1.67463 +** This file contains inline asm code for retrieving "high-performance"
 1.67464 +** counters for x86 class CPUs.
 1.67465 +*/
 1.67466 +#ifndef _HWTIME_H_
 1.67467 +#define _HWTIME_H_
 1.67468 +
 1.67469 +/*
 1.67470 +** The following routine only works on pentium-class (or newer) processors.
 1.67471 +** It uses the RDTSC opcode to read the cycle count value out of the
 1.67472 +** processor and returns that value.  This can be used for high-res
 1.67473 +** profiling.
 1.67474 +*/
 1.67475 +#if (defined(__GNUC__) || defined(_MSC_VER)) && \
 1.67476 +      (defined(i386) || defined(__i386__) || defined(_M_IX86))
 1.67477 +
 1.67478 +  #if defined(__GNUC__)
 1.67479 +
 1.67480 +  __inline__ sqlite_uint64 sqlite3Hwtime(void){
 1.67481 +     unsigned int lo, hi;
 1.67482 +     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
 1.67483 +     return (sqlite_uint64)hi << 32 | lo;
 1.67484 +  }
 1.67485 +
 1.67486 +  #elif defined(_MSC_VER)
 1.67487 +
 1.67488 +  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
 1.67489 +     __asm {
 1.67490 +        rdtsc
 1.67491 +        ret       ; return value at EDX:EAX
 1.67492 +     }
 1.67493 +  }
 1.67494 +
 1.67495 +  #endif
 1.67496 +
 1.67497 +#elif (defined(__GNUC__) && defined(__x86_64__))
 1.67498 +
 1.67499 +  __inline__ sqlite_uint64 sqlite3Hwtime(void){
 1.67500 +      unsigned long val;
 1.67501 +      __asm__ __volatile__ ("rdtsc" : "=A" (val));
 1.67502 +      return val;
 1.67503 +  }
 1.67504 + 
 1.67505 +#elif (defined(__GNUC__) && defined(__ppc__))
 1.67506 +
 1.67507 +  __inline__ sqlite_uint64 sqlite3Hwtime(void){
 1.67508 +      unsigned long long retval;
 1.67509 +      unsigned long junk;
 1.67510 +      __asm__ __volatile__ ("\n\
 1.67511 +          1:      mftbu   %1\n\
 1.67512 +                  mftb    %L0\n\
 1.67513 +                  mftbu   %0\n\
 1.67514 +                  cmpw    %0,%1\n\
 1.67515 +                  bne     1b"
 1.67516 +                  : "=r" (retval), "=r" (junk));
 1.67517 +      return retval;
 1.67518 +  }
 1.67519 +
 1.67520 +#else
 1.67521 +
 1.67522 +  #error Need implementation of sqlite3Hwtime() for your platform.
 1.67523 +
 1.67524 +  /*
 1.67525 +  ** To compile without implementing sqlite3Hwtime() for your platform,
 1.67526 +  ** you can remove the above #error and use the following
 1.67527 +  ** stub function.  You will lose timing support for many
 1.67528 +  ** of the debugging and testing utilities, but it should at
 1.67529 +  ** least compile and run.
 1.67530 +  */
 1.67531 +SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
 1.67532 +
 1.67533 +#endif
 1.67534 +
 1.67535 +#endif /* !defined(_HWTIME_H_) */
 1.67536 +
 1.67537 +/************** End of hwtime.h **********************************************/
 1.67538 +/************** Continuing where we left off in vdbe.c ***********************/
 1.67539 +
 1.67540 +#endif
 1.67541 +
 1.67542 +#ifndef NDEBUG
 1.67543 +/*
 1.67544 +** This function is only called from within an assert() expression. It
 1.67545 +** checks that the sqlite3.nTransaction variable is correctly set to
 1.67546 +** the number of non-transaction savepoints currently in the 
 1.67547 +** linked list starting at sqlite3.pSavepoint.
 1.67548 +** 
 1.67549 +** Usage:
 1.67550 +**
 1.67551 +**     assert( checkSavepointCount(db) );
 1.67552 +*/
 1.67553 +static int checkSavepointCount(sqlite3 *db){
 1.67554 +  int n = 0;
 1.67555 +  Savepoint *p;
 1.67556 +  for(p=db->pSavepoint; p; p=p->pNext) n++;
 1.67557 +  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
 1.67558 +  return 1;
 1.67559 +}
 1.67560 +#endif
 1.67561 +
 1.67562 +
 1.67563 +/*
 1.67564 +** Execute as much of a VDBE program as we can.
 1.67565 +** This is the core of sqlite3_step().  
 1.67566 +*/
 1.67567 +SQLITE_PRIVATE int sqlite3VdbeExec(
 1.67568 +  Vdbe *p                    /* The VDBE */
 1.67569 +){
 1.67570 +  int pc=0;                  /* The program counter */
 1.67571 +  Op *aOp = p->aOp;          /* Copy of p->aOp */
 1.67572 +  Op *pOp;                   /* Current operation */
 1.67573 +  int rc = SQLITE_OK;        /* Value to return */
 1.67574 +  sqlite3 *db = p->db;       /* The database */
 1.67575 +  u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
 1.67576 +  u8 encoding = ENC(db);     /* The database encoding */
 1.67577 +  int iCompare = 0;          /* Result of last OP_Compare operation */
 1.67578 +  unsigned nVmStep = 0;      /* Number of virtual machine steps */
 1.67579 +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
 1.67580 +  unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
 1.67581 +#endif
 1.67582 +  Mem *aMem = p->aMem;       /* Copy of p->aMem */
 1.67583 +  Mem *pIn1 = 0;             /* 1st input operand */
 1.67584 +  Mem *pIn2 = 0;             /* 2nd input operand */
 1.67585 +  Mem *pIn3 = 0;             /* 3rd input operand */
 1.67586 +  Mem *pOut = 0;             /* Output operand */
 1.67587 +  int *aPermute = 0;         /* Permutation of columns for OP_Compare */
 1.67588 +  i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
 1.67589 +#ifdef VDBE_PROFILE
 1.67590 +  u64 start;                 /* CPU clock count at start of opcode */
 1.67591 +#endif
 1.67592 +  /*** INSERT STACK UNION HERE ***/
 1.67593 +
 1.67594 +  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
 1.67595 +  sqlite3VdbeEnter(p);
 1.67596 +  if( p->rc==SQLITE_NOMEM ){
 1.67597 +    /* This happens if a malloc() inside a call to sqlite3_column_text() or
 1.67598 +    ** sqlite3_column_text16() failed.  */
 1.67599 +    goto no_mem;
 1.67600 +  }
 1.67601 +  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
 1.67602 +  assert( p->bIsReader || p->readOnly!=0 );
 1.67603 +  p->rc = SQLITE_OK;
 1.67604 +  p->iCurrentTime = 0;
 1.67605 +  assert( p->explain==0 );
 1.67606 +  p->pResultSet = 0;
 1.67607 +  db->busyHandler.nBusy = 0;
 1.67608 +  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
 1.67609 +  sqlite3VdbeIOTraceSql(p);
 1.67610 +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
 1.67611 +  if( db->xProgress ){
 1.67612 +    assert( 0 < db->nProgressOps );
 1.67613 +    nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
 1.67614 +    if( nProgressLimit==0 ){
 1.67615 +      nProgressLimit = db->nProgressOps;
 1.67616 +    }else{
 1.67617 +      nProgressLimit %= (unsigned)db->nProgressOps;
 1.67618 +    }
 1.67619 +  }
 1.67620 +#endif
 1.67621 +#ifdef SQLITE_DEBUG
 1.67622 +  sqlite3BeginBenignMalloc();
 1.67623 +  if( p->pc==0
 1.67624 +   && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
 1.67625 +  ){
 1.67626 +    int i;
 1.67627 +    int once = 1;
 1.67628 +    sqlite3VdbePrintSql(p);
 1.67629 +    if( p->db->flags & SQLITE_VdbeListing ){
 1.67630 +      printf("VDBE Program Listing:\n");
 1.67631 +      for(i=0; i<p->nOp; i++){
 1.67632 +        sqlite3VdbePrintOp(stdout, i, &aOp[i]);
 1.67633 +      }
 1.67634 +    }
 1.67635 +    if( p->db->flags & SQLITE_VdbeEQP ){
 1.67636 +      for(i=0; i<p->nOp; i++){
 1.67637 +        if( aOp[i].opcode==OP_Explain ){
 1.67638 +          if( once ) printf("VDBE Query Plan:\n");
 1.67639 +          printf("%s\n", aOp[i].p4.z);
 1.67640 +          once = 0;
 1.67641 +        }
 1.67642 +      }
 1.67643 +    }
 1.67644 +    if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
 1.67645 +  }
 1.67646 +  sqlite3EndBenignMalloc();
 1.67647 +#endif
 1.67648 +  for(pc=p->pc; rc==SQLITE_OK; pc++){
 1.67649 +    assert( pc>=0 && pc<p->nOp );
 1.67650 +    if( db->mallocFailed ) goto no_mem;
 1.67651 +#ifdef VDBE_PROFILE
 1.67652 +    start = sqlite3Hwtime();
 1.67653 +#endif
 1.67654 +    nVmStep++;
 1.67655 +    pOp = &aOp[pc];
 1.67656 +
 1.67657 +    /* Only allow tracing if SQLITE_DEBUG is defined.
 1.67658 +    */
 1.67659 +#ifdef SQLITE_DEBUG
 1.67660 +    if( db->flags & SQLITE_VdbeTrace ){
 1.67661 +      sqlite3VdbePrintOp(stdout, pc, pOp);
 1.67662 +    }
 1.67663 +#endif
 1.67664 +      
 1.67665 +
 1.67666 +    /* Check to see if we need to simulate an interrupt.  This only happens
 1.67667 +    ** if we have a special test build.
 1.67668 +    */
 1.67669 +#ifdef SQLITE_TEST
 1.67670 +    if( sqlite3_interrupt_count>0 ){
 1.67671 +      sqlite3_interrupt_count--;
 1.67672 +      if( sqlite3_interrupt_count==0 ){
 1.67673 +        sqlite3_interrupt(db);
 1.67674 +      }
 1.67675 +    }
 1.67676 +#endif
 1.67677 +
 1.67678 +    /* On any opcode with the "out2-prerelease" tag, free any
 1.67679 +    ** external allocations out of mem[p2] and set mem[p2] to be
 1.67680 +    ** an undefined integer.  Opcodes will either fill in the integer
 1.67681 +    ** value or convert mem[p2] to a different type.
 1.67682 +    */
 1.67683 +    assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
 1.67684 +    if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
 1.67685 +      assert( pOp->p2>0 );
 1.67686 +      assert( pOp->p2<=(p->nMem-p->nCursor) );
 1.67687 +      pOut = &aMem[pOp->p2];
 1.67688 +      memAboutToChange(p, pOut);
 1.67689 +      VdbeMemRelease(pOut);
 1.67690 +      pOut->flags = MEM_Int;
 1.67691 +    }
 1.67692 +
 1.67693 +    /* Sanity checking on other operands */
 1.67694 +#ifdef SQLITE_DEBUG
 1.67695 +    if( (pOp->opflags & OPFLG_IN1)!=0 ){
 1.67696 +      assert( pOp->p1>0 );
 1.67697 +      assert( pOp->p1<=(p->nMem-p->nCursor) );
 1.67698 +      assert( memIsValid(&aMem[pOp->p1]) );
 1.67699 +      assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
 1.67700 +      REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
 1.67701 +    }
 1.67702 +    if( (pOp->opflags & OPFLG_IN2)!=0 ){
 1.67703 +      assert( pOp->p2>0 );
 1.67704 +      assert( pOp->p2<=(p->nMem-p->nCursor) );
 1.67705 +      assert( memIsValid(&aMem[pOp->p2]) );
 1.67706 +      assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
 1.67707 +      REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
 1.67708 +    }
 1.67709 +    if( (pOp->opflags & OPFLG_IN3)!=0 ){
 1.67710 +      assert( pOp->p3>0 );
 1.67711 +      assert( pOp->p3<=(p->nMem-p->nCursor) );
 1.67712 +      assert( memIsValid(&aMem[pOp->p3]) );
 1.67713 +      assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
 1.67714 +      REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
 1.67715 +    }
 1.67716 +    if( (pOp->opflags & OPFLG_OUT2)!=0 ){
 1.67717 +      assert( pOp->p2>0 );
 1.67718 +      assert( pOp->p2<=(p->nMem-p->nCursor) );
 1.67719 +      memAboutToChange(p, &aMem[pOp->p2]);
 1.67720 +    }
 1.67721 +    if( (pOp->opflags & OPFLG_OUT3)!=0 ){
 1.67722 +      assert( pOp->p3>0 );
 1.67723 +      assert( pOp->p3<=(p->nMem-p->nCursor) );
 1.67724 +      memAboutToChange(p, &aMem[pOp->p3]);
 1.67725 +    }
 1.67726 +#endif
 1.67727 +  
 1.67728 +    switch( pOp->opcode ){
 1.67729 +
 1.67730 +/*****************************************************************************
 1.67731 +** What follows is a massive switch statement where each case implements a
 1.67732 +** separate instruction in the virtual machine.  If we follow the usual
 1.67733 +** indentation conventions, each case should be indented by 6 spaces.  But
 1.67734 +** that is a lot of wasted space on the left margin.  So the code within
 1.67735 +** the switch statement will break with convention and be flush-left. Another
 1.67736 +** big comment (similar to this one) will mark the point in the code where
 1.67737 +** we transition back to normal indentation.
 1.67738 +**
 1.67739 +** The formatting of each case is important.  The makefile for SQLite
 1.67740 +** generates two C files "opcodes.h" and "opcodes.c" by scanning this
 1.67741 +** file looking for lines that begin with "case OP_".  The opcodes.h files
 1.67742 +** will be filled with #defines that give unique integer values to each
 1.67743 +** opcode and the opcodes.c file is filled with an array of strings where
 1.67744 +** each string is the symbolic name for the corresponding opcode.  If the
 1.67745 +** case statement is followed by a comment of the form "/# same as ... #/"
 1.67746 +** that comment is used to determine the particular value of the opcode.
 1.67747 +**
 1.67748 +** Other keywords in the comment that follows each case are used to
 1.67749 +** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
 1.67750 +** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
 1.67751 +** the mkopcodeh.awk script for additional information.
 1.67752 +**
 1.67753 +** Documentation about VDBE opcodes is generated by scanning this file
 1.67754 +** for lines of that contain "Opcode:".  That line and all subsequent
 1.67755 +** comment lines are used in the generation of the opcode.html documentation
 1.67756 +** file.
 1.67757 +**
 1.67758 +** SUMMARY:
 1.67759 +**
 1.67760 +**     Formatting is important to scripts that scan this file.
 1.67761 +**     Do not deviate from the formatting style currently in use.
 1.67762 +**
 1.67763 +*****************************************************************************/
 1.67764 +
 1.67765 +/* Opcode:  Goto * P2 * * *
 1.67766 +**
 1.67767 +** An unconditional jump to address P2.
 1.67768 +** The next instruction executed will be 
 1.67769 +** the one at index P2 from the beginning of
 1.67770 +** the program.
 1.67771 +**
 1.67772 +** The P1 parameter is not actually used by this opcode.  However, it
 1.67773 +** is sometimes set to 1 instead of 0 as a hint to the command-line shell
 1.67774 +** that this Goto is the bottom of a loop and that the lines from P2 down
 1.67775 +** to the current line should be indented for EXPLAIN output.
 1.67776 +*/
 1.67777 +case OP_Goto: {             /* jump */
 1.67778 +  pc = pOp->p2 - 1;
 1.67779 +
 1.67780 +  /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
 1.67781 +  ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
 1.67782 +  ** completion.  Check to see if sqlite3_interrupt() has been called
 1.67783 +  ** or if the progress callback needs to be invoked. 
 1.67784 +  **
 1.67785 +  ** This code uses unstructured "goto" statements and does not look clean.
 1.67786 +  ** But that is not due to sloppy coding habits. The code is written this
 1.67787 +  ** way for performance, to avoid having to run the interrupt and progress
 1.67788 +  ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
 1.67789 +  ** faster according to "valgrind --tool=cachegrind" */
 1.67790 +check_for_interrupt:
 1.67791 +  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
 1.67792 +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
 1.67793 +  /* Call the progress callback if it is configured and the required number
 1.67794 +  ** of VDBE ops have been executed (either since this invocation of
 1.67795 +  ** sqlite3VdbeExec() or since last time the progress callback was called).
 1.67796 +  ** If the progress callback returns non-zero, exit the virtual machine with
 1.67797 +  ** a return code SQLITE_ABORT.
 1.67798 +  */
 1.67799 +  if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
 1.67800 +    assert( db->nProgressOps!=0 );
 1.67801 +    nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
 1.67802 +    if( db->xProgress(db->pProgressArg) ){
 1.67803 +      rc = SQLITE_INTERRUPT;
 1.67804 +      goto vdbe_error_halt;
 1.67805 +    }
 1.67806 +  }
 1.67807 +#endif
 1.67808 +  
 1.67809 +  break;
 1.67810 +}
 1.67811 +
 1.67812 +/* Opcode:  Gosub P1 P2 * * *
 1.67813 +**
 1.67814 +** Write the current address onto register P1
 1.67815 +** and then jump to address P2.
 1.67816 +*/
 1.67817 +case OP_Gosub: {            /* jump */
 1.67818 +  assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
 1.67819 +  pIn1 = &aMem[pOp->p1];
 1.67820 +  assert( VdbeMemDynamic(pIn1)==0 );
 1.67821 +  memAboutToChange(p, pIn1);
 1.67822 +  pIn1->flags = MEM_Int;
 1.67823 +  pIn1->u.i = pc;
 1.67824 +  REGISTER_TRACE(pOp->p1, pIn1);
 1.67825 +  pc = pOp->p2 - 1;
 1.67826 +  break;
 1.67827 +}
 1.67828 +
 1.67829 +/* Opcode:  Return P1 * * * *
 1.67830 +**
 1.67831 +** Jump to the next instruction after the address in register P1.  After
 1.67832 +** the jump, register P1 becomes undefined.
 1.67833 +*/
 1.67834 +case OP_Return: {           /* in1 */
 1.67835 +  pIn1 = &aMem[pOp->p1];
 1.67836 +  assert( pIn1->flags==MEM_Int );
 1.67837 +  pc = (int)pIn1->u.i;
 1.67838 +  pIn1->flags = MEM_Undefined;
 1.67839 +  break;
 1.67840 +}
 1.67841 +
 1.67842 +/* Opcode: InitCoroutine P1 P2 P3 * *
 1.67843 +**
 1.67844 +** Set up register P1 so that it will OP_Yield to the co-routine
 1.67845 +** located at address P3.
 1.67846 +**
 1.67847 +** If P2!=0 then the co-routine implementation immediately follows
 1.67848 +** this opcode.  So jump over the co-routine implementation to
 1.67849 +** address P2.
 1.67850 +*/
 1.67851 +case OP_InitCoroutine: {     /* jump */
 1.67852 +  assert( pOp->p1>0 &&  pOp->p1<=(p->nMem-p->nCursor) );
 1.67853 +  assert( pOp->p2>=0 && pOp->p2<p->nOp );
 1.67854 +  assert( pOp->p3>=0 && pOp->p3<p->nOp );
 1.67855 +  pOut = &aMem[pOp->p1];
 1.67856 +  assert( !VdbeMemDynamic(pOut) );
 1.67857 +  pOut->u.i = pOp->p3 - 1;
 1.67858 +  pOut->flags = MEM_Int;
 1.67859 +  if( pOp->p2 ) pc = pOp->p2 - 1;
 1.67860 +  break;
 1.67861 +}
 1.67862 +
 1.67863 +/* Opcode:  EndCoroutine P1 * * * *
 1.67864 +**
 1.67865 +** The instruction at the address in register P1 is an OP_Yield.
 1.67866 +** Jump to the P2 parameter of that OP_Yield.
 1.67867 +** After the jump, register P1 becomes undefined.
 1.67868 +*/
 1.67869 +case OP_EndCoroutine: {           /* in1 */
 1.67870 +  VdbeOp *pCaller;
 1.67871 +  pIn1 = &aMem[pOp->p1];
 1.67872 +  assert( pIn1->flags==MEM_Int );
 1.67873 +  assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
 1.67874 +  pCaller = &aOp[pIn1->u.i];
 1.67875 +  assert( pCaller->opcode==OP_Yield );
 1.67876 +  assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
 1.67877 +  pc = pCaller->p2 - 1;
 1.67878 +  pIn1->flags = MEM_Undefined;
 1.67879 +  break;
 1.67880 +}
 1.67881 +
 1.67882 +/* Opcode:  Yield P1 P2 * * *
 1.67883 +**
 1.67884 +** Swap the program counter with the value in register P1.
 1.67885 +**
 1.67886 +** If the co-routine ends with OP_Yield or OP_Return then continue
 1.67887 +** to the next instruction.  But if the co-routine ends with
 1.67888 +** OP_EndCoroutine, jump immediately to P2.
 1.67889 +*/
 1.67890 +case OP_Yield: {            /* in1, jump */
 1.67891 +  int pcDest;
 1.67892 +  pIn1 = &aMem[pOp->p1];
 1.67893 +  assert( VdbeMemDynamic(pIn1)==0 );
 1.67894 +  pIn1->flags = MEM_Int;
 1.67895 +  pcDest = (int)pIn1->u.i;
 1.67896 +  pIn1->u.i = pc;
 1.67897 +  REGISTER_TRACE(pOp->p1, pIn1);
 1.67898 +  pc = pcDest;
 1.67899 +  break;
 1.67900 +}
 1.67901 +
 1.67902 +/* Opcode:  HaltIfNull  P1 P2 P3 P4 P5
 1.67903 +** Synopsis:  if r[P3]=null halt
 1.67904 +**
 1.67905 +** Check the value in register P3.  If it is NULL then Halt using
 1.67906 +** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
 1.67907 +** value in register P3 is not NULL, then this routine is a no-op.
 1.67908 +** The P5 parameter should be 1.
 1.67909 +*/
 1.67910 +case OP_HaltIfNull: {      /* in3 */
 1.67911 +  pIn3 = &aMem[pOp->p3];
 1.67912 +  if( (pIn3->flags & MEM_Null)==0 ) break;
 1.67913 +  /* Fall through into OP_Halt */
 1.67914 +}
 1.67915 +
 1.67916 +/* Opcode:  Halt P1 P2 * P4 P5
 1.67917 +**
 1.67918 +** Exit immediately.  All open cursors, etc are closed
 1.67919 +** automatically.
 1.67920 +**
 1.67921 +** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
 1.67922 +** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
 1.67923 +** For errors, it can be some other value.  If P1!=0 then P2 will determine
 1.67924 +** whether or not to rollback the current transaction.  Do not rollback
 1.67925 +** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
 1.67926 +** then back out all changes that have occurred during this execution of the
 1.67927 +** VDBE, but do not rollback the transaction. 
 1.67928 +**
 1.67929 +** If P4 is not null then it is an error message string.
 1.67930 +**
 1.67931 +** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
 1.67932 +**
 1.67933 +**    0:  (no change)
 1.67934 +**    1:  NOT NULL contraint failed: P4
 1.67935 +**    2:  UNIQUE constraint failed: P4
 1.67936 +**    3:  CHECK constraint failed: P4
 1.67937 +**    4:  FOREIGN KEY constraint failed: P4
 1.67938 +**
 1.67939 +** If P5 is not zero and P4 is NULL, then everything after the ":" is
 1.67940 +** omitted.
 1.67941 +**
 1.67942 +** There is an implied "Halt 0 0 0" instruction inserted at the very end of
 1.67943 +** every program.  So a jump past the last instruction of the program
 1.67944 +** is the same as executing Halt.
 1.67945 +*/
 1.67946 +case OP_Halt: {
 1.67947 +  const char *zType;
 1.67948 +  const char *zLogFmt;
 1.67949 +
 1.67950 +  if( pOp->p1==SQLITE_OK && p->pFrame ){
 1.67951 +    /* Halt the sub-program. Return control to the parent frame. */
 1.67952 +    VdbeFrame *pFrame = p->pFrame;
 1.67953 +    p->pFrame = pFrame->pParent;
 1.67954 +    p->nFrame--;
 1.67955 +    sqlite3VdbeSetChanges(db, p->nChange);
 1.67956 +    pc = sqlite3VdbeFrameRestore(pFrame);
 1.67957 +    lastRowid = db->lastRowid;
 1.67958 +    if( pOp->p2==OE_Ignore ){
 1.67959 +      /* Instruction pc is the OP_Program that invoked the sub-program 
 1.67960 +      ** currently being halted. If the p2 instruction of this OP_Halt
 1.67961 +      ** instruction is set to OE_Ignore, then the sub-program is throwing
 1.67962 +      ** an IGNORE exception. In this case jump to the address specified
 1.67963 +      ** as the p2 of the calling OP_Program.  */
 1.67964 +      pc = p->aOp[pc].p2-1;
 1.67965 +    }
 1.67966 +    aOp = p->aOp;
 1.67967 +    aMem = p->aMem;
 1.67968 +    break;
 1.67969 +  }
 1.67970 +  p->rc = pOp->p1;
 1.67971 +  p->errorAction = (u8)pOp->p2;
 1.67972 +  p->pc = pc;
 1.67973 +  if( p->rc ){
 1.67974 +    if( pOp->p5 ){
 1.67975 +      static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
 1.67976 +                                             "FOREIGN KEY" };
 1.67977 +      assert( pOp->p5>=1 && pOp->p5<=4 );
 1.67978 +      testcase( pOp->p5==1 );
 1.67979 +      testcase( pOp->p5==2 );
 1.67980 +      testcase( pOp->p5==3 );
 1.67981 +      testcase( pOp->p5==4 );
 1.67982 +      zType = azType[pOp->p5-1];
 1.67983 +    }else{
 1.67984 +      zType = 0;
 1.67985 +    }
 1.67986 +    assert( zType!=0 || pOp->p4.z!=0 );
 1.67987 +    zLogFmt = "abort at %d in [%s]: %s";
 1.67988 +    if( zType && pOp->p4.z ){
 1.67989 +      sqlite3SetString(&p->zErrMsg, db, "%s constraint failed: %s", 
 1.67990 +                       zType, pOp->p4.z);
 1.67991 +    }else if( pOp->p4.z ){
 1.67992 +      sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
 1.67993 +    }else{
 1.67994 +      sqlite3SetString(&p->zErrMsg, db, "%s constraint failed", zType);
 1.67995 +    }
 1.67996 +    sqlite3_log(pOp->p1, zLogFmt, pc, p->zSql, p->zErrMsg);
 1.67997 +  }
 1.67998 +  rc = sqlite3VdbeHalt(p);
 1.67999 +  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
 1.68000 +  if( rc==SQLITE_BUSY ){
 1.68001 +    p->rc = rc = SQLITE_BUSY;
 1.68002 +  }else{
 1.68003 +    assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
 1.68004 +    assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
 1.68005 +    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
 1.68006 +  }
 1.68007 +  goto vdbe_return;
 1.68008 +}
 1.68009 +
 1.68010 +/* Opcode: Integer P1 P2 * * *
 1.68011 +** Synopsis: r[P2]=P1
 1.68012 +**
 1.68013 +** The 32-bit integer value P1 is written into register P2.
 1.68014 +*/
 1.68015 +case OP_Integer: {         /* out2-prerelease */
 1.68016 +  pOut->u.i = pOp->p1;
 1.68017 +  break;
 1.68018 +}
 1.68019 +
 1.68020 +/* Opcode: Int64 * P2 * P4 *
 1.68021 +** Synopsis: r[P2]=P4
 1.68022 +**
 1.68023 +** P4 is a pointer to a 64-bit integer value.
 1.68024 +** Write that value into register P2.
 1.68025 +*/
 1.68026 +case OP_Int64: {           /* out2-prerelease */
 1.68027 +  assert( pOp->p4.pI64!=0 );
 1.68028 +  pOut->u.i = *pOp->p4.pI64;
 1.68029 +  break;
 1.68030 +}
 1.68031 +
 1.68032 +#ifndef SQLITE_OMIT_FLOATING_POINT
 1.68033 +/* Opcode: Real * P2 * P4 *
 1.68034 +** Synopsis: r[P2]=P4
 1.68035 +**
 1.68036 +** P4 is a pointer to a 64-bit floating point value.
 1.68037 +** Write that value into register P2.
 1.68038 +*/
 1.68039 +case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
 1.68040 +  pOut->flags = MEM_Real;
 1.68041 +  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
 1.68042 +  pOut->r = *pOp->p4.pReal;
 1.68043 +  break;
 1.68044 +}
 1.68045 +#endif
 1.68046 +
 1.68047 +/* Opcode: String8 * P2 * P4 *
 1.68048 +** Synopsis: r[P2]='P4'
 1.68049 +**
 1.68050 +** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
 1.68051 +** into an OP_String before it is executed for the first time.  During
 1.68052 +** this transformation, the length of string P4 is computed and stored
 1.68053 +** as the P1 parameter.
 1.68054 +*/
 1.68055 +case OP_String8: {         /* same as TK_STRING, out2-prerelease */
 1.68056 +  assert( pOp->p4.z!=0 );
 1.68057 +  pOp->opcode = OP_String;
 1.68058 +  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
 1.68059 +
 1.68060 +#ifndef SQLITE_OMIT_UTF16
 1.68061 +  if( encoding!=SQLITE_UTF8 ){
 1.68062 +    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
 1.68063 +    if( rc==SQLITE_TOOBIG ) goto too_big;
 1.68064 +    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
 1.68065 +    assert( pOut->zMalloc==pOut->z );
 1.68066 +    assert( VdbeMemDynamic(pOut)==0 );
 1.68067 +    pOut->zMalloc = 0;
 1.68068 +    pOut->flags |= MEM_Static;
 1.68069 +    if( pOp->p4type==P4_DYNAMIC ){
 1.68070 +      sqlite3DbFree(db, pOp->p4.z);
 1.68071 +    }
 1.68072 +    pOp->p4type = P4_DYNAMIC;
 1.68073 +    pOp->p4.z = pOut->z;
 1.68074 +    pOp->p1 = pOut->n;
 1.68075 +  }
 1.68076 +#endif
 1.68077 +  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
 1.68078 +    goto too_big;
 1.68079 +  }
 1.68080 +  /* Fall through to the next case, OP_String */
 1.68081 +}
 1.68082 +  
 1.68083 +/* Opcode: String P1 P2 * P4 *
 1.68084 +** Synopsis: r[P2]='P4' (len=P1)
 1.68085 +**
 1.68086 +** The string value P4 of length P1 (bytes) is stored in register P2.
 1.68087 +*/
 1.68088 +case OP_String: {          /* out2-prerelease */
 1.68089 +  assert( pOp->p4.z!=0 );
 1.68090 +  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
 1.68091 +  pOut->z = pOp->p4.z;
 1.68092 +  pOut->n = pOp->p1;
 1.68093 +  pOut->enc = encoding;
 1.68094 +  UPDATE_MAX_BLOBSIZE(pOut);
 1.68095 +  break;
 1.68096 +}
 1.68097 +
 1.68098 +/* Opcode: Null P1 P2 P3 * *
 1.68099 +** Synopsis:  r[P2..P3]=NULL
 1.68100 +**
 1.68101 +** Write a NULL into registers P2.  If P3 greater than P2, then also write
 1.68102 +** NULL into register P3 and every register in between P2 and P3.  If P3
 1.68103 +** is less than P2 (typically P3 is zero) then only register P2 is
 1.68104 +** set to NULL.
 1.68105 +**
 1.68106 +** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
 1.68107 +** NULL values will not compare equal even if SQLITE_NULLEQ is set on
 1.68108 +** OP_Ne or OP_Eq.
 1.68109 +*/
 1.68110 +case OP_Null: {           /* out2-prerelease */
 1.68111 +  int cnt;
 1.68112 +  u16 nullFlag;
 1.68113 +  cnt = pOp->p3-pOp->p2;
 1.68114 +  assert( pOp->p3<=(p->nMem-p->nCursor) );
 1.68115 +  pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
 1.68116 +  while( cnt>0 ){
 1.68117 +    pOut++;
 1.68118 +    memAboutToChange(p, pOut);
 1.68119 +    VdbeMemRelease(pOut);
 1.68120 +    pOut->flags = nullFlag;
 1.68121 +    cnt--;
 1.68122 +  }
 1.68123 +  break;
 1.68124 +}
 1.68125 +
 1.68126 +/* Opcode: SoftNull P1 * * * *
 1.68127 +** Synopsis:  r[P1]=NULL
 1.68128 +**
 1.68129 +** Set register P1 to have the value NULL as seen by the OP_MakeRecord
 1.68130 +** instruction, but do not free any string or blob memory associated with
 1.68131 +** the register, so that if the value was a string or blob that was
 1.68132 +** previously copied using OP_SCopy, the copies will continue to be valid.
 1.68133 +*/
 1.68134 +case OP_SoftNull: {
 1.68135 +  assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
 1.68136 +  pOut = &aMem[pOp->p1];
 1.68137 +  pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
 1.68138 +  break;
 1.68139 +}
 1.68140 +
 1.68141 +/* Opcode: Blob P1 P2 * P4 *
 1.68142 +** Synopsis: r[P2]=P4 (len=P1)
 1.68143 +**
 1.68144 +** P4 points to a blob of data P1 bytes long.  Store this
 1.68145 +** blob in register P2.
 1.68146 +*/
 1.68147 +case OP_Blob: {                /* out2-prerelease */
 1.68148 +  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
 1.68149 +  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
 1.68150 +  pOut->enc = encoding;
 1.68151 +  UPDATE_MAX_BLOBSIZE(pOut);
 1.68152 +  break;
 1.68153 +}
 1.68154 +
 1.68155 +/* Opcode: Variable P1 P2 * P4 *
 1.68156 +** Synopsis: r[P2]=parameter(P1,P4)
 1.68157 +**
 1.68158 +** Transfer the values of bound parameter P1 into register P2
 1.68159 +**
 1.68160 +** If the parameter is named, then its name appears in P4.
 1.68161 +** The P4 value is used by sqlite3_bind_parameter_name().
 1.68162 +*/
 1.68163 +case OP_Variable: {            /* out2-prerelease */
 1.68164 +  Mem *pVar;       /* Value being transferred */
 1.68165 +
 1.68166 +  assert( pOp->p1>0 && pOp->p1<=p->nVar );
 1.68167 +  assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
 1.68168 +  pVar = &p->aVar[pOp->p1 - 1];
 1.68169 +  if( sqlite3VdbeMemTooBig(pVar) ){
 1.68170 +    goto too_big;
 1.68171 +  }
 1.68172 +  sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
 1.68173 +  UPDATE_MAX_BLOBSIZE(pOut);
 1.68174 +  break;
 1.68175 +}
 1.68176 +
 1.68177 +/* Opcode: Move P1 P2 P3 * *
 1.68178 +** Synopsis:  r[P2@P3]=r[P1@P3]
 1.68179 +**
 1.68180 +** Move the values in register P1..P1+P3 over into
 1.68181 +** registers P2..P2+P3.  Registers P1..P1+P3 are
 1.68182 +** left holding a NULL.  It is an error for register ranges
 1.68183 +** P1..P1+P3 and P2..P2+P3 to overlap.
 1.68184 +*/
 1.68185 +case OP_Move: {
 1.68186 +  char *zMalloc;   /* Holding variable for allocated memory */
 1.68187 +  int n;           /* Number of registers left to copy */
 1.68188 +  int p1;          /* Register to copy from */
 1.68189 +  int p2;          /* Register to copy to */
 1.68190 +
 1.68191 +  n = pOp->p3;
 1.68192 +  p1 = pOp->p1;
 1.68193 +  p2 = pOp->p2;
 1.68194 +  assert( n>=0 && p1>0 && p2>0 );
 1.68195 +  assert( p1+n<=p2 || p2+n<=p1 );
 1.68196 +
 1.68197 +  pIn1 = &aMem[p1];
 1.68198 +  pOut = &aMem[p2];
 1.68199 +  do{
 1.68200 +    assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
 1.68201 +    assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
 1.68202 +    assert( memIsValid(pIn1) );
 1.68203 +    memAboutToChange(p, pOut);
 1.68204 +    VdbeMemRelease(pOut);
 1.68205 +    zMalloc = pOut->zMalloc;
 1.68206 +    memcpy(pOut, pIn1, sizeof(Mem));
 1.68207 +#ifdef SQLITE_DEBUG
 1.68208 +    if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<&aMem[p1+pOp->p3] ){
 1.68209 +      pOut->pScopyFrom += p1 - pOp->p2;
 1.68210 +    }
 1.68211 +#endif
 1.68212 +    pIn1->flags = MEM_Undefined;
 1.68213 +    pIn1->xDel = 0;
 1.68214 +    pIn1->zMalloc = zMalloc;
 1.68215 +    REGISTER_TRACE(p2++, pOut);
 1.68216 +    pIn1++;
 1.68217 +    pOut++;
 1.68218 +  }while( n-- );
 1.68219 +  break;
 1.68220 +}
 1.68221 +
 1.68222 +/* Opcode: Copy P1 P2 P3 * *
 1.68223 +** Synopsis: r[P2@P3+1]=r[P1@P3+1]
 1.68224 +**
 1.68225 +** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
 1.68226 +**
 1.68227 +** This instruction makes a deep copy of the value.  A duplicate
 1.68228 +** is made of any string or blob constant.  See also OP_SCopy.
 1.68229 +*/
 1.68230 +case OP_Copy: {
 1.68231 +  int n;
 1.68232 +
 1.68233 +  n = pOp->p3;
 1.68234 +  pIn1 = &aMem[pOp->p1];
 1.68235 +  pOut = &aMem[pOp->p2];
 1.68236 +  assert( pOut!=pIn1 );
 1.68237 +  while( 1 ){
 1.68238 +    sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
 1.68239 +    Deephemeralize(pOut);
 1.68240 +#ifdef SQLITE_DEBUG
 1.68241 +    pOut->pScopyFrom = 0;
 1.68242 +#endif
 1.68243 +    REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
 1.68244 +    if( (n--)==0 ) break;
 1.68245 +    pOut++;
 1.68246 +    pIn1++;
 1.68247 +  }
 1.68248 +  break;
 1.68249 +}
 1.68250 +
 1.68251 +/* Opcode: SCopy P1 P2 * * *
 1.68252 +** Synopsis: r[P2]=r[P1]
 1.68253 +**
 1.68254 +** Make a shallow copy of register P1 into register P2.
 1.68255 +**
 1.68256 +** This instruction makes a shallow copy of the value.  If the value
 1.68257 +** is a string or blob, then the copy is only a pointer to the
 1.68258 +** original and hence if the original changes so will the copy.
 1.68259 +** Worse, if the original is deallocated, the copy becomes invalid.
 1.68260 +** Thus the program must guarantee that the original will not change
 1.68261 +** during the lifetime of the copy.  Use OP_Copy to make a complete
 1.68262 +** copy.
 1.68263 +*/
 1.68264 +case OP_SCopy: {            /* out2 */
 1.68265 +  pIn1 = &aMem[pOp->p1];
 1.68266 +  pOut = &aMem[pOp->p2];
 1.68267 +  assert( pOut!=pIn1 );
 1.68268 +  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
 1.68269 +#ifdef SQLITE_DEBUG
 1.68270 +  if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
 1.68271 +#endif
 1.68272 +  break;
 1.68273 +}
 1.68274 +
 1.68275 +/* Opcode: ResultRow P1 P2 * * *
 1.68276 +** Synopsis:  output=r[P1@P2]
 1.68277 +**
 1.68278 +** The registers P1 through P1+P2-1 contain a single row of
 1.68279 +** results. This opcode causes the sqlite3_step() call to terminate
 1.68280 +** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
 1.68281 +** structure to provide access to the r(P1)..r(P1+P2-1) values as
 1.68282 +** the result row.
 1.68283 +*/
 1.68284 +case OP_ResultRow: {
 1.68285 +  Mem *pMem;
 1.68286 +  int i;
 1.68287 +  assert( p->nResColumn==pOp->p2 );
 1.68288 +  assert( pOp->p1>0 );
 1.68289 +  assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
 1.68290 +
 1.68291 +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
 1.68292 +  /* Run the progress counter just before returning.
 1.68293 +  */
 1.68294 +  if( db->xProgress!=0
 1.68295 +   && nVmStep>=nProgressLimit
 1.68296 +   && db->xProgress(db->pProgressArg)!=0
 1.68297 +  ){
 1.68298 +    rc = SQLITE_INTERRUPT;
 1.68299 +    goto vdbe_error_halt;
 1.68300 +  }
 1.68301 +#endif
 1.68302 +
 1.68303 +  /* If this statement has violated immediate foreign key constraints, do
 1.68304 +  ** not return the number of rows modified. And do not RELEASE the statement
 1.68305 +  ** transaction. It needs to be rolled back.  */
 1.68306 +  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
 1.68307 +    assert( db->flags&SQLITE_CountRows );
 1.68308 +    assert( p->usesStmtJournal );
 1.68309 +    break;
 1.68310 +  }
 1.68311 +
 1.68312 +  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then 
 1.68313 +  ** DML statements invoke this opcode to return the number of rows 
 1.68314 +  ** modified to the user. This is the only way that a VM that
 1.68315 +  ** opens a statement transaction may invoke this opcode.
 1.68316 +  **
 1.68317 +  ** In case this is such a statement, close any statement transaction
 1.68318 +  ** opened by this VM before returning control to the user. This is to
 1.68319 +  ** ensure that statement-transactions are always nested, not overlapping.
 1.68320 +  ** If the open statement-transaction is not closed here, then the user
 1.68321 +  ** may step another VM that opens its own statement transaction. This
 1.68322 +  ** may lead to overlapping statement transactions.
 1.68323 +  **
 1.68324 +  ** The statement transaction is never a top-level transaction.  Hence
 1.68325 +  ** the RELEASE call below can never fail.
 1.68326 +  */
 1.68327 +  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
 1.68328 +  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
 1.68329 +  if( NEVER(rc!=SQLITE_OK) ){
 1.68330 +    break;
 1.68331 +  }
 1.68332 +
 1.68333 +  /* Invalidate all ephemeral cursor row caches */
 1.68334 +  p->cacheCtr = (p->cacheCtr + 2)|1;
 1.68335 +
 1.68336 +  /* Make sure the results of the current row are \000 terminated
 1.68337 +  ** and have an assigned type.  The results are de-ephemeralized as
 1.68338 +  ** a side effect.
 1.68339 +  */
 1.68340 +  pMem = p->pResultSet = &aMem[pOp->p1];
 1.68341 +  for(i=0; i<pOp->p2; i++){
 1.68342 +    assert( memIsValid(&pMem[i]) );
 1.68343 +    Deephemeralize(&pMem[i]);
 1.68344 +    assert( (pMem[i].flags & MEM_Ephem)==0
 1.68345 +            || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
 1.68346 +    sqlite3VdbeMemNulTerminate(&pMem[i]);
 1.68347 +    REGISTER_TRACE(pOp->p1+i, &pMem[i]);
 1.68348 +  }
 1.68349 +  if( db->mallocFailed ) goto no_mem;
 1.68350 +
 1.68351 +  /* Return SQLITE_ROW
 1.68352 +  */
 1.68353 +  p->pc = pc + 1;
 1.68354 +  rc = SQLITE_ROW;
 1.68355 +  goto vdbe_return;
 1.68356 +}
 1.68357 +
 1.68358 +/* Opcode: Concat P1 P2 P3 * *
 1.68359 +** Synopsis: r[P3]=r[P2]+r[P1]
 1.68360 +**
 1.68361 +** Add the text in register P1 onto the end of the text in
 1.68362 +** register P2 and store the result in register P3.
 1.68363 +** If either the P1 or P2 text are NULL then store NULL in P3.
 1.68364 +**
 1.68365 +**   P3 = P2 || P1
 1.68366 +**
 1.68367 +** It is illegal for P1 and P3 to be the same register. Sometimes,
 1.68368 +** if P3 is the same register as P2, the implementation is able
 1.68369 +** to avoid a memcpy().
 1.68370 +*/
 1.68371 +case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
 1.68372 +  i64 nByte;
 1.68373 +
 1.68374 +  pIn1 = &aMem[pOp->p1];
 1.68375 +  pIn2 = &aMem[pOp->p2];
 1.68376 +  pOut = &aMem[pOp->p3];
 1.68377 +  assert( pIn1!=pOut );
 1.68378 +  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
 1.68379 +    sqlite3VdbeMemSetNull(pOut);
 1.68380 +    break;
 1.68381 +  }
 1.68382 +  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
 1.68383 +  Stringify(pIn1, encoding);
 1.68384 +  Stringify(pIn2, encoding);
 1.68385 +  nByte = pIn1->n + pIn2->n;
 1.68386 +  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
 1.68387 +    goto too_big;
 1.68388 +  }
 1.68389 +  if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
 1.68390 +    goto no_mem;
 1.68391 +  }
 1.68392 +  MemSetTypeFlag(pOut, MEM_Str);
 1.68393 +  if( pOut!=pIn2 ){
 1.68394 +    memcpy(pOut->z, pIn2->z, pIn2->n);
 1.68395 +  }
 1.68396 +  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
 1.68397 +  pOut->z[nByte]=0;
 1.68398 +  pOut->z[nByte+1] = 0;
 1.68399 +  pOut->flags |= MEM_Term;
 1.68400 +  pOut->n = (int)nByte;
 1.68401 +  pOut->enc = encoding;
 1.68402 +  UPDATE_MAX_BLOBSIZE(pOut);
 1.68403 +  break;
 1.68404 +}
 1.68405 +
 1.68406 +/* Opcode: Add P1 P2 P3 * *
 1.68407 +** Synopsis:  r[P3]=r[P1]+r[P2]
 1.68408 +**
 1.68409 +** Add the value in register P1 to the value in register P2
 1.68410 +** and store the result in register P3.
 1.68411 +** If either input is NULL, the result is NULL.
 1.68412 +*/
 1.68413 +/* Opcode: Multiply P1 P2 P3 * *
 1.68414 +** Synopsis:  r[P3]=r[P1]*r[P2]
 1.68415 +**
 1.68416 +**
 1.68417 +** Multiply the value in register P1 by the value in register P2
 1.68418 +** and store the result in register P3.
 1.68419 +** If either input is NULL, the result is NULL.
 1.68420 +*/
 1.68421 +/* Opcode: Subtract P1 P2 P3 * *
 1.68422 +** Synopsis:  r[P3]=r[P2]-r[P1]
 1.68423 +**
 1.68424 +** Subtract the value in register P1 from the value in register P2
 1.68425 +** and store the result in register P3.
 1.68426 +** If either input is NULL, the result is NULL.
 1.68427 +*/
 1.68428 +/* Opcode: Divide P1 P2 P3 * *
 1.68429 +** Synopsis:  r[P3]=r[P2]/r[P1]
 1.68430 +**
 1.68431 +** Divide the value in register P1 by the value in register P2
 1.68432 +** and store the result in register P3 (P3=P2/P1). If the value in 
 1.68433 +** register P1 is zero, then the result is NULL. If either input is 
 1.68434 +** NULL, the result is NULL.
 1.68435 +*/
 1.68436 +/* Opcode: Remainder P1 P2 P3 * *
 1.68437 +** Synopsis:  r[P3]=r[P2]%r[P1]
 1.68438 +**
 1.68439 +** Compute the remainder after integer register P2 is divided by 
 1.68440 +** register P1 and store the result in register P3. 
 1.68441 +** If the value in register P1 is zero the result is NULL.
 1.68442 +** If either operand is NULL, the result is NULL.
 1.68443 +*/
 1.68444 +case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
 1.68445 +case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
 1.68446 +case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
 1.68447 +case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
 1.68448 +case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
 1.68449 +  char bIntint;   /* Started out as two integer operands */
 1.68450 +  int flags;      /* Combined MEM_* flags from both inputs */
 1.68451 +  i64 iA;         /* Integer value of left operand */
 1.68452 +  i64 iB;         /* Integer value of right operand */
 1.68453 +  double rA;      /* Real value of left operand */
 1.68454 +  double rB;      /* Real value of right operand */
 1.68455 +
 1.68456 +  pIn1 = &aMem[pOp->p1];
 1.68457 +  applyNumericAffinity(pIn1);
 1.68458 +  pIn2 = &aMem[pOp->p2];
 1.68459 +  applyNumericAffinity(pIn2);
 1.68460 +  pOut = &aMem[pOp->p3];
 1.68461 +  flags = pIn1->flags | pIn2->flags;
 1.68462 +  if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
 1.68463 +  if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
 1.68464 +    iA = pIn1->u.i;
 1.68465 +    iB = pIn2->u.i;
 1.68466 +    bIntint = 1;
 1.68467 +    switch( pOp->opcode ){
 1.68468 +      case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;
 1.68469 +      case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;
 1.68470 +      case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;
 1.68471 +      case OP_Divide: {
 1.68472 +        if( iA==0 ) goto arithmetic_result_is_null;
 1.68473 +        if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
 1.68474 +        iB /= iA;
 1.68475 +        break;
 1.68476 +      }
 1.68477 +      default: {
 1.68478 +        if( iA==0 ) goto arithmetic_result_is_null;
 1.68479 +        if( iA==-1 ) iA = 1;
 1.68480 +        iB %= iA;
 1.68481 +        break;
 1.68482 +      }
 1.68483 +    }
 1.68484 +    pOut->u.i = iB;
 1.68485 +    MemSetTypeFlag(pOut, MEM_Int);
 1.68486 +  }else{
 1.68487 +    bIntint = 0;
 1.68488 +fp_math:
 1.68489 +    rA = sqlite3VdbeRealValue(pIn1);
 1.68490 +    rB = sqlite3VdbeRealValue(pIn2);
 1.68491 +    switch( pOp->opcode ){
 1.68492 +      case OP_Add:         rB += rA;       break;
 1.68493 +      case OP_Subtract:    rB -= rA;       break;
 1.68494 +      case OP_Multiply:    rB *= rA;       break;
 1.68495 +      case OP_Divide: {
 1.68496 +        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
 1.68497 +        if( rA==(double)0 ) goto arithmetic_result_is_null;
 1.68498 +        rB /= rA;
 1.68499 +        break;
 1.68500 +      }
 1.68501 +      default: {
 1.68502 +        iA = (i64)rA;
 1.68503 +        iB = (i64)rB;
 1.68504 +        if( iA==0 ) goto arithmetic_result_is_null;
 1.68505 +        if( iA==-1 ) iA = 1;
 1.68506 +        rB = (double)(iB % iA);
 1.68507 +        break;
 1.68508 +      }
 1.68509 +    }
 1.68510 +#ifdef SQLITE_OMIT_FLOATING_POINT
 1.68511 +    pOut->u.i = rB;
 1.68512 +    MemSetTypeFlag(pOut, MEM_Int);
 1.68513 +#else
 1.68514 +    if( sqlite3IsNaN(rB) ){
 1.68515 +      goto arithmetic_result_is_null;
 1.68516 +    }
 1.68517 +    pOut->r = rB;
 1.68518 +    MemSetTypeFlag(pOut, MEM_Real);
 1.68519 +    if( (flags & MEM_Real)==0 && !bIntint ){
 1.68520 +      sqlite3VdbeIntegerAffinity(pOut);
 1.68521 +    }
 1.68522 +#endif
 1.68523 +  }
 1.68524 +  break;
 1.68525 +
 1.68526 +arithmetic_result_is_null:
 1.68527 +  sqlite3VdbeMemSetNull(pOut);
 1.68528 +  break;
 1.68529 +}
 1.68530 +
 1.68531 +/* Opcode: CollSeq P1 * * P4
 1.68532 +**
 1.68533 +** P4 is a pointer to a CollSeq struct. If the next call to a user function
 1.68534 +** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
 1.68535 +** be returned. This is used by the built-in min(), max() and nullif()
 1.68536 +** functions.
 1.68537 +**
 1.68538 +** If P1 is not zero, then it is a register that a subsequent min() or
 1.68539 +** max() aggregate will set to 1 if the current row is not the minimum or
 1.68540 +** maximum.  The P1 register is initialized to 0 by this instruction.
 1.68541 +**
 1.68542 +** The interface used by the implementation of the aforementioned functions
 1.68543 +** to retrieve the collation sequence set by this opcode is not available
 1.68544 +** publicly, only to user functions defined in func.c.
 1.68545 +*/
 1.68546 +case OP_CollSeq: {
 1.68547 +  assert( pOp->p4type==P4_COLLSEQ );
 1.68548 +  if( pOp->p1 ){
 1.68549 +    sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
 1.68550 +  }
 1.68551 +  break;
 1.68552 +}
 1.68553 +
 1.68554 +/* Opcode: Function P1 P2 P3 P4 P5
 1.68555 +** Synopsis: r[P3]=func(r[P2@P5])
 1.68556 +**
 1.68557 +** Invoke a user function (P4 is a pointer to a Function structure that
 1.68558 +** defines the function) with P5 arguments taken from register P2 and
 1.68559 +** successors.  The result of the function is stored in register P3.
 1.68560 +** Register P3 must not be one of the function inputs.
 1.68561 +**
 1.68562 +** P1 is a 32-bit bitmask indicating whether or not each argument to the 
 1.68563 +** function was determined to be constant at compile time. If the first
 1.68564 +** argument was constant then bit 0 of P1 is set. This is used to determine
 1.68565 +** whether meta data associated with a user function argument using the
 1.68566 +** sqlite3_set_auxdata() API may be safely retained until the next
 1.68567 +** invocation of this opcode.
 1.68568 +**
 1.68569 +** See also: AggStep and AggFinal
 1.68570 +*/
 1.68571 +case OP_Function: {
 1.68572 +  int i;
 1.68573 +  Mem *pArg;
 1.68574 +  sqlite3_context ctx;
 1.68575 +  sqlite3_value **apVal;
 1.68576 +  int n;
 1.68577 +
 1.68578 +  n = pOp->p5;
 1.68579 +  apVal = p->apArg;
 1.68580 +  assert( apVal || n==0 );
 1.68581 +  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
 1.68582 +  pOut = &aMem[pOp->p3];
 1.68583 +  memAboutToChange(p, pOut);
 1.68584 +
 1.68585 +  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
 1.68586 +  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
 1.68587 +  pArg = &aMem[pOp->p2];
 1.68588 +  for(i=0; i<n; i++, pArg++){
 1.68589 +    assert( memIsValid(pArg) );
 1.68590 +    apVal[i] = pArg;
 1.68591 +    Deephemeralize(pArg);
 1.68592 +    REGISTER_TRACE(pOp->p2+i, pArg);
 1.68593 +  }
 1.68594 +
 1.68595 +  assert( pOp->p4type==P4_FUNCDEF );
 1.68596 +  ctx.pFunc = pOp->p4.pFunc;
 1.68597 +  ctx.iOp = pc;
 1.68598 +  ctx.pVdbe = p;
 1.68599 +
 1.68600 +  /* The output cell may already have a buffer allocated. Move
 1.68601 +  ** the pointer to ctx.s so in case the user-function can use
 1.68602 +  ** the already allocated buffer instead of allocating a new one.
 1.68603 +  */
 1.68604 +  memcpy(&ctx.s, pOut, sizeof(Mem));
 1.68605 +  pOut->flags = MEM_Null;
 1.68606 +  pOut->xDel = 0;
 1.68607 +  pOut->zMalloc = 0;
 1.68608 +  MemSetTypeFlag(&ctx.s, MEM_Null);
 1.68609 +
 1.68610 +  ctx.fErrorOrAux = 0;
 1.68611 +  if( ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
 1.68612 +    assert( pOp>aOp );
 1.68613 +    assert( pOp[-1].p4type==P4_COLLSEQ );
 1.68614 +    assert( pOp[-1].opcode==OP_CollSeq );
 1.68615 +    ctx.pColl = pOp[-1].p4.pColl;
 1.68616 +  }
 1.68617 +  db->lastRowid = lastRowid;
 1.68618 +  (*ctx.pFunc->xFunc)(&ctx, n, apVal); /* IMP: R-24505-23230 */
 1.68619 +  lastRowid = db->lastRowid;
 1.68620 +
 1.68621 +  if( db->mallocFailed ){
 1.68622 +    /* Even though a malloc() has failed, the implementation of the
 1.68623 +    ** user function may have called an sqlite3_result_XXX() function
 1.68624 +    ** to return a value. The following call releases any resources
 1.68625 +    ** associated with such a value.
 1.68626 +    */
 1.68627 +    sqlite3VdbeMemRelease(&ctx.s);
 1.68628 +    goto no_mem;
 1.68629 +  }
 1.68630 +
 1.68631 +  /* If the function returned an error, throw an exception */
 1.68632 +  if( ctx.fErrorOrAux ){
 1.68633 +    if( ctx.isError ){
 1.68634 +      sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
 1.68635 +      rc = ctx.isError;
 1.68636 +    }
 1.68637 +    sqlite3VdbeDeleteAuxData(p, pc, pOp->p1);
 1.68638 +  }
 1.68639 +
 1.68640 +  /* Copy the result of the function into register P3 */
 1.68641 +  sqlite3VdbeChangeEncoding(&ctx.s, encoding);
 1.68642 +  assert( pOut->flags==MEM_Null );
 1.68643 +  memcpy(pOut, &ctx.s, sizeof(Mem));
 1.68644 +  if( sqlite3VdbeMemTooBig(pOut) ){
 1.68645 +    goto too_big;
 1.68646 +  }
 1.68647 +
 1.68648 +#if 0
 1.68649 +  /* The app-defined function has done something that as caused this
 1.68650 +  ** statement to expire.  (Perhaps the function called sqlite3_exec()
 1.68651 +  ** with a CREATE TABLE statement.)
 1.68652 +  */
 1.68653 +  if( p->expired ) rc = SQLITE_ABORT;
 1.68654 +#endif
 1.68655 +
 1.68656 +  REGISTER_TRACE(pOp->p3, pOut);
 1.68657 +  UPDATE_MAX_BLOBSIZE(pOut);
 1.68658 +  break;
 1.68659 +}
 1.68660 +
 1.68661 +/* Opcode: BitAnd P1 P2 P3 * *
 1.68662 +** Synopsis:  r[P3]=r[P1]&r[P2]
 1.68663 +**
 1.68664 +** Take the bit-wise AND of the values in register P1 and P2 and
 1.68665 +** store the result in register P3.
 1.68666 +** If either input is NULL, the result is NULL.
 1.68667 +*/
 1.68668 +/* Opcode: BitOr P1 P2 P3 * *
 1.68669 +** Synopsis:  r[P3]=r[P1]|r[P2]
 1.68670 +**
 1.68671 +** Take the bit-wise OR of the values in register P1 and P2 and
 1.68672 +** store the result in register P3.
 1.68673 +** If either input is NULL, the result is NULL.
 1.68674 +*/
 1.68675 +/* Opcode: ShiftLeft P1 P2 P3 * *
 1.68676 +** Synopsis:  r[P3]=r[P2]<<r[P1]
 1.68677 +**
 1.68678 +** Shift the integer value in register P2 to the left by the
 1.68679 +** number of bits specified by the integer in register P1.
 1.68680 +** Store the result in register P3.
 1.68681 +** If either input is NULL, the result is NULL.
 1.68682 +*/
 1.68683 +/* Opcode: ShiftRight P1 P2 P3 * *
 1.68684 +** Synopsis:  r[P3]=r[P2]>>r[P1]
 1.68685 +**
 1.68686 +** Shift the integer value in register P2 to the right by the
 1.68687 +** number of bits specified by the integer in register P1.
 1.68688 +** Store the result in register P3.
 1.68689 +** If either input is NULL, the result is NULL.
 1.68690 +*/
 1.68691 +case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
 1.68692 +case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
 1.68693 +case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
 1.68694 +case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
 1.68695 +  i64 iA;
 1.68696 +  u64 uA;
 1.68697 +  i64 iB;
 1.68698 +  u8 op;
 1.68699 +
 1.68700 +  pIn1 = &aMem[pOp->p1];
 1.68701 +  pIn2 = &aMem[pOp->p2];
 1.68702 +  pOut = &aMem[pOp->p3];
 1.68703 +  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
 1.68704 +    sqlite3VdbeMemSetNull(pOut);
 1.68705 +    break;
 1.68706 +  }
 1.68707 +  iA = sqlite3VdbeIntValue(pIn2);
 1.68708 +  iB = sqlite3VdbeIntValue(pIn1);
 1.68709 +  op = pOp->opcode;
 1.68710 +  if( op==OP_BitAnd ){
 1.68711 +    iA &= iB;
 1.68712 +  }else if( op==OP_BitOr ){
 1.68713 +    iA |= iB;
 1.68714 +  }else if( iB!=0 ){
 1.68715 +    assert( op==OP_ShiftRight || op==OP_ShiftLeft );
 1.68716 +
 1.68717 +    /* If shifting by a negative amount, shift in the other direction */
 1.68718 +    if( iB<0 ){
 1.68719 +      assert( OP_ShiftRight==OP_ShiftLeft+1 );
 1.68720 +      op = 2*OP_ShiftLeft + 1 - op;
 1.68721 +      iB = iB>(-64) ? -iB : 64;
 1.68722 +    }
 1.68723 +
 1.68724 +    if( iB>=64 ){
 1.68725 +      iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
 1.68726 +    }else{
 1.68727 +      memcpy(&uA, &iA, sizeof(uA));
 1.68728 +      if( op==OP_ShiftLeft ){
 1.68729 +        uA <<= iB;
 1.68730 +      }else{
 1.68731 +        uA >>= iB;
 1.68732 +        /* Sign-extend on a right shift of a negative number */
 1.68733 +        if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
 1.68734 +      }
 1.68735 +      memcpy(&iA, &uA, sizeof(iA));
 1.68736 +    }
 1.68737 +  }
 1.68738 +  pOut->u.i = iA;
 1.68739 +  MemSetTypeFlag(pOut, MEM_Int);
 1.68740 +  break;
 1.68741 +}
 1.68742 +
 1.68743 +/* Opcode: AddImm  P1 P2 * * *
 1.68744 +** Synopsis:  r[P1]=r[P1]+P2
 1.68745 +** 
 1.68746 +** Add the constant P2 to the value in register P1.
 1.68747 +** The result is always an integer.
 1.68748 +**
 1.68749 +** To force any register to be an integer, just add 0.
 1.68750 +*/
 1.68751 +case OP_AddImm: {            /* in1 */
 1.68752 +  pIn1 = &aMem[pOp->p1];
 1.68753 +  memAboutToChange(p, pIn1);
 1.68754 +  sqlite3VdbeMemIntegerify(pIn1);
 1.68755 +  pIn1->u.i += pOp->p2;
 1.68756 +  break;
 1.68757 +}
 1.68758 +
 1.68759 +/* Opcode: MustBeInt P1 P2 * * *
 1.68760 +** 
 1.68761 +** Force the value in register P1 to be an integer.  If the value
 1.68762 +** in P1 is not an integer and cannot be converted into an integer
 1.68763 +** without data loss, then jump immediately to P2, or if P2==0
 1.68764 +** raise an SQLITE_MISMATCH exception.
 1.68765 +*/
 1.68766 +case OP_MustBeInt: {            /* jump, in1 */
 1.68767 +  pIn1 = &aMem[pOp->p1];
 1.68768 +  if( (pIn1->flags & MEM_Int)==0 ){
 1.68769 +    applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
 1.68770 +    VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
 1.68771 +    if( (pIn1->flags & MEM_Int)==0 ){
 1.68772 +      if( pOp->p2==0 ){
 1.68773 +        rc = SQLITE_MISMATCH;
 1.68774 +        goto abort_due_to_error;
 1.68775 +      }else{
 1.68776 +        pc = pOp->p2 - 1;
 1.68777 +        break;
 1.68778 +      }
 1.68779 +    }
 1.68780 +  }
 1.68781 +  MemSetTypeFlag(pIn1, MEM_Int);
 1.68782 +  break;
 1.68783 +}
 1.68784 +
 1.68785 +#ifndef SQLITE_OMIT_FLOATING_POINT
 1.68786 +/* Opcode: RealAffinity P1 * * * *
 1.68787 +**
 1.68788 +** If register P1 holds an integer convert it to a real value.
 1.68789 +**
 1.68790 +** This opcode is used when extracting information from a column that
 1.68791 +** has REAL affinity.  Such column values may still be stored as
 1.68792 +** integers, for space efficiency, but after extraction we want them
 1.68793 +** to have only a real value.
 1.68794 +*/
 1.68795 +case OP_RealAffinity: {                  /* in1 */
 1.68796 +  pIn1 = &aMem[pOp->p1];
 1.68797 +  if( pIn1->flags & MEM_Int ){
 1.68798 +    sqlite3VdbeMemRealify(pIn1);
 1.68799 +  }
 1.68800 +  break;
 1.68801 +}
 1.68802 +#endif
 1.68803 +
 1.68804 +#ifndef SQLITE_OMIT_CAST
 1.68805 +/* Opcode: ToText P1 * * * *
 1.68806 +**
 1.68807 +** Force the value in register P1 to be text.
 1.68808 +** If the value is numeric, convert it to a string using the
 1.68809 +** equivalent of sprintf().  Blob values are unchanged and
 1.68810 +** are afterwards simply interpreted as text.
 1.68811 +**
 1.68812 +** A NULL value is not changed by this routine.  It remains NULL.
 1.68813 +*/
 1.68814 +case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
 1.68815 +  pIn1 = &aMem[pOp->p1];
 1.68816 +  memAboutToChange(p, pIn1);
 1.68817 +  if( pIn1->flags & MEM_Null ) break;
 1.68818 +  assert( MEM_Str==(MEM_Blob>>3) );
 1.68819 +  pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
 1.68820 +  applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
 1.68821 +  rc = ExpandBlob(pIn1);
 1.68822 +  assert( pIn1->flags & MEM_Str || db->mallocFailed );
 1.68823 +  pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
 1.68824 +  UPDATE_MAX_BLOBSIZE(pIn1);
 1.68825 +  break;
 1.68826 +}
 1.68827 +
 1.68828 +/* Opcode: ToBlob P1 * * * *
 1.68829 +**
 1.68830 +** Force the value in register P1 to be a BLOB.
 1.68831 +** If the value is numeric, convert it to a string first.
 1.68832 +** Strings are simply reinterpreted as blobs with no change
 1.68833 +** to the underlying data.
 1.68834 +**
 1.68835 +** A NULL value is not changed by this routine.  It remains NULL.
 1.68836 +*/
 1.68837 +case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
 1.68838 +  pIn1 = &aMem[pOp->p1];
 1.68839 +  if( pIn1->flags & MEM_Null ) break;
 1.68840 +  if( (pIn1->flags & MEM_Blob)==0 ){
 1.68841 +    applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
 1.68842 +    assert( pIn1->flags & MEM_Str || db->mallocFailed );
 1.68843 +    MemSetTypeFlag(pIn1, MEM_Blob);
 1.68844 +  }else{
 1.68845 +    pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
 1.68846 +  }
 1.68847 +  UPDATE_MAX_BLOBSIZE(pIn1);
 1.68848 +  break;
 1.68849 +}
 1.68850 +
 1.68851 +/* Opcode: ToNumeric P1 * * * *
 1.68852 +**
 1.68853 +** Force the value in register P1 to be numeric (either an
 1.68854 +** integer or a floating-point number.)
 1.68855 +** If the value is text or blob, try to convert it to an using the
 1.68856 +** equivalent of atoi() or atof() and store 0 if no such conversion 
 1.68857 +** is possible.
 1.68858 +**
 1.68859 +** A NULL value is not changed by this routine.  It remains NULL.
 1.68860 +*/
 1.68861 +case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
 1.68862 +  pIn1 = &aMem[pOp->p1];
 1.68863 +  sqlite3VdbeMemNumerify(pIn1);
 1.68864 +  break;
 1.68865 +}
 1.68866 +#endif /* SQLITE_OMIT_CAST */
 1.68867 +
 1.68868 +/* Opcode: ToInt P1 * * * *
 1.68869 +**
 1.68870 +** Force the value in register P1 to be an integer.  If
 1.68871 +** The value is currently a real number, drop its fractional part.
 1.68872 +** If the value is text or blob, try to convert it to an integer using the
 1.68873 +** equivalent of atoi() and store 0 if no such conversion is possible.
 1.68874 +**
 1.68875 +** A NULL value is not changed by this routine.  It remains NULL.
 1.68876 +*/
 1.68877 +case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
 1.68878 +  pIn1 = &aMem[pOp->p1];
 1.68879 +  if( (pIn1->flags & MEM_Null)==0 ){
 1.68880 +    sqlite3VdbeMemIntegerify(pIn1);
 1.68881 +  }
 1.68882 +  break;
 1.68883 +}
 1.68884 +
 1.68885 +#if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
 1.68886 +/* Opcode: ToReal P1 * * * *
 1.68887 +**
 1.68888 +** Force the value in register P1 to be a floating point number.
 1.68889 +** If The value is currently an integer, convert it.
 1.68890 +** If the value is text or blob, try to convert it to an integer using the
 1.68891 +** equivalent of atoi() and store 0.0 if no such conversion is possible.
 1.68892 +**
 1.68893 +** A NULL value is not changed by this routine.  It remains NULL.
 1.68894 +*/
 1.68895 +case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
 1.68896 +  pIn1 = &aMem[pOp->p1];
 1.68897 +  memAboutToChange(p, pIn1);
 1.68898 +  if( (pIn1->flags & MEM_Null)==0 ){
 1.68899 +    sqlite3VdbeMemRealify(pIn1);
 1.68900 +  }
 1.68901 +  break;
 1.68902 +}
 1.68903 +#endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
 1.68904 +
 1.68905 +/* Opcode: Lt P1 P2 P3 P4 P5
 1.68906 +** Synopsis: if r[P1]<r[P3] goto P2
 1.68907 +**
 1.68908 +** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
 1.68909 +** jump to address P2.  
 1.68910 +**
 1.68911 +** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
 1.68912 +** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
 1.68913 +** bit is clear then fall through if either operand is NULL.
 1.68914 +**
 1.68915 +** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
 1.68916 +** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
 1.68917 +** to coerce both inputs according to this affinity before the
 1.68918 +** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
 1.68919 +** affinity is used. Note that the affinity conversions are stored
 1.68920 +** back into the input registers P1 and P3.  So this opcode can cause
 1.68921 +** persistent changes to registers P1 and P3.
 1.68922 +**
 1.68923 +** Once any conversions have taken place, and neither value is NULL, 
 1.68924 +** the values are compared. If both values are blobs then memcmp() is
 1.68925 +** used to determine the results of the comparison.  If both values
 1.68926 +** are text, then the appropriate collating function specified in
 1.68927 +** P4 is  used to do the comparison.  If P4 is not specified then
 1.68928 +** memcmp() is used to compare text string.  If both values are
 1.68929 +** numeric, then a numeric comparison is used. If the two values
 1.68930 +** are of different types, then numbers are considered less than
 1.68931 +** strings and strings are considered less than blobs.
 1.68932 +**
 1.68933 +** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
 1.68934 +** store a boolean result (either 0, or 1, or NULL) in register P2.
 1.68935 +**
 1.68936 +** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
 1.68937 +** equal to one another, provided that they do not have their MEM_Cleared
 1.68938 +** bit set.
 1.68939 +*/
 1.68940 +/* Opcode: Ne P1 P2 P3 P4 P5
 1.68941 +** Synopsis: if r[P1]!=r[P3] goto P2
 1.68942 +**
 1.68943 +** This works just like the Lt opcode except that the jump is taken if
 1.68944 +** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
 1.68945 +** additional information.
 1.68946 +**
 1.68947 +** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
 1.68948 +** true or false and is never NULL.  If both operands are NULL then the result
 1.68949 +** of comparison is false.  If either operand is NULL then the result is true.
 1.68950 +** If neither operand is NULL the result is the same as it would be if
 1.68951 +** the SQLITE_NULLEQ flag were omitted from P5.
 1.68952 +*/
 1.68953 +/* Opcode: Eq P1 P2 P3 P4 P5
 1.68954 +** Synopsis: if r[P1]==r[P3] goto P2
 1.68955 +**
 1.68956 +** This works just like the Lt opcode except that the jump is taken if
 1.68957 +** the operands in registers P1 and P3 are equal.
 1.68958 +** See the Lt opcode for additional information.
 1.68959 +**
 1.68960 +** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
 1.68961 +** true or false and is never NULL.  If both operands are NULL then the result
 1.68962 +** of comparison is true.  If either operand is NULL then the result is false.
 1.68963 +** If neither operand is NULL the result is the same as it would be if
 1.68964 +** the SQLITE_NULLEQ flag were omitted from P5.
 1.68965 +*/
 1.68966 +/* Opcode: Le P1 P2 P3 P4 P5
 1.68967 +** Synopsis: if r[P1]<=r[P3] goto P2
 1.68968 +**
 1.68969 +** This works just like the Lt opcode except that the jump is taken if
 1.68970 +** the content of register P3 is less than or equal to the content of
 1.68971 +** register P1.  See the Lt opcode for additional information.
 1.68972 +*/
 1.68973 +/* Opcode: Gt P1 P2 P3 P4 P5
 1.68974 +** Synopsis: if r[P1]>r[P3] goto P2
 1.68975 +**
 1.68976 +** This works just like the Lt opcode except that the jump is taken if
 1.68977 +** the content of register P3 is greater than the content of
 1.68978 +** register P1.  See the Lt opcode for additional information.
 1.68979 +*/
 1.68980 +/* Opcode: Ge P1 P2 P3 P4 P5
 1.68981 +** Synopsis: if r[P1]>=r[P3] goto P2
 1.68982 +**
 1.68983 +** This works just like the Lt opcode except that the jump is taken if
 1.68984 +** the content of register P3 is greater than or equal to the content of
 1.68985 +** register P1.  See the Lt opcode for additional information.
 1.68986 +*/
 1.68987 +case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
 1.68988 +case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
 1.68989 +case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
 1.68990 +case OP_Le:               /* same as TK_LE, jump, in1, in3 */
 1.68991 +case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
 1.68992 +case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
 1.68993 +  int res;            /* Result of the comparison of pIn1 against pIn3 */
 1.68994 +  char affinity;      /* Affinity to use for comparison */
 1.68995 +  u16 flags1;         /* Copy of initial value of pIn1->flags */
 1.68996 +  u16 flags3;         /* Copy of initial value of pIn3->flags */
 1.68997 +
 1.68998 +  pIn1 = &aMem[pOp->p1];
 1.68999 +  pIn3 = &aMem[pOp->p3];
 1.69000 +  flags1 = pIn1->flags;
 1.69001 +  flags3 = pIn3->flags;
 1.69002 +  if( (flags1 | flags3)&MEM_Null ){
 1.69003 +    /* One or both operands are NULL */
 1.69004 +    if( pOp->p5 & SQLITE_NULLEQ ){
 1.69005 +      /* If SQLITE_NULLEQ is set (which will only happen if the operator is
 1.69006 +      ** OP_Eq or OP_Ne) then take the jump or not depending on whether
 1.69007 +      ** or not both operands are null.
 1.69008 +      */
 1.69009 +      assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
 1.69010 +      assert( (flags1 & MEM_Cleared)==0 );
 1.69011 +      assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
 1.69012 +      if( (flags1&MEM_Null)!=0
 1.69013 +       && (flags3&MEM_Null)!=0
 1.69014 +       && (flags3&MEM_Cleared)==0
 1.69015 +      ){
 1.69016 +        res = 0;  /* Results are equal */
 1.69017 +      }else{
 1.69018 +        res = 1;  /* Results are not equal */
 1.69019 +      }
 1.69020 +    }else{
 1.69021 +      /* SQLITE_NULLEQ is clear and at least one operand is NULL,
 1.69022 +      ** then the result is always NULL.
 1.69023 +      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
 1.69024 +      */
 1.69025 +      if( pOp->p5 & SQLITE_STOREP2 ){
 1.69026 +        pOut = &aMem[pOp->p2];
 1.69027 +        MemSetTypeFlag(pOut, MEM_Null);
 1.69028 +        REGISTER_TRACE(pOp->p2, pOut);
 1.69029 +      }else{
 1.69030 +        VdbeBranchTaken(2,3);
 1.69031 +        if( pOp->p5 & SQLITE_JUMPIFNULL ){
 1.69032 +          pc = pOp->p2-1;
 1.69033 +        }
 1.69034 +      }
 1.69035 +      break;
 1.69036 +    }
 1.69037 +  }else{
 1.69038 +    /* Neither operand is NULL.  Do a comparison. */
 1.69039 +    affinity = pOp->p5 & SQLITE_AFF_MASK;
 1.69040 +    if( affinity ){
 1.69041 +      applyAffinity(pIn1, affinity, encoding);
 1.69042 +      applyAffinity(pIn3, affinity, encoding);
 1.69043 +      if( db->mallocFailed ) goto no_mem;
 1.69044 +    }
 1.69045 +
 1.69046 +    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
 1.69047 +    ExpandBlob(pIn1);
 1.69048 +    ExpandBlob(pIn3);
 1.69049 +    res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
 1.69050 +  }
 1.69051 +  switch( pOp->opcode ){
 1.69052 +    case OP_Eq:    res = res==0;     break;
 1.69053 +    case OP_Ne:    res = res!=0;     break;
 1.69054 +    case OP_Lt:    res = res<0;      break;
 1.69055 +    case OP_Le:    res = res<=0;     break;
 1.69056 +    case OP_Gt:    res = res>0;      break;
 1.69057 +    default:       res = res>=0;     break;
 1.69058 +  }
 1.69059 +
 1.69060 +  if( pOp->p5 & SQLITE_STOREP2 ){
 1.69061 +    pOut = &aMem[pOp->p2];
 1.69062 +    memAboutToChange(p, pOut);
 1.69063 +    MemSetTypeFlag(pOut, MEM_Int);
 1.69064 +    pOut->u.i = res;
 1.69065 +    REGISTER_TRACE(pOp->p2, pOut);
 1.69066 +  }else{
 1.69067 +    VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
 1.69068 +    if( res ){
 1.69069 +      pc = pOp->p2-1;
 1.69070 +    }
 1.69071 +  }
 1.69072 +  /* Undo any changes made by applyAffinity() to the input registers. */
 1.69073 +  pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (flags1&MEM_TypeMask);
 1.69074 +  pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (flags3&MEM_TypeMask);
 1.69075 +  break;
 1.69076 +}
 1.69077 +
 1.69078 +/* Opcode: Permutation * * * P4 *
 1.69079 +**
 1.69080 +** Set the permutation used by the OP_Compare operator to be the array
 1.69081 +** of integers in P4.
 1.69082 +**
 1.69083 +** The permutation is only valid until the next OP_Compare that has
 1.69084 +** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should 
 1.69085 +** occur immediately prior to the OP_Compare.
 1.69086 +*/
 1.69087 +case OP_Permutation: {
 1.69088 +  assert( pOp->p4type==P4_INTARRAY );
 1.69089 +  assert( pOp->p4.ai );
 1.69090 +  aPermute = pOp->p4.ai;
 1.69091 +  break;
 1.69092 +}
 1.69093 +
 1.69094 +/* Opcode: Compare P1 P2 P3 P4 P5
 1.69095 +**
 1.69096 +** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
 1.69097 +** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
 1.69098 +** the comparison for use by the next OP_Jump instruct.
 1.69099 +**
 1.69100 +** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
 1.69101 +** determined by the most recent OP_Permutation operator.  If the
 1.69102 +** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
 1.69103 +** order.
 1.69104 +**
 1.69105 +** P4 is a KeyInfo structure that defines collating sequences and sort
 1.69106 +** orders for the comparison.  The permutation applies to registers
 1.69107 +** only.  The KeyInfo elements are used sequentially.
 1.69108 +**
 1.69109 +** The comparison is a sort comparison, so NULLs compare equal,
 1.69110 +** NULLs are less than numbers, numbers are less than strings,
 1.69111 +** and strings are less than blobs.
 1.69112 +*/
 1.69113 +case OP_Compare: {
 1.69114 +  int n;
 1.69115 +  int i;
 1.69116 +  int p1;
 1.69117 +  int p2;
 1.69118 +  const KeyInfo *pKeyInfo;
 1.69119 +  int idx;
 1.69120 +  CollSeq *pColl;    /* Collating sequence to use on this term */
 1.69121 +  int bRev;          /* True for DESCENDING sort order */
 1.69122 +
 1.69123 +  if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
 1.69124 +  n = pOp->p3;
 1.69125 +  pKeyInfo = pOp->p4.pKeyInfo;
 1.69126 +  assert( n>0 );
 1.69127 +  assert( pKeyInfo!=0 );
 1.69128 +  p1 = pOp->p1;
 1.69129 +  p2 = pOp->p2;
 1.69130 +#if SQLITE_DEBUG
 1.69131 +  if( aPermute ){
 1.69132 +    int k, mx = 0;
 1.69133 +    for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
 1.69134 +    assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
 1.69135 +    assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
 1.69136 +  }else{
 1.69137 +    assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
 1.69138 +    assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
 1.69139 +  }
 1.69140 +#endif /* SQLITE_DEBUG */
 1.69141 +  for(i=0; i<n; i++){
 1.69142 +    idx = aPermute ? aPermute[i] : i;
 1.69143 +    assert( memIsValid(&aMem[p1+idx]) );
 1.69144 +    assert( memIsValid(&aMem[p2+idx]) );
 1.69145 +    REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
 1.69146 +    REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
 1.69147 +    assert( i<pKeyInfo->nField );
 1.69148 +    pColl = pKeyInfo->aColl[i];
 1.69149 +    bRev = pKeyInfo->aSortOrder[i];
 1.69150 +    iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
 1.69151 +    if( iCompare ){
 1.69152 +      if( bRev ) iCompare = -iCompare;
 1.69153 +      break;
 1.69154 +    }
 1.69155 +  }
 1.69156 +  aPermute = 0;
 1.69157 +  break;
 1.69158 +}
 1.69159 +
 1.69160 +/* Opcode: Jump P1 P2 P3 * *
 1.69161 +**
 1.69162 +** Jump to the instruction at address P1, P2, or P3 depending on whether
 1.69163 +** in the most recent OP_Compare instruction the P1 vector was less than
 1.69164 +** equal to, or greater than the P2 vector, respectively.
 1.69165 +*/
 1.69166 +case OP_Jump: {             /* jump */
 1.69167 +  if( iCompare<0 ){
 1.69168 +    pc = pOp->p1 - 1;  VdbeBranchTaken(0,3);
 1.69169 +  }else if( iCompare==0 ){
 1.69170 +    pc = pOp->p2 - 1;  VdbeBranchTaken(1,3);
 1.69171 +  }else{
 1.69172 +    pc = pOp->p3 - 1;  VdbeBranchTaken(2,3);
 1.69173 +  }
 1.69174 +  break;
 1.69175 +}
 1.69176 +
 1.69177 +/* Opcode: And P1 P2 P3 * *
 1.69178 +** Synopsis: r[P3]=(r[P1] && r[P2])
 1.69179 +**
 1.69180 +** Take the logical AND of the values in registers P1 and P2 and
 1.69181 +** write the result into register P3.
 1.69182 +**
 1.69183 +** If either P1 or P2 is 0 (false) then the result is 0 even if
 1.69184 +** the other input is NULL.  A NULL and true or two NULLs give
 1.69185 +** a NULL output.
 1.69186 +*/
 1.69187 +/* Opcode: Or P1 P2 P3 * *
 1.69188 +** Synopsis: r[P3]=(r[P1] || r[P2])
 1.69189 +**
 1.69190 +** Take the logical OR of the values in register P1 and P2 and
 1.69191 +** store the answer in register P3.
 1.69192 +**
 1.69193 +** If either P1 or P2 is nonzero (true) then the result is 1 (true)
 1.69194 +** even if the other input is NULL.  A NULL and false or two NULLs
 1.69195 +** give a NULL output.
 1.69196 +*/
 1.69197 +case OP_And:              /* same as TK_AND, in1, in2, out3 */
 1.69198 +case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
 1.69199 +  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
 1.69200 +  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
 1.69201 +
 1.69202 +  pIn1 = &aMem[pOp->p1];
 1.69203 +  if( pIn1->flags & MEM_Null ){
 1.69204 +    v1 = 2;
 1.69205 +  }else{
 1.69206 +    v1 = sqlite3VdbeIntValue(pIn1)!=0;
 1.69207 +  }
 1.69208 +  pIn2 = &aMem[pOp->p2];
 1.69209 +  if( pIn2->flags & MEM_Null ){
 1.69210 +    v2 = 2;
 1.69211 +  }else{
 1.69212 +    v2 = sqlite3VdbeIntValue(pIn2)!=0;
 1.69213 +  }
 1.69214 +  if( pOp->opcode==OP_And ){
 1.69215 +    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
 1.69216 +    v1 = and_logic[v1*3+v2];
 1.69217 +  }else{
 1.69218 +    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
 1.69219 +    v1 = or_logic[v1*3+v2];
 1.69220 +  }
 1.69221 +  pOut = &aMem[pOp->p3];
 1.69222 +  if( v1==2 ){
 1.69223 +    MemSetTypeFlag(pOut, MEM_Null);
 1.69224 +  }else{
 1.69225 +    pOut->u.i = v1;
 1.69226 +    MemSetTypeFlag(pOut, MEM_Int);
 1.69227 +  }
 1.69228 +  break;
 1.69229 +}
 1.69230 +
 1.69231 +/* Opcode: Not P1 P2 * * *
 1.69232 +** Synopsis: r[P2]= !r[P1]
 1.69233 +**
 1.69234 +** Interpret the value in register P1 as a boolean value.  Store the
 1.69235 +** boolean complement in register P2.  If the value in register P1 is 
 1.69236 +** NULL, then a NULL is stored in P2.
 1.69237 +*/
 1.69238 +case OP_Not: {                /* same as TK_NOT, in1, out2 */
 1.69239 +  pIn1 = &aMem[pOp->p1];
 1.69240 +  pOut = &aMem[pOp->p2];
 1.69241 +  if( pIn1->flags & MEM_Null ){
 1.69242 +    sqlite3VdbeMemSetNull(pOut);
 1.69243 +  }else{
 1.69244 +    sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
 1.69245 +  }
 1.69246 +  break;
 1.69247 +}
 1.69248 +
 1.69249 +/* Opcode: BitNot P1 P2 * * *
 1.69250 +** Synopsis: r[P1]= ~r[P1]
 1.69251 +**
 1.69252 +** Interpret the content of register P1 as an integer.  Store the
 1.69253 +** ones-complement of the P1 value into register P2.  If P1 holds
 1.69254 +** a NULL then store a NULL in P2.
 1.69255 +*/
 1.69256 +case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
 1.69257 +  pIn1 = &aMem[pOp->p1];
 1.69258 +  pOut = &aMem[pOp->p2];
 1.69259 +  if( pIn1->flags & MEM_Null ){
 1.69260 +    sqlite3VdbeMemSetNull(pOut);
 1.69261 +  }else{
 1.69262 +    sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
 1.69263 +  }
 1.69264 +  break;
 1.69265 +}
 1.69266 +
 1.69267 +/* Opcode: Once P1 P2 * * *
 1.69268 +**
 1.69269 +** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
 1.69270 +** set the flag and fall through to the next instruction.  In other words,
 1.69271 +** this opcode causes all following opcodes up through P2 (but not including
 1.69272 +** P2) to run just once and to be skipped on subsequent times through the loop.
 1.69273 +*/
 1.69274 +case OP_Once: {             /* jump */
 1.69275 +  assert( pOp->p1<p->nOnceFlag );
 1.69276 +  VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
 1.69277 +  if( p->aOnceFlag[pOp->p1] ){
 1.69278 +    pc = pOp->p2-1;
 1.69279 +  }else{
 1.69280 +    p->aOnceFlag[pOp->p1] = 1;
 1.69281 +  }
 1.69282 +  break;
 1.69283 +}
 1.69284 +
 1.69285 +/* Opcode: If P1 P2 P3 * *
 1.69286 +**
 1.69287 +** Jump to P2 if the value in register P1 is true.  The value
 1.69288 +** is considered true if it is numeric and non-zero.  If the value
 1.69289 +** in P1 is NULL then take the jump if P3 is non-zero.
 1.69290 +*/
 1.69291 +/* Opcode: IfNot P1 P2 P3 * *
 1.69292 +**
 1.69293 +** Jump to P2 if the value in register P1 is False.  The value
 1.69294 +** is considered false if it has a numeric value of zero.  If the value
 1.69295 +** in P1 is NULL then take the jump if P3 is zero.
 1.69296 +*/
 1.69297 +case OP_If:                 /* jump, in1 */
 1.69298 +case OP_IfNot: {            /* jump, in1 */
 1.69299 +  int c;
 1.69300 +  pIn1 = &aMem[pOp->p1];
 1.69301 +  if( pIn1->flags & MEM_Null ){
 1.69302 +    c = pOp->p3;
 1.69303 +  }else{
 1.69304 +#ifdef SQLITE_OMIT_FLOATING_POINT
 1.69305 +    c = sqlite3VdbeIntValue(pIn1)!=0;
 1.69306 +#else
 1.69307 +    c = sqlite3VdbeRealValue(pIn1)!=0.0;
 1.69308 +#endif
 1.69309 +    if( pOp->opcode==OP_IfNot ) c = !c;
 1.69310 +  }
 1.69311 +  VdbeBranchTaken(c!=0, 2);
 1.69312 +  if( c ){
 1.69313 +    pc = pOp->p2-1;
 1.69314 +  }
 1.69315 +  break;
 1.69316 +}
 1.69317 +
 1.69318 +/* Opcode: IsNull P1 P2 * * *
 1.69319 +** Synopsis:  if r[P1]==NULL goto P2
 1.69320 +**
 1.69321 +** Jump to P2 if the value in register P1 is NULL.
 1.69322 +*/
 1.69323 +case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
 1.69324 +  pIn1 = &aMem[pOp->p1];
 1.69325 +  VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
 1.69326 +  if( (pIn1->flags & MEM_Null)!=0 ){
 1.69327 +    pc = pOp->p2 - 1;
 1.69328 +  }
 1.69329 +  break;
 1.69330 +}
 1.69331 +
 1.69332 +/* Opcode: NotNull P1 P2 * * *
 1.69333 +** Synopsis: if r[P1]!=NULL goto P2
 1.69334 +**
 1.69335 +** Jump to P2 if the value in register P1 is not NULL.  
 1.69336 +*/
 1.69337 +case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
 1.69338 +  pIn1 = &aMem[pOp->p1];
 1.69339 +  VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
 1.69340 +  if( (pIn1->flags & MEM_Null)==0 ){
 1.69341 +    pc = pOp->p2 - 1;
 1.69342 +  }
 1.69343 +  break;
 1.69344 +}
 1.69345 +
 1.69346 +/* Opcode: Column P1 P2 P3 P4 P5
 1.69347 +** Synopsis:  r[P3]=PX
 1.69348 +**
 1.69349 +** Interpret the data that cursor P1 points to as a structure built using
 1.69350 +** the MakeRecord instruction.  (See the MakeRecord opcode for additional
 1.69351 +** information about the format of the data.)  Extract the P2-th column
 1.69352 +** from this record.  If there are less that (P2+1) 
 1.69353 +** values in the record, extract a NULL.
 1.69354 +**
 1.69355 +** The value extracted is stored in register P3.
 1.69356 +**
 1.69357 +** If the column contains fewer than P2 fields, then extract a NULL.  Or,
 1.69358 +** if the P4 argument is a P4_MEM use the value of the P4 argument as
 1.69359 +** the result.
 1.69360 +**
 1.69361 +** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
 1.69362 +** then the cache of the cursor is reset prior to extracting the column.
 1.69363 +** The first OP_Column against a pseudo-table after the value of the content
 1.69364 +** register has changed should have this bit set.
 1.69365 +**
 1.69366 +** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
 1.69367 +** the result is guaranteed to only be used as the argument of a length()
 1.69368 +** or typeof() function, respectively.  The loading of large blobs can be
 1.69369 +** skipped for length() and all content loading can be skipped for typeof().
 1.69370 +*/
 1.69371 +case OP_Column: {
 1.69372 +  i64 payloadSize64; /* Number of bytes in the record */
 1.69373 +  int p2;            /* column number to retrieve */
 1.69374 +  VdbeCursor *pC;    /* The VDBE cursor */
 1.69375 +  BtCursor *pCrsr;   /* The BTree cursor */
 1.69376 +  u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
 1.69377 +  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
 1.69378 +  int len;           /* The length of the serialized data for the column */
 1.69379 +  int i;             /* Loop counter */
 1.69380 +  Mem *pDest;        /* Where to write the extracted value */
 1.69381 +  Mem sMem;          /* For storing the record being decoded */
 1.69382 +  const u8 *zData;   /* Part of the record being decoded */
 1.69383 +  const u8 *zHdr;    /* Next unparsed byte of the header */
 1.69384 +  const u8 *zEndHdr; /* Pointer to first byte after the header */
 1.69385 +  u32 offset;        /* Offset into the data */
 1.69386 +  u32 szField;       /* Number of bytes in the content of a field */
 1.69387 +  u32 avail;         /* Number of bytes of available data */
 1.69388 +  u32 t;             /* A type code from the record header */
 1.69389 +  Mem *pReg;         /* PseudoTable input register */
 1.69390 +
 1.69391 +  p2 = pOp->p2;
 1.69392 +  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
 1.69393 +  pDest = &aMem[pOp->p3];
 1.69394 +  memAboutToChange(p, pDest);
 1.69395 +  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 1.69396 +  pC = p->apCsr[pOp->p1];
 1.69397 +  assert( pC!=0 );
 1.69398 +  assert( p2<pC->nField );
 1.69399 +  aType = pC->aType;
 1.69400 +  aOffset = aType + pC->nField;
 1.69401 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.69402 +  assert( pC->pVtabCursor==0 ); /* OP_Column never called on virtual table */
 1.69403 +#endif
 1.69404 +  pCrsr = pC->pCursor;
 1.69405 +  assert( pCrsr!=0 || pC->pseudoTableReg>0 ); /* pCrsr NULL on PseudoTables */
 1.69406 +  assert( pCrsr!=0 || pC->nullRow );          /* pC->nullRow on PseudoTables */
 1.69407 +
 1.69408 +  /* If the cursor cache is stale, bring it up-to-date */
 1.69409 +  rc = sqlite3VdbeCursorMoveto(pC);
 1.69410 +  if( rc ) goto abort_due_to_error;
 1.69411 +  if( pC->cacheStatus!=p->cacheCtr || (pOp->p5&OPFLAG_CLEARCACHE)!=0 ){
 1.69412 +    if( pC->nullRow ){
 1.69413 +      if( pCrsr==0 ){
 1.69414 +        assert( pC->pseudoTableReg>0 );
 1.69415 +        pReg = &aMem[pC->pseudoTableReg];
 1.69416 +        assert( pReg->flags & MEM_Blob );
 1.69417 +        assert( memIsValid(pReg) );
 1.69418 +        pC->payloadSize = pC->szRow = avail = pReg->n;
 1.69419 +        pC->aRow = (u8*)pReg->z;
 1.69420 +      }else{
 1.69421 +        MemSetTypeFlag(pDest, MEM_Null);
 1.69422 +        goto op_column_out;
 1.69423 +      }
 1.69424 +    }else{
 1.69425 +      assert( pCrsr );
 1.69426 +      if( pC->isTable==0 ){
 1.69427 +        assert( sqlite3BtreeCursorIsValid(pCrsr) );
 1.69428 +        VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
 1.69429 +        assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
 1.69430 +        /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
 1.69431 +        ** payload size, so it is impossible for payloadSize64 to be
 1.69432 +        ** larger than 32 bits. */
 1.69433 +        assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
 1.69434 +        pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
 1.69435 +        pC->payloadSize = (u32)payloadSize64;
 1.69436 +      }else{
 1.69437 +        assert( sqlite3BtreeCursorIsValid(pCrsr) );
 1.69438 +        VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
 1.69439 +        assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
 1.69440 +        pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
 1.69441 +      }
 1.69442 +      assert( avail<=65536 );  /* Maximum page size is 64KiB */
 1.69443 +      if( pC->payloadSize <= (u32)avail ){
 1.69444 +        pC->szRow = pC->payloadSize;
 1.69445 +      }else{
 1.69446 +        pC->szRow = avail;
 1.69447 +      }
 1.69448 +      if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
 1.69449 +        goto too_big;
 1.69450 +      }
 1.69451 +    }
 1.69452 +    pC->cacheStatus = p->cacheCtr;
 1.69453 +    pC->iHdrOffset = getVarint32(pC->aRow, offset);
 1.69454 +    pC->nHdrParsed = 0;
 1.69455 +    aOffset[0] = offset;
 1.69456 +    if( avail<offset ){
 1.69457 +      /* pC->aRow does not have to hold the entire row, but it does at least
 1.69458 +      ** need to cover the header of the record.  If pC->aRow does not contain
 1.69459 +      ** the complete header, then set it to zero, forcing the header to be
 1.69460 +      ** dynamically allocated. */
 1.69461 +      pC->aRow = 0;
 1.69462 +      pC->szRow = 0;
 1.69463 +    }
 1.69464 +
 1.69465 +    /* Make sure a corrupt database has not given us an oversize header.
 1.69466 +    ** Do this now to avoid an oversize memory allocation.
 1.69467 +    **
 1.69468 +    ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
 1.69469 +    ** types use so much data space that there can only be 4096 and 32 of
 1.69470 +    ** them, respectively.  So the maximum header length results from a
 1.69471 +    ** 3-byte type for each of the maximum of 32768 columns plus three
 1.69472 +    ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
 1.69473 +    */
 1.69474 +    if( offset > 98307 || offset > pC->payloadSize ){
 1.69475 +      rc = SQLITE_CORRUPT_BKPT;
 1.69476 +      goto op_column_error;
 1.69477 +    }
 1.69478 +  }
 1.69479 +
 1.69480 +  /* Make sure at least the first p2+1 entries of the header have been
 1.69481 +  ** parsed and valid information is in aOffset[] and aType[].
 1.69482 +  */
 1.69483 +  if( pC->nHdrParsed<=p2 ){
 1.69484 +    /* If there is more header available for parsing in the record, try
 1.69485 +    ** to extract additional fields up through the p2+1-th field 
 1.69486 +    */
 1.69487 +    if( pC->iHdrOffset<aOffset[0] ){
 1.69488 +      /* Make sure zData points to enough of the record to cover the header. */
 1.69489 +      if( pC->aRow==0 ){
 1.69490 +        memset(&sMem, 0, sizeof(sMem));
 1.69491 +        rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0], 
 1.69492 +                                     !pC->isTable, &sMem);
 1.69493 +        if( rc!=SQLITE_OK ){
 1.69494 +          goto op_column_error;
 1.69495 +        }
 1.69496 +        zData = (u8*)sMem.z;
 1.69497 +      }else{
 1.69498 +        zData = pC->aRow;
 1.69499 +      }
 1.69500 +  
 1.69501 +      /* Fill in aType[i] and aOffset[i] values through the p2-th field. */
 1.69502 +      i = pC->nHdrParsed;
 1.69503 +      offset = aOffset[i];
 1.69504 +      zHdr = zData + pC->iHdrOffset;
 1.69505 +      zEndHdr = zData + aOffset[0];
 1.69506 +      assert( i<=p2 && zHdr<zEndHdr );
 1.69507 +      do{
 1.69508 +        if( zHdr[0]<0x80 ){
 1.69509 +          t = zHdr[0];
 1.69510 +          zHdr++;
 1.69511 +        }else{
 1.69512 +          zHdr += sqlite3GetVarint32(zHdr, &t);
 1.69513 +        }
 1.69514 +        aType[i] = t;
 1.69515 +        szField = sqlite3VdbeSerialTypeLen(t);
 1.69516 +        offset += szField;
 1.69517 +        if( offset<szField ){  /* True if offset overflows */
 1.69518 +          zHdr = &zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
 1.69519 +          break;
 1.69520 +        }
 1.69521 +        i++;
 1.69522 +        aOffset[i] = offset;
 1.69523 +      }while( i<=p2 && zHdr<zEndHdr );
 1.69524 +      pC->nHdrParsed = i;
 1.69525 +      pC->iHdrOffset = (u32)(zHdr - zData);
 1.69526 +      if( pC->aRow==0 ){
 1.69527 +        sqlite3VdbeMemRelease(&sMem);
 1.69528 +        sMem.flags = MEM_Null;
 1.69529 +      }
 1.69530 +  
 1.69531 +      /* If we have read more header data than was contained in the header,
 1.69532 +      ** or if the end of the last field appears to be past the end of the
 1.69533 +      ** record, or if the end of the last field appears to be before the end
 1.69534 +      ** of the record (when all fields present), then we must be dealing 
 1.69535 +      ** with a corrupt database.
 1.69536 +      */
 1.69537 +      if( (zHdr > zEndHdr)
 1.69538 +       || (offset > pC->payloadSize)
 1.69539 +       || (zHdr==zEndHdr && offset!=pC->payloadSize)
 1.69540 +      ){
 1.69541 +        rc = SQLITE_CORRUPT_BKPT;
 1.69542 +        goto op_column_error;
 1.69543 +      }
 1.69544 +    }
 1.69545 +
 1.69546 +    /* If after trying to extra new entries from the header, nHdrParsed is
 1.69547 +    ** still not up to p2, that means that the record has fewer than p2
 1.69548 +    ** columns.  So the result will be either the default value or a NULL.
 1.69549 +    */
 1.69550 +    if( pC->nHdrParsed<=p2 ){
 1.69551 +      if( pOp->p4type==P4_MEM ){
 1.69552 +        sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
 1.69553 +      }else{
 1.69554 +        MemSetTypeFlag(pDest, MEM_Null);
 1.69555 +      }
 1.69556 +      goto op_column_out;
 1.69557 +    }
 1.69558 +  }
 1.69559 +
 1.69560 +  /* Extract the content for the p2+1-th column.  Control can only
 1.69561 +  ** reach this point if aOffset[p2], aOffset[p2+1], and aType[p2] are
 1.69562 +  ** all valid.
 1.69563 +  */
 1.69564 +  assert( p2<pC->nHdrParsed );
 1.69565 +  assert( rc==SQLITE_OK );
 1.69566 +  assert( sqlite3VdbeCheckMemInvariants(pDest) );
 1.69567 +  if( pC->szRow>=aOffset[p2+1] ){
 1.69568 +    /* This is the common case where the desired content fits on the original
 1.69569 +    ** page - where the content is not on an overflow page */
 1.69570 +    VdbeMemRelease(pDest);
 1.69571 +    sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], aType[p2], pDest);
 1.69572 +  }else{
 1.69573 +    /* This branch happens only when content is on overflow pages */
 1.69574 +    t = aType[p2];
 1.69575 +    if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
 1.69576 +          && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
 1.69577 +     || (len = sqlite3VdbeSerialTypeLen(t))==0
 1.69578 +    ){
 1.69579 +      /* Content is irrelevant for the typeof() function and for
 1.69580 +      ** the length(X) function if X is a blob.  So we might as well use
 1.69581 +      ** bogus content rather than reading content from disk.  NULL works
 1.69582 +      ** for text and blob and whatever is in the payloadSize64 variable
 1.69583 +      ** will work for everything else.  Content is also irrelevant if
 1.69584 +      ** the content length is 0. */
 1.69585 +      zData = t<=13 ? (u8*)&payloadSize64 : 0;
 1.69586 +      sMem.zMalloc = 0;
 1.69587 +    }else{
 1.69588 +      memset(&sMem, 0, sizeof(sMem));
 1.69589 +      sqlite3VdbeMemMove(&sMem, pDest);
 1.69590 +      rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
 1.69591 +                                   &sMem);
 1.69592 +      if( rc!=SQLITE_OK ){
 1.69593 +        goto op_column_error;
 1.69594 +      }
 1.69595 +      zData = (u8*)sMem.z;
 1.69596 +    }
 1.69597 +    sqlite3VdbeSerialGet(zData, t, pDest);
 1.69598 +    /* If we dynamically allocated space to hold the data (in the
 1.69599 +    ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
 1.69600 +    ** dynamically allocated space over to the pDest structure.
 1.69601 +    ** This prevents a memory copy. */
 1.69602 +    if( sMem.zMalloc ){
 1.69603 +      assert( sMem.z==sMem.zMalloc );
 1.69604 +      assert( VdbeMemDynamic(pDest)==0 );
 1.69605 +      assert( (pDest->flags & (MEM_Blob|MEM_Str))==0 || pDest->z==sMem.z );
 1.69606 +      pDest->flags &= ~(MEM_Ephem|MEM_Static);
 1.69607 +      pDest->flags |= MEM_Term;
 1.69608 +      pDest->z = sMem.z;
 1.69609 +      pDest->zMalloc = sMem.zMalloc;
 1.69610 +    }
 1.69611 +  }
 1.69612 +  pDest->enc = encoding;
 1.69613 +
 1.69614 +op_column_out:
 1.69615 +  Deephemeralize(pDest);
 1.69616 +op_column_error:
 1.69617 +  UPDATE_MAX_BLOBSIZE(pDest);
 1.69618 +  REGISTER_TRACE(pOp->p3, pDest);
 1.69619 +  break;
 1.69620 +}
 1.69621 +
 1.69622 +/* Opcode: Affinity P1 P2 * P4 *
 1.69623 +** Synopsis: affinity(r[P1@P2])
 1.69624 +**
 1.69625 +** Apply affinities to a range of P2 registers starting with P1.
 1.69626 +**
 1.69627 +** P4 is a string that is P2 characters long. The nth character of the
 1.69628 +** string indicates the column affinity that should be used for the nth
 1.69629 +** memory cell in the range.
 1.69630 +*/
 1.69631 +case OP_Affinity: {
 1.69632 +  const char *zAffinity;   /* The affinity to be applied */
 1.69633 +  char cAff;               /* A single character of affinity */
 1.69634 +
 1.69635 +  zAffinity = pOp->p4.z;
 1.69636 +  assert( zAffinity!=0 );
 1.69637 +  assert( zAffinity[pOp->p2]==0 );
 1.69638 +  pIn1 = &aMem[pOp->p1];
 1.69639 +  while( (cAff = *(zAffinity++))!=0 ){
 1.69640 +    assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
 1.69641 +    assert( memIsValid(pIn1) );
 1.69642 +    applyAffinity(pIn1, cAff, encoding);
 1.69643 +    pIn1++;
 1.69644 +  }
 1.69645 +  break;
 1.69646 +}
 1.69647 +
 1.69648 +/* Opcode: MakeRecord P1 P2 P3 P4 *
 1.69649 +** Synopsis: r[P3]=mkrec(r[P1@P2])
 1.69650 +**
 1.69651 +** Convert P2 registers beginning with P1 into the [record format]
 1.69652 +** use as a data record in a database table or as a key
 1.69653 +** in an index.  The OP_Column opcode can decode the record later.
 1.69654 +**
 1.69655 +** P4 may be a string that is P2 characters long.  The nth character of the
 1.69656 +** string indicates the column affinity that should be used for the nth
 1.69657 +** field of the index key.
 1.69658 +**
 1.69659 +** The mapping from character to affinity is given by the SQLITE_AFF_
 1.69660 +** macros defined in sqliteInt.h.
 1.69661 +**
 1.69662 +** If P4 is NULL then all index fields have the affinity NONE.
 1.69663 +*/
 1.69664 +case OP_MakeRecord: {
 1.69665 +  u8 *zNewRecord;        /* A buffer to hold the data for the new record */
 1.69666 +  Mem *pRec;             /* The new record */
 1.69667 +  u64 nData;             /* Number of bytes of data space */
 1.69668 +  int nHdr;              /* Number of bytes of header space */
 1.69669 +  i64 nByte;             /* Data space required for this record */
 1.69670 +  int nZero;             /* Number of zero bytes at the end of the record */
 1.69671 +  int nVarint;           /* Number of bytes in a varint */
 1.69672 +  u32 serial_type;       /* Type field */
 1.69673 +  Mem *pData0;           /* First field to be combined into the record */
 1.69674 +  Mem *pLast;            /* Last field of the record */
 1.69675 +  int nField;            /* Number of fields in the record */
 1.69676 +  char *zAffinity;       /* The affinity string for the record */
 1.69677 +  int file_format;       /* File format to use for encoding */
 1.69678 +  int i;                 /* Space used in zNewRecord[] header */
 1.69679 +  int j;                 /* Space used in zNewRecord[] content */
 1.69680 +  int len;               /* Length of a field */
 1.69681 +
 1.69682 +  /* Assuming the record contains N fields, the record format looks
 1.69683 +  ** like this:
 1.69684 +  **
 1.69685 +  ** ------------------------------------------------------------------------
 1.69686 +  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | 
 1.69687 +  ** ------------------------------------------------------------------------
 1.69688 +  **
 1.69689 +  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
 1.69690 +  ** and so froth.
 1.69691 +  **
 1.69692 +  ** Each type field is a varint representing the serial type of the 
 1.69693 +  ** corresponding data element (see sqlite3VdbeSerialType()). The
 1.69694 +  ** hdr-size field is also a varint which is the offset from the beginning
 1.69695 +  ** of the record to data0.
 1.69696 +  */
 1.69697 +  nData = 0;         /* Number of bytes of data space */
 1.69698 +  nHdr = 0;          /* Number of bytes of header space */
 1.69699 +  nZero = 0;         /* Number of zero bytes at the end of the record */
 1.69700 +  nField = pOp->p1;
 1.69701 +  zAffinity = pOp->p4.z;
 1.69702 +  assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
 1.69703 +  pData0 = &aMem[nField];
 1.69704 +  nField = pOp->p2;
 1.69705 +  pLast = &pData0[nField-1];
 1.69706 +  file_format = p->minWriteFileFormat;
 1.69707 +
 1.69708 +  /* Identify the output register */
 1.69709 +  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
 1.69710 +  pOut = &aMem[pOp->p3];
 1.69711 +  memAboutToChange(p, pOut);
 1.69712 +
 1.69713 +  /* Apply the requested affinity to all inputs
 1.69714 +  */
 1.69715 +  assert( pData0<=pLast );
 1.69716 +  if( zAffinity ){
 1.69717 +    pRec = pData0;
 1.69718 +    do{
 1.69719 +      applyAffinity(pRec++, *(zAffinity++), encoding);
 1.69720 +      assert( zAffinity[0]==0 || pRec<=pLast );
 1.69721 +    }while( zAffinity[0] );
 1.69722 +  }
 1.69723 +
 1.69724 +  /* Loop through the elements that will make up the record to figure
 1.69725 +  ** out how much space is required for the new record.
 1.69726 +  */
 1.69727 +  pRec = pLast;
 1.69728 +  do{
 1.69729 +    assert( memIsValid(pRec) );
 1.69730 +    serial_type = sqlite3VdbeSerialType(pRec, file_format);
 1.69731 +    len = sqlite3VdbeSerialTypeLen(serial_type);
 1.69732 +    if( pRec->flags & MEM_Zero ){
 1.69733 +      if( nData ){
 1.69734 +        sqlite3VdbeMemExpandBlob(pRec);
 1.69735 +      }else{
 1.69736 +        nZero += pRec->u.nZero;
 1.69737 +        len -= pRec->u.nZero;
 1.69738 +      }
 1.69739 +    }
 1.69740 +    nData += len;
 1.69741 +    testcase( serial_type==127 );
 1.69742 +    testcase( serial_type==128 );
 1.69743 +    nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
 1.69744 +  }while( (--pRec)>=pData0 );
 1.69745 +
 1.69746 +  /* Add the initial header varint and total the size */
 1.69747 +  testcase( nHdr==126 );
 1.69748 +  testcase( nHdr==127 );
 1.69749 +  if( nHdr<=126 ){
 1.69750 +    /* The common case */
 1.69751 +    nHdr += 1;
 1.69752 +  }else{
 1.69753 +    /* Rare case of a really large header */
 1.69754 +    nVarint = sqlite3VarintLen(nHdr);
 1.69755 +    nHdr += nVarint;
 1.69756 +    if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
 1.69757 +  }
 1.69758 +  nByte = nHdr+nData;
 1.69759 +  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
 1.69760 +    goto too_big;
 1.69761 +  }
 1.69762 +
 1.69763 +  /* Make sure the output register has a buffer large enough to store 
 1.69764 +  ** the new record. The output register (pOp->p3) is not allowed to
 1.69765 +  ** be one of the input registers (because the following call to
 1.69766 +  ** sqlite3VdbeMemGrow() could clobber the value before it is used).
 1.69767 +  */
 1.69768 +  if( sqlite3VdbeMemGrow(pOut, (int)nByte, 0) ){
 1.69769 +    goto no_mem;
 1.69770 +  }
 1.69771 +  zNewRecord = (u8 *)pOut->z;
 1.69772 +
 1.69773 +  /* Write the record */
 1.69774 +  i = putVarint32(zNewRecord, nHdr);
 1.69775 +  j = nHdr;
 1.69776 +  assert( pData0<=pLast );
 1.69777 +  pRec = pData0;
 1.69778 +  do{
 1.69779 +    serial_type = sqlite3VdbeSerialType(pRec, file_format);
 1.69780 +    i += putVarint32(&zNewRecord[i], serial_type);            /* serial type */
 1.69781 +    j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
 1.69782 +  }while( (++pRec)<=pLast );
 1.69783 +  assert( i==nHdr );
 1.69784 +  assert( j==nByte );
 1.69785 +
 1.69786 +  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
 1.69787 +  pOut->n = (int)nByte;
 1.69788 +  pOut->flags = MEM_Blob;
 1.69789 +  pOut->xDel = 0;
 1.69790 +  if( nZero ){
 1.69791 +    pOut->u.nZero = nZero;
 1.69792 +    pOut->flags |= MEM_Zero;
 1.69793 +  }
 1.69794 +  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
 1.69795 +  REGISTER_TRACE(pOp->p3, pOut);
 1.69796 +  UPDATE_MAX_BLOBSIZE(pOut);
 1.69797 +  break;
 1.69798 +}
 1.69799 +
 1.69800 +/* Opcode: Count P1 P2 * * *
 1.69801 +** Synopsis: r[P2]=count()
 1.69802 +**
 1.69803 +** Store the number of entries (an integer value) in the table or index 
 1.69804 +** opened by cursor P1 in register P2
 1.69805 +*/
 1.69806 +#ifndef SQLITE_OMIT_BTREECOUNT
 1.69807 +case OP_Count: {         /* out2-prerelease */
 1.69808 +  i64 nEntry;
 1.69809 +  BtCursor *pCrsr;
 1.69810 +
 1.69811 +  pCrsr = p->apCsr[pOp->p1]->pCursor;
 1.69812 +  assert( pCrsr );
 1.69813 +  nEntry = 0;  /* Not needed.  Only used to silence a warning. */
 1.69814 +  rc = sqlite3BtreeCount(pCrsr, &nEntry);
 1.69815 +  pOut->u.i = nEntry;
 1.69816 +  break;
 1.69817 +}
 1.69818 +#endif
 1.69819 +
 1.69820 +/* Opcode: Savepoint P1 * * P4 *
 1.69821 +**
 1.69822 +** Open, release or rollback the savepoint named by parameter P4, depending
 1.69823 +** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
 1.69824 +** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
 1.69825 +*/
 1.69826 +case OP_Savepoint: {
 1.69827 +  int p1;                         /* Value of P1 operand */
 1.69828 +  char *zName;                    /* Name of savepoint */
 1.69829 +  int nName;
 1.69830 +  Savepoint *pNew;
 1.69831 +  Savepoint *pSavepoint;
 1.69832 +  Savepoint *pTmp;
 1.69833 +  int iSavepoint;
 1.69834 +  int ii;
 1.69835 +
 1.69836 +  p1 = pOp->p1;
 1.69837 +  zName = pOp->p4.z;
 1.69838 +
 1.69839 +  /* Assert that the p1 parameter is valid. Also that if there is no open
 1.69840 +  ** transaction, then there cannot be any savepoints. 
 1.69841 +  */
 1.69842 +  assert( db->pSavepoint==0 || db->autoCommit==0 );
 1.69843 +  assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
 1.69844 +  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
 1.69845 +  assert( checkSavepointCount(db) );
 1.69846 +  assert( p->bIsReader );
 1.69847 +
 1.69848 +  if( p1==SAVEPOINT_BEGIN ){
 1.69849 +    if( db->nVdbeWrite>0 ){
 1.69850 +      /* A new savepoint cannot be created if there are active write 
 1.69851 +      ** statements (i.e. open read/write incremental blob handles).
 1.69852 +      */
 1.69853 +      sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
 1.69854 +        "SQL statements in progress");
 1.69855 +      rc = SQLITE_BUSY;
 1.69856 +    }else{
 1.69857 +      nName = sqlite3Strlen30(zName);
 1.69858 +
 1.69859 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.69860 +      /* This call is Ok even if this savepoint is actually a transaction
 1.69861 +      ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
 1.69862 +      ** If this is a transaction savepoint being opened, it is guaranteed
 1.69863 +      ** that the db->aVTrans[] array is empty.  */
 1.69864 +      assert( db->autoCommit==0 || db->nVTrans==0 );
 1.69865 +      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
 1.69866 +                                db->nStatement+db->nSavepoint);
 1.69867 +      if( rc!=SQLITE_OK ) goto abort_due_to_error;
 1.69868 +#endif
 1.69869 +
 1.69870 +      /* Create a new savepoint structure. */
 1.69871 +      pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
 1.69872 +      if( pNew ){
 1.69873 +        pNew->zName = (char *)&pNew[1];
 1.69874 +        memcpy(pNew->zName, zName, nName+1);
 1.69875 +    
 1.69876 +        /* If there is no open transaction, then mark this as a special
 1.69877 +        ** "transaction savepoint". */
 1.69878 +        if( db->autoCommit ){
 1.69879 +          db->autoCommit = 0;
 1.69880 +          db->isTransactionSavepoint = 1;
 1.69881 +        }else{
 1.69882 +          db->nSavepoint++;
 1.69883 +        }
 1.69884 +    
 1.69885 +        /* Link the new savepoint into the database handle's list. */
 1.69886 +        pNew->pNext = db->pSavepoint;
 1.69887 +        db->pSavepoint = pNew;
 1.69888 +        pNew->nDeferredCons = db->nDeferredCons;
 1.69889 +        pNew->nDeferredImmCons = db->nDeferredImmCons;
 1.69890 +      }
 1.69891 +    }
 1.69892 +  }else{
 1.69893 +    iSavepoint = 0;
 1.69894 +
 1.69895 +    /* Find the named savepoint. If there is no such savepoint, then an
 1.69896 +    ** an error is returned to the user.  */
 1.69897 +    for(
 1.69898 +      pSavepoint = db->pSavepoint; 
 1.69899 +      pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
 1.69900 +      pSavepoint = pSavepoint->pNext
 1.69901 +    ){
 1.69902 +      iSavepoint++;
 1.69903 +    }
 1.69904 +    if( !pSavepoint ){
 1.69905 +      sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName);
 1.69906 +      rc = SQLITE_ERROR;
 1.69907 +    }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
 1.69908 +      /* It is not possible to release (commit) a savepoint if there are 
 1.69909 +      ** active write statements.
 1.69910 +      */
 1.69911 +      sqlite3SetString(&p->zErrMsg, db, 
 1.69912 +        "cannot release savepoint - SQL statements in progress"
 1.69913 +      );
 1.69914 +      rc = SQLITE_BUSY;
 1.69915 +    }else{
 1.69916 +
 1.69917 +      /* Determine whether or not this is a transaction savepoint. If so,
 1.69918 +      ** and this is a RELEASE command, then the current transaction 
 1.69919 +      ** is committed. 
 1.69920 +      */
 1.69921 +      int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
 1.69922 +      if( isTransaction && p1==SAVEPOINT_RELEASE ){
 1.69923 +        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
 1.69924 +          goto vdbe_return;
 1.69925 +        }
 1.69926 +        db->autoCommit = 1;
 1.69927 +        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
 1.69928 +          p->pc = pc;
 1.69929 +          db->autoCommit = 0;
 1.69930 +          p->rc = rc = SQLITE_BUSY;
 1.69931 +          goto vdbe_return;
 1.69932 +        }
 1.69933 +        db->isTransactionSavepoint = 0;
 1.69934 +        rc = p->rc;
 1.69935 +      }else{
 1.69936 +        iSavepoint = db->nSavepoint - iSavepoint - 1;
 1.69937 +        if( p1==SAVEPOINT_ROLLBACK ){
 1.69938 +          for(ii=0; ii<db->nDb; ii++){
 1.69939 +            sqlite3BtreeTripAllCursors(db->aDb[ii].pBt, SQLITE_ABORT);
 1.69940 +          }
 1.69941 +        }
 1.69942 +        for(ii=0; ii<db->nDb; ii++){
 1.69943 +          rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
 1.69944 +          if( rc!=SQLITE_OK ){
 1.69945 +            goto abort_due_to_error;
 1.69946 +          }
 1.69947 +        }
 1.69948 +        if( p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
 1.69949 +          sqlite3ExpirePreparedStatements(db);
 1.69950 +          sqlite3ResetAllSchemasOfConnection(db);
 1.69951 +          db->flags = (db->flags | SQLITE_InternChanges);
 1.69952 +        }
 1.69953 +      }
 1.69954 +  
 1.69955 +      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all 
 1.69956 +      ** savepoints nested inside of the savepoint being operated on. */
 1.69957 +      while( db->pSavepoint!=pSavepoint ){
 1.69958 +        pTmp = db->pSavepoint;
 1.69959 +        db->pSavepoint = pTmp->pNext;
 1.69960 +        sqlite3DbFree(db, pTmp);
 1.69961 +        db->nSavepoint--;
 1.69962 +      }
 1.69963 +
 1.69964 +      /* If it is a RELEASE, then destroy the savepoint being operated on 
 1.69965 +      ** too. If it is a ROLLBACK TO, then set the number of deferred 
 1.69966 +      ** constraint violations present in the database to the value stored
 1.69967 +      ** when the savepoint was created.  */
 1.69968 +      if( p1==SAVEPOINT_RELEASE ){
 1.69969 +        assert( pSavepoint==db->pSavepoint );
 1.69970 +        db->pSavepoint = pSavepoint->pNext;
 1.69971 +        sqlite3DbFree(db, pSavepoint);
 1.69972 +        if( !isTransaction ){
 1.69973 +          db->nSavepoint--;
 1.69974 +        }
 1.69975 +      }else{
 1.69976 +        db->nDeferredCons = pSavepoint->nDeferredCons;
 1.69977 +        db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
 1.69978 +      }
 1.69979 +
 1.69980 +      if( !isTransaction ){
 1.69981 +        rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
 1.69982 +        if( rc!=SQLITE_OK ) goto abort_due_to_error;
 1.69983 +      }
 1.69984 +    }
 1.69985 +  }
 1.69986 +
 1.69987 +  break;
 1.69988 +}
 1.69989 +
 1.69990 +/* Opcode: AutoCommit P1 P2 * * *
 1.69991 +**
 1.69992 +** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
 1.69993 +** back any currently active btree transactions. If there are any active
 1.69994 +** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
 1.69995 +** there are active writing VMs or active VMs that use shared cache.
 1.69996 +**
 1.69997 +** This instruction causes the VM to halt.
 1.69998 +*/
 1.69999 +case OP_AutoCommit: {
 1.70000 +  int desiredAutoCommit;
 1.70001 +  int iRollback;
 1.70002 +  int turnOnAC;
 1.70003 +
 1.70004 +  desiredAutoCommit = pOp->p1;
 1.70005 +  iRollback = pOp->p2;
 1.70006 +  turnOnAC = desiredAutoCommit && !db->autoCommit;
 1.70007 +  assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
 1.70008 +  assert( desiredAutoCommit==1 || iRollback==0 );
 1.70009 +  assert( db->nVdbeActive>0 );  /* At least this one VM is active */
 1.70010 +  assert( p->bIsReader );
 1.70011 +
 1.70012 +#if 0
 1.70013 +  if( turnOnAC && iRollback && db->nVdbeActive>1 ){
 1.70014 +    /* If this instruction implements a ROLLBACK and other VMs are
 1.70015 +    ** still running, and a transaction is active, return an error indicating
 1.70016 +    ** that the other VMs must complete first. 
 1.70017 +    */
 1.70018 +    sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
 1.70019 +        "SQL statements in progress");
 1.70020 +    rc = SQLITE_BUSY;
 1.70021 +  }else
 1.70022 +#endif
 1.70023 +  if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){
 1.70024 +    /* If this instruction implements a COMMIT and other VMs are writing
 1.70025 +    ** return an error indicating that the other VMs must complete first. 
 1.70026 +    */
 1.70027 +    sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
 1.70028 +        "SQL statements in progress");
 1.70029 +    rc = SQLITE_BUSY;
 1.70030 +  }else if( desiredAutoCommit!=db->autoCommit ){
 1.70031 +    if( iRollback ){
 1.70032 +      assert( desiredAutoCommit==1 );
 1.70033 +      sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
 1.70034 +      db->autoCommit = 1;
 1.70035 +    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
 1.70036 +      goto vdbe_return;
 1.70037 +    }else{
 1.70038 +      db->autoCommit = (u8)desiredAutoCommit;
 1.70039 +      if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
 1.70040 +        p->pc = pc;
 1.70041 +        db->autoCommit = (u8)(1-desiredAutoCommit);
 1.70042 +        p->rc = rc = SQLITE_BUSY;
 1.70043 +        goto vdbe_return;
 1.70044 +      }
 1.70045 +    }
 1.70046 +    assert( db->nStatement==0 );
 1.70047 +    sqlite3CloseSavepoints(db);
 1.70048 +    if( p->rc==SQLITE_OK ){
 1.70049 +      rc = SQLITE_DONE;
 1.70050 +    }else{
 1.70051 +      rc = SQLITE_ERROR;
 1.70052 +    }
 1.70053 +    goto vdbe_return;
 1.70054 +  }else{
 1.70055 +    sqlite3SetString(&p->zErrMsg, db,
 1.70056 +        (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
 1.70057 +        (iRollback)?"cannot rollback - no transaction is active":
 1.70058 +                   "cannot commit - no transaction is active"));
 1.70059 +         
 1.70060 +    rc = SQLITE_ERROR;
 1.70061 +  }
 1.70062 +  break;
 1.70063 +}
 1.70064 +
 1.70065 +/* Opcode: Transaction P1 P2 P3 P4 P5
 1.70066 +**
 1.70067 +** Begin a transaction on database P1 if a transaction is not already
 1.70068 +** active.
 1.70069 +** If P2 is non-zero, then a write-transaction is started, or if a 
 1.70070 +** read-transaction is already active, it is upgraded to a write-transaction.
 1.70071 +** If P2 is zero, then a read-transaction is started.
 1.70072 +**
 1.70073 +** P1 is the index of the database file on which the transaction is
 1.70074 +** started.  Index 0 is the main database file and index 1 is the
 1.70075 +** file used for temporary tables.  Indices of 2 or more are used for
 1.70076 +** attached databases.
 1.70077 +**
 1.70078 +** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
 1.70079 +** true (this flag is set if the Vdbe may modify more than one row and may
 1.70080 +** throw an ABORT exception), a statement transaction may also be opened.
 1.70081 +** More specifically, a statement transaction is opened iff the database
 1.70082 +** connection is currently not in autocommit mode, or if there are other
 1.70083 +** active statements. A statement transaction allows the changes made by this
 1.70084 +** VDBE to be rolled back after an error without having to roll back the
 1.70085 +** entire transaction. If no error is encountered, the statement transaction
 1.70086 +** will automatically commit when the VDBE halts.
 1.70087 +**
 1.70088 +** If P5!=0 then this opcode also checks the schema cookie against P3
 1.70089 +** and the schema generation counter against P4.
 1.70090 +** The cookie changes its value whenever the database schema changes.
 1.70091 +** This operation is used to detect when that the cookie has changed
 1.70092 +** and that the current process needs to reread the schema.  If the schema
 1.70093 +** cookie in P3 differs from the schema cookie in the database header or
 1.70094 +** if the schema generation counter in P4 differs from the current
 1.70095 +** generation counter, then an SQLITE_SCHEMA error is raised and execution
 1.70096 +** halts.  The sqlite3_step() wrapper function might then reprepare the
 1.70097 +** statement and rerun it from the beginning.
 1.70098 +*/
 1.70099 +case OP_Transaction: {
 1.70100 +  Btree *pBt;
 1.70101 +  int iMeta;
 1.70102 +  int iGen;
 1.70103 +
 1.70104 +  assert( p->bIsReader );
 1.70105 +  assert( p->readOnly==0 || pOp->p2==0 );
 1.70106 +  assert( pOp->p1>=0 && pOp->p1<db->nDb );
 1.70107 +  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
 1.70108 +  if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
 1.70109 +    rc = SQLITE_READONLY;
 1.70110 +    goto abort_due_to_error;
 1.70111 +  }
 1.70112 +  pBt = db->aDb[pOp->p1].pBt;
 1.70113 +
 1.70114 +  if( pBt ){
 1.70115 +    rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
 1.70116 +    if( rc==SQLITE_BUSY ){
 1.70117 +      p->pc = pc;
 1.70118 +      p->rc = rc = SQLITE_BUSY;
 1.70119 +      goto vdbe_return;
 1.70120 +    }
 1.70121 +    if( rc!=SQLITE_OK ){
 1.70122 +      goto abort_due_to_error;
 1.70123 +    }
 1.70124 +
 1.70125 +    if( pOp->p2 && p->usesStmtJournal 
 1.70126 +     && (db->autoCommit==0 || db->nVdbeRead>1) 
 1.70127 +    ){
 1.70128 +      assert( sqlite3BtreeIsInTrans(pBt) );
 1.70129 +      if( p->iStatement==0 ){
 1.70130 +        assert( db->nStatement>=0 && db->nSavepoint>=0 );
 1.70131 +        db->nStatement++; 
 1.70132 +        p->iStatement = db->nSavepoint + db->nStatement;
 1.70133 +      }
 1.70134 +
 1.70135 +      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
 1.70136 +      if( rc==SQLITE_OK ){
 1.70137 +        rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
 1.70138 +      }
 1.70139 +
 1.70140 +      /* Store the current value of the database handles deferred constraint
 1.70141 +      ** counter. If the statement transaction needs to be rolled back,
 1.70142 +      ** the value of this counter needs to be restored too.  */
 1.70143 +      p->nStmtDefCons = db->nDeferredCons;
 1.70144 +      p->nStmtDefImmCons = db->nDeferredImmCons;
 1.70145 +    }
 1.70146 +
 1.70147 +    /* Gather the schema version number for checking */
 1.70148 +    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
 1.70149 +    iGen = db->aDb[pOp->p1].pSchema->iGeneration;
 1.70150 +  }else{
 1.70151 +    iGen = iMeta = 0;
 1.70152 +  }
 1.70153 +  assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
 1.70154 +  if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
 1.70155 +    sqlite3DbFree(db, p->zErrMsg);
 1.70156 +    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
 1.70157 +    /* If the schema-cookie from the database file matches the cookie 
 1.70158 +    ** stored with the in-memory representation of the schema, do
 1.70159 +    ** not reload the schema from the database file.
 1.70160 +    **
 1.70161 +    ** If virtual-tables are in use, this is not just an optimization.
 1.70162 +    ** Often, v-tables store their data in other SQLite tables, which
 1.70163 +    ** are queried from within xNext() and other v-table methods using
 1.70164 +    ** prepared queries. If such a query is out-of-date, we do not want to
 1.70165 +    ** discard the database schema, as the user code implementing the
 1.70166 +    ** v-table would have to be ready for the sqlite3_vtab structure itself
 1.70167 +    ** to be invalidated whenever sqlite3_step() is called from within 
 1.70168 +    ** a v-table method.
 1.70169 +    */
 1.70170 +    if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
 1.70171 +      sqlite3ResetOneSchema(db, pOp->p1);
 1.70172 +    }
 1.70173 +    p->expired = 1;
 1.70174 +    rc = SQLITE_SCHEMA;
 1.70175 +  }
 1.70176 +  break;
 1.70177 +}
 1.70178 +
 1.70179 +/* Opcode: ReadCookie P1 P2 P3 * *
 1.70180 +**
 1.70181 +** Read cookie number P3 from database P1 and write it into register P2.
 1.70182 +** P3==1 is the schema version.  P3==2 is the database format.
 1.70183 +** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
 1.70184 +** the main database file and P1==1 is the database file used to store
 1.70185 +** temporary tables.
 1.70186 +**
 1.70187 +** There must be a read-lock on the database (either a transaction
 1.70188 +** must be started or there must be an open cursor) before
 1.70189 +** executing this instruction.
 1.70190 +*/
 1.70191 +case OP_ReadCookie: {               /* out2-prerelease */
 1.70192 +  int iMeta;
 1.70193 +  int iDb;
 1.70194 +  int iCookie;
 1.70195 +
 1.70196 +  assert( p->bIsReader );
 1.70197 +  iDb = pOp->p1;
 1.70198 +  iCookie = pOp->p3;
 1.70199 +  assert( pOp->p3<SQLITE_N_BTREE_META );
 1.70200 +  assert( iDb>=0 && iDb<db->nDb );
 1.70201 +  assert( db->aDb[iDb].pBt!=0 );
 1.70202 +  assert( (p->btreeMask & (((yDbMask)1)<<iDb))!=0 );
 1.70203 +
 1.70204 +  sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
 1.70205 +  pOut->u.i = iMeta;
 1.70206 +  break;
 1.70207 +}
 1.70208 +
 1.70209 +/* Opcode: SetCookie P1 P2 P3 * *
 1.70210 +**
 1.70211 +** Write the content of register P3 (interpreted as an integer)
 1.70212 +** into cookie number P2 of database P1.  P2==1 is the schema version.  
 1.70213 +** P2==2 is the database format. P2==3 is the recommended pager cache 
 1.70214 +** size, and so forth.  P1==0 is the main database file and P1==1 is the 
 1.70215 +** database file used to store temporary tables.
 1.70216 +**
 1.70217 +** A transaction must be started before executing this opcode.
 1.70218 +*/
 1.70219 +case OP_SetCookie: {       /* in3 */
 1.70220 +  Db *pDb;
 1.70221 +  assert( pOp->p2<SQLITE_N_BTREE_META );
 1.70222 +  assert( pOp->p1>=0 && pOp->p1<db->nDb );
 1.70223 +  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
 1.70224 +  assert( p->readOnly==0 );
 1.70225 +  pDb = &db->aDb[pOp->p1];
 1.70226 +  assert( pDb->pBt!=0 );
 1.70227 +  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
 1.70228 +  pIn3 = &aMem[pOp->p3];
 1.70229 +  sqlite3VdbeMemIntegerify(pIn3);
 1.70230 +  /* See note about index shifting on OP_ReadCookie */
 1.70231 +  rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
 1.70232 +  if( pOp->p2==BTREE_SCHEMA_VERSION ){
 1.70233 +    /* When the schema cookie changes, record the new cookie internally */
 1.70234 +    pDb->pSchema->schema_cookie = (int)pIn3->u.i;
 1.70235 +    db->flags |= SQLITE_InternChanges;
 1.70236 +  }else if( pOp->p2==BTREE_FILE_FORMAT ){
 1.70237 +    /* Record changes in the file format */
 1.70238 +    pDb->pSchema->file_format = (u8)pIn3->u.i;
 1.70239 +  }
 1.70240 +  if( pOp->p1==1 ){
 1.70241 +    /* Invalidate all prepared statements whenever the TEMP database
 1.70242 +    ** schema is changed.  Ticket #1644 */
 1.70243 +    sqlite3ExpirePreparedStatements(db);
 1.70244 +    p->expired = 0;
 1.70245 +  }
 1.70246 +  break;
 1.70247 +}
 1.70248 +
 1.70249 +/* Opcode: OpenRead P1 P2 P3 P4 P5
 1.70250 +** Synopsis: root=P2 iDb=P3
 1.70251 +**
 1.70252 +** Open a read-only cursor for the database table whose root page is
 1.70253 +** P2 in a database file.  The database file is determined by P3. 
 1.70254 +** P3==0 means the main database, P3==1 means the database used for 
 1.70255 +** temporary tables, and P3>1 means used the corresponding attached
 1.70256 +** database.  Give the new cursor an identifier of P1.  The P1
 1.70257 +** values need not be contiguous but all P1 values should be small integers.
 1.70258 +** It is an error for P1 to be negative.
 1.70259 +**
 1.70260 +** If P5!=0 then use the content of register P2 as the root page, not
 1.70261 +** the value of P2 itself.
 1.70262 +**
 1.70263 +** There will be a read lock on the database whenever there is an
 1.70264 +** open cursor.  If the database was unlocked prior to this instruction
 1.70265 +** then a read lock is acquired as part of this instruction.  A read
 1.70266 +** lock allows other processes to read the database but prohibits
 1.70267 +** any other process from modifying the database.  The read lock is
 1.70268 +** released when all cursors are closed.  If this instruction attempts
 1.70269 +** to get a read lock but fails, the script terminates with an
 1.70270 +** SQLITE_BUSY error code.
 1.70271 +**
 1.70272 +** The P4 value may be either an integer (P4_INT32) or a pointer to
 1.70273 +** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
 1.70274 +** structure, then said structure defines the content and collating 
 1.70275 +** sequence of the index being opened. Otherwise, if P4 is an integer 
 1.70276 +** value, it is set to the number of columns in the table.
 1.70277 +**
 1.70278 +** See also OpenWrite.
 1.70279 +*/
 1.70280 +/* Opcode: OpenWrite P1 P2 P3 P4 P5
 1.70281 +** Synopsis: root=P2 iDb=P3
 1.70282 +**
 1.70283 +** Open a read/write cursor named P1 on the table or index whose root
 1.70284 +** page is P2.  Or if P5!=0 use the content of register P2 to find the
 1.70285 +** root page.
 1.70286 +**
 1.70287 +** The P4 value may be either an integer (P4_INT32) or a pointer to
 1.70288 +** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
 1.70289 +** structure, then said structure defines the content and collating 
 1.70290 +** sequence of the index being opened. Otherwise, if P4 is an integer 
 1.70291 +** value, it is set to the number of columns in the table, or to the
 1.70292 +** largest index of any column of the table that is actually used.
 1.70293 +**
 1.70294 +** This instruction works just like OpenRead except that it opens the cursor
 1.70295 +** in read/write mode.  For a given table, there can be one or more read-only
 1.70296 +** cursors or a single read/write cursor but not both.
 1.70297 +**
 1.70298 +** See also OpenRead.
 1.70299 +*/
 1.70300 +case OP_OpenRead:
 1.70301 +case OP_OpenWrite: {
 1.70302 +  int nField;
 1.70303 +  KeyInfo *pKeyInfo;
 1.70304 +  int p2;
 1.70305 +  int iDb;
 1.70306 +  int wrFlag;
 1.70307 +  Btree *pX;
 1.70308 +  VdbeCursor *pCur;
 1.70309 +  Db *pDb;
 1.70310 +
 1.70311 +  assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
 1.70312 +  assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
 1.70313 +  assert( p->bIsReader );
 1.70314 +  assert( pOp->opcode==OP_OpenRead || p->readOnly==0 );
 1.70315 +
 1.70316 +  if( p->expired ){
 1.70317 +    rc = SQLITE_ABORT;
 1.70318 +    break;
 1.70319 +  }
 1.70320 +
 1.70321 +  nField = 0;
 1.70322 +  pKeyInfo = 0;
 1.70323 +  p2 = pOp->p2;
 1.70324 +  iDb = pOp->p3;
 1.70325 +  assert( iDb>=0 && iDb<db->nDb );
 1.70326 +  assert( (p->btreeMask & (((yDbMask)1)<<iDb))!=0 );
 1.70327 +  pDb = &db->aDb[iDb];
 1.70328 +  pX = pDb->pBt;
 1.70329 +  assert( pX!=0 );
 1.70330 +  if( pOp->opcode==OP_OpenWrite ){
 1.70331 +    wrFlag = 1;
 1.70332 +    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 1.70333 +    if( pDb->pSchema->file_format < p->minWriteFileFormat ){
 1.70334 +      p->minWriteFileFormat = pDb->pSchema->file_format;
 1.70335 +    }
 1.70336 +  }else{
 1.70337 +    wrFlag = 0;
 1.70338 +  }
 1.70339 +  if( pOp->p5 & OPFLAG_P2ISREG ){
 1.70340 +    assert( p2>0 );
 1.70341 +    assert( p2<=(p->nMem-p->nCursor) );
 1.70342 +    pIn2 = &aMem[p2];
 1.70343 +    assert( memIsValid(pIn2) );
 1.70344 +    assert( (pIn2->flags & MEM_Int)!=0 );
 1.70345 +    sqlite3VdbeMemIntegerify(pIn2);
 1.70346 +    p2 = (int)pIn2->u.i;
 1.70347 +    /* The p2 value always comes from a prior OP_CreateTable opcode and
 1.70348 +    ** that opcode will always set the p2 value to 2 or more or else fail.
 1.70349 +    ** If there were a failure, the prepared statement would have halted
 1.70350 +    ** before reaching this instruction. */
 1.70351 +    if( NEVER(p2<2) ) {
 1.70352 +      rc = SQLITE_CORRUPT_BKPT;
 1.70353 +      goto abort_due_to_error;
 1.70354 +    }
 1.70355 +  }
 1.70356 +  if( pOp->p4type==P4_KEYINFO ){
 1.70357 +    pKeyInfo = pOp->p4.pKeyInfo;
 1.70358 +    assert( pKeyInfo->enc==ENC(db) );
 1.70359 +    assert( pKeyInfo->db==db );
 1.70360 +    nField = pKeyInfo->nField+pKeyInfo->nXField;
 1.70361 +  }else if( pOp->p4type==P4_INT32 ){
 1.70362 +    nField = pOp->p4.i;
 1.70363 +  }
 1.70364 +  assert( pOp->p1>=0 );
 1.70365 +  assert( nField>=0 );
 1.70366 +  testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
 1.70367 +  pCur = allocateCursor(p, pOp->p1, nField, iDb, 1);
 1.70368 +  if( pCur==0 ) goto no_mem;
 1.70369 +  pCur->nullRow = 1;
 1.70370 +  pCur->isOrdered = 1;
 1.70371 +  rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
 1.70372 +  pCur->pKeyInfo = pKeyInfo;
 1.70373 +  assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
 1.70374 +  sqlite3BtreeCursorHints(pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
 1.70375 +
 1.70376 +  /* Since it performs no memory allocation or IO, the only value that
 1.70377 +  ** sqlite3BtreeCursor() may return is SQLITE_OK. */
 1.70378 +  assert( rc==SQLITE_OK );
 1.70379 +
 1.70380 +  /* Set the VdbeCursor.isTable variable. Previous versions of
 1.70381 +  ** SQLite used to check if the root-page flags were sane at this point
 1.70382 +  ** and report database corruption if they were not, but this check has
 1.70383 +  ** since moved into the btree layer.  */  
 1.70384 +  pCur->isTable = pOp->p4type!=P4_KEYINFO;
 1.70385 +  break;
 1.70386 +}
 1.70387 +
 1.70388 +/* Opcode: OpenEphemeral P1 P2 * P4 P5
 1.70389 +** Synopsis: nColumn=P2
 1.70390 +**
 1.70391 +** Open a new cursor P1 to a transient table.
 1.70392 +** The cursor is always opened read/write even if 
 1.70393 +** the main database is read-only.  The ephemeral
 1.70394 +** table is deleted automatically when the cursor is closed.
 1.70395 +**
 1.70396 +** P2 is the number of columns in the ephemeral table.
 1.70397 +** The cursor points to a BTree table if P4==0 and to a BTree index
 1.70398 +** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
 1.70399 +** that defines the format of keys in the index.
 1.70400 +**
 1.70401 +** The P5 parameter can be a mask of the BTREE_* flags defined
 1.70402 +** in btree.h.  These flags control aspects of the operation of
 1.70403 +** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
 1.70404 +** added automatically.
 1.70405 +*/
 1.70406 +/* Opcode: OpenAutoindex P1 P2 * P4 *
 1.70407 +** Synopsis: nColumn=P2
 1.70408 +**
 1.70409 +** This opcode works the same as OP_OpenEphemeral.  It has a
 1.70410 +** different name to distinguish its use.  Tables created using
 1.70411 +** by this opcode will be used for automatically created transient
 1.70412 +** indices in joins.
 1.70413 +*/
 1.70414 +case OP_OpenAutoindex: 
 1.70415 +case OP_OpenEphemeral: {
 1.70416 +  VdbeCursor *pCx;
 1.70417 +  KeyInfo *pKeyInfo;
 1.70418 +
 1.70419 +  static const int vfsFlags = 
 1.70420 +      SQLITE_OPEN_READWRITE |
 1.70421 +      SQLITE_OPEN_CREATE |
 1.70422 +      SQLITE_OPEN_EXCLUSIVE |
 1.70423 +      SQLITE_OPEN_DELETEONCLOSE |
 1.70424 +      SQLITE_OPEN_TRANSIENT_DB;
 1.70425 +  assert( pOp->p1>=0 );
 1.70426 +  assert( pOp->p2>=0 );
 1.70427 +  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
 1.70428 +  if( pCx==0 ) goto no_mem;
 1.70429 +  pCx->nullRow = 1;
 1.70430 +  rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt, 
 1.70431 +                        BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
 1.70432 +  if( rc==SQLITE_OK ){
 1.70433 +    rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
 1.70434 +  }
 1.70435 +  if( rc==SQLITE_OK ){
 1.70436 +    /* If a transient index is required, create it by calling
 1.70437 +    ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
 1.70438 +    ** opening it. If a transient table is required, just use the
 1.70439 +    ** automatically created table with root-page 1 (an BLOB_INTKEY table).
 1.70440 +    */
 1.70441 +    if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
 1.70442 +      int pgno;
 1.70443 +      assert( pOp->p4type==P4_KEYINFO );
 1.70444 +      rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5); 
 1.70445 +      if( rc==SQLITE_OK ){
 1.70446 +        assert( pgno==MASTER_ROOT+1 );
 1.70447 +        assert( pKeyInfo->db==db );
 1.70448 +        assert( pKeyInfo->enc==ENC(db) );
 1.70449 +        pCx->pKeyInfo = pKeyInfo;
 1.70450 +        rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, pKeyInfo, pCx->pCursor);
 1.70451 +      }
 1.70452 +      pCx->isTable = 0;
 1.70453 +    }else{
 1.70454 +      rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
 1.70455 +      pCx->isTable = 1;
 1.70456 +    }
 1.70457 +  }
 1.70458 +  pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
 1.70459 +  break;
 1.70460 +}
 1.70461 +
 1.70462 +/* Opcode: SorterOpen P1 P2 * P4 *
 1.70463 +**
 1.70464 +** This opcode works like OP_OpenEphemeral except that it opens
 1.70465 +** a transient index that is specifically designed to sort large
 1.70466 +** tables using an external merge-sort algorithm.
 1.70467 +*/
 1.70468 +case OP_SorterOpen: {
 1.70469 +  VdbeCursor *pCx;
 1.70470 +
 1.70471 +  assert( pOp->p1>=0 );
 1.70472 +  assert( pOp->p2>=0 );
 1.70473 +  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
 1.70474 +  if( pCx==0 ) goto no_mem;
 1.70475 +  pCx->pKeyInfo = pOp->p4.pKeyInfo;
 1.70476 +  assert( pCx->pKeyInfo->db==db );
 1.70477 +  assert( pCx->pKeyInfo->enc==ENC(db) );
 1.70478 +  rc = sqlite3VdbeSorterInit(db, pCx);
 1.70479 +  break;
 1.70480 +}
 1.70481 +
 1.70482 +/* Opcode: OpenPseudo P1 P2 P3 * *
 1.70483 +** Synopsis: P3 columns in r[P2]
 1.70484 +**
 1.70485 +** Open a new cursor that points to a fake table that contains a single
 1.70486 +** row of data.  The content of that one row is the content of memory
 1.70487 +** register P2.  In other words, cursor P1 becomes an alias for the 
 1.70488 +** MEM_Blob content contained in register P2.
 1.70489 +**
 1.70490 +** A pseudo-table created by this opcode is used to hold a single
 1.70491 +** row output from the sorter so that the row can be decomposed into
 1.70492 +** individual columns using the OP_Column opcode.  The OP_Column opcode
 1.70493 +** is the only cursor opcode that works with a pseudo-table.
 1.70494 +**
 1.70495 +** P3 is the number of fields in the records that will be stored by
 1.70496 +** the pseudo-table.
 1.70497 +*/
 1.70498 +case OP_OpenPseudo: {
 1.70499 +  VdbeCursor *pCx;
 1.70500 +
 1.70501 +  assert( pOp->p1>=0 );
 1.70502 +  assert( pOp->p3>=0 );
 1.70503 +  pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
 1.70504 +  if( pCx==0 ) goto no_mem;
 1.70505 +  pCx->nullRow = 1;
 1.70506 +  pCx->pseudoTableReg = pOp->p2;
 1.70507 +  pCx->isTable = 1;
 1.70508 +  assert( pOp->p5==0 );
 1.70509 +  break;
 1.70510 +}
 1.70511 +
 1.70512 +/* Opcode: Close P1 * * * *
 1.70513 +**
 1.70514 +** Close a cursor previously opened as P1.  If P1 is not
 1.70515 +** currently open, this instruction is a no-op.
 1.70516 +*/
 1.70517 +case OP_Close: {
 1.70518 +  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 1.70519 +  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
 1.70520 +  p->apCsr[pOp->p1] = 0;
 1.70521 +  break;
 1.70522 +}
 1.70523 +
 1.70524 +/* Opcode: SeekGe P1 P2 P3 P4 *
 1.70525 +** Synopsis: key=r[P3@P4]
 1.70526 +**
 1.70527 +** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
 1.70528 +** use the value in register P3 as the key.  If cursor P1 refers 
 1.70529 +** to an SQL index, then P3 is the first in an array of P4 registers 
 1.70530 +** that are used as an unpacked index key. 
 1.70531 +**
 1.70532 +** Reposition cursor P1 so that  it points to the smallest entry that 
 1.70533 +** is greater than or equal to the key value. If there are no records 
 1.70534 +** greater than or equal to the key and P2 is not zero, then jump to P2.
 1.70535 +**
 1.70536 +** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
 1.70537 +*/
 1.70538 +/* Opcode: SeekGt P1 P2 P3 P4 *
 1.70539 +** Synopsis: key=r[P3@P4]
 1.70540 +**
 1.70541 +** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
 1.70542 +** use the value in register P3 as a key. If cursor P1 refers 
 1.70543 +** to an SQL index, then P3 is the first in an array of P4 registers 
 1.70544 +** that are used as an unpacked index key. 
 1.70545 +**
 1.70546 +** Reposition cursor P1 so that  it points to the smallest entry that 
 1.70547 +** is greater than the key value. If there are no records greater than 
 1.70548 +** the key and P2 is not zero, then jump to P2.
 1.70549 +**
 1.70550 +** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
 1.70551 +*/
 1.70552 +/* Opcode: SeekLt P1 P2 P3 P4 * 
 1.70553 +** Synopsis: key=r[P3@P4]
 1.70554 +**
 1.70555 +** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
 1.70556 +** use the value in register P3 as a key. If cursor P1 refers 
 1.70557 +** to an SQL index, then P3 is the first in an array of P4 registers 
 1.70558 +** that are used as an unpacked index key. 
 1.70559 +**
 1.70560 +** Reposition cursor P1 so that  it points to the largest entry that 
 1.70561 +** is less than the key value. If there are no records less than 
 1.70562 +** the key and P2 is not zero, then jump to P2.
 1.70563 +**
 1.70564 +** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
 1.70565 +*/
 1.70566 +/* Opcode: SeekLe P1 P2 P3 P4 *
 1.70567 +** Synopsis: key=r[P3@P4]
 1.70568 +**
 1.70569 +** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
 1.70570 +** use the value in register P3 as a key. If cursor P1 refers 
 1.70571 +** to an SQL index, then P3 is the first in an array of P4 registers 
 1.70572 +** that are used as an unpacked index key. 
 1.70573 +**
 1.70574 +** Reposition cursor P1 so that it points to the largest entry that 
 1.70575 +** is less than or equal to the key value. If there are no records 
 1.70576 +** less than or equal to the key and P2 is not zero, then jump to P2.
 1.70577 +**
 1.70578 +** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
 1.70579 +*/
 1.70580 +case OP_SeekLT:         /* jump, in3 */
 1.70581 +case OP_SeekLE:         /* jump, in3 */
 1.70582 +case OP_SeekGE:         /* jump, in3 */
 1.70583 +case OP_SeekGT: {       /* jump, in3 */
 1.70584 +  int res;
 1.70585 +  int oc;
 1.70586 +  VdbeCursor *pC;
 1.70587 +  UnpackedRecord r;
 1.70588 +  int nField;
 1.70589 +  i64 iKey;      /* The rowid we are to seek to */
 1.70590 +
 1.70591 +  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 1.70592 +  assert( pOp->p2!=0 );
 1.70593 +  pC = p->apCsr[pOp->p1];
 1.70594 +  assert( pC!=0 );
 1.70595 +  assert( pC->pseudoTableReg==0 );
 1.70596 +  assert( OP_SeekLE == OP_SeekLT+1 );
 1.70597 +  assert( OP_SeekGE == OP_SeekLT+2 );
 1.70598 +  assert( OP_SeekGT == OP_SeekLT+3 );
 1.70599 +  assert( pC->isOrdered );
 1.70600 +  assert( pC->pCursor!=0 );
 1.70601 +  oc = pOp->opcode;
 1.70602 +  pC->nullRow = 0;
 1.70603 +  if( pC->isTable ){
 1.70604 +    /* The input value in P3 might be of any type: integer, real, string,
 1.70605 +    ** blob, or NULL.  But it needs to be an integer before we can do
 1.70606 +    ** the seek, so covert it. */
 1.70607 +    pIn3 = &aMem[pOp->p3];
 1.70608 +    applyNumericAffinity(pIn3);
 1.70609 +    iKey = sqlite3VdbeIntValue(pIn3);
 1.70610 +    pC->rowidIsValid = 0;
 1.70611 +
 1.70612 +    /* If the P3 value could not be converted into an integer without
 1.70613 +    ** loss of information, then special processing is required... */
 1.70614 +    if( (pIn3->flags & MEM_Int)==0 ){
 1.70615 +      if( (pIn3->flags & MEM_Real)==0 ){
 1.70616 +        /* If the P3 value cannot be converted into any kind of a number,
 1.70617 +        ** then the seek is not possible, so jump to P2 */
 1.70618 +        pc = pOp->p2 - 1;  VdbeBranchTaken(1,2);
 1.70619 +        break;
 1.70620 +      }
 1.70621 +
 1.70622 +      /* If the approximation iKey is larger than the actual real search
 1.70623 +      ** term, substitute >= for > and < for <=. e.g. if the search term
 1.70624 +      ** is 4.9 and the integer approximation 5:
 1.70625 +      **
 1.70626 +      **        (x >  4.9)    ->     (x >= 5)
 1.70627 +      **        (x <= 4.9)    ->     (x <  5)
 1.70628 +      */
 1.70629 +      if( pIn3->r<(double)iKey ){
 1.70630 +        assert( OP_SeekGE==(OP_SeekGT-1) );
 1.70631 +        assert( OP_SeekLT==(OP_SeekLE-1) );
 1.70632 +        assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
 1.70633 +        if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
 1.70634 +      }
 1.70635 +
 1.70636 +      /* If the approximation iKey is smaller than the actual real search
 1.70637 +      ** term, substitute <= for < and > for >=.  */
 1.70638 +      else if( pIn3->r>(double)iKey ){
 1.70639 +        assert( OP_SeekLE==(OP_SeekLT+1) );
 1.70640 +        assert( OP_SeekGT==(OP_SeekGE+1) );
 1.70641 +        assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
 1.70642 +        if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
 1.70643 +      }
 1.70644 +    } 
 1.70645 +    rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
 1.70646 +    if( rc!=SQLITE_OK ){
 1.70647 +      goto abort_due_to_error;
 1.70648 +    }
 1.70649 +    if( res==0 ){
 1.70650 +      pC->rowidIsValid = 1;
 1.70651 +      pC->lastRowid = iKey;
 1.70652 +    }
 1.70653 +  }else{
 1.70654 +    nField = pOp->p4.i;
 1.70655 +    assert( pOp->p4type==P4_INT32 );
 1.70656 +    assert( nField>0 );
 1.70657 +    r.pKeyInfo = pC->pKeyInfo;
 1.70658 +    r.nField = (u16)nField;
 1.70659 +
 1.70660 +    /* The next line of code computes as follows, only faster:
 1.70661 +    **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
 1.70662 +    **     r.default_rc = -1;
 1.70663 +    **   }else{
 1.70664 +    **     r.default_rc = +1;
 1.70665 +    **   }
 1.70666 +    */
 1.70667 +    r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
 1.70668 +    assert( oc!=OP_SeekGT || r.default_rc==-1 );
 1.70669 +    assert( oc!=OP_SeekLE || r.default_rc==-1 );
 1.70670 +    assert( oc!=OP_SeekGE || r.default_rc==+1 );
 1.70671 +    assert( oc!=OP_SeekLT || r.default_rc==+1 );
 1.70672 +
 1.70673 +    r.aMem = &aMem[pOp->p3];
 1.70674 +#ifdef SQLITE_DEBUG
 1.70675 +    { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
 1.70676 +#endif
 1.70677 +    ExpandBlob(r.aMem);
 1.70678 +    rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
 1.70679 +    if( rc!=SQLITE_OK ){
 1.70680 +      goto abort_due_to_error;
 1.70681 +    }
 1.70682 +    pC->rowidIsValid = 0;
 1.70683 +  }
 1.70684 +  pC->deferredMoveto = 0;
 1.70685 +  pC->cacheStatus = CACHE_STALE;
 1.70686 +#ifdef SQLITE_TEST
 1.70687 +  sqlite3_search_count++;
 1.70688 +#endif
 1.70689 +  if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
 1.70690 +    if( res<0 || (res==0 && oc==OP_SeekGT) ){
 1.70691 +      res = 0;
 1.70692 +      rc = sqlite3BtreeNext(pC->pCursor, &res);
 1.70693 +      if( rc!=SQLITE_OK ) goto abort_due_to_error;
 1.70694 +      pC->rowidIsValid = 0;
 1.70695 +    }else{
 1.70696 +      res = 0;
 1.70697 +    }
 1.70698 +  }else{
 1.70699 +    assert( oc==OP_SeekLT || oc==OP_SeekLE );
 1.70700 +    if( res>0 || (res==0 && oc==OP_SeekLT) ){
 1.70701 +      res = 0;
 1.70702 +      rc = sqlite3BtreePrevious(pC->pCursor, &res);
 1.70703 +      if( rc!=SQLITE_OK ) goto abort_due_to_error;
 1.70704 +      pC->rowidIsValid = 0;
 1.70705 +    }else{
 1.70706 +      /* res might be negative because the table is empty.  Check to
 1.70707 +      ** see if this is the case.
 1.70708 +      */
 1.70709 +      res = sqlite3BtreeEof(pC->pCursor);
 1.70710 +    }
 1.70711 +  }
 1.70712 +  assert( pOp->p2>0 );
 1.70713 +  VdbeBranchTaken(res!=0,2);
 1.70714 +  if( res ){
 1.70715 +    pc = pOp->p2 - 1;
 1.70716 +  }
 1.70717 +  break;
 1.70718 +}
 1.70719 +
 1.70720 +/* Opcode: Seek P1 P2 * * *
 1.70721 +** Synopsis:  intkey=r[P2]
 1.70722 +**
 1.70723 +** P1 is an open table cursor and P2 is a rowid integer.  Arrange
 1.70724 +** for P1 to move so that it points to the rowid given by P2.
 1.70725 +**
 1.70726 +** This is actually a deferred seek.  Nothing actually happens until
 1.70727 +** the cursor is used to read a record.  That way, if no reads
 1.70728 +** occur, no unnecessary I/O happens.
 1.70729 +*/
 1.70730 +case OP_Seek: {    /* in2 */
 1.70731 +  VdbeCursor *pC;
 1.70732 +
 1.70733 +  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 1.70734 +  pC = p->apCsr[pOp->p1];
 1.70735 +  assert( pC!=0 );
 1.70736 +  assert( pC->pCursor!=0 );
 1.70737 +  assert( pC->isTable );
 1.70738 +  pC->nullRow = 0;
 1.70739 +  pIn2 = &aMem[pOp->p2];
 1.70740 +  pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
 1.70741 +  pC->rowidIsValid = 0;
 1.70742 +  pC->deferredMoveto = 1;
 1.70743 +  break;
 1.70744 +}
 1.70745 +  
 1.70746 +
 1.70747 +/* Opcode: Found P1 P2 P3 P4 *
 1.70748 +** Synopsis: key=r[P3@P4]
 1.70749 +**
 1.70750 +** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
 1.70751 +** P4>0 then register P3 is the first of P4 registers that form an unpacked
 1.70752 +** record.
 1.70753 +**
 1.70754 +** Cursor P1 is on an index btree.  If the record identified by P3 and P4
 1.70755 +** is a prefix of any entry in P1 then a jump is made to P2 and
 1.70756 +** P1 is left pointing at the matching entry.
 1.70757 +**
 1.70758 +** See also: NotFound, NoConflict, NotExists. SeekGe
 1.70759 +*/
 1.70760 +/* Opcode: NotFound P1 P2 P3 P4 *
 1.70761 +** Synopsis: key=r[P3@P4]
 1.70762 +**
 1.70763 +** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
 1.70764 +** P4>0 then register P3 is the first of P4 registers that form an unpacked
 1.70765 +** record.
 1.70766 +** 
 1.70767 +** Cursor P1 is on an index btree.  If the record identified by P3 and P4
 1.70768 +** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
 1.70769 +** does contain an entry whose prefix matches the P3/P4 record then control
 1.70770 +** falls through to the next instruction and P1 is left pointing at the
 1.70771 +** matching entry.
 1.70772 +**
 1.70773 +** See also: Found, NotExists, NoConflict
 1.70774 +*/
 1.70775 +/* Opcode: NoConflict P1 P2 P3 P4 *
 1.70776 +** Synopsis: key=r[P3@P4]
 1.70777 +**
 1.70778 +** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
 1.70779 +** P4>0 then register P3 is the first of P4 registers that form an unpacked
 1.70780 +** record.
 1.70781 +** 
 1.70782 +** Cursor P1 is on an index btree.  If the record identified by P3 and P4
 1.70783 +** contains any NULL value, jump immediately to P2.  If all terms of the
 1.70784 +** record are not-NULL then a check is done to determine if any row in the
 1.70785 +** P1 index btree has a matching key prefix.  If there are no matches, jump
 1.70786 +** immediately to P2.  If there is a match, fall through and leave the P1
 1.70787 +** cursor pointing to the matching row.
 1.70788 +**
 1.70789 +** This opcode is similar to OP_NotFound with the exceptions that the
 1.70790 +** branch is always taken if any part of the search key input is NULL.
 1.70791 +**
 1.70792 +** See also: NotFound, Found, NotExists
 1.70793 +*/
 1.70794 +case OP_NoConflict:     /* jump, in3 */
 1.70795 +case OP_NotFound:       /* jump, in3 */
 1.70796 +case OP_Found: {        /* jump, in3 */
 1.70797 +  int alreadyExists;
 1.70798 +  int ii;
 1.70799 +  VdbeCursor *pC;
 1.70800 +  int res;
 1.70801 +  char *pFree;
 1.70802 +  UnpackedRecord *pIdxKey;
 1.70803 +  UnpackedRecord r;
 1.70804 +  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
 1.70805 +
 1.70806 +#ifdef SQLITE_TEST
 1.70807 +  if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
 1.70808 +#endif
 1.70809 +
 1.70810 +  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 1.70811 +  assert( pOp->p4type==P4_INT32 );
 1.70812 +  pC = p->apCsr[pOp->p1];
 1.70813 +  assert( pC!=0 );
 1.70814 +  pIn3 = &aMem[pOp->p3];
 1.70815 +  assert( pC->pCursor!=0 );
 1.70816 +  assert( pC->isTable==0 );
 1.70817 +  pFree = 0;  /* Not needed.  Only used to suppress a compiler warning. */
 1.70818 +  if( pOp->p4.i>0 ){
 1.70819 +    r.pKeyInfo = pC->pKeyInfo;
 1.70820 +    r.nField = (u16)pOp->p4.i;
 1.70821 +    r.aMem = pIn3;
 1.70822 +    for(ii=0; ii<r.nField; ii++){
 1.70823 +      assert( memIsValid(&r.aMem[ii]) );
 1.70824 +      ExpandBlob(&r.aMem[ii]);
 1.70825 +#ifdef SQLITE_DEBUG
 1.70826 +      if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
 1.70827 +#endif
 1.70828 +    }
 1.70829 +    pIdxKey = &r;
 1.70830 +  }else{
 1.70831 +    pIdxKey = sqlite3VdbeAllocUnpackedRecord(
 1.70832 +        pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
 1.70833 +    ); 
 1.70834 +    if( pIdxKey==0 ) goto no_mem;
 1.70835 +    assert( pIn3->flags & MEM_Blob );
 1.70836 +    assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
 1.70837 +    sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
 1.70838 +  }
 1.70839 +  pIdxKey->default_rc = 0;
 1.70840 +  if( pOp->opcode==OP_NoConflict ){
 1.70841 +    /* For the OP_NoConflict opcode, take the jump if any of the
 1.70842 +    ** input fields are NULL, since any key with a NULL will not
 1.70843 +    ** conflict */
 1.70844 +    for(ii=0; ii<r.nField; ii++){
 1.70845 +      if( r.aMem[ii].flags & MEM_Null ){
 1.70846 +        pc = pOp->p2 - 1; VdbeBranchTaken(1,2);
 1.70847 +        break;
 1.70848 +      }
 1.70849 +    }
 1.70850 +  }
 1.70851 +  rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
 1.70852 +  if( pOp->p4.i==0 ){
 1.70853 +    sqlite3DbFree(db, pFree);
 1.70854 +  }
 1.70855 +  if( rc!=SQLITE_OK ){
 1.70856 +    break;
 1.70857 +  }
 1.70858 +  pC->seekResult = res;
 1.70859 +  alreadyExists = (res==0);
 1.70860 +  pC->nullRow = 1-alreadyExists;
 1.70861 +  pC->deferredMoveto = 0;
 1.70862 +  pC->cacheStatus = CACHE_STALE;
 1.70863 +  if( pOp->opcode==OP_Found ){
 1.70864 +    VdbeBranchTaken(alreadyExists!=0,2);
 1.70865 +    if( alreadyExists ) pc = pOp->p2 - 1;
 1.70866 +  }else{
 1.70867 +    VdbeBranchTaken(alreadyExists==0,2);
 1.70868 +    if( !alreadyExists ) pc = pOp->p2 - 1;
 1.70869 +  }
 1.70870 +  break;
 1.70871 +}
 1.70872 +
 1.70873 +/* Opcode: NotExists P1 P2 P3 * *
 1.70874 +** Synopsis: intkey=r[P3]
 1.70875 +**
 1.70876 +** P1 is the index of a cursor open on an SQL table btree (with integer
 1.70877 +** keys).  P3 is an integer rowid.  If P1 does not contain a record with
 1.70878 +** rowid P3 then jump immediately to P2.  If P1 does contain a record
 1.70879 +** with rowid P3 then leave the cursor pointing at that record and fall
 1.70880 +** through to the next instruction.
 1.70881 +**
 1.70882 +** The OP_NotFound opcode performs the same operation on index btrees
 1.70883 +** (with arbitrary multi-value keys).
 1.70884 +**
 1.70885 +** See also: Found, NotFound, NoConflict
 1.70886 +*/
 1.70887 +case OP_NotExists: {        /* jump, in3 */
 1.70888 +  VdbeCursor *pC;
 1.70889 +  BtCursor *pCrsr;
 1.70890 +  int res;
 1.70891 +  u64 iKey;
 1.70892 +
 1.70893 +  pIn3 = &aMem[pOp->p3];
 1.70894 +  assert( pIn3->flags & MEM_Int );
 1.70895 +  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 1.70896 +  pC = p->apCsr[pOp->p1];
 1.70897 +  assert( pC!=0 );
 1.70898 +  assert( pC->isTable );
 1.70899 +  assert( pC->pseudoTableReg==0 );
 1.70900 +  pCrsr = pC->pCursor;
 1.70901 +  assert( pCrsr!=0 );
 1.70902 +  res = 0;
 1.70903 +  iKey = pIn3->u.i;
 1.70904 +  rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
 1.70905 +  pC->lastRowid = pIn3->u.i;
 1.70906 +  pC->rowidIsValid = res==0 ?1:0;
 1.70907 +  pC->nullRow = 0;
 1.70908 +  pC->cacheStatus = CACHE_STALE;
 1.70909 +  pC->deferredMoveto = 0;
 1.70910 +  VdbeBranchTaken(res!=0,2);
 1.70911 +  if( res!=0 ){
 1.70912 +    pc = pOp->p2 - 1;
 1.70913 +    assert( pC->rowidIsValid==0 );
 1.70914 +  }
 1.70915 +  pC->seekResult = res;
 1.70916 +  break;
 1.70917 +}
 1.70918 +
 1.70919 +/* Opcode: Sequence P1 P2 * * *
 1.70920 +** Synopsis: r[P2]=rowid
 1.70921 +**
 1.70922 +** Find the next available sequence number for cursor P1.
 1.70923 +** Write the sequence number into register P2.
 1.70924 +** The sequence number on the cursor is incremented after this
 1.70925 +** instruction.  
 1.70926 +*/
 1.70927 +case OP_Sequence: {           /* out2-prerelease */
 1.70928 +  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 1.70929 +  assert( p->apCsr[pOp->p1]!=0 );
 1.70930 +  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
 1.70931 +  break;
 1.70932 +}
 1.70933 +
 1.70934 +
 1.70935 +/* Opcode: NewRowid P1 P2 P3 * *
 1.70936 +** Synopsis: r[P2]=rowid
 1.70937 +**
 1.70938 +** Get a new integer record number (a.k.a "rowid") used as the key to a table.
 1.70939 +** The record number is not previously used as a key in the database
 1.70940 +** table that cursor P1 points to.  The new record number is written
 1.70941 +** written to register P2.
 1.70942 +**
 1.70943 +** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
 1.70944 +** the largest previously generated record number. No new record numbers are
 1.70945 +** allowed to be less than this value. When this value reaches its maximum, 
 1.70946 +** an SQLITE_FULL error is generated. The P3 register is updated with the '
 1.70947 +** generated record number. This P3 mechanism is used to help implement the
 1.70948 +** AUTOINCREMENT feature.
 1.70949 +*/
 1.70950 +case OP_NewRowid: {           /* out2-prerelease */
 1.70951 +  i64 v;                 /* The new rowid */
 1.70952 +  VdbeCursor *pC;        /* Cursor of table to get the new rowid */
 1.70953 +  int res;               /* Result of an sqlite3BtreeLast() */
 1.70954 +  int cnt;               /* Counter to limit the number of searches */
 1.70955 +  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
 1.70956 +  VdbeFrame *pFrame;     /* Root frame of VDBE */
 1.70957 +
 1.70958 +  v = 0;
 1.70959 +  res = 0;
 1.70960 +  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 1.70961 +  pC = p->apCsr[pOp->p1];
 1.70962 +  assert( pC!=0 );
 1.70963 +  if( NEVER(pC->pCursor==0) ){
 1.70964 +    /* The zero initialization above is all that is needed */
 1.70965 +  }else{
 1.70966 +    /* The next rowid or record number (different terms for the same
 1.70967 +    ** thing) is obtained in a two-step algorithm.
 1.70968 +    **
 1.70969 +    ** First we attempt to find the largest existing rowid and add one
 1.70970 +    ** to that.  But if the largest existing rowid is already the maximum
 1.70971 +    ** positive integer, we have to fall through to the second
 1.70972 +    ** probabilistic algorithm
 1.70973 +    **
 1.70974 +    ** The second algorithm is to select a rowid at random and see if
 1.70975 +    ** it already exists in the table.  If it does not exist, we have
 1.70976 +    ** succeeded.  If the random rowid does exist, we select a new one
 1.70977 +    ** and try again, up to 100 times.
 1.70978 +    */
 1.70979 +    assert( pC->isTable );
 1.70980 +
 1.70981 +#ifdef SQLITE_32BIT_ROWID
 1.70982 +#   define MAX_ROWID 0x7fffffff
 1.70983 +#else
 1.70984 +    /* Some compilers complain about constants of the form 0x7fffffffffffffff.
 1.70985 +    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
 1.70986 +    ** to provide the constant while making all compilers happy.
 1.70987 +    */
 1.70988 +#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
 1.70989 +#endif
 1.70990 +
 1.70991 +    if( !pC->useRandomRowid ){
 1.70992 +      rc = sqlite3BtreeLast(pC->pCursor, &res);
 1.70993 +      if( rc!=SQLITE_OK ){
 1.70994 +        goto abort_due_to_error;
 1.70995 +      }
 1.70996 +      if( res ){
 1.70997 +        v = 1;   /* IMP: R-61914-48074 */
 1.70998 +      }else{
 1.70999 +        assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
 1.71000 +        rc = sqlite3BtreeKeySize(pC->pCursor, &v);
 1.71001 +        assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
 1.71002 +        if( v>=MAX_ROWID ){
 1.71003 +          pC->useRandomRowid = 1;
 1.71004 +        }else{
 1.71005 +          v++;   /* IMP: R-29538-34987 */
 1.71006 +        }
 1.71007 +      }
 1.71008 +    }
 1.71009 +
 1.71010 +#ifndef SQLITE_OMIT_AUTOINCREMENT
 1.71011 +    if( pOp->p3 ){
 1.71012 +      /* Assert that P3 is a valid memory cell. */
 1.71013 +      assert( pOp->p3>0 );
 1.71014 +      if( p->pFrame ){
 1.71015 +        for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
 1.71016 +        /* Assert that P3 is a valid memory cell. */
 1.71017 +        assert( pOp->p3<=pFrame->nMem );
 1.71018 +        pMem = &pFrame->aMem[pOp->p3];
 1.71019 +      }else{
 1.71020 +        /* Assert that P3 is a valid memory cell. */
 1.71021 +        assert( pOp->p3<=(p->nMem-p->nCursor) );
 1.71022 +        pMem = &aMem[pOp->p3];
 1.71023 +        memAboutToChange(p, pMem);
 1.71024 +      }
 1.71025 +      assert( memIsValid(pMem) );
 1.71026 +
 1.71027 +      REGISTER_TRACE(pOp->p3, pMem);
 1.71028 +      sqlite3VdbeMemIntegerify(pMem);
 1.71029 +      assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
 1.71030 +      if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
 1.71031 +        rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
 1.71032 +        goto abort_due_to_error;
 1.71033 +      }
 1.71034 +      if( v<pMem->u.i+1 ){
 1.71035 +        v = pMem->u.i + 1;
 1.71036 +      }
 1.71037 +      pMem->u.i = v;
 1.71038 +    }
 1.71039 +#endif
 1.71040 +    if( pC->useRandomRowid ){
 1.71041 +      /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
 1.71042 +      ** largest possible integer (9223372036854775807) then the database
 1.71043 +      ** engine starts picking positive candidate ROWIDs at random until
 1.71044 +      ** it finds one that is not previously used. */
 1.71045 +      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
 1.71046 +                             ** an AUTOINCREMENT table. */
 1.71047 +      /* on the first attempt, simply do one more than previous */
 1.71048 +      v = lastRowid;
 1.71049 +      v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
 1.71050 +      v++; /* ensure non-zero */
 1.71051 +      cnt = 0;
 1.71052 +      while(   ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
 1.71053 +                                                 0, &res))==SQLITE_OK)
 1.71054 +            && (res==0)
 1.71055 +            && (++cnt<100)){
 1.71056 +        /* collision - try another random rowid */
 1.71057 +        sqlite3_randomness(sizeof(v), &v);
 1.71058 +        if( cnt<5 ){
 1.71059 +          /* try "small" random rowids for the initial attempts */
 1.71060 +          v &= 0xffffff;
 1.71061 +        }else{
 1.71062 +          v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
 1.71063 +        }
 1.71064 +        v++; /* ensure non-zero */
 1.71065 +      }
 1.71066 +      if( rc==SQLITE_OK && res==0 ){
 1.71067 +        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
 1.71068 +        goto abort_due_to_error;
 1.71069 +      }
 1.71070 +      assert( v>0 );  /* EV: R-40812-03570 */
 1.71071 +    }
 1.71072 +    pC->rowidIsValid = 0;
 1.71073 +    pC->deferredMoveto = 0;
 1.71074 +    pC->cacheStatus = CACHE_STALE;
 1.71075 +  }
 1.71076 +  pOut->u.i = v;
 1.71077 +  break;
 1.71078 +}
 1.71079 +
 1.71080 +/* Opcode: Insert P1 P2 P3 P4 P5
 1.71081 +** Synopsis: intkey=r[P3] data=r[P2]
 1.71082 +**
 1.71083 +** Write an entry into the table of cursor P1.  A new entry is
 1.71084 +** created if it doesn't already exist or the data for an existing
 1.71085 +** entry is overwritten.  The data is the value MEM_Blob stored in register
 1.71086 +** number P2. The key is stored in register P3. The key must
 1.71087 +** be a MEM_Int.
 1.71088 +**
 1.71089 +** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
 1.71090 +** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
 1.71091 +** then rowid is stored for subsequent return by the
 1.71092 +** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
 1.71093 +**
 1.71094 +** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
 1.71095 +** the last seek operation (OP_NotExists) was a success, then this
 1.71096 +** operation will not attempt to find the appropriate row before doing
 1.71097 +** the insert but will instead overwrite the row that the cursor is
 1.71098 +** currently pointing to.  Presumably, the prior OP_NotExists opcode
 1.71099 +** has already positioned the cursor correctly.  This is an optimization
 1.71100 +** that boosts performance by avoiding redundant seeks.
 1.71101 +**
 1.71102 +** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
 1.71103 +** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
 1.71104 +** is part of an INSERT operation.  The difference is only important to
 1.71105 +** the update hook.
 1.71106 +**
 1.71107 +** Parameter P4 may point to a string containing the table-name, or
 1.71108 +** may be NULL. If it is not NULL, then the update-hook 
 1.71109 +** (sqlite3.xUpdateCallback) is invoked following a successful insert.
 1.71110 +**
 1.71111 +** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
 1.71112 +** allocated, then ownership of P2 is transferred to the pseudo-cursor
 1.71113 +** and register P2 becomes ephemeral.  If the cursor is changed, the
 1.71114 +** value of register P2 will then change.  Make sure this does not
 1.71115 +** cause any problems.)
 1.71116 +**
 1.71117 +** This instruction only works on tables.  The equivalent instruction
 1.71118 +** for indices is OP_IdxInsert.
 1.71119 +*/
 1.71120 +/* Opcode: InsertInt P1 P2 P3 P4 P5
 1.71121 +** Synopsis:  intkey=P3 data=r[P2]
 1.71122 +**
 1.71123 +** This works exactly like OP_Insert except that the key is the
 1.71124 +** integer value P3, not the value of the integer stored in register P3.
 1.71125 +*/
 1.71126 +case OP_Insert: 
 1.71127 +case OP_InsertInt: {
 1.71128 +  Mem *pData;       /* MEM cell holding data for the record to be inserted */
 1.71129 +  Mem *pKey;        /* MEM cell holding key  for the record */
 1.71130 +  i64 iKey;         /* The integer ROWID or key for the record to be inserted */
 1.71131 +  VdbeCursor *pC;   /* Cursor to table into which insert is written */
 1.71132 +  int nZero;        /* Number of zero-bytes to append */
 1.71133 +  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
 1.71134 +  const char *zDb;  /* database name - used by the update hook */
 1.71135 +  const char *zTbl; /* Table name - used by the opdate hook */
 1.71136 +  int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
 1.71137 +
 1.71138 +  pData = &aMem[pOp->p2];
 1.71139 +  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 1.71140 +  assert( memIsValid(pData) );
 1.71141 +  pC = p->apCsr[pOp->p1];
 1.71142 +  assert( pC!=0 );
 1.71143 +  assert( pC->pCursor!=0 );
 1.71144 +  assert( pC->pseudoTableReg==0 );
 1.71145 +  assert( pC->isTable );
 1.71146 +  REGISTER_TRACE(pOp->p2, pData);
 1.71147 +
 1.71148 +  if( pOp->opcode==OP_Insert ){
 1.71149 +    pKey = &aMem[pOp->p3];
 1.71150 +    assert( pKey->flags & MEM_Int );
 1.71151 +    assert( memIsValid(pKey) );
 1.71152 +    REGISTER_TRACE(pOp->p3, pKey);
 1.71153 +    iKey = pKey->u.i;
 1.71154 +  }else{
 1.71155 +    assert( pOp->opcode==OP_InsertInt );
 1.71156 +    iKey = pOp->p3;
 1.71157 +  }
 1.71158 +
 1.71159 +  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
 1.71160 +  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
 1.71161 +  if( pData->flags & MEM_Null ){
 1.71162 +    pData->z = 0;
 1.71163 +    pData->n = 0;
 1.71164 +  }else{
 1.71165 +    assert( pData->flags & (MEM_Blob|MEM_Str) );
 1.71166 +  }
 1.71167 +  seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
 1.71168 +  if( pData->flags & MEM_Zero ){
 1.71169 +    nZero = pData->u.nZero;
 1.71170 +  }else{
 1.71171 +    nZero = 0;
 1.71172 +  }
 1.71173 +  rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
 1.71174 +                          pData->z, pData->n, nZero,
 1.71175 +                          (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
 1.71176 +  );
 1.71177 +  pC->rowidIsValid = 0;
 1.71178 +  pC->deferredMoveto = 0;
 1.71179 +  pC->cacheStatus = CACHE_STALE;
 1.71180 +
 1.71181 +  /* Invoke the update-hook if required. */
 1.71182 +  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
 1.71183 +    zDb = db->aDb[pC->iDb].zName;
 1.71184 +    zTbl = pOp->p4.z;
 1.71185 +    op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
 1.71186 +    assert( pC->isTable );
 1.71187 +    db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
 1.71188 +    assert( pC->iDb>=0 );
 1.71189 +  }
 1.71190 +  break;
 1.71191 +}
 1.71192 +
 1.71193 +/* Opcode: Delete P1 P2 * P4 *
 1.71194 +**
 1.71195 +** Delete the record at which the P1 cursor is currently pointing.
 1.71196 +**
 1.71197 +** The cursor will be left pointing at either the next or the previous
 1.71198 +** record in the table. If it is left pointing at the next record, then
 1.71199 +** the next Next instruction will be a no-op.  Hence it is OK to delete
 1.71200 +** a record from within an Next loop.
 1.71201 +**
 1.71202 +** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
 1.71203 +** incremented (otherwise not).
 1.71204 +**
 1.71205 +** P1 must not be pseudo-table.  It has to be a real table with
 1.71206 +** multiple rows.
 1.71207 +**
 1.71208 +** If P4 is not NULL, then it is the name of the table that P1 is
 1.71209 +** pointing to.  The update hook will be invoked, if it exists.
 1.71210 +** If P4 is not NULL then the P1 cursor must have been positioned
 1.71211 +** using OP_NotFound prior to invoking this opcode.
 1.71212 +*/
 1.71213 +case OP_Delete: {
 1.71214 +  i64 iKey;
 1.71215 +  VdbeCursor *pC;
 1.71216 +
 1.71217 +  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 1.71218 +  pC = p->apCsr[pOp->p1];
 1.71219 +  assert( pC!=0 );
 1.71220 +  assert( pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
 1.71221 +  iKey = pC->lastRowid;      /* Only used for the update hook */
 1.71222 +
 1.71223 +  /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
 1.71224 +  ** OP_Column on the same table without any intervening operations that
 1.71225 +  ** might move or invalidate the cursor.  Hence cursor pC is always pointing
 1.71226 +  ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
 1.71227 +  ** below is always a no-op and cannot fail.  We will run it anyhow, though,
 1.71228 +  ** to guard against future changes to the code generator.
 1.71229 +  **/
 1.71230 +  assert( pC->deferredMoveto==0 );
 1.71231 +  rc = sqlite3VdbeCursorMoveto(pC);
 1.71232 +  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
 1.71233 +
 1.71234 +  rc = sqlite3BtreeDelete(pC->pCursor);
 1.71235 +  pC->cacheStatus = CACHE_STALE;
 1.71236 +
 1.71237 +  /* Invoke the update-hook if required. */
 1.71238 +  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z && pC->isTable ){
 1.71239 +    db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
 1.71240 +                        db->aDb[pC->iDb].zName, pOp->p4.z, iKey);
 1.71241 +    assert( pC->iDb>=0 );
 1.71242 +  }
 1.71243 +  if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
 1.71244 +  break;
 1.71245 +}
 1.71246 +/* Opcode: ResetCount * * * * *
 1.71247 +**
 1.71248 +** The value of the change counter is copied to the database handle
 1.71249 +** change counter (returned by subsequent calls to sqlite3_changes()).
 1.71250 +** Then the VMs internal change counter resets to 0.
 1.71251 +** This is used by trigger programs.
 1.71252 +*/
 1.71253 +case OP_ResetCount: {
 1.71254 +  sqlite3VdbeSetChanges(db, p->nChange);
 1.71255 +  p->nChange = 0;
 1.71256 +  break;
 1.71257 +}
 1.71258 +
 1.71259 +/* Opcode: SorterCompare P1 P2 P3 P4
 1.71260 +** Synopsis:  if key(P1)!=rtrim(r[P3],P4) goto P2
 1.71261 +**
 1.71262 +** P1 is a sorter cursor. This instruction compares a prefix of the
 1.71263 +** the record blob in register P3 against a prefix of the entry that 
 1.71264 +** the sorter cursor currently points to.  The final P4 fields of both
 1.71265 +** the P3 and sorter record are ignored.
 1.71266 +**
 1.71267 +** If either P3 or the sorter contains a NULL in one of their significant
 1.71268 +** fields (not counting the P4 fields at the end which are ignored) then
 1.71269 +** the comparison is assumed to be equal.
 1.71270 +**
 1.71271 +** Fall through to next instruction if the two records compare equal to
 1.71272 +** each other.  Jump to P2 if they are different.
 1.71273 +*/
 1.71274 +case OP_SorterCompare: {
 1.71275 +  VdbeCursor *pC;
 1.71276 +  int res;
 1.71277 +  int nIgnore;
 1.71278 +
 1.71279 +  pC = p->apCsr[pOp->p1];
 1.71280 +  assert( isSorter(pC) );
 1.71281 +  assert( pOp->p4type==P4_INT32 );
 1.71282 +  pIn3 = &aMem[pOp->p3];
 1.71283 +  nIgnore = pOp->p4.i;
 1.71284 +  rc = sqlite3VdbeSorterCompare(pC, pIn3, nIgnore, &res);
 1.71285 +  VdbeBranchTaken(res!=0,2);
 1.71286 +  if( res ){
 1.71287 +    pc = pOp->p2-1;
 1.71288 +  }
 1.71289 +  break;
 1.71290 +};
 1.71291 +
 1.71292 +/* Opcode: SorterData P1 P2 * * *
 1.71293 +** Synopsis: r[P2]=data
 1.71294 +**
 1.71295 +** Write into register P2 the current sorter data for sorter cursor P1.
 1.71296 +*/
 1.71297 +case OP_SorterData: {
 1.71298 +  VdbeCursor *pC;
 1.71299 +
 1.71300 +  pOut = &aMem[pOp->p2];
 1.71301 +  pC = p->apCsr[pOp->p1];
 1.71302 +  assert( isSorter(pC) );
 1.71303 +  rc = sqlite3VdbeSorterRowkey(pC, pOut);
 1.71304 +  break;
 1.71305 +}
 1.71306 +
 1.71307 +/* Opcode: RowData P1 P2 * * *
 1.71308 +** Synopsis: r[P2]=data
 1.71309 +**
 1.71310 +** Write into register P2 the complete row data for cursor P1.
 1.71311 +** There is no interpretation of the data.  
 1.71312 +** It is just copied onto the P2 register exactly as 
 1.71313 +** it is found in the database file.
 1.71314 +**
 1.71315 +** If the P1 cursor must be pointing to a valid row (not a NULL row)
 1.71316 +** of a real table, not a pseudo-table.
 1.71317 +*/
 1.71318 +/* Opcode: RowKey P1 P2 * * *
 1.71319 +** Synopsis: r[P2]=key
 1.71320 +**
 1.71321 +** Write into register P2 the complete row key for cursor P1.
 1.71322 +** There is no interpretation of the data.  
 1.71323 +** The key is copied onto the P2 register exactly as 
 1.71324 +** it is found in the database file.
 1.71325 +**
 1.71326 +** If the P1 cursor must be pointing to a valid row (not a NULL row)
 1.71327 +** of a real table, not a pseudo-table.
 1.71328 +*/
 1.71329 +case OP_RowKey:
 1.71330 +case OP_RowData: {
 1.71331 +  VdbeCursor *pC;
 1.71332 +  BtCursor *pCrsr;
 1.71333 +  u32 n;
 1.71334 +  i64 n64;
 1.71335 +
 1.71336 +  pOut = &aMem[pOp->p2];
 1.71337 +  memAboutToChange(p, pOut);
 1.71338 +
 1.71339 +  /* Note that RowKey and RowData are really exactly the same instruction */
 1.71340 +  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 1.71341 +  pC = p->apCsr[pOp->p1];
 1.71342 +  assert( isSorter(pC)==0 );
 1.71343 +  assert( pC->isTable || pOp->opcode!=OP_RowData );
 1.71344 +  assert( pC->isTable==0 || pOp->opcode==OP_RowData );
 1.71345 +  assert( pC!=0 );
 1.71346 +  assert( pC->nullRow==0 );
 1.71347 +  assert( pC->pseudoTableReg==0 );
 1.71348 +  assert( pC->pCursor!=0 );
 1.71349 +  pCrsr = pC->pCursor;
 1.71350 +  assert( sqlite3BtreeCursorIsValid(pCrsr) );
 1.71351 +
 1.71352 +  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
 1.71353 +  ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
 1.71354 +  ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
 1.71355 +  ** a no-op and can never fail.  But we leave it in place as a safety.
 1.71356 +  */
 1.71357 +  assert( pC->deferredMoveto==0 );
 1.71358 +  rc = sqlite3VdbeCursorMoveto(pC);
 1.71359 +  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
 1.71360 +
 1.71361 +  if( pC->isTable==0 ){
 1.71362 +    assert( !pC->isTable );
 1.71363 +    VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
 1.71364 +    assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
 1.71365 +    if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
 1.71366 +      goto too_big;
 1.71367 +    }
 1.71368 +    n = (u32)n64;
 1.71369 +  }else{
 1.71370 +    VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
 1.71371 +    assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
 1.71372 +    if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
 1.71373 +      goto too_big;
 1.71374 +    }
 1.71375 +  }
 1.71376 +  if( sqlite3VdbeMemGrow(pOut, n, 0) ){
 1.71377 +    goto no_mem;
 1.71378 +  }
 1.71379 +  pOut->n = n;
 1.71380 +  MemSetTypeFlag(pOut, MEM_Blob);
 1.71381 +  if( pC->isTable==0 ){
 1.71382 +    rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
 1.71383 +  }else{
 1.71384 +    rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
 1.71385 +  }
 1.71386 +  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
 1.71387 +  UPDATE_MAX_BLOBSIZE(pOut);
 1.71388 +  REGISTER_TRACE(pOp->p2, pOut);
 1.71389 +  break;
 1.71390 +}
 1.71391 +
 1.71392 +/* Opcode: Rowid P1 P2 * * *
 1.71393 +** Synopsis: r[P2]=rowid
 1.71394 +**
 1.71395 +** Store in register P2 an integer which is the key of the table entry that
 1.71396 +** P1 is currently point to.
 1.71397 +**
 1.71398 +** P1 can be either an ordinary table or a virtual table.  There used to
 1.71399 +** be a separate OP_VRowid opcode for use with virtual tables, but this
 1.71400 +** one opcode now works for both table types.
 1.71401 +*/
 1.71402 +case OP_Rowid: {                 /* out2-prerelease */
 1.71403 +  VdbeCursor *pC;
 1.71404 +  i64 v;
 1.71405 +  sqlite3_vtab *pVtab;
 1.71406 +  const sqlite3_module *pModule;
 1.71407 +
 1.71408 +  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 1.71409 +  pC = p->apCsr[pOp->p1];
 1.71410 +  assert( pC!=0 );
 1.71411 +  assert( pC->pseudoTableReg==0 || pC->nullRow );
 1.71412 +  if( pC->nullRow ){
 1.71413 +    pOut->flags = MEM_Null;
 1.71414 +    break;
 1.71415 +  }else if( pC->deferredMoveto ){
 1.71416 +    v = pC->movetoTarget;
 1.71417 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.71418 +  }else if( pC->pVtabCursor ){
 1.71419 +    pVtab = pC->pVtabCursor->pVtab;
 1.71420 +    pModule = pVtab->pModule;
 1.71421 +    assert( pModule->xRowid );
 1.71422 +    rc = pModule->xRowid(pC->pVtabCursor, &v);
 1.71423 +    sqlite3VtabImportErrmsg(p, pVtab);
 1.71424 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
 1.71425 +  }else{
 1.71426 +    assert( pC->pCursor!=0 );
 1.71427 +    rc = sqlite3VdbeCursorMoveto(pC);
 1.71428 +    if( rc ) goto abort_due_to_error;
 1.71429 +    if( pC->rowidIsValid ){
 1.71430 +      v = pC->lastRowid;
 1.71431 +    }else{
 1.71432 +      rc = sqlite3BtreeKeySize(pC->pCursor, &v);
 1.71433 +      assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
 1.71434 +    }
 1.71435 +  }
 1.71436 +  pOut->u.i = v;
 1.71437 +  break;
 1.71438 +}
 1.71439 +
 1.71440 +/* Opcode: NullRow P1 * * * *
 1.71441 +**
 1.71442 +** Move the cursor P1 to a null row.  Any OP_Column operations
 1.71443 +** that occur while the cursor is on the null row will always
 1.71444 +** write a NULL.
 1.71445 +*/
 1.71446 +case OP_NullRow: {
 1.71447 +  VdbeCursor *pC;
 1.71448 +
 1.71449 +  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 1.71450 +  pC = p->apCsr[pOp->p1];
 1.71451 +  assert( pC!=0 );
 1.71452 +  pC->nullRow = 1;
 1.71453 +  pC->rowidIsValid = 0;
 1.71454 +  pC->cacheStatus = CACHE_STALE;
 1.71455 +  if( pC->pCursor ){
 1.71456 +    sqlite3BtreeClearCursor(pC->pCursor);
 1.71457 +  }
 1.71458 +  break;
 1.71459 +}
 1.71460 +
 1.71461 +/* Opcode: Last P1 P2 * * *
 1.71462 +**
 1.71463 +** The next use of the Rowid or Column or Next instruction for P1 
 1.71464 +** will refer to the last entry in the database table or index.
 1.71465 +** If the table or index is empty and P2>0, then jump immediately to P2.
 1.71466 +** If P2 is 0 or if the table or index is not empty, fall through
 1.71467 +** to the following instruction.
 1.71468 +*/
 1.71469 +case OP_Last: {        /* jump */
 1.71470 +  VdbeCursor *pC;
 1.71471 +  BtCursor *pCrsr;
 1.71472 +  int res;
 1.71473 +
 1.71474 +  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 1.71475 +  pC = p->apCsr[pOp->p1];
 1.71476 +  assert( pC!=0 );
 1.71477 +  pCrsr = pC->pCursor;
 1.71478 +  res = 0;
 1.71479 +  assert( pCrsr!=0 );
 1.71480 +  rc = sqlite3BtreeLast(pCrsr, &res);
 1.71481 +  pC->nullRow = (u8)res;
 1.71482 +  pC->deferredMoveto = 0;
 1.71483 +  pC->rowidIsValid = 0;
 1.71484 +  pC->cacheStatus = CACHE_STALE;
 1.71485 +  if( pOp->p2>0 ){
 1.71486 +    VdbeBranchTaken(res!=0,2);
 1.71487 +    if( res ) pc = pOp->p2 - 1;
 1.71488 +  }
 1.71489 +  break;
 1.71490 +}
 1.71491 +
 1.71492 +
 1.71493 +/* Opcode: Sort P1 P2 * * *
 1.71494 +**
 1.71495 +** This opcode does exactly the same thing as OP_Rewind except that
 1.71496 +** it increments an undocumented global variable used for testing.
 1.71497 +**
 1.71498 +** Sorting is accomplished by writing records into a sorting index,
 1.71499 +** then rewinding that index and playing it back from beginning to
 1.71500 +** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
 1.71501 +** rewinding so that the global variable will be incremented and
 1.71502 +** regression tests can determine whether or not the optimizer is
 1.71503 +** correctly optimizing out sorts.
 1.71504 +*/
 1.71505 +case OP_SorterSort:    /* jump */
 1.71506 +case OP_Sort: {        /* jump */
 1.71507 +#ifdef SQLITE_TEST
 1.71508 +  sqlite3_sort_count++;
 1.71509 +  sqlite3_search_count--;
 1.71510 +#endif
 1.71511 +  p->aCounter[SQLITE_STMTSTATUS_SORT]++;
 1.71512 +  /* Fall through into OP_Rewind */
 1.71513 +}
 1.71514 +/* Opcode: Rewind P1 P2 * * *
 1.71515 +**
 1.71516 +** The next use of the Rowid or Column or Next instruction for P1 
 1.71517 +** will refer to the first entry in the database table or index.
 1.71518 +** If the table or index is empty and P2>0, then jump immediately to P2.
 1.71519 +** If P2 is 0 or if the table or index is not empty, fall through
 1.71520 +** to the following instruction.
 1.71521 +*/
 1.71522 +case OP_Rewind: {        /* jump */
 1.71523 +  VdbeCursor *pC;
 1.71524 +  BtCursor *pCrsr;
 1.71525 +  int res;
 1.71526 +
 1.71527 +  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 1.71528 +  pC = p->apCsr[pOp->p1];
 1.71529 +  assert( pC!=0 );
 1.71530 +  assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
 1.71531 +  res = 1;
 1.71532 +  if( isSorter(pC) ){
 1.71533 +    rc = sqlite3VdbeSorterRewind(db, pC, &res);
 1.71534 +  }else{
 1.71535 +    pCrsr = pC->pCursor;
 1.71536 +    assert( pCrsr );
 1.71537 +    rc = sqlite3BtreeFirst(pCrsr, &res);
 1.71538 +    pC->deferredMoveto = 0;
 1.71539 +    pC->cacheStatus = CACHE_STALE;
 1.71540 +    pC->rowidIsValid = 0;
 1.71541 +  }
 1.71542 +  pC->nullRow = (u8)res;
 1.71543 +  assert( pOp->p2>0 && pOp->p2<p->nOp );
 1.71544 +  VdbeBranchTaken(res!=0,2);
 1.71545 +  if( res ){
 1.71546 +    pc = pOp->p2 - 1;
 1.71547 +  }
 1.71548 +  break;
 1.71549 +}
 1.71550 +
 1.71551 +/* Opcode: Next P1 P2 P3 P4 P5
 1.71552 +**
 1.71553 +** Advance cursor P1 so that it points to the next key/data pair in its
 1.71554 +** table or index.  If there are no more key/value pairs then fall through
 1.71555 +** to the following instruction.  But if the cursor advance was successful,
 1.71556 +** jump immediately to P2.
 1.71557 +**
 1.71558 +** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
 1.71559 +** been opened prior to this opcode or the program will segfault.
 1.71560 +**
 1.71561 +** The P3 value is a hint to the btree implementation. If P3==1, that
 1.71562 +** means P1 is an SQL index and that this instruction could have been
 1.71563 +** omitted if that index had been unique.  P3 is usually 0.  P3 is
 1.71564 +** always either 0 or 1.
 1.71565 +**
 1.71566 +** P4 is always of type P4_ADVANCE. The function pointer points to
 1.71567 +** sqlite3BtreeNext().
 1.71568 +**
 1.71569 +** If P5 is positive and the jump is taken, then event counter
 1.71570 +** number P5-1 in the prepared statement is incremented.
 1.71571 +**
 1.71572 +** See also: Prev, NextIfOpen
 1.71573 +*/
 1.71574 +/* Opcode: NextIfOpen P1 P2 P3 P4 P5
 1.71575 +**
 1.71576 +** This opcode works just like OP_Next except that if cursor P1 is not
 1.71577 +** open it behaves a no-op.
 1.71578 +*/
 1.71579 +/* Opcode: Prev P1 P2 P3 P4 P5
 1.71580 +**
 1.71581 +** Back up cursor P1 so that it points to the previous key/data pair in its
 1.71582 +** table or index.  If there is no previous key/value pairs then fall through
 1.71583 +** to the following instruction.  But if the cursor backup was successful,
 1.71584 +** jump immediately to P2.
 1.71585 +**
 1.71586 +** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
 1.71587 +** not open then the behavior is undefined.
 1.71588 +**
 1.71589 +** The P3 value is a hint to the btree implementation. If P3==1, that
 1.71590 +** means P1 is an SQL index and that this instruction could have been
 1.71591 +** omitted if that index had been unique.  P3 is usually 0.  P3 is
 1.71592 +** always either 0 or 1.
 1.71593 +**
 1.71594 +** P4 is always of type P4_ADVANCE. The function pointer points to
 1.71595 +** sqlite3BtreePrevious().
 1.71596 +**
 1.71597 +** If P5 is positive and the jump is taken, then event counter
 1.71598 +** number P5-1 in the prepared statement is incremented.
 1.71599 +*/
 1.71600 +/* Opcode: PrevIfOpen P1 P2 P3 P4 P5
 1.71601 +**
 1.71602 +** This opcode works just like OP_Prev except that if cursor P1 is not
 1.71603 +** open it behaves a no-op.
 1.71604 +*/
 1.71605 +case OP_SorterNext: {  /* jump */
 1.71606 +  VdbeCursor *pC;
 1.71607 +  int res;
 1.71608 +
 1.71609 +  pC = p->apCsr[pOp->p1];
 1.71610 +  assert( isSorter(pC) );
 1.71611 +  rc = sqlite3VdbeSorterNext(db, pC, &res);
 1.71612 +  goto next_tail;
 1.71613 +case OP_PrevIfOpen:    /* jump */
 1.71614 +case OP_NextIfOpen:    /* jump */
 1.71615 +  if( p->apCsr[pOp->p1]==0 ) break;
 1.71616 +  /* Fall through */
 1.71617 +case OP_Prev:          /* jump */
 1.71618 +case OP_Next:          /* jump */
 1.71619 +  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 1.71620 +  assert( pOp->p5<ArraySize(p->aCounter) );
 1.71621 +  pC = p->apCsr[pOp->p1];
 1.71622 +  res = pOp->p3;
 1.71623 +  assert( pC!=0 );
 1.71624 +  assert( pC->deferredMoveto==0 );
 1.71625 +  assert( pC->pCursor );
 1.71626 +  assert( res==0 || (res==1 && pC->isTable==0) );
 1.71627 +  testcase( res==1 );
 1.71628 +  assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
 1.71629 +  assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
 1.71630 +  assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
 1.71631 +  assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
 1.71632 +  rc = pOp->p4.xAdvance(pC->pCursor, &res);
 1.71633 +next_tail:
 1.71634 +  pC->cacheStatus = CACHE_STALE;
 1.71635 +  VdbeBranchTaken(res==0,2);
 1.71636 +  if( res==0 ){
 1.71637 +    pC->nullRow = 0;
 1.71638 +    pc = pOp->p2 - 1;
 1.71639 +    p->aCounter[pOp->p5]++;
 1.71640 +#ifdef SQLITE_TEST
 1.71641 +    sqlite3_search_count++;
 1.71642 +#endif
 1.71643 +  }else{
 1.71644 +    pC->nullRow = 1;
 1.71645 +  }
 1.71646 +  pC->rowidIsValid = 0;
 1.71647 +  goto check_for_interrupt;
 1.71648 +}
 1.71649 +
 1.71650 +/* Opcode: IdxInsert P1 P2 P3 * P5
 1.71651 +** Synopsis: key=r[P2]
 1.71652 +**
 1.71653 +** Register P2 holds an SQL index key made using the
 1.71654 +** MakeRecord instructions.  This opcode writes that key
 1.71655 +** into the index P1.  Data for the entry is nil.
 1.71656 +**
 1.71657 +** P3 is a flag that provides a hint to the b-tree layer that this
 1.71658 +** insert is likely to be an append.
 1.71659 +**
 1.71660 +** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
 1.71661 +** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
 1.71662 +** then the change counter is unchanged.
 1.71663 +**
 1.71664 +** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
 1.71665 +** just done a seek to the spot where the new entry is to be inserted.
 1.71666 +** This flag avoids doing an extra seek.
 1.71667 +**
 1.71668 +** This instruction only works for indices.  The equivalent instruction
 1.71669 +** for tables is OP_Insert.
 1.71670 +*/
 1.71671 +case OP_SorterInsert:       /* in2 */
 1.71672 +case OP_IdxInsert: {        /* in2 */
 1.71673 +  VdbeCursor *pC;
 1.71674 +  BtCursor *pCrsr;
 1.71675 +  int nKey;
 1.71676 +  const char *zKey;
 1.71677 +
 1.71678 +  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 1.71679 +  pC = p->apCsr[pOp->p1];
 1.71680 +  assert( pC!=0 );
 1.71681 +  assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
 1.71682 +  pIn2 = &aMem[pOp->p2];
 1.71683 +  assert( pIn2->flags & MEM_Blob );
 1.71684 +  pCrsr = pC->pCursor;
 1.71685 +  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
 1.71686 +  assert( pCrsr!=0 );
 1.71687 +  assert( pC->isTable==0 );
 1.71688 +  rc = ExpandBlob(pIn2);
 1.71689 +  if( rc==SQLITE_OK ){
 1.71690 +    if( isSorter(pC) ){
 1.71691 +      rc = sqlite3VdbeSorterWrite(db, pC, pIn2);
 1.71692 +    }else{
 1.71693 +      nKey = pIn2->n;
 1.71694 +      zKey = pIn2->z;
 1.71695 +      rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3, 
 1.71696 +          ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
 1.71697 +          );
 1.71698 +      assert( pC->deferredMoveto==0 );
 1.71699 +      pC->cacheStatus = CACHE_STALE;
 1.71700 +    }
 1.71701 +  }
 1.71702 +  break;
 1.71703 +}
 1.71704 +
 1.71705 +/* Opcode: IdxDelete P1 P2 P3 * *
 1.71706 +** Synopsis: key=r[P2@P3]
 1.71707 +**
 1.71708 +** The content of P3 registers starting at register P2 form
 1.71709 +** an unpacked index key. This opcode removes that entry from the 
 1.71710 +** index opened by cursor P1.
 1.71711 +*/
 1.71712 +case OP_IdxDelete: {
 1.71713 +  VdbeCursor *pC;
 1.71714 +  BtCursor *pCrsr;
 1.71715 +  int res;
 1.71716 +  UnpackedRecord r;
 1.71717 +
 1.71718 +  assert( pOp->p3>0 );
 1.71719 +  assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
 1.71720 +  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 1.71721 +  pC = p->apCsr[pOp->p1];
 1.71722 +  assert( pC!=0 );
 1.71723 +  pCrsr = pC->pCursor;
 1.71724 +  assert( pCrsr!=0 );
 1.71725 +  assert( pOp->p5==0 );
 1.71726 +  r.pKeyInfo = pC->pKeyInfo;
 1.71727 +  r.nField = (u16)pOp->p3;
 1.71728 +  r.default_rc = 0;
 1.71729 +  r.aMem = &aMem[pOp->p2];
 1.71730 +#ifdef SQLITE_DEBUG
 1.71731 +  { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
 1.71732 +#endif
 1.71733 +  rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
 1.71734 +  if( rc==SQLITE_OK && res==0 ){
 1.71735 +    rc = sqlite3BtreeDelete(pCrsr);
 1.71736 +  }
 1.71737 +  assert( pC->deferredMoveto==0 );
 1.71738 +  pC->cacheStatus = CACHE_STALE;
 1.71739 +  break;
 1.71740 +}
 1.71741 +
 1.71742 +/* Opcode: IdxRowid P1 P2 * * *
 1.71743 +** Synopsis: r[P2]=rowid
 1.71744 +**
 1.71745 +** Write into register P2 an integer which is the last entry in the record at
 1.71746 +** the end of the index key pointed to by cursor P1.  This integer should be
 1.71747 +** the rowid of the table entry to which this index entry points.
 1.71748 +**
 1.71749 +** See also: Rowid, MakeRecord.
 1.71750 +*/
 1.71751 +case OP_IdxRowid: {              /* out2-prerelease */
 1.71752 +  BtCursor *pCrsr;
 1.71753 +  VdbeCursor *pC;
 1.71754 +  i64 rowid;
 1.71755 +
 1.71756 +  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 1.71757 +  pC = p->apCsr[pOp->p1];
 1.71758 +  assert( pC!=0 );
 1.71759 +  pCrsr = pC->pCursor;
 1.71760 +  assert( pCrsr!=0 );
 1.71761 +  pOut->flags = MEM_Null;
 1.71762 +  rc = sqlite3VdbeCursorMoveto(pC);
 1.71763 +  if( NEVER(rc) ) goto abort_due_to_error;
 1.71764 +  assert( pC->deferredMoveto==0 );
 1.71765 +  assert( pC->isTable==0 );
 1.71766 +  if( !pC->nullRow ){
 1.71767 +    rowid = 0;  /* Not needed.  Only used to silence a warning. */
 1.71768 +    rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
 1.71769 +    if( rc!=SQLITE_OK ){
 1.71770 +      goto abort_due_to_error;
 1.71771 +    }
 1.71772 +    pOut->u.i = rowid;
 1.71773 +    pOut->flags = MEM_Int;
 1.71774 +  }
 1.71775 +  break;
 1.71776 +}
 1.71777 +
 1.71778 +/* Opcode: IdxGE P1 P2 P3 P4 P5
 1.71779 +** Synopsis: key=r[P3@P4]
 1.71780 +**
 1.71781 +** The P4 register values beginning with P3 form an unpacked index 
 1.71782 +** key that omits the PRIMARY KEY.  Compare this key value against the index 
 1.71783 +** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID 
 1.71784 +** fields at the end.
 1.71785 +**
 1.71786 +** If the P1 index entry is greater than or equal to the key value
 1.71787 +** then jump to P2.  Otherwise fall through to the next instruction.
 1.71788 +*/
 1.71789 +/* Opcode: IdxGT P1 P2 P3 P4 P5
 1.71790 +** Synopsis: key=r[P3@P4]
 1.71791 +**
 1.71792 +** The P4 register values beginning with P3 form an unpacked index 
 1.71793 +** key that omits the PRIMARY KEY.  Compare this key value against the index 
 1.71794 +** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID 
 1.71795 +** fields at the end.
 1.71796 +**
 1.71797 +** If the P1 index entry is greater than the key value
 1.71798 +** then jump to P2.  Otherwise fall through to the next instruction.
 1.71799 +*/
 1.71800 +/* Opcode: IdxLT P1 P2 P3 P4 P5
 1.71801 +** Synopsis: key=r[P3@P4]
 1.71802 +**
 1.71803 +** The P4 register values beginning with P3 form an unpacked index 
 1.71804 +** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
 1.71805 +** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
 1.71806 +** ROWID on the P1 index.
 1.71807 +**
 1.71808 +** If the P1 index entry is less than the key value then jump to P2.
 1.71809 +** Otherwise fall through to the next instruction.
 1.71810 +*/
 1.71811 +/* Opcode: IdxLE P1 P2 P3 P4 P5
 1.71812 +** Synopsis: key=r[P3@P4]
 1.71813 +**
 1.71814 +** The P4 register values beginning with P3 form an unpacked index 
 1.71815 +** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
 1.71816 +** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
 1.71817 +** ROWID on the P1 index.
 1.71818 +**
 1.71819 +** If the P1 index entry is less than or equal to the key value then jump
 1.71820 +** to P2. Otherwise fall through to the next instruction.
 1.71821 +*/
 1.71822 +case OP_IdxLE:          /* jump */
 1.71823 +case OP_IdxGT:          /* jump */
 1.71824 +case OP_IdxLT:          /* jump */
 1.71825 +case OP_IdxGE:  {       /* jump */
 1.71826 +  VdbeCursor *pC;
 1.71827 +  int res;
 1.71828 +  UnpackedRecord r;
 1.71829 +
 1.71830 +  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 1.71831 +  pC = p->apCsr[pOp->p1];
 1.71832 +  assert( pC!=0 );
 1.71833 +  assert( pC->isOrdered );
 1.71834 +  assert( pC->pCursor!=0);
 1.71835 +  assert( pC->deferredMoveto==0 );
 1.71836 +  assert( pOp->p5==0 || pOp->p5==1 );
 1.71837 +  assert( pOp->p4type==P4_INT32 );
 1.71838 +  r.pKeyInfo = pC->pKeyInfo;
 1.71839 +  r.nField = (u16)pOp->p4.i;
 1.71840 +  if( pOp->opcode<OP_IdxLT ){
 1.71841 +    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
 1.71842 +    r.default_rc = -1;
 1.71843 +  }else{
 1.71844 +    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
 1.71845 +    r.default_rc = 0;
 1.71846 +  }
 1.71847 +  r.aMem = &aMem[pOp->p3];
 1.71848 +#ifdef SQLITE_DEBUG
 1.71849 +  { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
 1.71850 +#endif
 1.71851 +  res = 0;  /* Not needed.  Only used to silence a warning. */
 1.71852 +  rc = sqlite3VdbeIdxKeyCompare(pC, &r, &res);
 1.71853 +  assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
 1.71854 +  if( (pOp->opcode&1)==(OP_IdxLT&1) ){
 1.71855 +    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
 1.71856 +    res = -res;
 1.71857 +  }else{
 1.71858 +    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
 1.71859 +    res++;
 1.71860 +  }
 1.71861 +  VdbeBranchTaken(res>0,2);
 1.71862 +  if( res>0 ){
 1.71863 +    pc = pOp->p2 - 1 ;
 1.71864 +  }
 1.71865 +  break;
 1.71866 +}
 1.71867 +
 1.71868 +/* Opcode: Destroy P1 P2 P3 * *
 1.71869 +**
 1.71870 +** Delete an entire database table or index whose root page in the database
 1.71871 +** file is given by P1.
 1.71872 +**
 1.71873 +** The table being destroyed is in the main database file if P3==0.  If
 1.71874 +** P3==1 then the table to be clear is in the auxiliary database file
 1.71875 +** that is used to store tables create using CREATE TEMPORARY TABLE.
 1.71876 +**
 1.71877 +** If AUTOVACUUM is enabled then it is possible that another root page
 1.71878 +** might be moved into the newly deleted root page in order to keep all
 1.71879 +** root pages contiguous at the beginning of the database.  The former
 1.71880 +** value of the root page that moved - its value before the move occurred -
 1.71881 +** is stored in register P2.  If no page 
 1.71882 +** movement was required (because the table being dropped was already 
 1.71883 +** the last one in the database) then a zero is stored in register P2.
 1.71884 +** If AUTOVACUUM is disabled then a zero is stored in register P2.
 1.71885 +**
 1.71886 +** See also: Clear
 1.71887 +*/
 1.71888 +case OP_Destroy: {     /* out2-prerelease */
 1.71889 +  int iMoved;
 1.71890 +  int iCnt;
 1.71891 +  Vdbe *pVdbe;
 1.71892 +  int iDb;
 1.71893 +
 1.71894 +  assert( p->readOnly==0 );
 1.71895 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.71896 +  iCnt = 0;
 1.71897 +  for(pVdbe=db->pVdbe; pVdbe; pVdbe = pVdbe->pNext){
 1.71898 +    if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->bIsReader 
 1.71899 +     && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 
 1.71900 +    ){
 1.71901 +      iCnt++;
 1.71902 +    }
 1.71903 +  }
 1.71904 +#else
 1.71905 +  iCnt = db->nVdbeRead;
 1.71906 +#endif
 1.71907 +  pOut->flags = MEM_Null;
 1.71908 +  if( iCnt>1 ){
 1.71909 +    rc = SQLITE_LOCKED;
 1.71910 +    p->errorAction = OE_Abort;
 1.71911 +  }else{
 1.71912 +    iDb = pOp->p3;
 1.71913 +    assert( iCnt==1 );
 1.71914 +    assert( (p->btreeMask & (((yDbMask)1)<<iDb))!=0 );
 1.71915 +    iMoved = 0;  /* Not needed.  Only to silence a warning. */
 1.71916 +    rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
 1.71917 +    pOut->flags = MEM_Int;
 1.71918 +    pOut->u.i = iMoved;
 1.71919 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.71920 +    if( rc==SQLITE_OK && iMoved!=0 ){
 1.71921 +      sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
 1.71922 +      /* All OP_Destroy operations occur on the same btree */
 1.71923 +      assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
 1.71924 +      resetSchemaOnFault = iDb+1;
 1.71925 +    }
 1.71926 +#endif
 1.71927 +  }
 1.71928 +  break;
 1.71929 +}
 1.71930 +
 1.71931 +/* Opcode: Clear P1 P2 P3
 1.71932 +**
 1.71933 +** Delete all contents of the database table or index whose root page
 1.71934 +** in the database file is given by P1.  But, unlike Destroy, do not
 1.71935 +** remove the table or index from the database file.
 1.71936 +**
 1.71937 +** The table being clear is in the main database file if P2==0.  If
 1.71938 +** P2==1 then the table to be clear is in the auxiliary database file
 1.71939 +** that is used to store tables create using CREATE TEMPORARY TABLE.
 1.71940 +**
 1.71941 +** If the P3 value is non-zero, then the table referred to must be an
 1.71942 +** intkey table (an SQL table, not an index). In this case the row change 
 1.71943 +** count is incremented by the number of rows in the table being cleared. 
 1.71944 +** If P3 is greater than zero, then the value stored in register P3 is
 1.71945 +** also incremented by the number of rows in the table being cleared.
 1.71946 +**
 1.71947 +** See also: Destroy
 1.71948 +*/
 1.71949 +case OP_Clear: {
 1.71950 +  int nChange;
 1.71951 + 
 1.71952 +  nChange = 0;
 1.71953 +  assert( p->readOnly==0 );
 1.71954 +  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
 1.71955 +  rc = sqlite3BtreeClearTable(
 1.71956 +      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
 1.71957 +  );
 1.71958 +  if( pOp->p3 ){
 1.71959 +    p->nChange += nChange;
 1.71960 +    if( pOp->p3>0 ){
 1.71961 +      assert( memIsValid(&aMem[pOp->p3]) );
 1.71962 +      memAboutToChange(p, &aMem[pOp->p3]);
 1.71963 +      aMem[pOp->p3].u.i += nChange;
 1.71964 +    }
 1.71965 +  }
 1.71966 +  break;
 1.71967 +}
 1.71968 +
 1.71969 +/* Opcode: CreateTable P1 P2 * * *
 1.71970 +** Synopsis: r[P2]=root iDb=P1
 1.71971 +**
 1.71972 +** Allocate a new table in the main database file if P1==0 or in the
 1.71973 +** auxiliary database file if P1==1 or in an attached database if
 1.71974 +** P1>1.  Write the root page number of the new table into
 1.71975 +** register P2
 1.71976 +**
 1.71977 +** The difference between a table and an index is this:  A table must
 1.71978 +** have a 4-byte integer key and can have arbitrary data.  An index
 1.71979 +** has an arbitrary key but no data.
 1.71980 +**
 1.71981 +** See also: CreateIndex
 1.71982 +*/
 1.71983 +/* Opcode: CreateIndex P1 P2 * * *
 1.71984 +** Synopsis: r[P2]=root iDb=P1
 1.71985 +**
 1.71986 +** Allocate a new index in the main database file if P1==0 or in the
 1.71987 +** auxiliary database file if P1==1 or in an attached database if
 1.71988 +** P1>1.  Write the root page number of the new table into
 1.71989 +** register P2.
 1.71990 +**
 1.71991 +** See documentation on OP_CreateTable for additional information.
 1.71992 +*/
 1.71993 +case OP_CreateIndex:            /* out2-prerelease */
 1.71994 +case OP_CreateTable: {          /* out2-prerelease */
 1.71995 +  int pgno;
 1.71996 +  int flags;
 1.71997 +  Db *pDb;
 1.71998 +
 1.71999 +  pgno = 0;
 1.72000 +  assert( pOp->p1>=0 && pOp->p1<db->nDb );
 1.72001 +  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
 1.72002 +  assert( p->readOnly==0 );
 1.72003 +  pDb = &db->aDb[pOp->p1];
 1.72004 +  assert( pDb->pBt!=0 );
 1.72005 +  if( pOp->opcode==OP_CreateTable ){
 1.72006 +    /* flags = BTREE_INTKEY; */
 1.72007 +    flags = BTREE_INTKEY;
 1.72008 +  }else{
 1.72009 +    flags = BTREE_BLOBKEY;
 1.72010 +  }
 1.72011 +  rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
 1.72012 +  pOut->u.i = pgno;
 1.72013 +  break;
 1.72014 +}
 1.72015 +
 1.72016 +/* Opcode: ParseSchema P1 * * P4 *
 1.72017 +**
 1.72018 +** Read and parse all entries from the SQLITE_MASTER table of database P1
 1.72019 +** that match the WHERE clause P4. 
 1.72020 +**
 1.72021 +** This opcode invokes the parser to create a new virtual machine,
 1.72022 +** then runs the new virtual machine.  It is thus a re-entrant opcode.
 1.72023 +*/
 1.72024 +case OP_ParseSchema: {
 1.72025 +  int iDb;
 1.72026 +  const char *zMaster;
 1.72027 +  char *zSql;
 1.72028 +  InitData initData;
 1.72029 +
 1.72030 +  /* Any prepared statement that invokes this opcode will hold mutexes
 1.72031 +  ** on every btree.  This is a prerequisite for invoking 
 1.72032 +  ** sqlite3InitCallback().
 1.72033 +  */
 1.72034 +#ifdef SQLITE_DEBUG
 1.72035 +  for(iDb=0; iDb<db->nDb; iDb++){
 1.72036 +    assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
 1.72037 +  }
 1.72038 +#endif
 1.72039 +
 1.72040 +  iDb = pOp->p1;
 1.72041 +  assert( iDb>=0 && iDb<db->nDb );
 1.72042 +  assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
 1.72043 +  /* Used to be a conditional */ {
 1.72044 +    zMaster = SCHEMA_TABLE(iDb);
 1.72045 +    initData.db = db;
 1.72046 +    initData.iDb = pOp->p1;
 1.72047 +    initData.pzErrMsg = &p->zErrMsg;
 1.72048 +    zSql = sqlite3MPrintf(db,
 1.72049 +       "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
 1.72050 +       db->aDb[iDb].zName, zMaster, pOp->p4.z);
 1.72051 +    if( zSql==0 ){
 1.72052 +      rc = SQLITE_NOMEM;
 1.72053 +    }else{
 1.72054 +      assert( db->init.busy==0 );
 1.72055 +      db->init.busy = 1;
 1.72056 +      initData.rc = SQLITE_OK;
 1.72057 +      assert( !db->mallocFailed );
 1.72058 +      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
 1.72059 +      if( rc==SQLITE_OK ) rc = initData.rc;
 1.72060 +      sqlite3DbFree(db, zSql);
 1.72061 +      db->init.busy = 0;
 1.72062 +    }
 1.72063 +  }
 1.72064 +  if( rc ) sqlite3ResetAllSchemasOfConnection(db);
 1.72065 +  if( rc==SQLITE_NOMEM ){
 1.72066 +    goto no_mem;
 1.72067 +  }
 1.72068 +  break;  
 1.72069 +}
 1.72070 +
 1.72071 +#if !defined(SQLITE_OMIT_ANALYZE)
 1.72072 +/* Opcode: LoadAnalysis P1 * * * *
 1.72073 +**
 1.72074 +** Read the sqlite_stat1 table for database P1 and load the content
 1.72075 +** of that table into the internal index hash table.  This will cause
 1.72076 +** the analysis to be used when preparing all subsequent queries.
 1.72077 +*/
 1.72078 +case OP_LoadAnalysis: {
 1.72079 +  assert( pOp->p1>=0 && pOp->p1<db->nDb );
 1.72080 +  rc = sqlite3AnalysisLoad(db, pOp->p1);
 1.72081 +  break;  
 1.72082 +}
 1.72083 +#endif /* !defined(SQLITE_OMIT_ANALYZE) */
 1.72084 +
 1.72085 +/* Opcode: DropTable P1 * * P4 *
 1.72086 +**
 1.72087 +** Remove the internal (in-memory) data structures that describe
 1.72088 +** the table named P4 in database P1.  This is called after a table
 1.72089 +** is dropped in order to keep the internal representation of the
 1.72090 +** schema consistent with what is on disk.
 1.72091 +*/
 1.72092 +case OP_DropTable: {
 1.72093 +  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
 1.72094 +  break;
 1.72095 +}
 1.72096 +
 1.72097 +/* Opcode: DropIndex P1 * * P4 *
 1.72098 +**
 1.72099 +** Remove the internal (in-memory) data structures that describe
 1.72100 +** the index named P4 in database P1.  This is called after an index
 1.72101 +** is dropped in order to keep the internal representation of the
 1.72102 +** schema consistent with what is on disk.
 1.72103 +*/
 1.72104 +case OP_DropIndex: {
 1.72105 +  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
 1.72106 +  break;
 1.72107 +}
 1.72108 +
 1.72109 +/* Opcode: DropTrigger P1 * * P4 *
 1.72110 +**
 1.72111 +** Remove the internal (in-memory) data structures that describe
 1.72112 +** the trigger named P4 in database P1.  This is called after a trigger
 1.72113 +** is dropped in order to keep the internal representation of the
 1.72114 +** schema consistent with what is on disk.
 1.72115 +*/
 1.72116 +case OP_DropTrigger: {
 1.72117 +  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
 1.72118 +  break;
 1.72119 +}
 1.72120 +
 1.72121 +
 1.72122 +#ifndef SQLITE_OMIT_INTEGRITY_CHECK
 1.72123 +/* Opcode: IntegrityCk P1 P2 P3 * P5
 1.72124 +**
 1.72125 +** Do an analysis of the currently open database.  Store in
 1.72126 +** register P1 the text of an error message describing any problems.
 1.72127 +** If no problems are found, store a NULL in register P1.
 1.72128 +**
 1.72129 +** The register P3 contains the maximum number of allowed errors.
 1.72130 +** At most reg(P3) errors will be reported.
 1.72131 +** In other words, the analysis stops as soon as reg(P1) errors are 
 1.72132 +** seen.  Reg(P1) is updated with the number of errors remaining.
 1.72133 +**
 1.72134 +** The root page numbers of all tables in the database are integer
 1.72135 +** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
 1.72136 +** total.
 1.72137 +**
 1.72138 +** If P5 is not zero, the check is done on the auxiliary database
 1.72139 +** file, not the main database file.
 1.72140 +**
 1.72141 +** This opcode is used to implement the integrity_check pragma.
 1.72142 +*/
 1.72143 +case OP_IntegrityCk: {
 1.72144 +  int nRoot;      /* Number of tables to check.  (Number of root pages.) */
 1.72145 +  int *aRoot;     /* Array of rootpage numbers for tables to be checked */
 1.72146 +  int j;          /* Loop counter */
 1.72147 +  int nErr;       /* Number of errors reported */
 1.72148 +  char *z;        /* Text of the error report */
 1.72149 +  Mem *pnErr;     /* Register keeping track of errors remaining */
 1.72150 +
 1.72151 +  assert( p->bIsReader );
 1.72152 +  nRoot = pOp->p2;
 1.72153 +  assert( nRoot>0 );
 1.72154 +  aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
 1.72155 +  if( aRoot==0 ) goto no_mem;
 1.72156 +  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
 1.72157 +  pnErr = &aMem[pOp->p3];
 1.72158 +  assert( (pnErr->flags & MEM_Int)!=0 );
 1.72159 +  assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
 1.72160 +  pIn1 = &aMem[pOp->p1];
 1.72161 +  for(j=0; j<nRoot; j++){
 1.72162 +    aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
 1.72163 +  }
 1.72164 +  aRoot[j] = 0;
 1.72165 +  assert( pOp->p5<db->nDb );
 1.72166 +  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
 1.72167 +  z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
 1.72168 +                                 (int)pnErr->u.i, &nErr);
 1.72169 +  sqlite3DbFree(db, aRoot);
 1.72170 +  pnErr->u.i -= nErr;
 1.72171 +  sqlite3VdbeMemSetNull(pIn1);
 1.72172 +  if( nErr==0 ){
 1.72173 +    assert( z==0 );
 1.72174 +  }else if( z==0 ){
 1.72175 +    goto no_mem;
 1.72176 +  }else{
 1.72177 +    sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
 1.72178 +  }
 1.72179 +  UPDATE_MAX_BLOBSIZE(pIn1);
 1.72180 +  sqlite3VdbeChangeEncoding(pIn1, encoding);
 1.72181 +  break;
 1.72182 +}
 1.72183 +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
 1.72184 +
 1.72185 +/* Opcode: RowSetAdd P1 P2 * * *
 1.72186 +** Synopsis:  rowset(P1)=r[P2]
 1.72187 +**
 1.72188 +** Insert the integer value held by register P2 into a boolean index
 1.72189 +** held in register P1.
 1.72190 +**
 1.72191 +** An assertion fails if P2 is not an integer.
 1.72192 +*/
 1.72193 +case OP_RowSetAdd: {       /* in1, in2 */
 1.72194 +  pIn1 = &aMem[pOp->p1];
 1.72195 +  pIn2 = &aMem[pOp->p2];
 1.72196 +  assert( (pIn2->flags & MEM_Int)!=0 );
 1.72197 +  if( (pIn1->flags & MEM_RowSet)==0 ){
 1.72198 +    sqlite3VdbeMemSetRowSet(pIn1);
 1.72199 +    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
 1.72200 +  }
 1.72201 +  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
 1.72202 +  break;
 1.72203 +}
 1.72204 +
 1.72205 +/* Opcode: RowSetRead P1 P2 P3 * *
 1.72206 +** Synopsis:  r[P3]=rowset(P1)
 1.72207 +**
 1.72208 +** Extract the smallest value from boolean index P1 and put that value into
 1.72209 +** register P3.  Or, if boolean index P1 is initially empty, leave P3
 1.72210 +** unchanged and jump to instruction P2.
 1.72211 +*/
 1.72212 +case OP_RowSetRead: {       /* jump, in1, out3 */
 1.72213 +  i64 val;
 1.72214 +
 1.72215 +  pIn1 = &aMem[pOp->p1];
 1.72216 +  if( (pIn1->flags & MEM_RowSet)==0 
 1.72217 +   || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
 1.72218 +  ){
 1.72219 +    /* The boolean index is empty */
 1.72220 +    sqlite3VdbeMemSetNull(pIn1);
 1.72221 +    pc = pOp->p2 - 1;
 1.72222 +    VdbeBranchTaken(1,2);
 1.72223 +  }else{
 1.72224 +    /* A value was pulled from the index */
 1.72225 +    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
 1.72226 +    VdbeBranchTaken(0,2);
 1.72227 +  }
 1.72228 +  goto check_for_interrupt;
 1.72229 +}
 1.72230 +
 1.72231 +/* Opcode: RowSetTest P1 P2 P3 P4
 1.72232 +** Synopsis: if r[P3] in rowset(P1) goto P2
 1.72233 +**
 1.72234 +** Register P3 is assumed to hold a 64-bit integer value. If register P1
 1.72235 +** contains a RowSet object and that RowSet object contains
 1.72236 +** the value held in P3, jump to register P2. Otherwise, insert the
 1.72237 +** integer in P3 into the RowSet and continue on to the
 1.72238 +** next opcode.
 1.72239 +**
 1.72240 +** The RowSet object is optimized for the case where successive sets
 1.72241 +** of integers, where each set contains no duplicates. Each set
 1.72242 +** of values is identified by a unique P4 value. The first set
 1.72243 +** must have P4==0, the final set P4=-1.  P4 must be either -1 or
 1.72244 +** non-negative.  For non-negative values of P4 only the lower 4
 1.72245 +** bits are significant.
 1.72246 +**
 1.72247 +** This allows optimizations: (a) when P4==0 there is no need to test
 1.72248 +** the rowset object for P3, as it is guaranteed not to contain it,
 1.72249 +** (b) when P4==-1 there is no need to insert the value, as it will
 1.72250 +** never be tested for, and (c) when a value that is part of set X is
 1.72251 +** inserted, there is no need to search to see if the same value was
 1.72252 +** previously inserted as part of set X (only if it was previously
 1.72253 +** inserted as part of some other set).
 1.72254 +*/
 1.72255 +case OP_RowSetTest: {                     /* jump, in1, in3 */
 1.72256 +  int iSet;
 1.72257 +  int exists;
 1.72258 +
 1.72259 +  pIn1 = &aMem[pOp->p1];
 1.72260 +  pIn3 = &aMem[pOp->p3];
 1.72261 +  iSet = pOp->p4.i;
 1.72262 +  assert( pIn3->flags&MEM_Int );
 1.72263 +
 1.72264 +  /* If there is anything other than a rowset object in memory cell P1,
 1.72265 +  ** delete it now and initialize P1 with an empty rowset
 1.72266 +  */
 1.72267 +  if( (pIn1->flags & MEM_RowSet)==0 ){
 1.72268 +    sqlite3VdbeMemSetRowSet(pIn1);
 1.72269 +    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
 1.72270 +  }
 1.72271 +
 1.72272 +  assert( pOp->p4type==P4_INT32 );
 1.72273 +  assert( iSet==-1 || iSet>=0 );
 1.72274 +  if( iSet ){
 1.72275 +    exists = sqlite3RowSetTest(pIn1->u.pRowSet, 
 1.72276 +                               (u8)(iSet>=0 ? iSet & 0xf : 0xff),
 1.72277 +                               pIn3->u.i);
 1.72278 +    VdbeBranchTaken(exists!=0,2);
 1.72279 +    if( exists ){
 1.72280 +      pc = pOp->p2 - 1;
 1.72281 +      break;
 1.72282 +    }
 1.72283 +  }
 1.72284 +  if( iSet>=0 ){
 1.72285 +    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
 1.72286 +  }
 1.72287 +  break;
 1.72288 +}
 1.72289 +
 1.72290 +
 1.72291 +#ifndef SQLITE_OMIT_TRIGGER
 1.72292 +
 1.72293 +/* Opcode: Program P1 P2 P3 P4 P5
 1.72294 +**
 1.72295 +** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
 1.72296 +**
 1.72297 +** P1 contains the address of the memory cell that contains the first memory 
 1.72298 +** cell in an array of values used as arguments to the sub-program. P2 
 1.72299 +** contains the address to jump to if the sub-program throws an IGNORE 
 1.72300 +** exception using the RAISE() function. Register P3 contains the address 
 1.72301 +** of a memory cell in this (the parent) VM that is used to allocate the 
 1.72302 +** memory required by the sub-vdbe at runtime.
 1.72303 +**
 1.72304 +** P4 is a pointer to the VM containing the trigger program.
 1.72305 +**
 1.72306 +** If P5 is non-zero, then recursive program invocation is enabled.
 1.72307 +*/
 1.72308 +case OP_Program: {        /* jump */
 1.72309 +  int nMem;               /* Number of memory registers for sub-program */
 1.72310 +  int nByte;              /* Bytes of runtime space required for sub-program */
 1.72311 +  Mem *pRt;               /* Register to allocate runtime space */
 1.72312 +  Mem *pMem;              /* Used to iterate through memory cells */
 1.72313 +  Mem *pEnd;              /* Last memory cell in new array */
 1.72314 +  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
 1.72315 +  SubProgram *pProgram;   /* Sub-program to execute */
 1.72316 +  void *t;                /* Token identifying trigger */
 1.72317 +
 1.72318 +  pProgram = pOp->p4.pProgram;
 1.72319 +  pRt = &aMem[pOp->p3];
 1.72320 +  assert( pProgram->nOp>0 );
 1.72321 +  
 1.72322 +  /* If the p5 flag is clear, then recursive invocation of triggers is 
 1.72323 +  ** disabled for backwards compatibility (p5 is set if this sub-program
 1.72324 +  ** is really a trigger, not a foreign key action, and the flag set
 1.72325 +  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
 1.72326 +  ** 
 1.72327 +  ** It is recursive invocation of triggers, at the SQL level, that is 
 1.72328 +  ** disabled. In some cases a single trigger may generate more than one 
 1.72329 +  ** SubProgram (if the trigger may be executed with more than one different 
 1.72330 +  ** ON CONFLICT algorithm). SubProgram structures associated with a
 1.72331 +  ** single trigger all have the same value for the SubProgram.token 
 1.72332 +  ** variable.  */
 1.72333 +  if( pOp->p5 ){
 1.72334 +    t = pProgram->token;
 1.72335 +    for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
 1.72336 +    if( pFrame ) break;
 1.72337 +  }
 1.72338 +
 1.72339 +  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
 1.72340 +    rc = SQLITE_ERROR;
 1.72341 +    sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
 1.72342 +    break;
 1.72343 +  }
 1.72344 +
 1.72345 +  /* Register pRt is used to store the memory required to save the state
 1.72346 +  ** of the current program, and the memory required at runtime to execute
 1.72347 +  ** the trigger program. If this trigger has been fired before, then pRt 
 1.72348 +  ** is already allocated. Otherwise, it must be initialized.  */
 1.72349 +  if( (pRt->flags&MEM_Frame)==0 ){
 1.72350 +    /* SubProgram.nMem is set to the number of memory cells used by the 
 1.72351 +    ** program stored in SubProgram.aOp. As well as these, one memory
 1.72352 +    ** cell is required for each cursor used by the program. Set local
 1.72353 +    ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
 1.72354 +    */
 1.72355 +    nMem = pProgram->nMem + pProgram->nCsr;
 1.72356 +    nByte = ROUND8(sizeof(VdbeFrame))
 1.72357 +              + nMem * sizeof(Mem)
 1.72358 +              + pProgram->nCsr * sizeof(VdbeCursor *)
 1.72359 +              + pProgram->nOnce * sizeof(u8);
 1.72360 +    pFrame = sqlite3DbMallocZero(db, nByte);
 1.72361 +    if( !pFrame ){
 1.72362 +      goto no_mem;
 1.72363 +    }
 1.72364 +    sqlite3VdbeMemRelease(pRt);
 1.72365 +    pRt->flags = MEM_Frame;
 1.72366 +    pRt->u.pFrame = pFrame;
 1.72367 +
 1.72368 +    pFrame->v = p;
 1.72369 +    pFrame->nChildMem = nMem;
 1.72370 +    pFrame->nChildCsr = pProgram->nCsr;
 1.72371 +    pFrame->pc = pc;
 1.72372 +    pFrame->aMem = p->aMem;
 1.72373 +    pFrame->nMem = p->nMem;
 1.72374 +    pFrame->apCsr = p->apCsr;
 1.72375 +    pFrame->nCursor = p->nCursor;
 1.72376 +    pFrame->aOp = p->aOp;
 1.72377 +    pFrame->nOp = p->nOp;
 1.72378 +    pFrame->token = pProgram->token;
 1.72379 +    pFrame->aOnceFlag = p->aOnceFlag;
 1.72380 +    pFrame->nOnceFlag = p->nOnceFlag;
 1.72381 +
 1.72382 +    pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
 1.72383 +    for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
 1.72384 +      pMem->flags = MEM_Undefined;
 1.72385 +      pMem->db = db;
 1.72386 +    }
 1.72387 +  }else{
 1.72388 +    pFrame = pRt->u.pFrame;
 1.72389 +    assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
 1.72390 +    assert( pProgram->nCsr==pFrame->nChildCsr );
 1.72391 +    assert( pc==pFrame->pc );
 1.72392 +  }
 1.72393 +
 1.72394 +  p->nFrame++;
 1.72395 +  pFrame->pParent = p->pFrame;
 1.72396 +  pFrame->lastRowid = lastRowid;
 1.72397 +  pFrame->nChange = p->nChange;
 1.72398 +  p->nChange = 0;
 1.72399 +  p->pFrame = pFrame;
 1.72400 +  p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
 1.72401 +  p->nMem = pFrame->nChildMem;
 1.72402 +  p->nCursor = (u16)pFrame->nChildCsr;
 1.72403 +  p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
 1.72404 +  p->aOp = aOp = pProgram->aOp;
 1.72405 +  p->nOp = pProgram->nOp;
 1.72406 +  p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
 1.72407 +  p->nOnceFlag = pProgram->nOnce;
 1.72408 +  pc = -1;
 1.72409 +  memset(p->aOnceFlag, 0, p->nOnceFlag);
 1.72410 +
 1.72411 +  break;
 1.72412 +}
 1.72413 +
 1.72414 +/* Opcode: Param P1 P2 * * *
 1.72415 +**
 1.72416 +** This opcode is only ever present in sub-programs called via the 
 1.72417 +** OP_Program instruction. Copy a value currently stored in a memory 
 1.72418 +** cell of the calling (parent) frame to cell P2 in the current frames 
 1.72419 +** address space. This is used by trigger programs to access the new.* 
 1.72420 +** and old.* values.
 1.72421 +**
 1.72422 +** The address of the cell in the parent frame is determined by adding
 1.72423 +** the value of the P1 argument to the value of the P1 argument to the
 1.72424 +** calling OP_Program instruction.
 1.72425 +*/
 1.72426 +case OP_Param: {           /* out2-prerelease */
 1.72427 +  VdbeFrame *pFrame;
 1.72428 +  Mem *pIn;
 1.72429 +  pFrame = p->pFrame;
 1.72430 +  pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];   
 1.72431 +  sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
 1.72432 +  break;
 1.72433 +}
 1.72434 +
 1.72435 +#endif /* #ifndef SQLITE_OMIT_TRIGGER */
 1.72436 +
 1.72437 +#ifndef SQLITE_OMIT_FOREIGN_KEY
 1.72438 +/* Opcode: FkCounter P1 P2 * * *
 1.72439 +** Synopsis: fkctr[P1]+=P2
 1.72440 +**
 1.72441 +** Increment a "constraint counter" by P2 (P2 may be negative or positive).
 1.72442 +** If P1 is non-zero, the database constraint counter is incremented 
 1.72443 +** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
 1.72444 +** statement counter is incremented (immediate foreign key constraints).
 1.72445 +*/
 1.72446 +case OP_FkCounter: {
 1.72447 +  if( db->flags & SQLITE_DeferFKs ){
 1.72448 +    db->nDeferredImmCons += pOp->p2;
 1.72449 +  }else if( pOp->p1 ){
 1.72450 +    db->nDeferredCons += pOp->p2;
 1.72451 +  }else{
 1.72452 +    p->nFkConstraint += pOp->p2;
 1.72453 +  }
 1.72454 +  break;
 1.72455 +}
 1.72456 +
 1.72457 +/* Opcode: FkIfZero P1 P2 * * *
 1.72458 +** Synopsis: if fkctr[P1]==0 goto P2
 1.72459 +**
 1.72460 +** This opcode tests if a foreign key constraint-counter is currently zero.
 1.72461 +** If so, jump to instruction P2. Otherwise, fall through to the next 
 1.72462 +** instruction.
 1.72463 +**
 1.72464 +** If P1 is non-zero, then the jump is taken if the database constraint-counter
 1.72465 +** is zero (the one that counts deferred constraint violations). If P1 is
 1.72466 +** zero, the jump is taken if the statement constraint-counter is zero
 1.72467 +** (immediate foreign key constraint violations).
 1.72468 +*/
 1.72469 +case OP_FkIfZero: {         /* jump */
 1.72470 +  if( pOp->p1 ){
 1.72471 +    VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
 1.72472 +    if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
 1.72473 +  }else{
 1.72474 +    VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
 1.72475 +    if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
 1.72476 +  }
 1.72477 +  break;
 1.72478 +}
 1.72479 +#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
 1.72480 +
 1.72481 +#ifndef SQLITE_OMIT_AUTOINCREMENT
 1.72482 +/* Opcode: MemMax P1 P2 * * *
 1.72483 +** Synopsis: r[P1]=max(r[P1],r[P2])
 1.72484 +**
 1.72485 +** P1 is a register in the root frame of this VM (the root frame is
 1.72486 +** different from the current frame if this instruction is being executed
 1.72487 +** within a sub-program). Set the value of register P1 to the maximum of 
 1.72488 +** its current value and the value in register P2.
 1.72489 +**
 1.72490 +** This instruction throws an error if the memory cell is not initially
 1.72491 +** an integer.
 1.72492 +*/
 1.72493 +case OP_MemMax: {        /* in2 */
 1.72494 +  VdbeFrame *pFrame;
 1.72495 +  if( p->pFrame ){
 1.72496 +    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
 1.72497 +    pIn1 = &pFrame->aMem[pOp->p1];
 1.72498 +  }else{
 1.72499 +    pIn1 = &aMem[pOp->p1];
 1.72500 +  }
 1.72501 +  assert( memIsValid(pIn1) );
 1.72502 +  sqlite3VdbeMemIntegerify(pIn1);
 1.72503 +  pIn2 = &aMem[pOp->p2];
 1.72504 +  sqlite3VdbeMemIntegerify(pIn2);
 1.72505 +  if( pIn1->u.i<pIn2->u.i){
 1.72506 +    pIn1->u.i = pIn2->u.i;
 1.72507 +  }
 1.72508 +  break;
 1.72509 +}
 1.72510 +#endif /* SQLITE_OMIT_AUTOINCREMENT */
 1.72511 +
 1.72512 +/* Opcode: IfPos P1 P2 * * *
 1.72513 +** Synopsis: if r[P1]>0 goto P2
 1.72514 +**
 1.72515 +** If the value of register P1 is 1 or greater, jump to P2.
 1.72516 +**
 1.72517 +** It is illegal to use this instruction on a register that does
 1.72518 +** not contain an integer.  An assertion fault will result if you try.
 1.72519 +*/
 1.72520 +case OP_IfPos: {        /* jump, in1 */
 1.72521 +  pIn1 = &aMem[pOp->p1];
 1.72522 +  assert( pIn1->flags&MEM_Int );
 1.72523 +  VdbeBranchTaken( pIn1->u.i>0, 2);
 1.72524 +  if( pIn1->u.i>0 ){
 1.72525 +     pc = pOp->p2 - 1;
 1.72526 +  }
 1.72527 +  break;
 1.72528 +}
 1.72529 +
 1.72530 +/* Opcode: IfNeg P1 P2 * * *
 1.72531 +** Synopsis: if r[P1]<0 goto P2
 1.72532 +**
 1.72533 +** If the value of register P1 is less than zero, jump to P2. 
 1.72534 +**
 1.72535 +** It is illegal to use this instruction on a register that does
 1.72536 +** not contain an integer.  An assertion fault will result if you try.
 1.72537 +*/
 1.72538 +case OP_IfNeg: {        /* jump, in1 */
 1.72539 +  pIn1 = &aMem[pOp->p1];
 1.72540 +  assert( pIn1->flags&MEM_Int );
 1.72541 +  VdbeBranchTaken(pIn1->u.i<0, 2);
 1.72542 +  if( pIn1->u.i<0 ){
 1.72543 +     pc = pOp->p2 - 1;
 1.72544 +  }
 1.72545 +  break;
 1.72546 +}
 1.72547 +
 1.72548 +/* Opcode: IfZero P1 P2 P3 * *
 1.72549 +** Synopsis: r[P1]+=P3, if r[P1]==0 goto P2
 1.72550 +**
 1.72551 +** The register P1 must contain an integer.  Add literal P3 to the
 1.72552 +** value in register P1.  If the result is exactly 0, jump to P2. 
 1.72553 +**
 1.72554 +** It is illegal to use this instruction on a register that does
 1.72555 +** not contain an integer.  An assertion fault will result if you try.
 1.72556 +*/
 1.72557 +case OP_IfZero: {        /* jump, in1 */
 1.72558 +  pIn1 = &aMem[pOp->p1];
 1.72559 +  assert( pIn1->flags&MEM_Int );
 1.72560 +  pIn1->u.i += pOp->p3;
 1.72561 +  VdbeBranchTaken(pIn1->u.i==0, 2);
 1.72562 +  if( pIn1->u.i==0 ){
 1.72563 +     pc = pOp->p2 - 1;
 1.72564 +  }
 1.72565 +  break;
 1.72566 +}
 1.72567 +
 1.72568 +/* Opcode: AggStep * P2 P3 P4 P5
 1.72569 +** Synopsis: accum=r[P3] step(r[P2@P5])
 1.72570 +**
 1.72571 +** Execute the step function for an aggregate.  The
 1.72572 +** function has P5 arguments.   P4 is a pointer to the FuncDef
 1.72573 +** structure that specifies the function.  Use register
 1.72574 +** P3 as the accumulator.
 1.72575 +**
 1.72576 +** The P5 arguments are taken from register P2 and its
 1.72577 +** successors.
 1.72578 +*/
 1.72579 +case OP_AggStep: {
 1.72580 +  int n;
 1.72581 +  int i;
 1.72582 +  Mem *pMem;
 1.72583 +  Mem *pRec;
 1.72584 +  sqlite3_context ctx;
 1.72585 +  sqlite3_value **apVal;
 1.72586 +
 1.72587 +  n = pOp->p5;
 1.72588 +  assert( n>=0 );
 1.72589 +  pRec = &aMem[pOp->p2];
 1.72590 +  apVal = p->apArg;
 1.72591 +  assert( apVal || n==0 );
 1.72592 +  for(i=0; i<n; i++, pRec++){
 1.72593 +    assert( memIsValid(pRec) );
 1.72594 +    apVal[i] = pRec;
 1.72595 +    memAboutToChange(p, pRec);
 1.72596 +  }
 1.72597 +  ctx.pFunc = pOp->p4.pFunc;
 1.72598 +  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
 1.72599 +  ctx.pMem = pMem = &aMem[pOp->p3];
 1.72600 +  pMem->n++;
 1.72601 +  ctx.s.flags = MEM_Null;
 1.72602 +  ctx.s.z = 0;
 1.72603 +  ctx.s.zMalloc = 0;
 1.72604 +  ctx.s.xDel = 0;
 1.72605 +  ctx.s.db = db;
 1.72606 +  ctx.isError = 0;
 1.72607 +  ctx.pColl = 0;
 1.72608 +  ctx.skipFlag = 0;
 1.72609 +  if( ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
 1.72610 +    assert( pOp>p->aOp );
 1.72611 +    assert( pOp[-1].p4type==P4_COLLSEQ );
 1.72612 +    assert( pOp[-1].opcode==OP_CollSeq );
 1.72613 +    ctx.pColl = pOp[-1].p4.pColl;
 1.72614 +  }
 1.72615 +  (ctx.pFunc->xStep)(&ctx, n, apVal); /* IMP: R-24505-23230 */
 1.72616 +  if( ctx.isError ){
 1.72617 +    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
 1.72618 +    rc = ctx.isError;
 1.72619 +  }
 1.72620 +  if( ctx.skipFlag ){
 1.72621 +    assert( pOp[-1].opcode==OP_CollSeq );
 1.72622 +    i = pOp[-1].p1;
 1.72623 +    if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
 1.72624 +  }
 1.72625 +
 1.72626 +  sqlite3VdbeMemRelease(&ctx.s);
 1.72627 +
 1.72628 +  break;
 1.72629 +}
 1.72630 +
 1.72631 +/* Opcode: AggFinal P1 P2 * P4 *
 1.72632 +** Synopsis: accum=r[P1] N=P2
 1.72633 +**
 1.72634 +** Execute the finalizer function for an aggregate.  P1 is
 1.72635 +** the memory location that is the accumulator for the aggregate.
 1.72636 +**
 1.72637 +** P2 is the number of arguments that the step function takes and
 1.72638 +** P4 is a pointer to the FuncDef for this function.  The P2
 1.72639 +** argument is not used by this opcode.  It is only there to disambiguate
 1.72640 +** functions that can take varying numbers of arguments.  The
 1.72641 +** P4 argument is only needed for the degenerate case where
 1.72642 +** the step function was not previously called.
 1.72643 +*/
 1.72644 +case OP_AggFinal: {
 1.72645 +  Mem *pMem;
 1.72646 +  assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
 1.72647 +  pMem = &aMem[pOp->p1];
 1.72648 +  assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
 1.72649 +  rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
 1.72650 +  if( rc ){
 1.72651 +    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
 1.72652 +  }
 1.72653 +  sqlite3VdbeChangeEncoding(pMem, encoding);
 1.72654 +  UPDATE_MAX_BLOBSIZE(pMem);
 1.72655 +  if( sqlite3VdbeMemTooBig(pMem) ){
 1.72656 +    goto too_big;
 1.72657 +  }
 1.72658 +  break;
 1.72659 +}
 1.72660 +
 1.72661 +#ifndef SQLITE_OMIT_WAL
 1.72662 +/* Opcode: Checkpoint P1 P2 P3 * *
 1.72663 +**
 1.72664 +** Checkpoint database P1. This is a no-op if P1 is not currently in
 1.72665 +** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
 1.72666 +** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
 1.72667 +** SQLITE_BUSY or not, respectively.  Write the number of pages in the
 1.72668 +** WAL after the checkpoint into mem[P3+1] and the number of pages
 1.72669 +** in the WAL that have been checkpointed after the checkpoint
 1.72670 +** completes into mem[P3+2].  However on an error, mem[P3+1] and
 1.72671 +** mem[P3+2] are initialized to -1.
 1.72672 +*/
 1.72673 +case OP_Checkpoint: {
 1.72674 +  int i;                          /* Loop counter */
 1.72675 +  int aRes[3];                    /* Results */
 1.72676 +  Mem *pMem;                      /* Write results here */
 1.72677 +
 1.72678 +  assert( p->readOnly==0 );
 1.72679 +  aRes[0] = 0;
 1.72680 +  aRes[1] = aRes[2] = -1;
 1.72681 +  assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
 1.72682 +       || pOp->p2==SQLITE_CHECKPOINT_FULL
 1.72683 +       || pOp->p2==SQLITE_CHECKPOINT_RESTART
 1.72684 +  );
 1.72685 +  rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
 1.72686 +  if( rc==SQLITE_BUSY ){
 1.72687 +    rc = SQLITE_OK;
 1.72688 +    aRes[0] = 1;
 1.72689 +  }
 1.72690 +  for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
 1.72691 +    sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
 1.72692 +  }    
 1.72693 +  break;
 1.72694 +};  
 1.72695 +#endif
 1.72696 +
 1.72697 +#ifndef SQLITE_OMIT_PRAGMA
 1.72698 +/* Opcode: JournalMode P1 P2 P3 * *
 1.72699 +**
 1.72700 +** Change the journal mode of database P1 to P3. P3 must be one of the
 1.72701 +** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
 1.72702 +** modes (delete, truncate, persist, off and memory), this is a simple
 1.72703 +** operation. No IO is required.
 1.72704 +**
 1.72705 +** If changing into or out of WAL mode the procedure is more complicated.
 1.72706 +**
 1.72707 +** Write a string containing the final journal-mode to register P2.
 1.72708 +*/
 1.72709 +case OP_JournalMode: {    /* out2-prerelease */
 1.72710 +  Btree *pBt;                     /* Btree to change journal mode of */
 1.72711 +  Pager *pPager;                  /* Pager associated with pBt */
 1.72712 +  int eNew;                       /* New journal mode */
 1.72713 +  int eOld;                       /* The old journal mode */
 1.72714 +#ifndef SQLITE_OMIT_WAL
 1.72715 +  const char *zFilename;          /* Name of database file for pPager */
 1.72716 +#endif
 1.72717 +
 1.72718 +  eNew = pOp->p3;
 1.72719 +  assert( eNew==PAGER_JOURNALMODE_DELETE 
 1.72720 +       || eNew==PAGER_JOURNALMODE_TRUNCATE 
 1.72721 +       || eNew==PAGER_JOURNALMODE_PERSIST 
 1.72722 +       || eNew==PAGER_JOURNALMODE_OFF
 1.72723 +       || eNew==PAGER_JOURNALMODE_MEMORY
 1.72724 +       || eNew==PAGER_JOURNALMODE_WAL
 1.72725 +       || eNew==PAGER_JOURNALMODE_QUERY
 1.72726 +  );
 1.72727 +  assert( pOp->p1>=0 && pOp->p1<db->nDb );
 1.72728 +  assert( p->readOnly==0 );
 1.72729 +
 1.72730 +  pBt = db->aDb[pOp->p1].pBt;
 1.72731 +  pPager = sqlite3BtreePager(pBt);
 1.72732 +  eOld = sqlite3PagerGetJournalMode(pPager);
 1.72733 +  if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
 1.72734 +  if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
 1.72735 +
 1.72736 +#ifndef SQLITE_OMIT_WAL
 1.72737 +  zFilename = sqlite3PagerFilename(pPager, 1);
 1.72738 +
 1.72739 +  /* Do not allow a transition to journal_mode=WAL for a database
 1.72740 +  ** in temporary storage or if the VFS does not support shared memory 
 1.72741 +  */
 1.72742 +  if( eNew==PAGER_JOURNALMODE_WAL
 1.72743 +   && (sqlite3Strlen30(zFilename)==0           /* Temp file */
 1.72744 +       || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
 1.72745 +  ){
 1.72746 +    eNew = eOld;
 1.72747 +  }
 1.72748 +
 1.72749 +  if( (eNew!=eOld)
 1.72750 +   && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
 1.72751 +  ){
 1.72752 +    if( !db->autoCommit || db->nVdbeRead>1 ){
 1.72753 +      rc = SQLITE_ERROR;
 1.72754 +      sqlite3SetString(&p->zErrMsg, db, 
 1.72755 +          "cannot change %s wal mode from within a transaction",
 1.72756 +          (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
 1.72757 +      );
 1.72758 +      break;
 1.72759 +    }else{
 1.72760 + 
 1.72761 +      if( eOld==PAGER_JOURNALMODE_WAL ){
 1.72762 +        /* If leaving WAL mode, close the log file. If successful, the call
 1.72763 +        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log 
 1.72764 +        ** file. An EXCLUSIVE lock may still be held on the database file 
 1.72765 +        ** after a successful return. 
 1.72766 +        */
 1.72767 +        rc = sqlite3PagerCloseWal(pPager);
 1.72768 +        if( rc==SQLITE_OK ){
 1.72769 +          sqlite3PagerSetJournalMode(pPager, eNew);
 1.72770 +        }
 1.72771 +      }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
 1.72772 +        /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
 1.72773 +        ** as an intermediate */
 1.72774 +        sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
 1.72775 +      }
 1.72776 +  
 1.72777 +      /* Open a transaction on the database file. Regardless of the journal
 1.72778 +      ** mode, this transaction always uses a rollback journal.
 1.72779 +      */
 1.72780 +      assert( sqlite3BtreeIsInTrans(pBt)==0 );
 1.72781 +      if( rc==SQLITE_OK ){
 1.72782 +        rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
 1.72783 +      }
 1.72784 +    }
 1.72785 +  }
 1.72786 +#endif /* ifndef SQLITE_OMIT_WAL */
 1.72787 +
 1.72788 +  if( rc ){
 1.72789 +    eNew = eOld;
 1.72790 +  }
 1.72791 +  eNew = sqlite3PagerSetJournalMode(pPager, eNew);
 1.72792 +
 1.72793 +  pOut = &aMem[pOp->p2];
 1.72794 +  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
 1.72795 +  pOut->z = (char *)sqlite3JournalModename(eNew);
 1.72796 +  pOut->n = sqlite3Strlen30(pOut->z);
 1.72797 +  pOut->enc = SQLITE_UTF8;
 1.72798 +  sqlite3VdbeChangeEncoding(pOut, encoding);
 1.72799 +  break;
 1.72800 +};
 1.72801 +#endif /* SQLITE_OMIT_PRAGMA */
 1.72802 +
 1.72803 +#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
 1.72804 +/* Opcode: Vacuum * * * * *
 1.72805 +**
 1.72806 +** Vacuum the entire database.  This opcode will cause other virtual
 1.72807 +** machines to be created and run.  It may not be called from within
 1.72808 +** a transaction.
 1.72809 +*/
 1.72810 +case OP_Vacuum: {
 1.72811 +  assert( p->readOnly==0 );
 1.72812 +  rc = sqlite3RunVacuum(&p->zErrMsg, db);
 1.72813 +  break;
 1.72814 +}
 1.72815 +#endif
 1.72816 +
 1.72817 +#if !defined(SQLITE_OMIT_AUTOVACUUM)
 1.72818 +/* Opcode: IncrVacuum P1 P2 * * *
 1.72819 +**
 1.72820 +** Perform a single step of the incremental vacuum procedure on
 1.72821 +** the P1 database. If the vacuum has finished, jump to instruction
 1.72822 +** P2. Otherwise, fall through to the next instruction.
 1.72823 +*/
 1.72824 +case OP_IncrVacuum: {        /* jump */
 1.72825 +  Btree *pBt;
 1.72826 +
 1.72827 +  assert( pOp->p1>=0 && pOp->p1<db->nDb );
 1.72828 +  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
 1.72829 +  assert( p->readOnly==0 );
 1.72830 +  pBt = db->aDb[pOp->p1].pBt;
 1.72831 +  rc = sqlite3BtreeIncrVacuum(pBt);
 1.72832 +  VdbeBranchTaken(rc==SQLITE_DONE,2);
 1.72833 +  if( rc==SQLITE_DONE ){
 1.72834 +    pc = pOp->p2 - 1;
 1.72835 +    rc = SQLITE_OK;
 1.72836 +  }
 1.72837 +  break;
 1.72838 +}
 1.72839 +#endif
 1.72840 +
 1.72841 +/* Opcode: Expire P1 * * * *
 1.72842 +**
 1.72843 +** Cause precompiled statements to become expired. An expired statement
 1.72844 +** fails with an error code of SQLITE_SCHEMA if it is ever executed 
 1.72845 +** (via sqlite3_step()).
 1.72846 +** 
 1.72847 +** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
 1.72848 +** then only the currently executing statement is affected. 
 1.72849 +*/
 1.72850 +case OP_Expire: {
 1.72851 +  if( !pOp->p1 ){
 1.72852 +    sqlite3ExpirePreparedStatements(db);
 1.72853 +  }else{
 1.72854 +    p->expired = 1;
 1.72855 +  }
 1.72856 +  break;
 1.72857 +}
 1.72858 +
 1.72859 +#ifndef SQLITE_OMIT_SHARED_CACHE
 1.72860 +/* Opcode: TableLock P1 P2 P3 P4 *
 1.72861 +** Synopsis: iDb=P1 root=P2 write=P3
 1.72862 +**
 1.72863 +** Obtain a lock on a particular table. This instruction is only used when
 1.72864 +** the shared-cache feature is enabled. 
 1.72865 +**
 1.72866 +** P1 is the index of the database in sqlite3.aDb[] of the database
 1.72867 +** on which the lock is acquired.  A readlock is obtained if P3==0 or
 1.72868 +** a write lock if P3==1.
 1.72869 +**
 1.72870 +** P2 contains the root-page of the table to lock.
 1.72871 +**
 1.72872 +** P4 contains a pointer to the name of the table being locked. This is only
 1.72873 +** used to generate an error message if the lock cannot be obtained.
 1.72874 +*/
 1.72875 +case OP_TableLock: {
 1.72876 +  u8 isWriteLock = (u8)pOp->p3;
 1.72877 +  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
 1.72878 +    int p1 = pOp->p1; 
 1.72879 +    assert( p1>=0 && p1<db->nDb );
 1.72880 +    assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
 1.72881 +    assert( isWriteLock==0 || isWriteLock==1 );
 1.72882 +    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
 1.72883 +    if( (rc&0xFF)==SQLITE_LOCKED ){
 1.72884 +      const char *z = pOp->p4.z;
 1.72885 +      sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
 1.72886 +    }
 1.72887 +  }
 1.72888 +  break;
 1.72889 +}
 1.72890 +#endif /* SQLITE_OMIT_SHARED_CACHE */
 1.72891 +
 1.72892 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.72893 +/* Opcode: VBegin * * * P4 *
 1.72894 +**
 1.72895 +** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
 1.72896 +** xBegin method for that table.
 1.72897 +**
 1.72898 +** Also, whether or not P4 is set, check that this is not being called from
 1.72899 +** within a callback to a virtual table xSync() method. If it is, the error
 1.72900 +** code will be set to SQLITE_LOCKED.
 1.72901 +*/
 1.72902 +case OP_VBegin: {
 1.72903 +  VTable *pVTab;
 1.72904 +  pVTab = pOp->p4.pVtab;
 1.72905 +  rc = sqlite3VtabBegin(db, pVTab);
 1.72906 +  if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
 1.72907 +  break;
 1.72908 +}
 1.72909 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
 1.72910 +
 1.72911 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.72912 +/* Opcode: VCreate P1 * * P4 *
 1.72913 +**
 1.72914 +** P4 is the name of a virtual table in database P1. Call the xCreate method
 1.72915 +** for that table.
 1.72916 +*/
 1.72917 +case OP_VCreate: {
 1.72918 +  rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
 1.72919 +  break;
 1.72920 +}
 1.72921 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
 1.72922 +
 1.72923 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.72924 +/* Opcode: VDestroy P1 * * P4 *
 1.72925 +**
 1.72926 +** P4 is the name of a virtual table in database P1.  Call the xDestroy method
 1.72927 +** of that table.
 1.72928 +*/
 1.72929 +case OP_VDestroy: {
 1.72930 +  p->inVtabMethod = 2;
 1.72931 +  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
 1.72932 +  p->inVtabMethod = 0;
 1.72933 +  break;
 1.72934 +}
 1.72935 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
 1.72936 +
 1.72937 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.72938 +/* Opcode: VOpen P1 * * P4 *
 1.72939 +**
 1.72940 +** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
 1.72941 +** P1 is a cursor number.  This opcode opens a cursor to the virtual
 1.72942 +** table and stores that cursor in P1.
 1.72943 +*/
 1.72944 +case OP_VOpen: {
 1.72945 +  VdbeCursor *pCur;
 1.72946 +  sqlite3_vtab_cursor *pVtabCursor;
 1.72947 +  sqlite3_vtab *pVtab;
 1.72948 +  sqlite3_module *pModule;
 1.72949 +
 1.72950 +  assert( p->bIsReader );
 1.72951 +  pCur = 0;
 1.72952 +  pVtabCursor = 0;
 1.72953 +  pVtab = pOp->p4.pVtab->pVtab;
 1.72954 +  pModule = (sqlite3_module *)pVtab->pModule;
 1.72955 +  assert(pVtab && pModule);
 1.72956 +  rc = pModule->xOpen(pVtab, &pVtabCursor);
 1.72957 +  sqlite3VtabImportErrmsg(p, pVtab);
 1.72958 +  if( SQLITE_OK==rc ){
 1.72959 +    /* Initialize sqlite3_vtab_cursor base class */
 1.72960 +    pVtabCursor->pVtab = pVtab;
 1.72961 +
 1.72962 +    /* Initialize vdbe cursor object */
 1.72963 +    pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
 1.72964 +    if( pCur ){
 1.72965 +      pCur->pVtabCursor = pVtabCursor;
 1.72966 +    }else{
 1.72967 +      db->mallocFailed = 1;
 1.72968 +      pModule->xClose(pVtabCursor);
 1.72969 +    }
 1.72970 +  }
 1.72971 +  break;
 1.72972 +}
 1.72973 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
 1.72974 +
 1.72975 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.72976 +/* Opcode: VFilter P1 P2 P3 P4 *
 1.72977 +** Synopsis: iPlan=r[P3] zPlan='P4'
 1.72978 +**
 1.72979 +** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
 1.72980 +** the filtered result set is empty.
 1.72981 +**
 1.72982 +** P4 is either NULL or a string that was generated by the xBestIndex
 1.72983 +** method of the module.  The interpretation of the P4 string is left
 1.72984 +** to the module implementation.
 1.72985 +**
 1.72986 +** This opcode invokes the xFilter method on the virtual table specified
 1.72987 +** by P1.  The integer query plan parameter to xFilter is stored in register
 1.72988 +** P3. Register P3+1 stores the argc parameter to be passed to the
 1.72989 +** xFilter method. Registers P3+2..P3+1+argc are the argc
 1.72990 +** additional parameters which are passed to
 1.72991 +** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
 1.72992 +**
 1.72993 +** A jump is made to P2 if the result set after filtering would be empty.
 1.72994 +*/
 1.72995 +case OP_VFilter: {   /* jump */
 1.72996 +  int nArg;
 1.72997 +  int iQuery;
 1.72998 +  const sqlite3_module *pModule;
 1.72999 +  Mem *pQuery;
 1.73000 +  Mem *pArgc;
 1.73001 +  sqlite3_vtab_cursor *pVtabCursor;
 1.73002 +  sqlite3_vtab *pVtab;
 1.73003 +  VdbeCursor *pCur;
 1.73004 +  int res;
 1.73005 +  int i;
 1.73006 +  Mem **apArg;
 1.73007 +
 1.73008 +  pQuery = &aMem[pOp->p3];
 1.73009 +  pArgc = &pQuery[1];
 1.73010 +  pCur = p->apCsr[pOp->p1];
 1.73011 +  assert( memIsValid(pQuery) );
 1.73012 +  REGISTER_TRACE(pOp->p3, pQuery);
 1.73013 +  assert( pCur->pVtabCursor );
 1.73014 +  pVtabCursor = pCur->pVtabCursor;
 1.73015 +  pVtab = pVtabCursor->pVtab;
 1.73016 +  pModule = pVtab->pModule;
 1.73017 +
 1.73018 +  /* Grab the index number and argc parameters */
 1.73019 +  assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
 1.73020 +  nArg = (int)pArgc->u.i;
 1.73021 +  iQuery = (int)pQuery->u.i;
 1.73022 +
 1.73023 +  /* Invoke the xFilter method */
 1.73024 +  {
 1.73025 +    res = 0;
 1.73026 +    apArg = p->apArg;
 1.73027 +    for(i = 0; i<nArg; i++){
 1.73028 +      apArg[i] = &pArgc[i+1];
 1.73029 +    }
 1.73030 +
 1.73031 +    p->inVtabMethod = 1;
 1.73032 +    rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
 1.73033 +    p->inVtabMethod = 0;
 1.73034 +    sqlite3VtabImportErrmsg(p, pVtab);
 1.73035 +    if( rc==SQLITE_OK ){
 1.73036 +      res = pModule->xEof(pVtabCursor);
 1.73037 +    }
 1.73038 +    VdbeBranchTaken(res!=0,2);
 1.73039 +    if( res ){
 1.73040 +      pc = pOp->p2 - 1;
 1.73041 +    }
 1.73042 +  }
 1.73043 +  pCur->nullRow = 0;
 1.73044 +
 1.73045 +  break;
 1.73046 +}
 1.73047 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
 1.73048 +
 1.73049 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.73050 +/* Opcode: VColumn P1 P2 P3 * *
 1.73051 +** Synopsis: r[P3]=vcolumn(P2)
 1.73052 +**
 1.73053 +** Store the value of the P2-th column of
 1.73054 +** the row of the virtual-table that the 
 1.73055 +** P1 cursor is pointing to into register P3.
 1.73056 +*/
 1.73057 +case OP_VColumn: {
 1.73058 +  sqlite3_vtab *pVtab;
 1.73059 +  const sqlite3_module *pModule;
 1.73060 +  Mem *pDest;
 1.73061 +  sqlite3_context sContext;
 1.73062 +
 1.73063 +  VdbeCursor *pCur = p->apCsr[pOp->p1];
 1.73064 +  assert( pCur->pVtabCursor );
 1.73065 +  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
 1.73066 +  pDest = &aMem[pOp->p3];
 1.73067 +  memAboutToChange(p, pDest);
 1.73068 +  if( pCur->nullRow ){
 1.73069 +    sqlite3VdbeMemSetNull(pDest);
 1.73070 +    break;
 1.73071 +  }
 1.73072 +  pVtab = pCur->pVtabCursor->pVtab;
 1.73073 +  pModule = pVtab->pModule;
 1.73074 +  assert( pModule->xColumn );
 1.73075 +  memset(&sContext, 0, sizeof(sContext));
 1.73076 +
 1.73077 +  /* The output cell may already have a buffer allocated. Move
 1.73078 +  ** the current contents to sContext.s so in case the user-function 
 1.73079 +  ** can use the already allocated buffer instead of allocating a 
 1.73080 +  ** new one.
 1.73081 +  */
 1.73082 +  sqlite3VdbeMemMove(&sContext.s, pDest);
 1.73083 +  MemSetTypeFlag(&sContext.s, MEM_Null);
 1.73084 +
 1.73085 +  rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
 1.73086 +  sqlite3VtabImportErrmsg(p, pVtab);
 1.73087 +  if( sContext.isError ){
 1.73088 +    rc = sContext.isError;
 1.73089 +  }
 1.73090 +
 1.73091 +  /* Copy the result of the function to the P3 register. We
 1.73092 +  ** do this regardless of whether or not an error occurred to ensure any
 1.73093 +  ** dynamic allocation in sContext.s (a Mem struct) is  released.
 1.73094 +  */
 1.73095 +  sqlite3VdbeChangeEncoding(&sContext.s, encoding);
 1.73096 +  sqlite3VdbeMemMove(pDest, &sContext.s);
 1.73097 +  REGISTER_TRACE(pOp->p3, pDest);
 1.73098 +  UPDATE_MAX_BLOBSIZE(pDest);
 1.73099 +
 1.73100 +  if( sqlite3VdbeMemTooBig(pDest) ){
 1.73101 +    goto too_big;
 1.73102 +  }
 1.73103 +  break;
 1.73104 +}
 1.73105 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
 1.73106 +
 1.73107 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.73108 +/* Opcode: VNext P1 P2 * * *
 1.73109 +**
 1.73110 +** Advance virtual table P1 to the next row in its result set and
 1.73111 +** jump to instruction P2.  Or, if the virtual table has reached
 1.73112 +** the end of its result set, then fall through to the next instruction.
 1.73113 +*/
 1.73114 +case OP_VNext: {   /* jump */
 1.73115 +  sqlite3_vtab *pVtab;
 1.73116 +  const sqlite3_module *pModule;
 1.73117 +  int res;
 1.73118 +  VdbeCursor *pCur;
 1.73119 +
 1.73120 +  res = 0;
 1.73121 +  pCur = p->apCsr[pOp->p1];
 1.73122 +  assert( pCur->pVtabCursor );
 1.73123 +  if( pCur->nullRow ){
 1.73124 +    break;
 1.73125 +  }
 1.73126 +  pVtab = pCur->pVtabCursor->pVtab;
 1.73127 +  pModule = pVtab->pModule;
 1.73128 +  assert( pModule->xNext );
 1.73129 +
 1.73130 +  /* Invoke the xNext() method of the module. There is no way for the
 1.73131 +  ** underlying implementation to return an error if one occurs during
 1.73132 +  ** xNext(). Instead, if an error occurs, true is returned (indicating that 
 1.73133 +  ** data is available) and the error code returned when xColumn or
 1.73134 +  ** some other method is next invoked on the save virtual table cursor.
 1.73135 +  */
 1.73136 +  p->inVtabMethod = 1;
 1.73137 +  rc = pModule->xNext(pCur->pVtabCursor);
 1.73138 +  p->inVtabMethod = 0;
 1.73139 +  sqlite3VtabImportErrmsg(p, pVtab);
 1.73140 +  if( rc==SQLITE_OK ){
 1.73141 +    res = pModule->xEof(pCur->pVtabCursor);
 1.73142 +  }
 1.73143 +  VdbeBranchTaken(!res,2);
 1.73144 +  if( !res ){
 1.73145 +    /* If there is data, jump to P2 */
 1.73146 +    pc = pOp->p2 - 1;
 1.73147 +  }
 1.73148 +  goto check_for_interrupt;
 1.73149 +}
 1.73150 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
 1.73151 +
 1.73152 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.73153 +/* Opcode: VRename P1 * * P4 *
 1.73154 +**
 1.73155 +** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
 1.73156 +** This opcode invokes the corresponding xRename method. The value
 1.73157 +** in register P1 is passed as the zName argument to the xRename method.
 1.73158 +*/
 1.73159 +case OP_VRename: {
 1.73160 +  sqlite3_vtab *pVtab;
 1.73161 +  Mem *pName;
 1.73162 +
 1.73163 +  pVtab = pOp->p4.pVtab->pVtab;
 1.73164 +  pName = &aMem[pOp->p1];
 1.73165 +  assert( pVtab->pModule->xRename );
 1.73166 +  assert( memIsValid(pName) );
 1.73167 +  assert( p->readOnly==0 );
 1.73168 +  REGISTER_TRACE(pOp->p1, pName);
 1.73169 +  assert( pName->flags & MEM_Str );
 1.73170 +  testcase( pName->enc==SQLITE_UTF8 );
 1.73171 +  testcase( pName->enc==SQLITE_UTF16BE );
 1.73172 +  testcase( pName->enc==SQLITE_UTF16LE );
 1.73173 +  rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
 1.73174 +  if( rc==SQLITE_OK ){
 1.73175 +    rc = pVtab->pModule->xRename(pVtab, pName->z);
 1.73176 +    sqlite3VtabImportErrmsg(p, pVtab);
 1.73177 +    p->expired = 0;
 1.73178 +  }
 1.73179 +  break;
 1.73180 +}
 1.73181 +#endif
 1.73182 +
 1.73183 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.73184 +/* Opcode: VUpdate P1 P2 P3 P4 P5
 1.73185 +** Synopsis: data=r[P3@P2]
 1.73186 +**
 1.73187 +** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
 1.73188 +** This opcode invokes the corresponding xUpdate method. P2 values
 1.73189 +** are contiguous memory cells starting at P3 to pass to the xUpdate 
 1.73190 +** invocation. The value in register (P3+P2-1) corresponds to the 
 1.73191 +** p2th element of the argv array passed to xUpdate.
 1.73192 +**
 1.73193 +** The xUpdate method will do a DELETE or an INSERT or both.
 1.73194 +** The argv[0] element (which corresponds to memory cell P3)
 1.73195 +** is the rowid of a row to delete.  If argv[0] is NULL then no 
 1.73196 +** deletion occurs.  The argv[1] element is the rowid of the new 
 1.73197 +** row.  This can be NULL to have the virtual table select the new 
 1.73198 +** rowid for itself.  The subsequent elements in the array are 
 1.73199 +** the values of columns in the new row.
 1.73200 +**
 1.73201 +** If P2==1 then no insert is performed.  argv[0] is the rowid of
 1.73202 +** a row to delete.
 1.73203 +**
 1.73204 +** P1 is a boolean flag. If it is set to true and the xUpdate call
 1.73205 +** is successful, then the value returned by sqlite3_last_insert_rowid() 
 1.73206 +** is set to the value of the rowid for the row just inserted.
 1.73207 +**
 1.73208 +** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
 1.73209 +** apply in the case of a constraint failure on an insert or update.
 1.73210 +*/
 1.73211 +case OP_VUpdate: {
 1.73212 +  sqlite3_vtab *pVtab;
 1.73213 +  sqlite3_module *pModule;
 1.73214 +  int nArg;
 1.73215 +  int i;
 1.73216 +  sqlite_int64 rowid;
 1.73217 +  Mem **apArg;
 1.73218 +  Mem *pX;
 1.73219 +
 1.73220 +  assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback 
 1.73221 +       || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
 1.73222 +  );
 1.73223 +  assert( p->readOnly==0 );
 1.73224 +  pVtab = pOp->p4.pVtab->pVtab;
 1.73225 +  pModule = (sqlite3_module *)pVtab->pModule;
 1.73226 +  nArg = pOp->p2;
 1.73227 +  assert( pOp->p4type==P4_VTAB );
 1.73228 +  if( ALWAYS(pModule->xUpdate) ){
 1.73229 +    u8 vtabOnConflict = db->vtabOnConflict;
 1.73230 +    apArg = p->apArg;
 1.73231 +    pX = &aMem[pOp->p3];
 1.73232 +    for(i=0; i<nArg; i++){
 1.73233 +      assert( memIsValid(pX) );
 1.73234 +      memAboutToChange(p, pX);
 1.73235 +      apArg[i] = pX;
 1.73236 +      pX++;
 1.73237 +    }
 1.73238 +    db->vtabOnConflict = pOp->p5;
 1.73239 +    rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
 1.73240 +    db->vtabOnConflict = vtabOnConflict;
 1.73241 +    sqlite3VtabImportErrmsg(p, pVtab);
 1.73242 +    if( rc==SQLITE_OK && pOp->p1 ){
 1.73243 +      assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
 1.73244 +      db->lastRowid = lastRowid = rowid;
 1.73245 +    }
 1.73246 +    if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
 1.73247 +      if( pOp->p5==OE_Ignore ){
 1.73248 +        rc = SQLITE_OK;
 1.73249 +      }else{
 1.73250 +        p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
 1.73251 +      }
 1.73252 +    }else{
 1.73253 +      p->nChange++;
 1.73254 +    }
 1.73255 +  }
 1.73256 +  break;
 1.73257 +}
 1.73258 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
 1.73259 +
 1.73260 +#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
 1.73261 +/* Opcode: Pagecount P1 P2 * * *
 1.73262 +**
 1.73263 +** Write the current number of pages in database P1 to memory cell P2.
 1.73264 +*/
 1.73265 +case OP_Pagecount: {            /* out2-prerelease */
 1.73266 +  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
 1.73267 +  break;
 1.73268 +}
 1.73269 +#endif
 1.73270 +
 1.73271 +
 1.73272 +#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
 1.73273 +/* Opcode: MaxPgcnt P1 P2 P3 * *
 1.73274 +**
 1.73275 +** Try to set the maximum page count for database P1 to the value in P3.
 1.73276 +** Do not let the maximum page count fall below the current page count and
 1.73277 +** do not change the maximum page count value if P3==0.
 1.73278 +**
 1.73279 +** Store the maximum page count after the change in register P2.
 1.73280 +*/
 1.73281 +case OP_MaxPgcnt: {            /* out2-prerelease */
 1.73282 +  unsigned int newMax;
 1.73283 +  Btree *pBt;
 1.73284 +
 1.73285 +  pBt = db->aDb[pOp->p1].pBt;
 1.73286 +  newMax = 0;
 1.73287 +  if( pOp->p3 ){
 1.73288 +    newMax = sqlite3BtreeLastPage(pBt);
 1.73289 +    if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
 1.73290 +  }
 1.73291 +  pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
 1.73292 +  break;
 1.73293 +}
 1.73294 +#endif
 1.73295 +
 1.73296 +
 1.73297 +/* Opcode: Init * P2 * P4 *
 1.73298 +** Synopsis:  Start at P2
 1.73299 +**
 1.73300 +** Programs contain a single instance of this opcode as the very first
 1.73301 +** opcode.
 1.73302 +**
 1.73303 +** If tracing is enabled (by the sqlite3_trace()) interface, then
 1.73304 +** the UTF-8 string contained in P4 is emitted on the trace callback.
 1.73305 +** Or if P4 is blank, use the string returned by sqlite3_sql().
 1.73306 +**
 1.73307 +** If P2 is not zero, jump to instruction P2.
 1.73308 +*/
 1.73309 +case OP_Init: {          /* jump */
 1.73310 +  char *zTrace;
 1.73311 +  char *z;
 1.73312 +
 1.73313 +  if( pOp->p2 ){
 1.73314 +    pc = pOp->p2 - 1;
 1.73315 +  }
 1.73316 +#ifndef SQLITE_OMIT_TRACE
 1.73317 +  if( db->xTrace
 1.73318 +   && !p->doingRerun
 1.73319 +   && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
 1.73320 +  ){
 1.73321 +    z = sqlite3VdbeExpandSql(p, zTrace);
 1.73322 +    db->xTrace(db->pTraceArg, z);
 1.73323 +    sqlite3DbFree(db, z);
 1.73324 +  }
 1.73325 +#ifdef SQLITE_USE_FCNTL_TRACE
 1.73326 +  zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
 1.73327 +  if( zTrace ){
 1.73328 +    int i;
 1.73329 +    for(i=0; i<db->nDb; i++){
 1.73330 +      if( MASKBIT(i) & p->btreeMask)==0 ) continue;
 1.73331 +      sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
 1.73332 +    }
 1.73333 +  }
 1.73334 +#endif /* SQLITE_USE_FCNTL_TRACE */
 1.73335 +#ifdef SQLITE_DEBUG
 1.73336 +  if( (db->flags & SQLITE_SqlTrace)!=0
 1.73337 +   && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
 1.73338 +  ){
 1.73339 +    sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
 1.73340 +  }
 1.73341 +#endif /* SQLITE_DEBUG */
 1.73342 +#endif /* SQLITE_OMIT_TRACE */
 1.73343 +  break;
 1.73344 +}
 1.73345 +
 1.73346 +
 1.73347 +/* Opcode: Noop * * * * *
 1.73348 +**
 1.73349 +** Do nothing.  This instruction is often useful as a jump
 1.73350 +** destination.
 1.73351 +*/
 1.73352 +/*
 1.73353 +** The magic Explain opcode are only inserted when explain==2 (which
 1.73354 +** is to say when the EXPLAIN QUERY PLAN syntax is used.)
 1.73355 +** This opcode records information from the optimizer.  It is the
 1.73356 +** the same as a no-op.  This opcodesnever appears in a real VM program.
 1.73357 +*/
 1.73358 +default: {          /* This is really OP_Noop and OP_Explain */
 1.73359 +  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
 1.73360 +  break;
 1.73361 +}
 1.73362 +
 1.73363 +/*****************************************************************************
 1.73364 +** The cases of the switch statement above this line should all be indented
 1.73365 +** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
 1.73366 +** readability.  From this point on down, the normal indentation rules are
 1.73367 +** restored.
 1.73368 +*****************************************************************************/
 1.73369 +    }
 1.73370 +
 1.73371 +#ifdef VDBE_PROFILE
 1.73372 +    {
 1.73373 +      u64 elapsed = sqlite3Hwtime() - start;
 1.73374 +      pOp->cycles += elapsed;
 1.73375 +      pOp->cnt++;
 1.73376 +    }
 1.73377 +#endif
 1.73378 +
 1.73379 +    /* The following code adds nothing to the actual functionality
 1.73380 +    ** of the program.  It is only here for testing and debugging.
 1.73381 +    ** On the other hand, it does burn CPU cycles every time through
 1.73382 +    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
 1.73383 +    */
 1.73384 +#ifndef NDEBUG
 1.73385 +    assert( pc>=-1 && pc<p->nOp );
 1.73386 +
 1.73387 +#ifdef SQLITE_DEBUG
 1.73388 +    if( db->flags & SQLITE_VdbeTrace ){
 1.73389 +      if( rc!=0 ) printf("rc=%d\n",rc);
 1.73390 +      if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
 1.73391 +        registerTrace(pOp->p2, &aMem[pOp->p2]);
 1.73392 +      }
 1.73393 +      if( pOp->opflags & OPFLG_OUT3 ){
 1.73394 +        registerTrace(pOp->p3, &aMem[pOp->p3]);
 1.73395 +      }
 1.73396 +    }
 1.73397 +#endif  /* SQLITE_DEBUG */
 1.73398 +#endif  /* NDEBUG */
 1.73399 +  }  /* The end of the for(;;) loop the loops through opcodes */
 1.73400 +
 1.73401 +  /* If we reach this point, it means that execution is finished with
 1.73402 +  ** an error of some kind.
 1.73403 +  */
 1.73404 +vdbe_error_halt:
 1.73405 +  assert( rc );
 1.73406 +  p->rc = rc;
 1.73407 +  testcase( sqlite3GlobalConfig.xLog!=0 );
 1.73408 +  sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
 1.73409 +                   pc, p->zSql, p->zErrMsg);
 1.73410 +  sqlite3VdbeHalt(p);
 1.73411 +  if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
 1.73412 +  rc = SQLITE_ERROR;
 1.73413 +  if( resetSchemaOnFault>0 ){
 1.73414 +    sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
 1.73415 +  }
 1.73416 +
 1.73417 +  /* This is the only way out of this procedure.  We have to
 1.73418 +  ** release the mutexes on btrees that were acquired at the
 1.73419 +  ** top. */
 1.73420 +vdbe_return:
 1.73421 +  db->lastRowid = lastRowid;
 1.73422 +  testcase( nVmStep>0 );
 1.73423 +  p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
 1.73424 +  sqlite3VdbeLeave(p);
 1.73425 +  return rc;
 1.73426 +
 1.73427 +  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
 1.73428 +  ** is encountered.
 1.73429 +  */
 1.73430 +too_big:
 1.73431 +  sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
 1.73432 +  rc = SQLITE_TOOBIG;
 1.73433 +  goto vdbe_error_halt;
 1.73434 +
 1.73435 +  /* Jump to here if a malloc() fails.
 1.73436 +  */
 1.73437 +no_mem:
 1.73438 +  db->mallocFailed = 1;
 1.73439 +  sqlite3SetString(&p->zErrMsg, db, "out of memory");
 1.73440 +  rc = SQLITE_NOMEM;
 1.73441 +  goto vdbe_error_halt;
 1.73442 +
 1.73443 +  /* Jump to here for any other kind of fatal error.  The "rc" variable
 1.73444 +  ** should hold the error number.
 1.73445 +  */
 1.73446 +abort_due_to_error:
 1.73447 +  assert( p->zErrMsg==0 );
 1.73448 +  if( db->mallocFailed ) rc = SQLITE_NOMEM;
 1.73449 +  if( rc!=SQLITE_IOERR_NOMEM ){
 1.73450 +    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
 1.73451 +  }
 1.73452 +  goto vdbe_error_halt;
 1.73453 +
 1.73454 +  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
 1.73455 +  ** flag.
 1.73456 +  */
 1.73457 +abort_due_to_interrupt:
 1.73458 +  assert( db->u1.isInterrupted );
 1.73459 +  rc = SQLITE_INTERRUPT;
 1.73460 +  p->rc = rc;
 1.73461 +  sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
 1.73462 +  goto vdbe_error_halt;
 1.73463 +}
 1.73464 +
 1.73465 +
 1.73466 +/************** End of vdbe.c ************************************************/
 1.73467 +/************** Begin file vdbeblob.c ****************************************/
 1.73468 +/*
 1.73469 +** 2007 May 1
 1.73470 +**
 1.73471 +** The author disclaims copyright to this source code.  In place of
 1.73472 +** a legal notice, here is a blessing:
 1.73473 +**
 1.73474 +**    May you do good and not evil.
 1.73475 +**    May you find forgiveness for yourself and forgive others.
 1.73476 +**    May you share freely, never taking more than you give.
 1.73477 +**
 1.73478 +*************************************************************************
 1.73479 +**
 1.73480 +** This file contains code used to implement incremental BLOB I/O.
 1.73481 +*/
 1.73482 +
 1.73483 +
 1.73484 +#ifndef SQLITE_OMIT_INCRBLOB
 1.73485 +
 1.73486 +/*
 1.73487 +** Valid sqlite3_blob* handles point to Incrblob structures.
 1.73488 +*/
 1.73489 +typedef struct Incrblob Incrblob;
 1.73490 +struct Incrblob {
 1.73491 +  int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
 1.73492 +  int nByte;              /* Size of open blob, in bytes */
 1.73493 +  int iOffset;            /* Byte offset of blob in cursor data */
 1.73494 +  int iCol;               /* Table column this handle is open on */
 1.73495 +  BtCursor *pCsr;         /* Cursor pointing at blob row */
 1.73496 +  sqlite3_stmt *pStmt;    /* Statement holding cursor open */
 1.73497 +  sqlite3 *db;            /* The associated database */
 1.73498 +};
 1.73499 +
 1.73500 +
 1.73501 +/*
 1.73502 +** This function is used by both blob_open() and blob_reopen(). It seeks
 1.73503 +** the b-tree cursor associated with blob handle p to point to row iRow.
 1.73504 +** If successful, SQLITE_OK is returned and subsequent calls to
 1.73505 +** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
 1.73506 +**
 1.73507 +** If an error occurs, or if the specified row does not exist or does not
 1.73508 +** contain a value of type TEXT or BLOB in the column nominated when the
 1.73509 +** blob handle was opened, then an error code is returned and *pzErr may
 1.73510 +** be set to point to a buffer containing an error message. It is the
 1.73511 +** responsibility of the caller to free the error message buffer using
 1.73512 +** sqlite3DbFree().
 1.73513 +**
 1.73514 +** If an error does occur, then the b-tree cursor is closed. All subsequent
 1.73515 +** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will 
 1.73516 +** immediately return SQLITE_ABORT.
 1.73517 +*/
 1.73518 +static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
 1.73519 +  int rc;                         /* Error code */
 1.73520 +  char *zErr = 0;                 /* Error message */
 1.73521 +  Vdbe *v = (Vdbe *)p->pStmt;
 1.73522 +
 1.73523 +  /* Set the value of the SQL statements only variable to integer iRow. 
 1.73524 +  ** This is done directly instead of using sqlite3_bind_int64() to avoid 
 1.73525 +  ** triggering asserts related to mutexes.
 1.73526 +  */
 1.73527 +  assert( v->aVar[0].flags&MEM_Int );
 1.73528 +  v->aVar[0].u.i = iRow;
 1.73529 +
 1.73530 +  rc = sqlite3_step(p->pStmt);
 1.73531 +  if( rc==SQLITE_ROW ){
 1.73532 +    VdbeCursor *pC = v->apCsr[0];
 1.73533 +    u32 type = pC->aType[p->iCol];
 1.73534 +    if( type<12 ){
 1.73535 +      zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
 1.73536 +          type==0?"null": type==7?"real": "integer"
 1.73537 +      );
 1.73538 +      rc = SQLITE_ERROR;
 1.73539 +      sqlite3_finalize(p->pStmt);
 1.73540 +      p->pStmt = 0;
 1.73541 +    }else{
 1.73542 +      p->iOffset = pC->aType[p->iCol + pC->nField];
 1.73543 +      p->nByte = sqlite3VdbeSerialTypeLen(type);
 1.73544 +      p->pCsr =  pC->pCursor;
 1.73545 +      sqlite3BtreeEnterCursor(p->pCsr);
 1.73546 +      sqlite3BtreeCacheOverflow(p->pCsr);
 1.73547 +      sqlite3BtreeLeaveCursor(p->pCsr);
 1.73548 +    }
 1.73549 +  }
 1.73550 +
 1.73551 +  if( rc==SQLITE_ROW ){
 1.73552 +    rc = SQLITE_OK;
 1.73553 +  }else if( p->pStmt ){
 1.73554 +    rc = sqlite3_finalize(p->pStmt);
 1.73555 +    p->pStmt = 0;
 1.73556 +    if( rc==SQLITE_OK ){
 1.73557 +      zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
 1.73558 +      rc = SQLITE_ERROR;
 1.73559 +    }else{
 1.73560 +      zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
 1.73561 +    }
 1.73562 +  }
 1.73563 +
 1.73564 +  assert( rc!=SQLITE_OK || zErr==0 );
 1.73565 +  assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
 1.73566 +
 1.73567 +  *pzErr = zErr;
 1.73568 +  return rc;
 1.73569 +}
 1.73570 +
 1.73571 +/*
 1.73572 +** Open a blob handle.
 1.73573 +*/
 1.73574 +SQLITE_API int sqlite3_blob_open(
 1.73575 +  sqlite3* db,            /* The database connection */
 1.73576 +  const char *zDb,        /* The attached database containing the blob */
 1.73577 +  const char *zTable,     /* The table containing the blob */
 1.73578 +  const char *zColumn,    /* The column containing the blob */
 1.73579 +  sqlite_int64 iRow,      /* The row containing the glob */
 1.73580 +  int flags,              /* True -> read/write access, false -> read-only */
 1.73581 +  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
 1.73582 +){
 1.73583 +  int nAttempt = 0;
 1.73584 +  int iCol;               /* Index of zColumn in row-record */
 1.73585 +
 1.73586 +  /* This VDBE program seeks a btree cursor to the identified 
 1.73587 +  ** db/table/row entry. The reason for using a vdbe program instead
 1.73588 +  ** of writing code to use the b-tree layer directly is that the
 1.73589 +  ** vdbe program will take advantage of the various transaction,
 1.73590 +  ** locking and error handling infrastructure built into the vdbe.
 1.73591 +  **
 1.73592 +  ** After seeking the cursor, the vdbe executes an OP_ResultRow.
 1.73593 +  ** Code external to the Vdbe then "borrows" the b-tree cursor and
 1.73594 +  ** uses it to implement the blob_read(), blob_write() and 
 1.73595 +  ** blob_bytes() functions.
 1.73596 +  **
 1.73597 +  ** The sqlite3_blob_close() function finalizes the vdbe program,
 1.73598 +  ** which closes the b-tree cursor and (possibly) commits the 
 1.73599 +  ** transaction.
 1.73600 +  */
 1.73601 +  static const int iLn = VDBE_OFFSET_LINENO(4);
 1.73602 +  static const VdbeOpList openBlob[] = {
 1.73603 +    /* {OP_Transaction, 0, 0, 0},  // 0: Inserted separately */
 1.73604 +    {OP_TableLock, 0, 0, 0},       /* 1: Acquire a read or write lock */
 1.73605 +    /* One of the following two instructions is replaced by an OP_Noop. */
 1.73606 +    {OP_OpenRead, 0, 0, 0},        /* 2: Open cursor 0 for reading */
 1.73607 +    {OP_OpenWrite, 0, 0, 0},       /* 3: Open cursor 0 for read/write */
 1.73608 +    {OP_Variable, 1, 1, 1},        /* 4: Push the rowid to the stack */
 1.73609 +    {OP_NotExists, 0, 10, 1},      /* 5: Seek the cursor */
 1.73610 +    {OP_Column, 0, 0, 1},          /* 6  */
 1.73611 +    {OP_ResultRow, 1, 0, 0},       /* 7  */
 1.73612 +    {OP_Goto, 0, 4, 0},            /* 8  */
 1.73613 +    {OP_Close, 0, 0, 0},           /* 9  */
 1.73614 +    {OP_Halt, 0, 0, 0},            /* 10 */
 1.73615 +  };
 1.73616 +
 1.73617 +  int rc = SQLITE_OK;
 1.73618 +  char *zErr = 0;
 1.73619 +  Table *pTab;
 1.73620 +  Parse *pParse = 0;
 1.73621 +  Incrblob *pBlob = 0;
 1.73622 +
 1.73623 +  flags = !!flags;                /* flags = (flags ? 1 : 0); */
 1.73624 +  *ppBlob = 0;
 1.73625 +
 1.73626 +  sqlite3_mutex_enter(db->mutex);
 1.73627 +
 1.73628 +  pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
 1.73629 +  if( !pBlob ) goto blob_open_out;
 1.73630 +  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
 1.73631 +  if( !pParse ) goto blob_open_out;
 1.73632 +
 1.73633 +  do {
 1.73634 +    memset(pParse, 0, sizeof(Parse));
 1.73635 +    pParse->db = db;
 1.73636 +    sqlite3DbFree(db, zErr);
 1.73637 +    zErr = 0;
 1.73638 +
 1.73639 +    sqlite3BtreeEnterAll(db);
 1.73640 +    pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
 1.73641 +    if( pTab && IsVirtual(pTab) ){
 1.73642 +      pTab = 0;
 1.73643 +      sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
 1.73644 +    }
 1.73645 +    if( pTab && !HasRowid(pTab) ){
 1.73646 +      pTab = 0;
 1.73647 +      sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
 1.73648 +    }
 1.73649 +#ifndef SQLITE_OMIT_VIEW
 1.73650 +    if( pTab && pTab->pSelect ){
 1.73651 +      pTab = 0;
 1.73652 +      sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
 1.73653 +    }
 1.73654 +#endif
 1.73655 +    if( !pTab ){
 1.73656 +      if( pParse->zErrMsg ){
 1.73657 +        sqlite3DbFree(db, zErr);
 1.73658 +        zErr = pParse->zErrMsg;
 1.73659 +        pParse->zErrMsg = 0;
 1.73660 +      }
 1.73661 +      rc = SQLITE_ERROR;
 1.73662 +      sqlite3BtreeLeaveAll(db);
 1.73663 +      goto blob_open_out;
 1.73664 +    }
 1.73665 +
 1.73666 +    /* Now search pTab for the exact column. */
 1.73667 +    for(iCol=0; iCol<pTab->nCol; iCol++) {
 1.73668 +      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
 1.73669 +        break;
 1.73670 +      }
 1.73671 +    }
 1.73672 +    if( iCol==pTab->nCol ){
 1.73673 +      sqlite3DbFree(db, zErr);
 1.73674 +      zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
 1.73675 +      rc = SQLITE_ERROR;
 1.73676 +      sqlite3BtreeLeaveAll(db);
 1.73677 +      goto blob_open_out;
 1.73678 +    }
 1.73679 +
 1.73680 +    /* If the value is being opened for writing, check that the
 1.73681 +    ** column is not indexed, and that it is not part of a foreign key. 
 1.73682 +    ** It is against the rules to open a column to which either of these
 1.73683 +    ** descriptions applies for writing.  */
 1.73684 +    if( flags ){
 1.73685 +      const char *zFault = 0;
 1.73686 +      Index *pIdx;
 1.73687 +#ifndef SQLITE_OMIT_FOREIGN_KEY
 1.73688 +      if( db->flags&SQLITE_ForeignKeys ){
 1.73689 +        /* Check that the column is not part of an FK child key definition. It
 1.73690 +        ** is not necessary to check if it is part of a parent key, as parent
 1.73691 +        ** key columns must be indexed. The check below will pick up this 
 1.73692 +        ** case.  */
 1.73693 +        FKey *pFKey;
 1.73694 +        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
 1.73695 +          int j;
 1.73696 +          for(j=0; j<pFKey->nCol; j++){
 1.73697 +            if( pFKey->aCol[j].iFrom==iCol ){
 1.73698 +              zFault = "foreign key";
 1.73699 +            }
 1.73700 +          }
 1.73701 +        }
 1.73702 +      }
 1.73703 +#endif
 1.73704 +      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
 1.73705 +        int j;
 1.73706 +        for(j=0; j<pIdx->nKeyCol; j++){
 1.73707 +          if( pIdx->aiColumn[j]==iCol ){
 1.73708 +            zFault = "indexed";
 1.73709 +          }
 1.73710 +        }
 1.73711 +      }
 1.73712 +      if( zFault ){
 1.73713 +        sqlite3DbFree(db, zErr);
 1.73714 +        zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
 1.73715 +        rc = SQLITE_ERROR;
 1.73716 +        sqlite3BtreeLeaveAll(db);
 1.73717 +        goto blob_open_out;
 1.73718 +      }
 1.73719 +    }
 1.73720 +
 1.73721 +    pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
 1.73722 +    assert( pBlob->pStmt || db->mallocFailed );
 1.73723 +    if( pBlob->pStmt ){
 1.73724 +      Vdbe *v = (Vdbe *)pBlob->pStmt;
 1.73725 +      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
 1.73726 +
 1.73727 +
 1.73728 +      sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags, 
 1.73729 +                           pTab->pSchema->schema_cookie,
 1.73730 +                           pTab->pSchema->iGeneration);
 1.73731 +      sqlite3VdbeChangeP5(v, 1);     
 1.73732 +      sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
 1.73733 +
 1.73734 +      /* Make sure a mutex is held on the table to be accessed */
 1.73735 +      sqlite3VdbeUsesBtree(v, iDb); 
 1.73736 +
 1.73737 +      /* Configure the OP_TableLock instruction */
 1.73738 +#ifdef SQLITE_OMIT_SHARED_CACHE
 1.73739 +      sqlite3VdbeChangeToNoop(v, 1);
 1.73740 +#else
 1.73741 +      sqlite3VdbeChangeP1(v, 1, iDb);
 1.73742 +      sqlite3VdbeChangeP2(v, 1, pTab->tnum);
 1.73743 +      sqlite3VdbeChangeP3(v, 1, flags);
 1.73744 +      sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
 1.73745 +#endif
 1.73746 +
 1.73747 +      /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
 1.73748 +      ** parameter of the other to pTab->tnum.  */
 1.73749 +      sqlite3VdbeChangeToNoop(v, 3 - flags);
 1.73750 +      sqlite3VdbeChangeP2(v, 2 + flags, pTab->tnum);
 1.73751 +      sqlite3VdbeChangeP3(v, 2 + flags, iDb);
 1.73752 +
 1.73753 +      /* Configure the number of columns. Configure the cursor to
 1.73754 +      ** think that the table has one more column than it really
 1.73755 +      ** does. An OP_Column to retrieve this imaginary column will
 1.73756 +      ** always return an SQL NULL. This is useful because it means
 1.73757 +      ** we can invoke OP_Column to fill in the vdbe cursors type 
 1.73758 +      ** and offset cache without causing any IO.
 1.73759 +      */
 1.73760 +      sqlite3VdbeChangeP4(v, 2+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
 1.73761 +      sqlite3VdbeChangeP2(v, 6, pTab->nCol);
 1.73762 +      if( !db->mallocFailed ){
 1.73763 +        pParse->nVar = 1;
 1.73764 +        pParse->nMem = 1;
 1.73765 +        pParse->nTab = 1;
 1.73766 +        sqlite3VdbeMakeReady(v, pParse);
 1.73767 +      }
 1.73768 +    }
 1.73769 +   
 1.73770 +    pBlob->flags = flags;
 1.73771 +    pBlob->iCol = iCol;
 1.73772 +    pBlob->db = db;
 1.73773 +    sqlite3BtreeLeaveAll(db);
 1.73774 +    if( db->mallocFailed ){
 1.73775 +      goto blob_open_out;
 1.73776 +    }
 1.73777 +    sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
 1.73778 +    rc = blobSeekToRow(pBlob, iRow, &zErr);
 1.73779 +  } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
 1.73780 +
 1.73781 +blob_open_out:
 1.73782 +  if( rc==SQLITE_OK && db->mallocFailed==0 ){
 1.73783 +    *ppBlob = (sqlite3_blob *)pBlob;
 1.73784 +  }else{
 1.73785 +    if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
 1.73786 +    sqlite3DbFree(db, pBlob);
 1.73787 +  }
 1.73788 +  sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
 1.73789 +  sqlite3DbFree(db, zErr);
 1.73790 +  sqlite3ParserReset(pParse);
 1.73791 +  sqlite3StackFree(db, pParse);
 1.73792 +  rc = sqlite3ApiExit(db, rc);
 1.73793 +  sqlite3_mutex_leave(db->mutex);
 1.73794 +  return rc;
 1.73795 +}
 1.73796 +
 1.73797 +/*
 1.73798 +** Close a blob handle that was previously created using
 1.73799 +** sqlite3_blob_open().
 1.73800 +*/
 1.73801 +SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
 1.73802 +  Incrblob *p = (Incrblob *)pBlob;
 1.73803 +  int rc;
 1.73804 +  sqlite3 *db;
 1.73805 +
 1.73806 +  if( p ){
 1.73807 +    db = p->db;
 1.73808 +    sqlite3_mutex_enter(db->mutex);
 1.73809 +    rc = sqlite3_finalize(p->pStmt);
 1.73810 +    sqlite3DbFree(db, p);
 1.73811 +    sqlite3_mutex_leave(db->mutex);
 1.73812 +  }else{
 1.73813 +    rc = SQLITE_OK;
 1.73814 +  }
 1.73815 +  return rc;
 1.73816 +}
 1.73817 +
 1.73818 +/*
 1.73819 +** Perform a read or write operation on a blob
 1.73820 +*/
 1.73821 +static int blobReadWrite(
 1.73822 +  sqlite3_blob *pBlob, 
 1.73823 +  void *z, 
 1.73824 +  int n, 
 1.73825 +  int iOffset, 
 1.73826 +  int (*xCall)(BtCursor*, u32, u32, void*)
 1.73827 +){
 1.73828 +  int rc;
 1.73829 +  Incrblob *p = (Incrblob *)pBlob;
 1.73830 +  Vdbe *v;
 1.73831 +  sqlite3 *db;
 1.73832 +
 1.73833 +  if( p==0 ) return SQLITE_MISUSE_BKPT;
 1.73834 +  db = p->db;
 1.73835 +  sqlite3_mutex_enter(db->mutex);
 1.73836 +  v = (Vdbe*)p->pStmt;
 1.73837 +
 1.73838 +  if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
 1.73839 +    /* Request is out of range. Return a transient error. */
 1.73840 +    rc = SQLITE_ERROR;
 1.73841 +    sqlite3Error(db, SQLITE_ERROR, 0);
 1.73842 +  }else if( v==0 ){
 1.73843 +    /* If there is no statement handle, then the blob-handle has
 1.73844 +    ** already been invalidated. Return SQLITE_ABORT in this case.
 1.73845 +    */
 1.73846 +    rc = SQLITE_ABORT;
 1.73847 +  }else{
 1.73848 +    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
 1.73849 +    ** returned, clean-up the statement handle.
 1.73850 +    */
 1.73851 +    assert( db == v->db );
 1.73852 +    sqlite3BtreeEnterCursor(p->pCsr);
 1.73853 +    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
 1.73854 +    sqlite3BtreeLeaveCursor(p->pCsr);
 1.73855 +    if( rc==SQLITE_ABORT ){
 1.73856 +      sqlite3VdbeFinalize(v);
 1.73857 +      p->pStmt = 0;
 1.73858 +    }else{
 1.73859 +      db->errCode = rc;
 1.73860 +      v->rc = rc;
 1.73861 +    }
 1.73862 +  }
 1.73863 +  rc = sqlite3ApiExit(db, rc);
 1.73864 +  sqlite3_mutex_leave(db->mutex);
 1.73865 +  return rc;
 1.73866 +}
 1.73867 +
 1.73868 +/*
 1.73869 +** Read data from a blob handle.
 1.73870 +*/
 1.73871 +SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
 1.73872 +  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
 1.73873 +}
 1.73874 +
 1.73875 +/*
 1.73876 +** Write data to a blob handle.
 1.73877 +*/
 1.73878 +SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
 1.73879 +  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
 1.73880 +}
 1.73881 +
 1.73882 +/*
 1.73883 +** Query a blob handle for the size of the data.
 1.73884 +**
 1.73885 +** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
 1.73886 +** so no mutex is required for access.
 1.73887 +*/
 1.73888 +SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
 1.73889 +  Incrblob *p = (Incrblob *)pBlob;
 1.73890 +  return (p && p->pStmt) ? p->nByte : 0;
 1.73891 +}
 1.73892 +
 1.73893 +/*
 1.73894 +** Move an existing blob handle to point to a different row of the same
 1.73895 +** database table.
 1.73896 +**
 1.73897 +** If an error occurs, or if the specified row does not exist or does not
 1.73898 +** contain a blob or text value, then an error code is returned and the
 1.73899 +** database handle error code and message set. If this happens, then all 
 1.73900 +** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) 
 1.73901 +** immediately return SQLITE_ABORT.
 1.73902 +*/
 1.73903 +SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
 1.73904 +  int rc;
 1.73905 +  Incrblob *p = (Incrblob *)pBlob;
 1.73906 +  sqlite3 *db;
 1.73907 +
 1.73908 +  if( p==0 ) return SQLITE_MISUSE_BKPT;
 1.73909 +  db = p->db;
 1.73910 +  sqlite3_mutex_enter(db->mutex);
 1.73911 +
 1.73912 +  if( p->pStmt==0 ){
 1.73913 +    /* If there is no statement handle, then the blob-handle has
 1.73914 +    ** already been invalidated. Return SQLITE_ABORT in this case.
 1.73915 +    */
 1.73916 +    rc = SQLITE_ABORT;
 1.73917 +  }else{
 1.73918 +    char *zErr;
 1.73919 +    rc = blobSeekToRow(p, iRow, &zErr);
 1.73920 +    if( rc!=SQLITE_OK ){
 1.73921 +      sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
 1.73922 +      sqlite3DbFree(db, zErr);
 1.73923 +    }
 1.73924 +    assert( rc!=SQLITE_SCHEMA );
 1.73925 +  }
 1.73926 +
 1.73927 +  rc = sqlite3ApiExit(db, rc);
 1.73928 +  assert( rc==SQLITE_OK || p->pStmt==0 );
 1.73929 +  sqlite3_mutex_leave(db->mutex);
 1.73930 +  return rc;
 1.73931 +}
 1.73932 +
 1.73933 +#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
 1.73934 +
 1.73935 +/************** End of vdbeblob.c ********************************************/
 1.73936 +/************** Begin file vdbesort.c ****************************************/
 1.73937 +/*
 1.73938 +** 2011 July 9
 1.73939 +**
 1.73940 +** The author disclaims copyright to this source code.  In place of
 1.73941 +** a legal notice, here is a blessing:
 1.73942 +**
 1.73943 +**    May you do good and not evil.
 1.73944 +**    May you find forgiveness for yourself and forgive others.
 1.73945 +**    May you share freely, never taking more than you give.
 1.73946 +**
 1.73947 +*************************************************************************
 1.73948 +** This file contains code for the VdbeSorter object, used in concert with
 1.73949 +** a VdbeCursor to sort large numbers of keys (as may be required, for
 1.73950 +** example, by CREATE INDEX statements on tables too large to fit in main
 1.73951 +** memory).
 1.73952 +*/
 1.73953 +
 1.73954 +
 1.73955 +
 1.73956 +typedef struct VdbeSorterIter VdbeSorterIter;
 1.73957 +typedef struct SorterRecord SorterRecord;
 1.73958 +typedef struct FileWriter FileWriter;
 1.73959 +
 1.73960 +/*
 1.73961 +** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
 1.73962 +**
 1.73963 +** As keys are added to the sorter, they are written to disk in a series
 1.73964 +** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
 1.73965 +** the same as the cache-size allowed for temporary databases. In order
 1.73966 +** to allow the caller to extract keys from the sorter in sorted order,
 1.73967 +** all PMAs currently stored on disk must be merged together. This comment
 1.73968 +** describes the data structure used to do so. The structure supports 
 1.73969 +** merging any number of arrays in a single pass with no redundant comparison 
 1.73970 +** operations.
 1.73971 +**
 1.73972 +** The aIter[] array contains an iterator for each of the PMAs being merged.
 1.73973 +** An aIter[] iterator either points to a valid key or else is at EOF. For 
 1.73974 +** the purposes of the paragraphs below, we assume that the array is actually 
 1.73975 +** N elements in size, where N is the smallest power of 2 greater to or equal 
 1.73976 +** to the number of iterators being merged. The extra aIter[] elements are 
 1.73977 +** treated as if they are empty (always at EOF).
 1.73978 +**
 1.73979 +** The aTree[] array is also N elements in size. The value of N is stored in
 1.73980 +** the VdbeSorter.nTree variable.
 1.73981 +**
 1.73982 +** The final (N/2) elements of aTree[] contain the results of comparing
 1.73983 +** pairs of iterator keys together. Element i contains the result of 
 1.73984 +** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
 1.73985 +** aTree element is set to the index of it. 
 1.73986 +**
 1.73987 +** For the purposes of this comparison, EOF is considered greater than any
 1.73988 +** other key value. If the keys are equal (only possible with two EOF
 1.73989 +** values), it doesn't matter which index is stored.
 1.73990 +**
 1.73991 +** The (N/4) elements of aTree[] that precede the final (N/2) described 
 1.73992 +** above contains the index of the smallest of each block of 4 iterators.
 1.73993 +** And so on. So that aTree[1] contains the index of the iterator that 
 1.73994 +** currently points to the smallest key value. aTree[0] is unused.
 1.73995 +**
 1.73996 +** Example:
 1.73997 +**
 1.73998 +**     aIter[0] -> Banana
 1.73999 +**     aIter[1] -> Feijoa
 1.74000 +**     aIter[2] -> Elderberry
 1.74001 +**     aIter[3] -> Currant
 1.74002 +**     aIter[4] -> Grapefruit
 1.74003 +**     aIter[5] -> Apple
 1.74004 +**     aIter[6] -> Durian
 1.74005 +**     aIter[7] -> EOF
 1.74006 +**
 1.74007 +**     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
 1.74008 +**
 1.74009 +** The current element is "Apple" (the value of the key indicated by 
 1.74010 +** iterator 5). When the Next() operation is invoked, iterator 5 will
 1.74011 +** be advanced to the next key in its segment. Say the next key is
 1.74012 +** "Eggplant":
 1.74013 +**
 1.74014 +**     aIter[5] -> Eggplant
 1.74015 +**
 1.74016 +** The contents of aTree[] are updated first by comparing the new iterator
 1.74017 +** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
 1.74018 +** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
 1.74019 +** The value of iterator 6 - "Durian" - is now smaller than that of iterator
 1.74020 +** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
 1.74021 +** so the value written into element 1 of the array is 0. As follows:
 1.74022 +**
 1.74023 +**     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
 1.74024 +**
 1.74025 +** In other words, each time we advance to the next sorter element, log2(N)
 1.74026 +** key comparison operations are required, where N is the number of segments
 1.74027 +** being merged (rounded up to the next power of 2).
 1.74028 +*/
 1.74029 +struct VdbeSorter {
 1.74030 +  i64 iWriteOff;                  /* Current write offset within file pTemp1 */
 1.74031 +  i64 iReadOff;                   /* Current read offset within file pTemp1 */
 1.74032 +  int nInMemory;                  /* Current size of pRecord list as PMA */
 1.74033 +  int nTree;                      /* Used size of aTree/aIter (power of 2) */
 1.74034 +  int nPMA;                       /* Number of PMAs stored in pTemp1 */
 1.74035 +  int mnPmaSize;                  /* Minimum PMA size, in bytes */
 1.74036 +  int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
 1.74037 +  VdbeSorterIter *aIter;          /* Array of iterators to merge */
 1.74038 +  int *aTree;                     /* Current state of incremental merge */
 1.74039 +  sqlite3_file *pTemp1;           /* PMA file 1 */
 1.74040 +  SorterRecord *pRecord;          /* Head of in-memory record list */
 1.74041 +  UnpackedRecord *pUnpacked;      /* Used to unpack keys */
 1.74042 +};
 1.74043 +
 1.74044 +/*
 1.74045 +** The following type is an iterator for a PMA. It caches the current key in 
 1.74046 +** variables nKey/aKey. If the iterator is at EOF, pFile==0.
 1.74047 +*/
 1.74048 +struct VdbeSorterIter {
 1.74049 +  i64 iReadOff;                   /* Current read offset */
 1.74050 +  i64 iEof;                       /* 1 byte past EOF for this iterator */
 1.74051 +  int nAlloc;                     /* Bytes of space at aAlloc */
 1.74052 +  int nKey;                       /* Number of bytes in key */
 1.74053 +  sqlite3_file *pFile;            /* File iterator is reading from */
 1.74054 +  u8 *aAlloc;                     /* Allocated space */
 1.74055 +  u8 *aKey;                       /* Pointer to current key */
 1.74056 +  u8 *aBuffer;                    /* Current read buffer */
 1.74057 +  int nBuffer;                    /* Size of read buffer in bytes */
 1.74058 +};
 1.74059 +
 1.74060 +/*
 1.74061 +** An instance of this structure is used to organize the stream of records
 1.74062 +** being written to files by the merge-sort code into aligned, page-sized
 1.74063 +** blocks.  Doing all I/O in aligned page-sized blocks helps I/O to go
 1.74064 +** faster on many operating systems.
 1.74065 +*/
 1.74066 +struct FileWriter {
 1.74067 +  int eFWErr;                     /* Non-zero if in an error state */
 1.74068 +  u8 *aBuffer;                    /* Pointer to write buffer */
 1.74069 +  int nBuffer;                    /* Size of write buffer in bytes */
 1.74070 +  int iBufStart;                  /* First byte of buffer to write */
 1.74071 +  int iBufEnd;                    /* Last byte of buffer to write */
 1.74072 +  i64 iWriteOff;                  /* Offset of start of buffer in file */
 1.74073 +  sqlite3_file *pFile;            /* File to write to */
 1.74074 +};
 1.74075 +
 1.74076 +/*
 1.74077 +** A structure to store a single record. All in-memory records are connected
 1.74078 +** together into a linked list headed at VdbeSorter.pRecord using the 
 1.74079 +** SorterRecord.pNext pointer.
 1.74080 +*/
 1.74081 +struct SorterRecord {
 1.74082 +  void *pVal;
 1.74083 +  int nVal;
 1.74084 +  SorterRecord *pNext;
 1.74085 +};
 1.74086 +
 1.74087 +/* Minimum allowable value for the VdbeSorter.nWorking variable */
 1.74088 +#define SORTER_MIN_WORKING 10
 1.74089 +
 1.74090 +/* Maximum number of segments to merge in a single pass. */
 1.74091 +#define SORTER_MAX_MERGE_COUNT 16
 1.74092 +
 1.74093 +/*
 1.74094 +** Free all memory belonging to the VdbeSorterIter object passed as the second
 1.74095 +** argument. All structure fields are set to zero before returning.
 1.74096 +*/
 1.74097 +static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
 1.74098 +  sqlite3DbFree(db, pIter->aAlloc);
 1.74099 +  sqlite3DbFree(db, pIter->aBuffer);
 1.74100 +  memset(pIter, 0, sizeof(VdbeSorterIter));
 1.74101 +}
 1.74102 +
 1.74103 +/*
 1.74104 +** Read nByte bytes of data from the stream of data iterated by object p.
 1.74105 +** If successful, set *ppOut to point to a buffer containing the data
 1.74106 +** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
 1.74107 +** error code.
 1.74108 +**
 1.74109 +** The buffer indicated by *ppOut may only be considered valid until the
 1.74110 +** next call to this function.
 1.74111 +*/
 1.74112 +static int vdbeSorterIterRead(
 1.74113 +  sqlite3 *db,                    /* Database handle (for malloc) */
 1.74114 +  VdbeSorterIter *p,              /* Iterator */
 1.74115 +  int nByte,                      /* Bytes of data to read */
 1.74116 +  u8 **ppOut                      /* OUT: Pointer to buffer containing data */
 1.74117 +){
 1.74118 +  int iBuf;                       /* Offset within buffer to read from */
 1.74119 +  int nAvail;                     /* Bytes of data available in buffer */
 1.74120 +  assert( p->aBuffer );
 1.74121 +
 1.74122 +  /* If there is no more data to be read from the buffer, read the next 
 1.74123 +  ** p->nBuffer bytes of data from the file into it. Or, if there are less
 1.74124 +  ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
 1.74125 +  iBuf = p->iReadOff % p->nBuffer;
 1.74126 +  if( iBuf==0 ){
 1.74127 +    int nRead;                    /* Bytes to read from disk */
 1.74128 +    int rc;                       /* sqlite3OsRead() return code */
 1.74129 +
 1.74130 +    /* Determine how many bytes of data to read. */
 1.74131 +    if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
 1.74132 +      nRead = p->nBuffer;
 1.74133 +    }else{
 1.74134 +      nRead = (int)(p->iEof - p->iReadOff);
 1.74135 +    }
 1.74136 +    assert( nRead>0 );
 1.74137 +
 1.74138 +    /* Read data from the file. Return early if an error occurs. */
 1.74139 +    rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
 1.74140 +    assert( rc!=SQLITE_IOERR_SHORT_READ );
 1.74141 +    if( rc!=SQLITE_OK ) return rc;
 1.74142 +  }
 1.74143 +  nAvail = p->nBuffer - iBuf; 
 1.74144 +
 1.74145 +  if( nByte<=nAvail ){
 1.74146 +    /* The requested data is available in the in-memory buffer. In this
 1.74147 +    ** case there is no need to make a copy of the data, just return a 
 1.74148 +    ** pointer into the buffer to the caller.  */
 1.74149 +    *ppOut = &p->aBuffer[iBuf];
 1.74150 +    p->iReadOff += nByte;
 1.74151 +  }else{
 1.74152 +    /* The requested data is not all available in the in-memory buffer.
 1.74153 +    ** In this case, allocate space at p->aAlloc[] to copy the requested
 1.74154 +    ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
 1.74155 +    int nRem;                     /* Bytes remaining to copy */
 1.74156 +
 1.74157 +    /* Extend the p->aAlloc[] allocation if required. */
 1.74158 +    if( p->nAlloc<nByte ){
 1.74159 +      int nNew = p->nAlloc*2;
 1.74160 +      while( nByte>nNew ) nNew = nNew*2;
 1.74161 +      p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
 1.74162 +      if( !p->aAlloc ) return SQLITE_NOMEM;
 1.74163 +      p->nAlloc = nNew;
 1.74164 +    }
 1.74165 +
 1.74166 +    /* Copy as much data as is available in the buffer into the start of
 1.74167 +    ** p->aAlloc[].  */
 1.74168 +    memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
 1.74169 +    p->iReadOff += nAvail;
 1.74170 +    nRem = nByte - nAvail;
 1.74171 +
 1.74172 +    /* The following loop copies up to p->nBuffer bytes per iteration into
 1.74173 +    ** the p->aAlloc[] buffer.  */
 1.74174 +    while( nRem>0 ){
 1.74175 +      int rc;                     /* vdbeSorterIterRead() return code */
 1.74176 +      int nCopy;                  /* Number of bytes to copy */
 1.74177 +      u8 *aNext;                  /* Pointer to buffer to copy data from */
 1.74178 +
 1.74179 +      nCopy = nRem;
 1.74180 +      if( nRem>p->nBuffer ) nCopy = p->nBuffer;
 1.74181 +      rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
 1.74182 +      if( rc!=SQLITE_OK ) return rc;
 1.74183 +      assert( aNext!=p->aAlloc );
 1.74184 +      memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
 1.74185 +      nRem -= nCopy;
 1.74186 +    }
 1.74187 +
 1.74188 +    *ppOut = p->aAlloc;
 1.74189 +  }
 1.74190 +
 1.74191 +  return SQLITE_OK;
 1.74192 +}
 1.74193 +
 1.74194 +/*
 1.74195 +** Read a varint from the stream of data accessed by p. Set *pnOut to
 1.74196 +** the value read.
 1.74197 +*/
 1.74198 +static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
 1.74199 +  int iBuf;
 1.74200 +
 1.74201 +  iBuf = p->iReadOff % p->nBuffer;
 1.74202 +  if( iBuf && (p->nBuffer-iBuf)>=9 ){
 1.74203 +    p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
 1.74204 +  }else{
 1.74205 +    u8 aVarint[16], *a;
 1.74206 +    int i = 0, rc;
 1.74207 +    do{
 1.74208 +      rc = vdbeSorterIterRead(db, p, 1, &a);
 1.74209 +      if( rc ) return rc;
 1.74210 +      aVarint[(i++)&0xf] = a[0];
 1.74211 +    }while( (a[0]&0x80)!=0 );
 1.74212 +    sqlite3GetVarint(aVarint, pnOut);
 1.74213 +  }
 1.74214 +
 1.74215 +  return SQLITE_OK;
 1.74216 +}
 1.74217 +
 1.74218 +
 1.74219 +/*
 1.74220 +** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
 1.74221 +** no error occurs, or an SQLite error code if one does.
 1.74222 +*/
 1.74223 +static int vdbeSorterIterNext(
 1.74224 +  sqlite3 *db,                    /* Database handle (for sqlite3DbMalloc() ) */
 1.74225 +  VdbeSorterIter *pIter           /* Iterator to advance */
 1.74226 +){
 1.74227 +  int rc;                         /* Return Code */
 1.74228 +  u64 nRec = 0;                   /* Size of record in bytes */
 1.74229 +
 1.74230 +  if( pIter->iReadOff>=pIter->iEof ){
 1.74231 +    /* This is an EOF condition */
 1.74232 +    vdbeSorterIterZero(db, pIter);
 1.74233 +    return SQLITE_OK;
 1.74234 +  }
 1.74235 +
 1.74236 +  rc = vdbeSorterIterVarint(db, pIter, &nRec);
 1.74237 +  if( rc==SQLITE_OK ){
 1.74238 +    pIter->nKey = (int)nRec;
 1.74239 +    rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
 1.74240 +  }
 1.74241 +
 1.74242 +  return rc;
 1.74243 +}
 1.74244 +
 1.74245 +/*
 1.74246 +** Initialize iterator pIter to scan through the PMA stored in file pFile
 1.74247 +** starting at offset iStart and ending at offset iEof-1. This function 
 1.74248 +** leaves the iterator pointing to the first key in the PMA (or EOF if the 
 1.74249 +** PMA is empty).
 1.74250 +*/
 1.74251 +static int vdbeSorterIterInit(
 1.74252 +  sqlite3 *db,                    /* Database handle */
 1.74253 +  const VdbeSorter *pSorter,      /* Sorter object */
 1.74254 +  i64 iStart,                     /* Start offset in pFile */
 1.74255 +  VdbeSorterIter *pIter,          /* Iterator to populate */
 1.74256 +  i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
 1.74257 +){
 1.74258 +  int rc = SQLITE_OK;
 1.74259 +  int nBuf;
 1.74260 +
 1.74261 +  nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
 1.74262 +
 1.74263 +  assert( pSorter->iWriteOff>iStart );
 1.74264 +  assert( pIter->aAlloc==0 );
 1.74265 +  assert( pIter->aBuffer==0 );
 1.74266 +  pIter->pFile = pSorter->pTemp1;
 1.74267 +  pIter->iReadOff = iStart;
 1.74268 +  pIter->nAlloc = 128;
 1.74269 +  pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
 1.74270 +  pIter->nBuffer = nBuf;
 1.74271 +  pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
 1.74272 +
 1.74273 +  if( !pIter->aBuffer ){
 1.74274 +    rc = SQLITE_NOMEM;
 1.74275 +  }else{
 1.74276 +    int iBuf;
 1.74277 +
 1.74278 +    iBuf = iStart % nBuf;
 1.74279 +    if( iBuf ){
 1.74280 +      int nRead = nBuf - iBuf;
 1.74281 +      if( (iStart + nRead) > pSorter->iWriteOff ){
 1.74282 +        nRead = (int)(pSorter->iWriteOff - iStart);
 1.74283 +      }
 1.74284 +      rc = sqlite3OsRead(
 1.74285 +          pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
 1.74286 +      );
 1.74287 +      assert( rc!=SQLITE_IOERR_SHORT_READ );
 1.74288 +    }
 1.74289 +
 1.74290 +    if( rc==SQLITE_OK ){
 1.74291 +      u64 nByte;                       /* Size of PMA in bytes */
 1.74292 +      pIter->iEof = pSorter->iWriteOff;
 1.74293 +      rc = vdbeSorterIterVarint(db, pIter, &nByte);
 1.74294 +      pIter->iEof = pIter->iReadOff + nByte;
 1.74295 +      *pnByte += nByte;
 1.74296 +    }
 1.74297 +  }
 1.74298 +
 1.74299 +  if( rc==SQLITE_OK ){
 1.74300 +    rc = vdbeSorterIterNext(db, pIter);
 1.74301 +  }
 1.74302 +  return rc;
 1.74303 +}
 1.74304 +
 1.74305 +
 1.74306 +/*
 1.74307 +** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, 
 1.74308 +** size nKey2 bytes).  Argument pKeyInfo supplies the collation functions
 1.74309 +** used by the comparison. If an error occurs, return an SQLite error code.
 1.74310 +** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
 1.74311 +** value, depending on whether key1 is smaller, equal to or larger than key2.
 1.74312 +**
 1.74313 +** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
 1.74314 +** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
 1.74315 +** is true and key1 contains even a single NULL value, it is considered to
 1.74316 +** be less than key2. Even if key2 also contains NULL values.
 1.74317 +**
 1.74318 +** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
 1.74319 +** has been allocated and contains an unpacked record that is used as key2.
 1.74320 +*/
 1.74321 +static void vdbeSorterCompare(
 1.74322 +  const VdbeCursor *pCsr,         /* Cursor object (for pKeyInfo) */
 1.74323 +  int nIgnore,                    /* Ignore the last nIgnore fields */
 1.74324 +  const void *pKey1, int nKey1,   /* Left side of comparison */
 1.74325 +  const void *pKey2, int nKey2,   /* Right side of comparison */
 1.74326 +  int *pRes                       /* OUT: Result of comparison */
 1.74327 +){
 1.74328 +  KeyInfo *pKeyInfo = pCsr->pKeyInfo;
 1.74329 +  VdbeSorter *pSorter = pCsr->pSorter;
 1.74330 +  UnpackedRecord *r2 = pSorter->pUnpacked;
 1.74331 +  int i;
 1.74332 +
 1.74333 +  if( pKey2 ){
 1.74334 +    sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
 1.74335 +  }
 1.74336 +
 1.74337 +  if( nIgnore ){
 1.74338 +    r2->nField = pKeyInfo->nField - nIgnore;
 1.74339 +    assert( r2->nField>0 );
 1.74340 +    for(i=0; i<r2->nField; i++){
 1.74341 +      if( r2->aMem[i].flags & MEM_Null ){
 1.74342 +        *pRes = -1;
 1.74343 +        return;
 1.74344 +      }
 1.74345 +    }
 1.74346 +    assert( r2->default_rc==0 );
 1.74347 +  }
 1.74348 +
 1.74349 +  *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2, 0);
 1.74350 +}
 1.74351 +
 1.74352 +/*
 1.74353 +** This function is called to compare two iterator keys when merging 
 1.74354 +** multiple b-tree segments. Parameter iOut is the index of the aTree[] 
 1.74355 +** value to recalculate.
 1.74356 +*/
 1.74357 +static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
 1.74358 +  VdbeSorter *pSorter = pCsr->pSorter;
 1.74359 +  int i1;
 1.74360 +  int i2;
 1.74361 +  int iRes;
 1.74362 +  VdbeSorterIter *p1;
 1.74363 +  VdbeSorterIter *p2;
 1.74364 +
 1.74365 +  assert( iOut<pSorter->nTree && iOut>0 );
 1.74366 +
 1.74367 +  if( iOut>=(pSorter->nTree/2) ){
 1.74368 +    i1 = (iOut - pSorter->nTree/2) * 2;
 1.74369 +    i2 = i1 + 1;
 1.74370 +  }else{
 1.74371 +    i1 = pSorter->aTree[iOut*2];
 1.74372 +    i2 = pSorter->aTree[iOut*2+1];
 1.74373 +  }
 1.74374 +
 1.74375 +  p1 = &pSorter->aIter[i1];
 1.74376 +  p2 = &pSorter->aIter[i2];
 1.74377 +
 1.74378 +  if( p1->pFile==0 ){
 1.74379 +    iRes = i2;
 1.74380 +  }else if( p2->pFile==0 ){
 1.74381 +    iRes = i1;
 1.74382 +  }else{
 1.74383 +    int res;
 1.74384 +    assert( pCsr->pSorter->pUnpacked!=0 );  /* allocated in vdbeSorterMerge() */
 1.74385 +    vdbeSorterCompare(
 1.74386 +        pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
 1.74387 +    );
 1.74388 +    if( res<=0 ){
 1.74389 +      iRes = i1;
 1.74390 +    }else{
 1.74391 +      iRes = i2;
 1.74392 +    }
 1.74393 +  }
 1.74394 +
 1.74395 +  pSorter->aTree[iOut] = iRes;
 1.74396 +  return SQLITE_OK;
 1.74397 +}
 1.74398 +
 1.74399 +/*
 1.74400 +** Initialize the temporary index cursor just opened as a sorter cursor.
 1.74401 +*/
 1.74402 +SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
 1.74403 +  int pgsz;                       /* Page size of main database */
 1.74404 +  int mxCache;                    /* Cache size */
 1.74405 +  VdbeSorter *pSorter;            /* The new sorter */
 1.74406 +  char *d;                        /* Dummy */
 1.74407 +
 1.74408 +  assert( pCsr->pKeyInfo && pCsr->pBt==0 );
 1.74409 +  pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
 1.74410 +  if( pSorter==0 ){
 1.74411 +    return SQLITE_NOMEM;
 1.74412 +  }
 1.74413 +  
 1.74414 +  pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
 1.74415 +  if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
 1.74416 +  assert( pSorter->pUnpacked==(UnpackedRecord *)d );
 1.74417 +
 1.74418 +  if( !sqlite3TempInMemory(db) ){
 1.74419 +    pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
 1.74420 +    pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
 1.74421 +    mxCache = db->aDb[0].pSchema->cache_size;
 1.74422 +    if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
 1.74423 +    pSorter->mxPmaSize = mxCache * pgsz;
 1.74424 +  }
 1.74425 +
 1.74426 +  return SQLITE_OK;
 1.74427 +}
 1.74428 +
 1.74429 +/*
 1.74430 +** Free the list of sorted records starting at pRecord.
 1.74431 +*/
 1.74432 +static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
 1.74433 +  SorterRecord *p;
 1.74434 +  SorterRecord *pNext;
 1.74435 +  for(p=pRecord; p; p=pNext){
 1.74436 +    pNext = p->pNext;
 1.74437 +    sqlite3DbFree(db, p);
 1.74438 +  }
 1.74439 +}
 1.74440 +
 1.74441 +/*
 1.74442 +** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
 1.74443 +*/
 1.74444 +SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
 1.74445 +  VdbeSorter *pSorter = pCsr->pSorter;
 1.74446 +  if( pSorter ){
 1.74447 +    if( pSorter->aIter ){
 1.74448 +      int i;
 1.74449 +      for(i=0; i<pSorter->nTree; i++){
 1.74450 +        vdbeSorterIterZero(db, &pSorter->aIter[i]);
 1.74451 +      }
 1.74452 +      sqlite3DbFree(db, pSorter->aIter);
 1.74453 +    }
 1.74454 +    if( pSorter->pTemp1 ){
 1.74455 +      sqlite3OsCloseFree(pSorter->pTemp1);
 1.74456 +    }
 1.74457 +    vdbeSorterRecordFree(db, pSorter->pRecord);
 1.74458 +    sqlite3DbFree(db, pSorter->pUnpacked);
 1.74459 +    sqlite3DbFree(db, pSorter);
 1.74460 +    pCsr->pSorter = 0;
 1.74461 +  }
 1.74462 +}
 1.74463 +
 1.74464 +/*
 1.74465 +** Allocate space for a file-handle and open a temporary file. If successful,
 1.74466 +** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
 1.74467 +** Otherwise, set *ppFile to 0 and return an SQLite error code.
 1.74468 +*/
 1.74469 +static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
 1.74470 +  int dummy;
 1.74471 +  return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
 1.74472 +      SQLITE_OPEN_TEMP_JOURNAL |
 1.74473 +      SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
 1.74474 +      SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &dummy
 1.74475 +  );
 1.74476 +}
 1.74477 +
 1.74478 +/*
 1.74479 +** Merge the two sorted lists p1 and p2 into a single list.
 1.74480 +** Set *ppOut to the head of the new list.
 1.74481 +*/
 1.74482 +static void vdbeSorterMerge(
 1.74483 +  const VdbeCursor *pCsr,         /* For pKeyInfo */
 1.74484 +  SorterRecord *p1,               /* First list to merge */
 1.74485 +  SorterRecord *p2,               /* Second list to merge */
 1.74486 +  SorterRecord **ppOut            /* OUT: Head of merged list */
 1.74487 +){
 1.74488 +  SorterRecord *pFinal = 0;
 1.74489 +  SorterRecord **pp = &pFinal;
 1.74490 +  void *pVal2 = p2 ? p2->pVal : 0;
 1.74491 +
 1.74492 +  while( p1 && p2 ){
 1.74493 +    int res;
 1.74494 +    vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
 1.74495 +    if( res<=0 ){
 1.74496 +      *pp = p1;
 1.74497 +      pp = &p1->pNext;
 1.74498 +      p1 = p1->pNext;
 1.74499 +      pVal2 = 0;
 1.74500 +    }else{
 1.74501 +      *pp = p2;
 1.74502 +       pp = &p2->pNext;
 1.74503 +      p2 = p2->pNext;
 1.74504 +      if( p2==0 ) break;
 1.74505 +      pVal2 = p2->pVal;
 1.74506 +    }
 1.74507 +  }
 1.74508 +  *pp = p1 ? p1 : p2;
 1.74509 +  *ppOut = pFinal;
 1.74510 +}
 1.74511 +
 1.74512 +/*
 1.74513 +** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
 1.74514 +** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
 1.74515 +** occurs.
 1.74516 +*/
 1.74517 +static int vdbeSorterSort(const VdbeCursor *pCsr){
 1.74518 +  int i;
 1.74519 +  SorterRecord **aSlot;
 1.74520 +  SorterRecord *p;
 1.74521 +  VdbeSorter *pSorter = pCsr->pSorter;
 1.74522 +
 1.74523 +  aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
 1.74524 +  if( !aSlot ){
 1.74525 +    return SQLITE_NOMEM;
 1.74526 +  }
 1.74527 +
 1.74528 +  p = pSorter->pRecord;
 1.74529 +  while( p ){
 1.74530 +    SorterRecord *pNext = p->pNext;
 1.74531 +    p->pNext = 0;
 1.74532 +    for(i=0; aSlot[i]; i++){
 1.74533 +      vdbeSorterMerge(pCsr, p, aSlot[i], &p);
 1.74534 +      aSlot[i] = 0;
 1.74535 +    }
 1.74536 +    aSlot[i] = p;
 1.74537 +    p = pNext;
 1.74538 +  }
 1.74539 +
 1.74540 +  p = 0;
 1.74541 +  for(i=0; i<64; i++){
 1.74542 +    vdbeSorterMerge(pCsr, p, aSlot[i], &p);
 1.74543 +  }
 1.74544 +  pSorter->pRecord = p;
 1.74545 +
 1.74546 +  sqlite3_free(aSlot);
 1.74547 +  return SQLITE_OK;
 1.74548 +}
 1.74549 +
 1.74550 +/*
 1.74551 +** Initialize a file-writer object.
 1.74552 +*/
 1.74553 +static void fileWriterInit(
 1.74554 +  sqlite3 *db,                    /* Database (for malloc) */
 1.74555 +  sqlite3_file *pFile,            /* File to write to */
 1.74556 +  FileWriter *p,                  /* Object to populate */
 1.74557 +  i64 iStart                      /* Offset of pFile to begin writing at */
 1.74558 +){
 1.74559 +  int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
 1.74560 +
 1.74561 +  memset(p, 0, sizeof(FileWriter));
 1.74562 +  p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
 1.74563 +  if( !p->aBuffer ){
 1.74564 +    p->eFWErr = SQLITE_NOMEM;
 1.74565 +  }else{
 1.74566 +    p->iBufEnd = p->iBufStart = (iStart % nBuf);
 1.74567 +    p->iWriteOff = iStart - p->iBufStart;
 1.74568 +    p->nBuffer = nBuf;
 1.74569 +    p->pFile = pFile;
 1.74570 +  }
 1.74571 +}
 1.74572 +
 1.74573 +/*
 1.74574 +** Write nData bytes of data to the file-write object. Return SQLITE_OK
 1.74575 +** if successful, or an SQLite error code if an error occurs.
 1.74576 +*/
 1.74577 +static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
 1.74578 +  int nRem = nData;
 1.74579 +  while( nRem>0 && p->eFWErr==0 ){
 1.74580 +    int nCopy = nRem;
 1.74581 +    if( nCopy>(p->nBuffer - p->iBufEnd) ){
 1.74582 +      nCopy = p->nBuffer - p->iBufEnd;
 1.74583 +    }
 1.74584 +
 1.74585 +    memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
 1.74586 +    p->iBufEnd += nCopy;
 1.74587 +    if( p->iBufEnd==p->nBuffer ){
 1.74588 +      p->eFWErr = sqlite3OsWrite(p->pFile, 
 1.74589 +          &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 
 1.74590 +          p->iWriteOff + p->iBufStart
 1.74591 +      );
 1.74592 +      p->iBufStart = p->iBufEnd = 0;
 1.74593 +      p->iWriteOff += p->nBuffer;
 1.74594 +    }
 1.74595 +    assert( p->iBufEnd<p->nBuffer );
 1.74596 +
 1.74597 +    nRem -= nCopy;
 1.74598 +  }
 1.74599 +}
 1.74600 +
 1.74601 +/*
 1.74602 +** Flush any buffered data to disk and clean up the file-writer object.
 1.74603 +** The results of using the file-writer after this call are undefined.
 1.74604 +** Return SQLITE_OK if flushing the buffered data succeeds or is not 
 1.74605 +** required. Otherwise, return an SQLite error code.
 1.74606 +**
 1.74607 +** Before returning, set *piEof to the offset immediately following the
 1.74608 +** last byte written to the file.
 1.74609 +*/
 1.74610 +static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
 1.74611 +  int rc;
 1.74612 +  if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
 1.74613 +    p->eFWErr = sqlite3OsWrite(p->pFile, 
 1.74614 +        &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 
 1.74615 +        p->iWriteOff + p->iBufStart
 1.74616 +    );
 1.74617 +  }
 1.74618 +  *piEof = (p->iWriteOff + p->iBufEnd);
 1.74619 +  sqlite3DbFree(db, p->aBuffer);
 1.74620 +  rc = p->eFWErr;
 1.74621 +  memset(p, 0, sizeof(FileWriter));
 1.74622 +  return rc;
 1.74623 +}
 1.74624 +
 1.74625 +/*
 1.74626 +** Write value iVal encoded as a varint to the file-write object. Return 
 1.74627 +** SQLITE_OK if successful, or an SQLite error code if an error occurs.
 1.74628 +*/
 1.74629 +static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
 1.74630 +  int nByte; 
 1.74631 +  u8 aByte[10];
 1.74632 +  nByte = sqlite3PutVarint(aByte, iVal);
 1.74633 +  fileWriterWrite(p, aByte, nByte);
 1.74634 +}
 1.74635 +
 1.74636 +/*
 1.74637 +** Write the current contents of the in-memory linked-list to a PMA. Return
 1.74638 +** SQLITE_OK if successful, or an SQLite error code otherwise.
 1.74639 +**
 1.74640 +** The format of a PMA is:
 1.74641 +**
 1.74642 +**     * A varint. This varint contains the total number of bytes of content
 1.74643 +**       in the PMA (not including the varint itself).
 1.74644 +**
 1.74645 +**     * One or more records packed end-to-end in order of ascending keys. 
 1.74646 +**       Each record consists of a varint followed by a blob of data (the 
 1.74647 +**       key). The varint is the number of bytes in the blob of data.
 1.74648 +*/
 1.74649 +static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
 1.74650 +  int rc = SQLITE_OK;             /* Return code */
 1.74651 +  VdbeSorter *pSorter = pCsr->pSorter;
 1.74652 +  FileWriter writer;
 1.74653 +
 1.74654 +  memset(&writer, 0, sizeof(FileWriter));
 1.74655 +
 1.74656 +  if( pSorter->nInMemory==0 ){
 1.74657 +    assert( pSorter->pRecord==0 );
 1.74658 +    return rc;
 1.74659 +  }
 1.74660 +
 1.74661 +  rc = vdbeSorterSort(pCsr);
 1.74662 +
 1.74663 +  /* If the first temporary PMA file has not been opened, open it now. */
 1.74664 +  if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
 1.74665 +    rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
 1.74666 +    assert( rc!=SQLITE_OK || pSorter->pTemp1 );
 1.74667 +    assert( pSorter->iWriteOff==0 );
 1.74668 +    assert( pSorter->nPMA==0 );
 1.74669 +  }
 1.74670 +
 1.74671 +  if( rc==SQLITE_OK ){
 1.74672 +    SorterRecord *p;
 1.74673 +    SorterRecord *pNext = 0;
 1.74674 +
 1.74675 +    fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
 1.74676 +    pSorter->nPMA++;
 1.74677 +    fileWriterWriteVarint(&writer, pSorter->nInMemory);
 1.74678 +    for(p=pSorter->pRecord; p; p=pNext){
 1.74679 +      pNext = p->pNext;
 1.74680 +      fileWriterWriteVarint(&writer, p->nVal);
 1.74681 +      fileWriterWrite(&writer, p->pVal, p->nVal);
 1.74682 +      sqlite3DbFree(db, p);
 1.74683 +    }
 1.74684 +    pSorter->pRecord = p;
 1.74685 +    rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
 1.74686 +  }
 1.74687 +
 1.74688 +  return rc;
 1.74689 +}
 1.74690 +
 1.74691 +/*
 1.74692 +** Add a record to the sorter.
 1.74693 +*/
 1.74694 +SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
 1.74695 +  sqlite3 *db,                    /* Database handle */
 1.74696 +  const VdbeCursor *pCsr,               /* Sorter cursor */
 1.74697 +  Mem *pVal                       /* Memory cell containing record */
 1.74698 +){
 1.74699 +  VdbeSorter *pSorter = pCsr->pSorter;
 1.74700 +  int rc = SQLITE_OK;             /* Return Code */
 1.74701 +  SorterRecord *pNew;             /* New list element */
 1.74702 +
 1.74703 +  assert( pSorter );
 1.74704 +  pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
 1.74705 +
 1.74706 +  pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
 1.74707 +  if( pNew==0 ){
 1.74708 +    rc = SQLITE_NOMEM;
 1.74709 +  }else{
 1.74710 +    pNew->pVal = (void *)&pNew[1];
 1.74711 +    memcpy(pNew->pVal, pVal->z, pVal->n);
 1.74712 +    pNew->nVal = pVal->n;
 1.74713 +    pNew->pNext = pSorter->pRecord;
 1.74714 +    pSorter->pRecord = pNew;
 1.74715 +  }
 1.74716 +
 1.74717 +  /* See if the contents of the sorter should now be written out. They
 1.74718 +  ** are written out when either of the following are true:
 1.74719 +  **
 1.74720 +  **   * The total memory allocated for the in-memory list is greater 
 1.74721 +  **     than (page-size * cache-size), or
 1.74722 +  **
 1.74723 +  **   * The total memory allocated for the in-memory list is greater 
 1.74724 +  **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
 1.74725 +  */
 1.74726 +  if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
 1.74727 +        (pSorter->nInMemory>pSorter->mxPmaSize)
 1.74728 +     || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
 1.74729 +  )){
 1.74730 +#ifdef SQLITE_DEBUG
 1.74731 +    i64 nExpect = pSorter->iWriteOff
 1.74732 +                + sqlite3VarintLen(pSorter->nInMemory)
 1.74733 +                + pSorter->nInMemory;
 1.74734 +#endif
 1.74735 +    rc = vdbeSorterListToPMA(db, pCsr);
 1.74736 +    pSorter->nInMemory = 0;
 1.74737 +    assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
 1.74738 +  }
 1.74739 +
 1.74740 +  return rc;
 1.74741 +}
 1.74742 +
 1.74743 +/*
 1.74744 +** Helper function for sqlite3VdbeSorterRewind(). 
 1.74745 +*/
 1.74746 +static int vdbeSorterInitMerge(
 1.74747 +  sqlite3 *db,                    /* Database handle */
 1.74748 +  const VdbeCursor *pCsr,         /* Cursor handle for this sorter */
 1.74749 +  i64 *pnByte                     /* Sum of bytes in all opened PMAs */
 1.74750 +){
 1.74751 +  VdbeSorter *pSorter = pCsr->pSorter;
 1.74752 +  int rc = SQLITE_OK;             /* Return code */
 1.74753 +  int i;                          /* Used to iterator through aIter[] */
 1.74754 +  i64 nByte = 0;                  /* Total bytes in all opened PMAs */
 1.74755 +
 1.74756 +  /* Initialize the iterators. */
 1.74757 +  for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
 1.74758 +    VdbeSorterIter *pIter = &pSorter->aIter[i];
 1.74759 +    rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
 1.74760 +    pSorter->iReadOff = pIter->iEof;
 1.74761 +    assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
 1.74762 +    if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
 1.74763 +  }
 1.74764 +
 1.74765 +  /* Initialize the aTree[] array. */
 1.74766 +  for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
 1.74767 +    rc = vdbeSorterDoCompare(pCsr, i);
 1.74768 +  }
 1.74769 +
 1.74770 +  *pnByte = nByte;
 1.74771 +  return rc;
 1.74772 +}
 1.74773 +
 1.74774 +/*
 1.74775 +** Once the sorter has been populated, this function is called to prepare
 1.74776 +** for iterating through its contents in sorted order.
 1.74777 +*/
 1.74778 +SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
 1.74779 +  VdbeSorter *pSorter = pCsr->pSorter;
 1.74780 +  int rc;                         /* Return code */
 1.74781 +  sqlite3_file *pTemp2 = 0;       /* Second temp file to use */
 1.74782 +  i64 iWrite2 = 0;                /* Write offset for pTemp2 */
 1.74783 +  int nIter;                      /* Number of iterators used */
 1.74784 +  int nByte;                      /* Bytes of space required for aIter/aTree */
 1.74785 +  int N = 2;                      /* Power of 2 >= nIter */
 1.74786 +
 1.74787 +  assert( pSorter );
 1.74788 +
 1.74789 +  /* If no data has been written to disk, then do not do so now. Instead,
 1.74790 +  ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
 1.74791 +  ** from the in-memory list.  */
 1.74792 +  if( pSorter->nPMA==0 ){
 1.74793 +    *pbEof = !pSorter->pRecord;
 1.74794 +    assert( pSorter->aTree==0 );
 1.74795 +    return vdbeSorterSort(pCsr);
 1.74796 +  }
 1.74797 +
 1.74798 +  /* Write the current in-memory list to a PMA. */
 1.74799 +  rc = vdbeSorterListToPMA(db, pCsr);
 1.74800 +  if( rc!=SQLITE_OK ) return rc;
 1.74801 +
 1.74802 +  /* Allocate space for aIter[] and aTree[]. */
 1.74803 +  nIter = pSorter->nPMA;
 1.74804 +  if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
 1.74805 +  assert( nIter>0 );
 1.74806 +  while( N<nIter ) N += N;
 1.74807 +  nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
 1.74808 +  pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
 1.74809 +  if( !pSorter->aIter ) return SQLITE_NOMEM;
 1.74810 +  pSorter->aTree = (int *)&pSorter->aIter[N];
 1.74811 +  pSorter->nTree = N;
 1.74812 +
 1.74813 +  do {
 1.74814 +    int iNew;                     /* Index of new, merged, PMA */
 1.74815 +
 1.74816 +    for(iNew=0; 
 1.74817 +        rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA; 
 1.74818 +        iNew++
 1.74819 +    ){
 1.74820 +      int rc2;                    /* Return code from fileWriterFinish() */
 1.74821 +      FileWriter writer;          /* Object used to write to disk */
 1.74822 +      i64 nWrite;                 /* Number of bytes in new PMA */
 1.74823 +
 1.74824 +      memset(&writer, 0, sizeof(FileWriter));
 1.74825 +
 1.74826 +      /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
 1.74827 +      ** initialize an iterator for each of them and break out of the loop.
 1.74828 +      ** These iterators will be incrementally merged as the VDBE layer calls
 1.74829 +      ** sqlite3VdbeSorterNext().
 1.74830 +      **
 1.74831 +      ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
 1.74832 +      ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
 1.74833 +      ** are merged into a single PMA that is written to file pTemp2.
 1.74834 +      */
 1.74835 +      rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
 1.74836 +      assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
 1.74837 +      if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
 1.74838 +        break;
 1.74839 +      }
 1.74840 +
 1.74841 +      /* Open the second temp file, if it is not already open. */
 1.74842 +      if( pTemp2==0 ){
 1.74843 +        assert( iWrite2==0 );
 1.74844 +        rc = vdbeSorterOpenTempFile(db, &pTemp2);
 1.74845 +      }
 1.74846 +
 1.74847 +      if( rc==SQLITE_OK ){
 1.74848 +        int bEof = 0;
 1.74849 +        fileWriterInit(db, pTemp2, &writer, iWrite2);
 1.74850 +        fileWriterWriteVarint(&writer, nWrite);
 1.74851 +        while( rc==SQLITE_OK && bEof==0 ){
 1.74852 +          VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
 1.74853 +          assert( pIter->pFile );
 1.74854 +
 1.74855 +          fileWriterWriteVarint(&writer, pIter->nKey);
 1.74856 +          fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
 1.74857 +          rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
 1.74858 +        }
 1.74859 +        rc2 = fileWriterFinish(db, &writer, &iWrite2);
 1.74860 +        if( rc==SQLITE_OK ) rc = rc2;
 1.74861 +      }
 1.74862 +    }
 1.74863 +
 1.74864 +    if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
 1.74865 +      break;
 1.74866 +    }else{
 1.74867 +      sqlite3_file *pTmp = pSorter->pTemp1;
 1.74868 +      pSorter->nPMA = iNew;
 1.74869 +      pSorter->pTemp1 = pTemp2;
 1.74870 +      pTemp2 = pTmp;
 1.74871 +      pSorter->iWriteOff = iWrite2;
 1.74872 +      pSorter->iReadOff = 0;
 1.74873 +      iWrite2 = 0;
 1.74874 +    }
 1.74875 +  }while( rc==SQLITE_OK );
 1.74876 +
 1.74877 +  if( pTemp2 ){
 1.74878 +    sqlite3OsCloseFree(pTemp2);
 1.74879 +  }
 1.74880 +  *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
 1.74881 +  return rc;
 1.74882 +}
 1.74883 +
 1.74884 +/*
 1.74885 +** Advance to the next element in the sorter.
 1.74886 +*/
 1.74887 +SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
 1.74888 +  VdbeSorter *pSorter = pCsr->pSorter;
 1.74889 +  int rc;                         /* Return code */
 1.74890 +
 1.74891 +  if( pSorter->aTree ){
 1.74892 +    int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
 1.74893 +    int i;                        /* Index of aTree[] to recalculate */
 1.74894 +
 1.74895 +    rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
 1.74896 +    for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
 1.74897 +      rc = vdbeSorterDoCompare(pCsr, i);
 1.74898 +    }
 1.74899 +
 1.74900 +    *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
 1.74901 +  }else{
 1.74902 +    SorterRecord *pFree = pSorter->pRecord;
 1.74903 +    pSorter->pRecord = pFree->pNext;
 1.74904 +    pFree->pNext = 0;
 1.74905 +    vdbeSorterRecordFree(db, pFree);
 1.74906 +    *pbEof = !pSorter->pRecord;
 1.74907 +    rc = SQLITE_OK;
 1.74908 +  }
 1.74909 +  return rc;
 1.74910 +}
 1.74911 +
 1.74912 +/*
 1.74913 +** Return a pointer to a buffer owned by the sorter that contains the 
 1.74914 +** current key.
 1.74915 +*/
 1.74916 +static void *vdbeSorterRowkey(
 1.74917 +  const VdbeSorter *pSorter,      /* Sorter object */
 1.74918 +  int *pnKey                      /* OUT: Size of current key in bytes */
 1.74919 +){
 1.74920 +  void *pKey;
 1.74921 +  if( pSorter->aTree ){
 1.74922 +    VdbeSorterIter *pIter;
 1.74923 +    pIter = &pSorter->aIter[ pSorter->aTree[1] ];
 1.74924 +    *pnKey = pIter->nKey;
 1.74925 +    pKey = pIter->aKey;
 1.74926 +  }else{
 1.74927 +    *pnKey = pSorter->pRecord->nVal;
 1.74928 +    pKey = pSorter->pRecord->pVal;
 1.74929 +  }
 1.74930 +  return pKey;
 1.74931 +}
 1.74932 +
 1.74933 +/*
 1.74934 +** Copy the current sorter key into the memory cell pOut.
 1.74935 +*/
 1.74936 +SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
 1.74937 +  VdbeSorter *pSorter = pCsr->pSorter;
 1.74938 +  void *pKey; int nKey;           /* Sorter key to copy into pOut */
 1.74939 +
 1.74940 +  pKey = vdbeSorterRowkey(pSorter, &nKey);
 1.74941 +  if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
 1.74942 +    return SQLITE_NOMEM;
 1.74943 +  }
 1.74944 +  pOut->n = nKey;
 1.74945 +  MemSetTypeFlag(pOut, MEM_Blob);
 1.74946 +  memcpy(pOut->z, pKey, nKey);
 1.74947 +
 1.74948 +  return SQLITE_OK;
 1.74949 +}
 1.74950 +
 1.74951 +/*
 1.74952 +** Compare the key in memory cell pVal with the key that the sorter cursor
 1.74953 +** passed as the first argument currently points to. For the purposes of
 1.74954 +** the comparison, ignore the rowid field at the end of each record.
 1.74955 +**
 1.74956 +** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
 1.74957 +** Otherwise, set *pRes to a negative, zero or positive value if the
 1.74958 +** key in pVal is smaller than, equal to or larger than the current sorter
 1.74959 +** key.
 1.74960 +*/
 1.74961 +SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
 1.74962 +  const VdbeCursor *pCsr,         /* Sorter cursor */
 1.74963 +  Mem *pVal,                      /* Value to compare to current sorter key */
 1.74964 +  int nIgnore,                    /* Ignore this many fields at the end */
 1.74965 +  int *pRes                       /* OUT: Result of comparison */
 1.74966 +){
 1.74967 +  VdbeSorter *pSorter = pCsr->pSorter;
 1.74968 +  void *pKey; int nKey;           /* Sorter key to compare pVal with */
 1.74969 +
 1.74970 +  pKey = vdbeSorterRowkey(pSorter, &nKey);
 1.74971 +  vdbeSorterCompare(pCsr, nIgnore, pVal->z, pVal->n, pKey, nKey, pRes);
 1.74972 +  return SQLITE_OK;
 1.74973 +}
 1.74974 +
 1.74975 +/************** End of vdbesort.c ********************************************/
 1.74976 +/************** Begin file journal.c *****************************************/
 1.74977 +/*
 1.74978 +** 2007 August 22
 1.74979 +**
 1.74980 +** The author disclaims copyright to this source code.  In place of
 1.74981 +** a legal notice, here is a blessing:
 1.74982 +**
 1.74983 +**    May you do good and not evil.
 1.74984 +**    May you find forgiveness for yourself and forgive others.
 1.74985 +**    May you share freely, never taking more than you give.
 1.74986 +**
 1.74987 +*************************************************************************
 1.74988 +**
 1.74989 +** This file implements a special kind of sqlite3_file object used
 1.74990 +** by SQLite to create journal files if the atomic-write optimization
 1.74991 +** is enabled.
 1.74992 +**
 1.74993 +** The distinctive characteristic of this sqlite3_file is that the
 1.74994 +** actual on disk file is created lazily. When the file is created,
 1.74995 +** the caller specifies a buffer size for an in-memory buffer to
 1.74996 +** be used to service read() and write() requests. The actual file
 1.74997 +** on disk is not created or populated until either:
 1.74998 +**
 1.74999 +**   1) The in-memory representation grows too large for the allocated 
 1.75000 +**      buffer, or
 1.75001 +**   2) The sqlite3JournalCreate() function is called.
 1.75002 +*/
 1.75003 +#ifdef SQLITE_ENABLE_ATOMIC_WRITE
 1.75004 +
 1.75005 +
 1.75006 +/*
 1.75007 +** A JournalFile object is a subclass of sqlite3_file used by
 1.75008 +** as an open file handle for journal files.
 1.75009 +*/
 1.75010 +struct JournalFile {
 1.75011 +  sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
 1.75012 +  int nBuf;                       /* Size of zBuf[] in bytes */
 1.75013 +  char *zBuf;                     /* Space to buffer journal writes */
 1.75014 +  int iSize;                      /* Amount of zBuf[] currently used */
 1.75015 +  int flags;                      /* xOpen flags */
 1.75016 +  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
 1.75017 +  sqlite3_file *pReal;            /* The "real" underlying file descriptor */
 1.75018 +  const char *zJournal;           /* Name of the journal file */
 1.75019 +};
 1.75020 +typedef struct JournalFile JournalFile;
 1.75021 +
 1.75022 +/*
 1.75023 +** If it does not already exists, create and populate the on-disk file 
 1.75024 +** for JournalFile p.
 1.75025 +*/
 1.75026 +static int createFile(JournalFile *p){
 1.75027 +  int rc = SQLITE_OK;
 1.75028 +  if( !p->pReal ){
 1.75029 +    sqlite3_file *pReal = (sqlite3_file *)&p[1];
 1.75030 +    rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
 1.75031 +    if( rc==SQLITE_OK ){
 1.75032 +      p->pReal = pReal;
 1.75033 +      if( p->iSize>0 ){
 1.75034 +        assert(p->iSize<=p->nBuf);
 1.75035 +        rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
 1.75036 +      }
 1.75037 +      if( rc!=SQLITE_OK ){
 1.75038 +        /* If an error occurred while writing to the file, close it before
 1.75039 +        ** returning. This way, SQLite uses the in-memory journal data to 
 1.75040 +        ** roll back changes made to the internal page-cache before this
 1.75041 +        ** function was called.  */
 1.75042 +        sqlite3OsClose(pReal);
 1.75043 +        p->pReal = 0;
 1.75044 +      }
 1.75045 +    }
 1.75046 +  }
 1.75047 +  return rc;
 1.75048 +}
 1.75049 +
 1.75050 +/*
 1.75051 +** Close the file.
 1.75052 +*/
 1.75053 +static int jrnlClose(sqlite3_file *pJfd){
 1.75054 +  JournalFile *p = (JournalFile *)pJfd;
 1.75055 +  if( p->pReal ){
 1.75056 +    sqlite3OsClose(p->pReal);
 1.75057 +  }
 1.75058 +  sqlite3_free(p->zBuf);
 1.75059 +  return SQLITE_OK;
 1.75060 +}
 1.75061 +
 1.75062 +/*
 1.75063 +** Read data from the file.
 1.75064 +*/
 1.75065 +static int jrnlRead(
 1.75066 +  sqlite3_file *pJfd,    /* The journal file from which to read */
 1.75067 +  void *zBuf,            /* Put the results here */
 1.75068 +  int iAmt,              /* Number of bytes to read */
 1.75069 +  sqlite_int64 iOfst     /* Begin reading at this offset */
 1.75070 +){
 1.75071 +  int rc = SQLITE_OK;
 1.75072 +  JournalFile *p = (JournalFile *)pJfd;
 1.75073 +  if( p->pReal ){
 1.75074 +    rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
 1.75075 +  }else if( (iAmt+iOfst)>p->iSize ){
 1.75076 +    rc = SQLITE_IOERR_SHORT_READ;
 1.75077 +  }else{
 1.75078 +    memcpy(zBuf, &p->zBuf[iOfst], iAmt);
 1.75079 +  }
 1.75080 +  return rc;
 1.75081 +}
 1.75082 +
 1.75083 +/*
 1.75084 +** Write data to the file.
 1.75085 +*/
 1.75086 +static int jrnlWrite(
 1.75087 +  sqlite3_file *pJfd,    /* The journal file into which to write */
 1.75088 +  const void *zBuf,      /* Take data to be written from here */
 1.75089 +  int iAmt,              /* Number of bytes to write */
 1.75090 +  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
 1.75091 +){
 1.75092 +  int rc = SQLITE_OK;
 1.75093 +  JournalFile *p = (JournalFile *)pJfd;
 1.75094 +  if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
 1.75095 +    rc = createFile(p);
 1.75096 +  }
 1.75097 +  if( rc==SQLITE_OK ){
 1.75098 +    if( p->pReal ){
 1.75099 +      rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
 1.75100 +    }else{
 1.75101 +      memcpy(&p->zBuf[iOfst], zBuf, iAmt);
 1.75102 +      if( p->iSize<(iOfst+iAmt) ){
 1.75103 +        p->iSize = (iOfst+iAmt);
 1.75104 +      }
 1.75105 +    }
 1.75106 +  }
 1.75107 +  return rc;
 1.75108 +}
 1.75109 +
 1.75110 +/*
 1.75111 +** Truncate the file.
 1.75112 +*/
 1.75113 +static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
 1.75114 +  int rc = SQLITE_OK;
 1.75115 +  JournalFile *p = (JournalFile *)pJfd;
 1.75116 +  if( p->pReal ){
 1.75117 +    rc = sqlite3OsTruncate(p->pReal, size);
 1.75118 +  }else if( size<p->iSize ){
 1.75119 +    p->iSize = size;
 1.75120 +  }
 1.75121 +  return rc;
 1.75122 +}
 1.75123 +
 1.75124 +/*
 1.75125 +** Sync the file.
 1.75126 +*/
 1.75127 +static int jrnlSync(sqlite3_file *pJfd, int flags){
 1.75128 +  int rc;
 1.75129 +  JournalFile *p = (JournalFile *)pJfd;
 1.75130 +  if( p->pReal ){
 1.75131 +    rc = sqlite3OsSync(p->pReal, flags);
 1.75132 +  }else{
 1.75133 +    rc = SQLITE_OK;
 1.75134 +  }
 1.75135 +  return rc;
 1.75136 +}
 1.75137 +
 1.75138 +/*
 1.75139 +** Query the size of the file in bytes.
 1.75140 +*/
 1.75141 +static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
 1.75142 +  int rc = SQLITE_OK;
 1.75143 +  JournalFile *p = (JournalFile *)pJfd;
 1.75144 +  if( p->pReal ){
 1.75145 +    rc = sqlite3OsFileSize(p->pReal, pSize);
 1.75146 +  }else{
 1.75147 +    *pSize = (sqlite_int64) p->iSize;
 1.75148 +  }
 1.75149 +  return rc;
 1.75150 +}
 1.75151 +
 1.75152 +/*
 1.75153 +** Table of methods for JournalFile sqlite3_file object.
 1.75154 +*/
 1.75155 +static struct sqlite3_io_methods JournalFileMethods = {
 1.75156 +  1,             /* iVersion */
 1.75157 +  jrnlClose,     /* xClose */
 1.75158 +  jrnlRead,      /* xRead */
 1.75159 +  jrnlWrite,     /* xWrite */
 1.75160 +  jrnlTruncate,  /* xTruncate */
 1.75161 +  jrnlSync,      /* xSync */
 1.75162 +  jrnlFileSize,  /* xFileSize */
 1.75163 +  0,             /* xLock */
 1.75164 +  0,             /* xUnlock */
 1.75165 +  0,             /* xCheckReservedLock */
 1.75166 +  0,             /* xFileControl */
 1.75167 +  0,             /* xSectorSize */
 1.75168 +  0,             /* xDeviceCharacteristics */
 1.75169 +  0,             /* xShmMap */
 1.75170 +  0,             /* xShmLock */
 1.75171 +  0,             /* xShmBarrier */
 1.75172 +  0              /* xShmUnmap */
 1.75173 +};
 1.75174 +
 1.75175 +/* 
 1.75176 +** Open a journal file.
 1.75177 +*/
 1.75178 +SQLITE_PRIVATE int sqlite3JournalOpen(
 1.75179 +  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
 1.75180 +  const char *zName,         /* Name of the journal file */
 1.75181 +  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
 1.75182 +  int flags,                 /* Opening flags */
 1.75183 +  int nBuf                   /* Bytes buffered before opening the file */
 1.75184 +){
 1.75185 +  JournalFile *p = (JournalFile *)pJfd;
 1.75186 +  memset(p, 0, sqlite3JournalSize(pVfs));
 1.75187 +  if( nBuf>0 ){
 1.75188 +    p->zBuf = sqlite3MallocZero(nBuf);
 1.75189 +    if( !p->zBuf ){
 1.75190 +      return SQLITE_NOMEM;
 1.75191 +    }
 1.75192 +  }else{
 1.75193 +    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
 1.75194 +  }
 1.75195 +  p->pMethod = &JournalFileMethods;
 1.75196 +  p->nBuf = nBuf;
 1.75197 +  p->flags = flags;
 1.75198 +  p->zJournal = zName;
 1.75199 +  p->pVfs = pVfs;
 1.75200 +  return SQLITE_OK;
 1.75201 +}
 1.75202 +
 1.75203 +/*
 1.75204 +** If the argument p points to a JournalFile structure, and the underlying
 1.75205 +** file has not yet been created, create it now.
 1.75206 +*/
 1.75207 +SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
 1.75208 +  if( p->pMethods!=&JournalFileMethods ){
 1.75209 +    return SQLITE_OK;
 1.75210 +  }
 1.75211 +  return createFile((JournalFile *)p);
 1.75212 +}
 1.75213 +
 1.75214 +/*
 1.75215 +** The file-handle passed as the only argument is guaranteed to be an open
 1.75216 +** file. It may or may not be of class JournalFile. If the file is a
 1.75217 +** JournalFile, and the underlying file on disk has not yet been opened,
 1.75218 +** return 0. Otherwise, return 1.
 1.75219 +*/
 1.75220 +SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
 1.75221 +  return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
 1.75222 +}
 1.75223 +
 1.75224 +/* 
 1.75225 +** Return the number of bytes required to store a JournalFile that uses vfs
 1.75226 +** pVfs to create the underlying on-disk files.
 1.75227 +*/
 1.75228 +SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
 1.75229 +  return (pVfs->szOsFile+sizeof(JournalFile));
 1.75230 +}
 1.75231 +#endif
 1.75232 +
 1.75233 +/************** End of journal.c *********************************************/
 1.75234 +/************** Begin file memjournal.c **************************************/
 1.75235 +/*
 1.75236 +** 2008 October 7
 1.75237 +**
 1.75238 +** The author disclaims copyright to this source code.  In place of
 1.75239 +** a legal notice, here is a blessing:
 1.75240 +**
 1.75241 +**    May you do good and not evil.
 1.75242 +**    May you find forgiveness for yourself and forgive others.
 1.75243 +**    May you share freely, never taking more than you give.
 1.75244 +**
 1.75245 +*************************************************************************
 1.75246 +**
 1.75247 +** This file contains code use to implement an in-memory rollback journal.
 1.75248 +** The in-memory rollback journal is used to journal transactions for
 1.75249 +** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
 1.75250 +*/
 1.75251 +
 1.75252 +/* Forward references to internal structures */
 1.75253 +typedef struct MemJournal MemJournal;
 1.75254 +typedef struct FilePoint FilePoint;
 1.75255 +typedef struct FileChunk FileChunk;
 1.75256 +
 1.75257 +/* Space to hold the rollback journal is allocated in increments of
 1.75258 +** this many bytes.
 1.75259 +**
 1.75260 +** The size chosen is a little less than a power of two.  That way,
 1.75261 +** the FileChunk object will have a size that almost exactly fills
 1.75262 +** a power-of-two allocation.  This mimimizes wasted space in power-of-two
 1.75263 +** memory allocators.
 1.75264 +*/
 1.75265 +#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
 1.75266 +
 1.75267 +/*
 1.75268 +** The rollback journal is composed of a linked list of these structures.
 1.75269 +*/
 1.75270 +struct FileChunk {
 1.75271 +  FileChunk *pNext;               /* Next chunk in the journal */
 1.75272 +  u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
 1.75273 +};
 1.75274 +
 1.75275 +/*
 1.75276 +** An instance of this object serves as a cursor into the rollback journal.
 1.75277 +** The cursor can be either for reading or writing.
 1.75278 +*/
 1.75279 +struct FilePoint {
 1.75280 +  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
 1.75281 +  FileChunk *pChunk;              /* Specific chunk into which cursor points */
 1.75282 +};
 1.75283 +
 1.75284 +/*
 1.75285 +** This subclass is a subclass of sqlite3_file.  Each open memory-journal
 1.75286 +** is an instance of this class.
 1.75287 +*/
 1.75288 +struct MemJournal {
 1.75289 +  sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
 1.75290 +  FileChunk *pFirst;              /* Head of in-memory chunk-list */
 1.75291 +  FilePoint endpoint;             /* Pointer to the end of the file */
 1.75292 +  FilePoint readpoint;            /* Pointer to the end of the last xRead() */
 1.75293 +};
 1.75294 +
 1.75295 +/*
 1.75296 +** Read data from the in-memory journal file.  This is the implementation
 1.75297 +** of the sqlite3_vfs.xRead method.
 1.75298 +*/
 1.75299 +static int memjrnlRead(
 1.75300 +  sqlite3_file *pJfd,    /* The journal file from which to read */
 1.75301 +  void *zBuf,            /* Put the results here */
 1.75302 +  int iAmt,              /* Number of bytes to read */
 1.75303 +  sqlite_int64 iOfst     /* Begin reading at this offset */
 1.75304 +){
 1.75305 +  MemJournal *p = (MemJournal *)pJfd;
 1.75306 +  u8 *zOut = zBuf;
 1.75307 +  int nRead = iAmt;
 1.75308 +  int iChunkOffset;
 1.75309 +  FileChunk *pChunk;
 1.75310 +
 1.75311 +  /* SQLite never tries to read past the end of a rollback journal file */
 1.75312 +  assert( iOfst+iAmt<=p->endpoint.iOffset );
 1.75313 +
 1.75314 +  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
 1.75315 +    sqlite3_int64 iOff = 0;
 1.75316 +    for(pChunk=p->pFirst; 
 1.75317 +        ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
 1.75318 +        pChunk=pChunk->pNext
 1.75319 +    ){
 1.75320 +      iOff += JOURNAL_CHUNKSIZE;
 1.75321 +    }
 1.75322 +  }else{
 1.75323 +    pChunk = p->readpoint.pChunk;
 1.75324 +  }
 1.75325 +
 1.75326 +  iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
 1.75327 +  do {
 1.75328 +    int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
 1.75329 +    int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
 1.75330 +    memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
 1.75331 +    zOut += nCopy;
 1.75332 +    nRead -= iSpace;
 1.75333 +    iChunkOffset = 0;
 1.75334 +  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
 1.75335 +  p->readpoint.iOffset = iOfst+iAmt;
 1.75336 +  p->readpoint.pChunk = pChunk;
 1.75337 +
 1.75338 +  return SQLITE_OK;
 1.75339 +}
 1.75340 +
 1.75341 +/*
 1.75342 +** Write data to the file.
 1.75343 +*/
 1.75344 +static int memjrnlWrite(
 1.75345 +  sqlite3_file *pJfd,    /* The journal file into which to write */
 1.75346 +  const void *zBuf,      /* Take data to be written from here */
 1.75347 +  int iAmt,              /* Number of bytes to write */
 1.75348 +  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
 1.75349 +){
 1.75350 +  MemJournal *p = (MemJournal *)pJfd;
 1.75351 +  int nWrite = iAmt;
 1.75352 +  u8 *zWrite = (u8 *)zBuf;
 1.75353 +
 1.75354 +  /* An in-memory journal file should only ever be appended to. Random
 1.75355 +  ** access writes are not required by sqlite.
 1.75356 +  */
 1.75357 +  assert( iOfst==p->endpoint.iOffset );
 1.75358 +  UNUSED_PARAMETER(iOfst);
 1.75359 +
 1.75360 +  while( nWrite>0 ){
 1.75361 +    FileChunk *pChunk = p->endpoint.pChunk;
 1.75362 +    int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
 1.75363 +    int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
 1.75364 +
 1.75365 +    if( iChunkOffset==0 ){
 1.75366 +      /* New chunk is required to extend the file. */
 1.75367 +      FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
 1.75368 +      if( !pNew ){
 1.75369 +        return SQLITE_IOERR_NOMEM;
 1.75370 +      }
 1.75371 +      pNew->pNext = 0;
 1.75372 +      if( pChunk ){
 1.75373 +        assert( p->pFirst );
 1.75374 +        pChunk->pNext = pNew;
 1.75375 +      }else{
 1.75376 +        assert( !p->pFirst );
 1.75377 +        p->pFirst = pNew;
 1.75378 +      }
 1.75379 +      p->endpoint.pChunk = pNew;
 1.75380 +    }
 1.75381 +
 1.75382 +    memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
 1.75383 +    zWrite += iSpace;
 1.75384 +    nWrite -= iSpace;
 1.75385 +    p->endpoint.iOffset += iSpace;
 1.75386 +  }
 1.75387 +
 1.75388 +  return SQLITE_OK;
 1.75389 +}
 1.75390 +
 1.75391 +/*
 1.75392 +** Truncate the file.
 1.75393 +*/
 1.75394 +static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
 1.75395 +  MemJournal *p = (MemJournal *)pJfd;
 1.75396 +  FileChunk *pChunk;
 1.75397 +  assert(size==0);
 1.75398 +  UNUSED_PARAMETER(size);
 1.75399 +  pChunk = p->pFirst;
 1.75400 +  while( pChunk ){
 1.75401 +    FileChunk *pTmp = pChunk;
 1.75402 +    pChunk = pChunk->pNext;
 1.75403 +    sqlite3_free(pTmp);
 1.75404 +  }
 1.75405 +  sqlite3MemJournalOpen(pJfd);
 1.75406 +  return SQLITE_OK;
 1.75407 +}
 1.75408 +
 1.75409 +/*
 1.75410 +** Close the file.
 1.75411 +*/
 1.75412 +static int memjrnlClose(sqlite3_file *pJfd){
 1.75413 +  memjrnlTruncate(pJfd, 0);
 1.75414 +  return SQLITE_OK;
 1.75415 +}
 1.75416 +
 1.75417 +
 1.75418 +/*
 1.75419 +** Sync the file.
 1.75420 +**
 1.75421 +** Syncing an in-memory journal is a no-op.  And, in fact, this routine
 1.75422 +** is never called in a working implementation.  This implementation
 1.75423 +** exists purely as a contingency, in case some malfunction in some other
 1.75424 +** part of SQLite causes Sync to be called by mistake.
 1.75425 +*/
 1.75426 +static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
 1.75427 +  UNUSED_PARAMETER2(NotUsed, NotUsed2);
 1.75428 +  return SQLITE_OK;
 1.75429 +}
 1.75430 +
 1.75431 +/*
 1.75432 +** Query the size of the file in bytes.
 1.75433 +*/
 1.75434 +static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
 1.75435 +  MemJournal *p = (MemJournal *)pJfd;
 1.75436 +  *pSize = (sqlite_int64) p->endpoint.iOffset;
 1.75437 +  return SQLITE_OK;
 1.75438 +}
 1.75439 +
 1.75440 +/*
 1.75441 +** Table of methods for MemJournal sqlite3_file object.
 1.75442 +*/
 1.75443 +static const struct sqlite3_io_methods MemJournalMethods = {
 1.75444 +  1,                /* iVersion */
 1.75445 +  memjrnlClose,     /* xClose */
 1.75446 +  memjrnlRead,      /* xRead */
 1.75447 +  memjrnlWrite,     /* xWrite */
 1.75448 +  memjrnlTruncate,  /* xTruncate */
 1.75449 +  memjrnlSync,      /* xSync */
 1.75450 +  memjrnlFileSize,  /* xFileSize */
 1.75451 +  0,                /* xLock */
 1.75452 +  0,                /* xUnlock */
 1.75453 +  0,                /* xCheckReservedLock */
 1.75454 +  0,                /* xFileControl */
 1.75455 +  0,                /* xSectorSize */
 1.75456 +  0,                /* xDeviceCharacteristics */
 1.75457 +  0,                /* xShmMap */
 1.75458 +  0,                /* xShmLock */
 1.75459 +  0,                /* xShmBarrier */
 1.75460 +  0,                /* xShmUnmap */
 1.75461 +  0,                /* xFetch */
 1.75462 +  0                 /* xUnfetch */
 1.75463 +};
 1.75464 +
 1.75465 +/* 
 1.75466 +** Open a journal file.
 1.75467 +*/
 1.75468 +SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
 1.75469 +  MemJournal *p = (MemJournal *)pJfd;
 1.75470 +  assert( EIGHT_BYTE_ALIGNMENT(p) );
 1.75471 +  memset(p, 0, sqlite3MemJournalSize());
 1.75472 +  p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
 1.75473 +}
 1.75474 +
 1.75475 +/*
 1.75476 +** Return true if the file-handle passed as an argument is 
 1.75477 +** an in-memory journal 
 1.75478 +*/
 1.75479 +SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
 1.75480 +  return pJfd->pMethods==&MemJournalMethods;
 1.75481 +}
 1.75482 +
 1.75483 +/* 
 1.75484 +** Return the number of bytes required to store a MemJournal file descriptor.
 1.75485 +*/
 1.75486 +SQLITE_PRIVATE int sqlite3MemJournalSize(void){
 1.75487 +  return sizeof(MemJournal);
 1.75488 +}
 1.75489 +
 1.75490 +/************** End of memjournal.c ******************************************/
 1.75491 +/************** Begin file walker.c ******************************************/
 1.75492 +/*
 1.75493 +** 2008 August 16
 1.75494 +**
 1.75495 +** The author disclaims copyright to this source code.  In place of
 1.75496 +** a legal notice, here is a blessing:
 1.75497 +**
 1.75498 +**    May you do good and not evil.
 1.75499 +**    May you find forgiveness for yourself and forgive others.
 1.75500 +**    May you share freely, never taking more than you give.
 1.75501 +**
 1.75502 +*************************************************************************
 1.75503 +** This file contains routines used for walking the parser tree for
 1.75504 +** an SQL statement.
 1.75505 +*/
 1.75506 +/* #include <stdlib.h> */
 1.75507 +/* #include <string.h> */
 1.75508 +
 1.75509 +
 1.75510 +/*
 1.75511 +** Walk an expression tree.  Invoke the callback once for each node
 1.75512 +** of the expression, while decending.  (In other words, the callback
 1.75513 +** is invoked before visiting children.)
 1.75514 +**
 1.75515 +** The return value from the callback should be one of the WRC_*
 1.75516 +** constants to specify how to proceed with the walk.
 1.75517 +**
 1.75518 +**    WRC_Continue      Continue descending down the tree.
 1.75519 +**
 1.75520 +**    WRC_Prune         Do not descend into child nodes.  But allow
 1.75521 +**                      the walk to continue with sibling nodes.
 1.75522 +**
 1.75523 +**    WRC_Abort         Do no more callbacks.  Unwind the stack and
 1.75524 +**                      return the top-level walk call.
 1.75525 +**
 1.75526 +** The return value from this routine is WRC_Abort to abandon the tree walk
 1.75527 +** and WRC_Continue to continue.
 1.75528 +*/
 1.75529 +SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
 1.75530 +  int rc;
 1.75531 +  if( pExpr==0 ) return WRC_Continue;
 1.75532 +  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
 1.75533 +  testcase( ExprHasProperty(pExpr, EP_Reduced) );
 1.75534 +  rc = pWalker->xExprCallback(pWalker, pExpr);
 1.75535 +  if( rc==WRC_Continue
 1.75536 +              && !ExprHasProperty(pExpr,EP_TokenOnly) ){
 1.75537 +    if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
 1.75538 +    if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
 1.75539 +    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
 1.75540 +      if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
 1.75541 +    }else{
 1.75542 +      if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
 1.75543 +    }
 1.75544 +  }
 1.75545 +  return rc & WRC_Abort;
 1.75546 +}
 1.75547 +
 1.75548 +/*
 1.75549 +** Call sqlite3WalkExpr() for every expression in list p or until
 1.75550 +** an abort request is seen.
 1.75551 +*/
 1.75552 +SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
 1.75553 +  int i;
 1.75554 +  struct ExprList_item *pItem;
 1.75555 +  if( p ){
 1.75556 +    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
 1.75557 +      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
 1.75558 +    }
 1.75559 +  }
 1.75560 +  return WRC_Continue;
 1.75561 +}
 1.75562 +
 1.75563 +/*
 1.75564 +** Walk all expressions associated with SELECT statement p.  Do
 1.75565 +** not invoke the SELECT callback on p, but do (of course) invoke
 1.75566 +** any expr callbacks and SELECT callbacks that come from subqueries.
 1.75567 +** Return WRC_Abort or WRC_Continue.
 1.75568 +*/
 1.75569 +SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
 1.75570 +  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
 1.75571 +  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
 1.75572 +  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
 1.75573 +  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
 1.75574 +  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
 1.75575 +  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
 1.75576 +  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
 1.75577 +  return WRC_Continue;
 1.75578 +}
 1.75579 +
 1.75580 +/*
 1.75581 +** Walk the parse trees associated with all subqueries in the
 1.75582 +** FROM clause of SELECT statement p.  Do not invoke the select
 1.75583 +** callback on p, but do invoke it on each FROM clause subquery
 1.75584 +** and on any subqueries further down in the tree.  Return 
 1.75585 +** WRC_Abort or WRC_Continue;
 1.75586 +*/
 1.75587 +SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
 1.75588 +  SrcList *pSrc;
 1.75589 +  int i;
 1.75590 +  struct SrcList_item *pItem;
 1.75591 +
 1.75592 +  pSrc = p->pSrc;
 1.75593 +  if( ALWAYS(pSrc) ){
 1.75594 +    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
 1.75595 +      if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
 1.75596 +        return WRC_Abort;
 1.75597 +      }
 1.75598 +    }
 1.75599 +  }
 1.75600 +  return WRC_Continue;
 1.75601 +} 
 1.75602 +
 1.75603 +/*
 1.75604 +** Call sqlite3WalkExpr() for every expression in Select statement p.
 1.75605 +** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
 1.75606 +** on the compound select chain, p->pPrior. 
 1.75607 +**
 1.75608 +** If it is not NULL, the xSelectCallback() callback is invoked before
 1.75609 +** the walk of the expressions and FROM clause. The xSelectCallback2()
 1.75610 +** method, if it is not NULL, is invoked following the walk of the 
 1.75611 +** expressions and FROM clause.
 1.75612 +**
 1.75613 +** Return WRC_Continue under normal conditions.  Return WRC_Abort if
 1.75614 +** there is an abort request.
 1.75615 +**
 1.75616 +** If the Walker does not have an xSelectCallback() then this routine
 1.75617 +** is a no-op returning WRC_Continue.
 1.75618 +*/
 1.75619 +SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
 1.75620 +  int rc;
 1.75621 +  if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
 1.75622 +    return WRC_Continue;
 1.75623 +  }
 1.75624 +  rc = WRC_Continue;
 1.75625 +  pWalker->walkerDepth++;
 1.75626 +  while( p ){
 1.75627 +    if( pWalker->xSelectCallback ){
 1.75628 +       rc = pWalker->xSelectCallback(pWalker, p);
 1.75629 +       if( rc ) break;
 1.75630 +    }
 1.75631 +    if( sqlite3WalkSelectExpr(pWalker, p)
 1.75632 +     || sqlite3WalkSelectFrom(pWalker, p)
 1.75633 +    ){
 1.75634 +      pWalker->walkerDepth--;
 1.75635 +      return WRC_Abort;
 1.75636 +    }
 1.75637 +    if( pWalker->xSelectCallback2 ){
 1.75638 +      pWalker->xSelectCallback2(pWalker, p);
 1.75639 +    }
 1.75640 +    p = p->pPrior;
 1.75641 +  }
 1.75642 +  pWalker->walkerDepth--;
 1.75643 +  return rc & WRC_Abort;
 1.75644 +}
 1.75645 +
 1.75646 +/************** End of walker.c **********************************************/
 1.75647 +/************** Begin file resolve.c *****************************************/
 1.75648 +/*
 1.75649 +** 2008 August 18
 1.75650 +**
 1.75651 +** The author disclaims copyright to this source code.  In place of
 1.75652 +** a legal notice, here is a blessing:
 1.75653 +**
 1.75654 +**    May you do good and not evil.
 1.75655 +**    May you find forgiveness for yourself and forgive others.
 1.75656 +**    May you share freely, never taking more than you give.
 1.75657 +**
 1.75658 +*************************************************************************
 1.75659 +**
 1.75660 +** This file contains routines used for walking the parser tree and
 1.75661 +** resolve all identifiers by associating them with a particular
 1.75662 +** table and column.
 1.75663 +*/
 1.75664 +/* #include <stdlib.h> */
 1.75665 +/* #include <string.h> */
 1.75666 +
 1.75667 +/*
 1.75668 +** Walk the expression tree pExpr and increase the aggregate function
 1.75669 +** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
 1.75670 +** This needs to occur when copying a TK_AGG_FUNCTION node from an
 1.75671 +** outer query into an inner subquery.
 1.75672 +**
 1.75673 +** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
 1.75674 +** is a helper function - a callback for the tree walker.
 1.75675 +*/
 1.75676 +static int incrAggDepth(Walker *pWalker, Expr *pExpr){
 1.75677 +  if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
 1.75678 +  return WRC_Continue;
 1.75679 +}
 1.75680 +static void incrAggFunctionDepth(Expr *pExpr, int N){
 1.75681 +  if( N>0 ){
 1.75682 +    Walker w;
 1.75683 +    memset(&w, 0, sizeof(w));
 1.75684 +    w.xExprCallback = incrAggDepth;
 1.75685 +    w.u.i = N;
 1.75686 +    sqlite3WalkExpr(&w, pExpr);
 1.75687 +  }
 1.75688 +}
 1.75689 +
 1.75690 +/*
 1.75691 +** Turn the pExpr expression into an alias for the iCol-th column of the
 1.75692 +** result set in pEList.
 1.75693 +**
 1.75694 +** If the result set column is a simple column reference, then this routine
 1.75695 +** makes an exact copy.  But for any other kind of expression, this
 1.75696 +** routine make a copy of the result set column as the argument to the
 1.75697 +** TK_AS operator.  The TK_AS operator causes the expression to be
 1.75698 +** evaluated just once and then reused for each alias.
 1.75699 +**
 1.75700 +** The reason for suppressing the TK_AS term when the expression is a simple
 1.75701 +** column reference is so that the column reference will be recognized as
 1.75702 +** usable by indices within the WHERE clause processing logic. 
 1.75703 +**
 1.75704 +** The TK_AS operator is inhibited if zType[0]=='G'.  This means
 1.75705 +** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
 1.75706 +**
 1.75707 +**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
 1.75708 +**
 1.75709 +** Is equivalent to:
 1.75710 +**
 1.75711 +**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
 1.75712 +**
 1.75713 +** The result of random()%5 in the GROUP BY clause is probably different
 1.75714 +** from the result in the result-set.  On the other hand Standard SQL does
 1.75715 +** not allow the GROUP BY clause to contain references to result-set columns.
 1.75716 +** So this should never come up in well-formed queries.
 1.75717 +**
 1.75718 +** If the reference is followed by a COLLATE operator, then make sure
 1.75719 +** the COLLATE operator is preserved.  For example:
 1.75720 +**
 1.75721 +**     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
 1.75722 +**
 1.75723 +** Should be transformed into:
 1.75724 +**
 1.75725 +**     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
 1.75726 +**
 1.75727 +** The nSubquery parameter specifies how many levels of subquery the
 1.75728 +** alias is removed from the original expression.  The usually value is
 1.75729 +** zero but it might be more if the alias is contained within a subquery
 1.75730 +** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
 1.75731 +** structures must be increased by the nSubquery amount.
 1.75732 +*/
 1.75733 +static void resolveAlias(
 1.75734 +  Parse *pParse,         /* Parsing context */
 1.75735 +  ExprList *pEList,      /* A result set */
 1.75736 +  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
 1.75737 +  Expr *pExpr,           /* Transform this into an alias to the result set */
 1.75738 +  const char *zType,     /* "GROUP" or "ORDER" or "" */
 1.75739 +  int nSubquery          /* Number of subqueries that the label is moving */
 1.75740 +){
 1.75741 +  Expr *pOrig;           /* The iCol-th column of the result set */
 1.75742 +  Expr *pDup;            /* Copy of pOrig */
 1.75743 +  sqlite3 *db;           /* The database connection */
 1.75744 +
 1.75745 +  assert( iCol>=0 && iCol<pEList->nExpr );
 1.75746 +  pOrig = pEList->a[iCol].pExpr;
 1.75747 +  assert( pOrig!=0 );
 1.75748 +  assert( pOrig->flags & EP_Resolved );
 1.75749 +  db = pParse->db;
 1.75750 +  pDup = sqlite3ExprDup(db, pOrig, 0);
 1.75751 +  if( pDup==0 ) return;
 1.75752 +  if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
 1.75753 +    incrAggFunctionDepth(pDup, nSubquery);
 1.75754 +    pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
 1.75755 +    if( pDup==0 ) return;
 1.75756 +    ExprSetProperty(pDup, EP_Skip);
 1.75757 +    if( pEList->a[iCol].u.x.iAlias==0 ){
 1.75758 +      pEList->a[iCol].u.x.iAlias = (u16)(++pParse->nAlias);
 1.75759 +    }
 1.75760 +    pDup->iTable = pEList->a[iCol].u.x.iAlias;
 1.75761 +  }
 1.75762 +  if( pExpr->op==TK_COLLATE ){
 1.75763 +    pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
 1.75764 +  }
 1.75765 +
 1.75766 +  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
 1.75767 +  ** prevents ExprDelete() from deleting the Expr structure itself,
 1.75768 +  ** allowing it to be repopulated by the memcpy() on the following line.
 1.75769 +  ** The pExpr->u.zToken might point into memory that will be freed by the
 1.75770 +  ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
 1.75771 +  ** make a copy of the token before doing the sqlite3DbFree().
 1.75772 +  */
 1.75773 +  ExprSetProperty(pExpr, EP_Static);
 1.75774 +  sqlite3ExprDelete(db, pExpr);
 1.75775 +  memcpy(pExpr, pDup, sizeof(*pExpr));
 1.75776 +  if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
 1.75777 +    assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
 1.75778 +    pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
 1.75779 +    pExpr->flags |= EP_MemToken;
 1.75780 +  }
 1.75781 +  sqlite3DbFree(db, pDup);
 1.75782 +}
 1.75783 +
 1.75784 +
 1.75785 +/*
 1.75786 +** Return TRUE if the name zCol occurs anywhere in the USING clause.
 1.75787 +**
 1.75788 +** Return FALSE if the USING clause is NULL or if it does not contain
 1.75789 +** zCol.
 1.75790 +*/
 1.75791 +static int nameInUsingClause(IdList *pUsing, const char *zCol){
 1.75792 +  if( pUsing ){
 1.75793 +    int k;
 1.75794 +    for(k=0; k<pUsing->nId; k++){
 1.75795 +      if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
 1.75796 +    }
 1.75797 +  }
 1.75798 +  return 0;
 1.75799 +}
 1.75800 +
 1.75801 +/*
 1.75802 +** Subqueries stores the original database, table and column names for their
 1.75803 +** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
 1.75804 +** Check to see if the zSpan given to this routine matches the zDb, zTab,
 1.75805 +** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
 1.75806 +** match anything.
 1.75807 +*/
 1.75808 +SQLITE_PRIVATE int sqlite3MatchSpanName(
 1.75809 +  const char *zSpan,
 1.75810 +  const char *zCol,
 1.75811 +  const char *zTab,
 1.75812 +  const char *zDb
 1.75813 +){
 1.75814 +  int n;
 1.75815 +  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
 1.75816 +  if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
 1.75817 +    return 0;
 1.75818 +  }
 1.75819 +  zSpan += n+1;
 1.75820 +  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
 1.75821 +  if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
 1.75822 +    return 0;
 1.75823 +  }
 1.75824 +  zSpan += n+1;
 1.75825 +  if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
 1.75826 +    return 0;
 1.75827 +  }
 1.75828 +  return 1;
 1.75829 +}
 1.75830 +
 1.75831 +/*
 1.75832 +** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
 1.75833 +** that name in the set of source tables in pSrcList and make the pExpr 
 1.75834 +** expression node refer back to that source column.  The following changes
 1.75835 +** are made to pExpr:
 1.75836 +**
 1.75837 +**    pExpr->iDb           Set the index in db->aDb[] of the database X
 1.75838 +**                         (even if X is implied).
 1.75839 +**    pExpr->iTable        Set to the cursor number for the table obtained
 1.75840 +**                         from pSrcList.
 1.75841 +**    pExpr->pTab          Points to the Table structure of X.Y (even if
 1.75842 +**                         X and/or Y are implied.)
 1.75843 +**    pExpr->iColumn       Set to the column number within the table.
 1.75844 +**    pExpr->op            Set to TK_COLUMN.
 1.75845 +**    pExpr->pLeft         Any expression this points to is deleted
 1.75846 +**    pExpr->pRight        Any expression this points to is deleted.
 1.75847 +**
 1.75848 +** The zDb variable is the name of the database (the "X").  This value may be
 1.75849 +** NULL meaning that name is of the form Y.Z or Z.  Any available database
 1.75850 +** can be used.  The zTable variable is the name of the table (the "Y").  This
 1.75851 +** value can be NULL if zDb is also NULL.  If zTable is NULL it
 1.75852 +** means that the form of the name is Z and that columns from any table
 1.75853 +** can be used.
 1.75854 +**
 1.75855 +** If the name cannot be resolved unambiguously, leave an error message
 1.75856 +** in pParse and return WRC_Abort.  Return WRC_Prune on success.
 1.75857 +*/
 1.75858 +static int lookupName(
 1.75859 +  Parse *pParse,       /* The parsing context */
 1.75860 +  const char *zDb,     /* Name of the database containing table, or NULL */
 1.75861 +  const char *zTab,    /* Name of table containing column, or NULL */
 1.75862 +  const char *zCol,    /* Name of the column. */
 1.75863 +  NameContext *pNC,    /* The name context used to resolve the name */
 1.75864 +  Expr *pExpr          /* Make this EXPR node point to the selected column */
 1.75865 +){
 1.75866 +  int i, j;                         /* Loop counters */
 1.75867 +  int cnt = 0;                      /* Number of matching column names */
 1.75868 +  int cntTab = 0;                   /* Number of matching table names */
 1.75869 +  int nSubquery = 0;                /* How many levels of subquery */
 1.75870 +  sqlite3 *db = pParse->db;         /* The database connection */
 1.75871 +  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
 1.75872 +  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
 1.75873 +  NameContext *pTopNC = pNC;        /* First namecontext in the list */
 1.75874 +  Schema *pSchema = 0;              /* Schema of the expression */
 1.75875 +  int isTrigger = 0;                /* True if resolved to a trigger column */
 1.75876 +  Table *pTab = 0;                  /* Table hold the row */
 1.75877 +  Column *pCol;                     /* A column of pTab */
 1.75878 +
 1.75879 +  assert( pNC );     /* the name context cannot be NULL. */
 1.75880 +  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
 1.75881 +  assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
 1.75882 +
 1.75883 +  /* Initialize the node to no-match */
 1.75884 +  pExpr->iTable = -1;
 1.75885 +  pExpr->pTab = 0;
 1.75886 +  ExprSetVVAProperty(pExpr, EP_NoReduce);
 1.75887 +
 1.75888 +  /* Translate the schema name in zDb into a pointer to the corresponding
 1.75889 +  ** schema.  If not found, pSchema will remain NULL and nothing will match
 1.75890 +  ** resulting in an appropriate error message toward the end of this routine
 1.75891 +  */
 1.75892 +  if( zDb ){
 1.75893 +    testcase( pNC->ncFlags & NC_PartIdx );
 1.75894 +    testcase( pNC->ncFlags & NC_IsCheck );
 1.75895 +    if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
 1.75896 +      /* Silently ignore database qualifiers inside CHECK constraints and partial
 1.75897 +      ** indices.  Do not raise errors because that might break legacy and
 1.75898 +      ** because it does not hurt anything to just ignore the database name. */
 1.75899 +      zDb = 0;
 1.75900 +    }else{
 1.75901 +      for(i=0; i<db->nDb; i++){
 1.75902 +        assert( db->aDb[i].zName );
 1.75903 +        if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
 1.75904 +          pSchema = db->aDb[i].pSchema;
 1.75905 +          break;
 1.75906 +        }
 1.75907 +      }
 1.75908 +    }
 1.75909 +  }
 1.75910 +
 1.75911 +  /* Start at the inner-most context and move outward until a match is found */
 1.75912 +  while( pNC && cnt==0 ){
 1.75913 +    ExprList *pEList;
 1.75914 +    SrcList *pSrcList = pNC->pSrcList;
 1.75915 +
 1.75916 +    if( pSrcList ){
 1.75917 +      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
 1.75918 +        pTab = pItem->pTab;
 1.75919 +        assert( pTab!=0 && pTab->zName!=0 );
 1.75920 +        assert( pTab->nCol>0 );
 1.75921 +        if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
 1.75922 +          int hit = 0;
 1.75923 +          pEList = pItem->pSelect->pEList;
 1.75924 +          for(j=0; j<pEList->nExpr; j++){
 1.75925 +            if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
 1.75926 +              cnt++;
 1.75927 +              cntTab = 2;
 1.75928 +              pMatch = pItem;
 1.75929 +              pExpr->iColumn = j;
 1.75930 +              hit = 1;
 1.75931 +            }
 1.75932 +          }
 1.75933 +          if( hit || zTab==0 ) continue;
 1.75934 +        }
 1.75935 +        if( zDb && pTab->pSchema!=pSchema ){
 1.75936 +          continue;
 1.75937 +        }
 1.75938 +        if( zTab ){
 1.75939 +          const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
 1.75940 +          assert( zTabName!=0 );
 1.75941 +          if( sqlite3StrICmp(zTabName, zTab)!=0 ){
 1.75942 +            continue;
 1.75943 +          }
 1.75944 +        }
 1.75945 +        if( 0==(cntTab++) ){
 1.75946 +          pMatch = pItem;
 1.75947 +        }
 1.75948 +        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
 1.75949 +          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
 1.75950 +            /* If there has been exactly one prior match and this match
 1.75951 +            ** is for the right-hand table of a NATURAL JOIN or is in a 
 1.75952 +            ** USING clause, then skip this match.
 1.75953 +            */
 1.75954 +            if( cnt==1 ){
 1.75955 +              if( pItem->jointype & JT_NATURAL ) continue;
 1.75956 +              if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
 1.75957 +            }
 1.75958 +            cnt++;
 1.75959 +            pMatch = pItem;
 1.75960 +            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
 1.75961 +            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
 1.75962 +            break;
 1.75963 +          }
 1.75964 +        }
 1.75965 +      }
 1.75966 +      if( pMatch ){
 1.75967 +        pExpr->iTable = pMatch->iCursor;
 1.75968 +        pExpr->pTab = pMatch->pTab;
 1.75969 +        pSchema = pExpr->pTab->pSchema;
 1.75970 +      }
 1.75971 +    } /* if( pSrcList ) */
 1.75972 +
 1.75973 +#ifndef SQLITE_OMIT_TRIGGER
 1.75974 +    /* If we have not already resolved the name, then maybe 
 1.75975 +    ** it is a new.* or old.* trigger argument reference
 1.75976 +    */
 1.75977 +    if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
 1.75978 +      int op = pParse->eTriggerOp;
 1.75979 +      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
 1.75980 +      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
 1.75981 +        pExpr->iTable = 1;
 1.75982 +        pTab = pParse->pTriggerTab;
 1.75983 +      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
 1.75984 +        pExpr->iTable = 0;
 1.75985 +        pTab = pParse->pTriggerTab;
 1.75986 +      }else{
 1.75987 +        pTab = 0;
 1.75988 +      }
 1.75989 +
 1.75990 +      if( pTab ){ 
 1.75991 +        int iCol;
 1.75992 +        pSchema = pTab->pSchema;
 1.75993 +        cntTab++;
 1.75994 +        for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
 1.75995 +          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
 1.75996 +            if( iCol==pTab->iPKey ){
 1.75997 +              iCol = -1;
 1.75998 +            }
 1.75999 +            break;
 1.76000 +          }
 1.76001 +        }
 1.76002 +        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && HasRowid(pTab) ){
 1.76003 +          /* IMP: R-24309-18625 */
 1.76004 +          /* IMP: R-44911-55124 */
 1.76005 +          iCol = -1;
 1.76006 +        }
 1.76007 +        if( iCol<pTab->nCol ){
 1.76008 +          cnt++;
 1.76009 +          if( iCol<0 ){
 1.76010 +            pExpr->affinity = SQLITE_AFF_INTEGER;
 1.76011 +          }else if( pExpr->iTable==0 ){
 1.76012 +            testcase( iCol==31 );
 1.76013 +            testcase( iCol==32 );
 1.76014 +            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
 1.76015 +          }else{
 1.76016 +            testcase( iCol==31 );
 1.76017 +            testcase( iCol==32 );
 1.76018 +            pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
 1.76019 +          }
 1.76020 +          pExpr->iColumn = (i16)iCol;
 1.76021 +          pExpr->pTab = pTab;
 1.76022 +          isTrigger = 1;
 1.76023 +        }
 1.76024 +      }
 1.76025 +    }
 1.76026 +#endif /* !defined(SQLITE_OMIT_TRIGGER) */
 1.76027 +
 1.76028 +    /*
 1.76029 +    ** Perhaps the name is a reference to the ROWID
 1.76030 +    */
 1.76031 +    if( cnt==0 && cntTab==1 && pMatch && sqlite3IsRowid(zCol)
 1.76032 +     && HasRowid(pMatch->pTab) ){
 1.76033 +      cnt = 1;
 1.76034 +      pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
 1.76035 +      pExpr->affinity = SQLITE_AFF_INTEGER;
 1.76036 +    }
 1.76037 +
 1.76038 +    /*
 1.76039 +    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
 1.76040 +    ** might refer to an result-set alias.  This happens, for example, when
 1.76041 +    ** we are resolving names in the WHERE clause of the following command:
 1.76042 +    **
 1.76043 +    **     SELECT a+b AS x FROM table WHERE x<10;
 1.76044 +    **
 1.76045 +    ** In cases like this, replace pExpr with a copy of the expression that
 1.76046 +    ** forms the result set entry ("a+b" in the example) and return immediately.
 1.76047 +    ** Note that the expression in the result set should have already been
 1.76048 +    ** resolved by the time the WHERE clause is resolved.
 1.76049 +    **
 1.76050 +    ** The ability to use an output result-set column in the WHERE, GROUP BY,
 1.76051 +    ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
 1.76052 +    ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
 1.76053 +    ** is supported for backwards compatibility only.  TO DO: Issue a warning
 1.76054 +    ** on sqlite3_log() whenever the capability is used.
 1.76055 +    */
 1.76056 +    if( (pEList = pNC->pEList)!=0
 1.76057 +     && zTab==0
 1.76058 +     && cnt==0
 1.76059 +    ){
 1.76060 +      for(j=0; j<pEList->nExpr; j++){
 1.76061 +        char *zAs = pEList->a[j].zName;
 1.76062 +        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
 1.76063 +          Expr *pOrig;
 1.76064 +          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
 1.76065 +          assert( pExpr->x.pList==0 );
 1.76066 +          assert( pExpr->x.pSelect==0 );
 1.76067 +          pOrig = pEList->a[j].pExpr;
 1.76068 +          if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
 1.76069 +            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
 1.76070 +            return WRC_Abort;
 1.76071 +          }
 1.76072 +          resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
 1.76073 +          cnt = 1;
 1.76074 +          pMatch = 0;
 1.76075 +          assert( zTab==0 && zDb==0 );
 1.76076 +          goto lookupname_end;
 1.76077 +        }
 1.76078 +      } 
 1.76079 +    }
 1.76080 +
 1.76081 +    /* Advance to the next name context.  The loop will exit when either
 1.76082 +    ** we have a match (cnt>0) or when we run out of name contexts.
 1.76083 +    */
 1.76084 +    if( cnt==0 ){
 1.76085 +      pNC = pNC->pNext;
 1.76086 +      nSubquery++;
 1.76087 +    }
 1.76088 +  }
 1.76089 +
 1.76090 +  /*
 1.76091 +  ** If X and Y are NULL (in other words if only the column name Z is
 1.76092 +  ** supplied) and the value of Z is enclosed in double-quotes, then
 1.76093 +  ** Z is a string literal if it doesn't match any column names.  In that
 1.76094 +  ** case, we need to return right away and not make any changes to
 1.76095 +  ** pExpr.
 1.76096 +  **
 1.76097 +  ** Because no reference was made to outer contexts, the pNC->nRef
 1.76098 +  ** fields are not changed in any context.
 1.76099 +  */
 1.76100 +  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
 1.76101 +    pExpr->op = TK_STRING;
 1.76102 +    pExpr->pTab = 0;
 1.76103 +    return WRC_Prune;
 1.76104 +  }
 1.76105 +
 1.76106 +  /*
 1.76107 +  ** cnt==0 means there was not match.  cnt>1 means there were two or
 1.76108 +  ** more matches.  Either way, we have an error.
 1.76109 +  */
 1.76110 +  if( cnt!=1 ){
 1.76111 +    const char *zErr;
 1.76112 +    zErr = cnt==0 ? "no such column" : "ambiguous column name";
 1.76113 +    if( zDb ){
 1.76114 +      sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
 1.76115 +    }else if( zTab ){
 1.76116 +      sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
 1.76117 +    }else{
 1.76118 +      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
 1.76119 +    }
 1.76120 +    pParse->checkSchema = 1;
 1.76121 +    pTopNC->nErr++;
 1.76122 +  }
 1.76123 +
 1.76124 +  /* If a column from a table in pSrcList is referenced, then record
 1.76125 +  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
 1.76126 +  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
 1.76127 +  ** column number is greater than the number of bits in the bitmask
 1.76128 +  ** then set the high-order bit of the bitmask.
 1.76129 +  */
 1.76130 +  if( pExpr->iColumn>=0 && pMatch!=0 ){
 1.76131 +    int n = pExpr->iColumn;
 1.76132 +    testcase( n==BMS-1 );
 1.76133 +    if( n>=BMS ){
 1.76134 +      n = BMS-1;
 1.76135 +    }
 1.76136 +    assert( pMatch->iCursor==pExpr->iTable );
 1.76137 +    pMatch->colUsed |= ((Bitmask)1)<<n;
 1.76138 +  }
 1.76139 +
 1.76140 +  /* Clean up and return
 1.76141 +  */
 1.76142 +  sqlite3ExprDelete(db, pExpr->pLeft);
 1.76143 +  pExpr->pLeft = 0;
 1.76144 +  sqlite3ExprDelete(db, pExpr->pRight);
 1.76145 +  pExpr->pRight = 0;
 1.76146 +  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
 1.76147 +lookupname_end:
 1.76148 +  if( cnt==1 ){
 1.76149 +    assert( pNC!=0 );
 1.76150 +    if( pExpr->op!=TK_AS ){
 1.76151 +      sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
 1.76152 +    }
 1.76153 +    /* Increment the nRef value on all name contexts from TopNC up to
 1.76154 +    ** the point where the name matched. */
 1.76155 +    for(;;){
 1.76156 +      assert( pTopNC!=0 );
 1.76157 +      pTopNC->nRef++;
 1.76158 +      if( pTopNC==pNC ) break;
 1.76159 +      pTopNC = pTopNC->pNext;
 1.76160 +    }
 1.76161 +    return WRC_Prune;
 1.76162 +  } else {
 1.76163 +    return WRC_Abort;
 1.76164 +  }
 1.76165 +}
 1.76166 +
 1.76167 +/*
 1.76168 +** Allocate and return a pointer to an expression to load the column iCol
 1.76169 +** from datasource iSrc in SrcList pSrc.
 1.76170 +*/
 1.76171 +SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
 1.76172 +  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
 1.76173 +  if( p ){
 1.76174 +    struct SrcList_item *pItem = &pSrc->a[iSrc];
 1.76175 +    p->pTab = pItem->pTab;
 1.76176 +    p->iTable = pItem->iCursor;
 1.76177 +    if( p->pTab->iPKey==iCol ){
 1.76178 +      p->iColumn = -1;
 1.76179 +    }else{
 1.76180 +      p->iColumn = (ynVar)iCol;
 1.76181 +      testcase( iCol==BMS );
 1.76182 +      testcase( iCol==BMS-1 );
 1.76183 +      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
 1.76184 +    }
 1.76185 +    ExprSetProperty(p, EP_Resolved);
 1.76186 +  }
 1.76187 +  return p;
 1.76188 +}
 1.76189 +
 1.76190 +/*
 1.76191 +** Report an error that an expression is not valid for a partial index WHERE
 1.76192 +** clause.
 1.76193 +*/
 1.76194 +static void notValidPartIdxWhere(
 1.76195 +  Parse *pParse,       /* Leave error message here */
 1.76196 +  NameContext *pNC,    /* The name context */
 1.76197 +  const char *zMsg     /* Type of error */
 1.76198 +){
 1.76199 +  if( (pNC->ncFlags & NC_PartIdx)!=0 ){
 1.76200 +    sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
 1.76201 +                    zMsg);
 1.76202 +  }
 1.76203 +}
 1.76204 +
 1.76205 +#ifndef SQLITE_OMIT_CHECK
 1.76206 +/*
 1.76207 +** Report an error that an expression is not valid for a CHECK constraint.
 1.76208 +*/
 1.76209 +static void notValidCheckConstraint(
 1.76210 +  Parse *pParse,       /* Leave error message here */
 1.76211 +  NameContext *pNC,    /* The name context */
 1.76212 +  const char *zMsg     /* Type of error */
 1.76213 +){
 1.76214 +  if( (pNC->ncFlags & NC_IsCheck)!=0 ){
 1.76215 +    sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
 1.76216 +  }
 1.76217 +}
 1.76218 +#else
 1.76219 +# define notValidCheckConstraint(P,N,M)
 1.76220 +#endif
 1.76221 +
 1.76222 +/*
 1.76223 +** Expression p should encode a floating point value between 1.0 and 0.0.
 1.76224 +** Return 1024 times this value.  Or return -1 if p is not a floating point
 1.76225 +** value between 1.0 and 0.0.
 1.76226 +*/
 1.76227 +static int exprProbability(Expr *p){
 1.76228 +  double r = -1.0;
 1.76229 +  if( p->op!=TK_FLOAT ) return -1;
 1.76230 +  sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
 1.76231 +  assert( r>=0.0 );
 1.76232 +  if( r>1.0 ) return -1;
 1.76233 +  return (int)(r*1000.0);
 1.76234 +}
 1.76235 +
 1.76236 +/*
 1.76237 +** This routine is callback for sqlite3WalkExpr().
 1.76238 +**
 1.76239 +** Resolve symbolic names into TK_COLUMN operators for the current
 1.76240 +** node in the expression tree.  Return 0 to continue the search down
 1.76241 +** the tree or 2 to abort the tree walk.
 1.76242 +**
 1.76243 +** This routine also does error checking and name resolution for
 1.76244 +** function names.  The operator for aggregate functions is changed
 1.76245 +** to TK_AGG_FUNCTION.
 1.76246 +*/
 1.76247 +static int resolveExprStep(Walker *pWalker, Expr *pExpr){
 1.76248 +  NameContext *pNC;
 1.76249 +  Parse *pParse;
 1.76250 +
 1.76251 +  pNC = pWalker->u.pNC;
 1.76252 +  assert( pNC!=0 );
 1.76253 +  pParse = pNC->pParse;
 1.76254 +  assert( pParse==pWalker->pParse );
 1.76255 +
 1.76256 +  if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
 1.76257 +  ExprSetProperty(pExpr, EP_Resolved);
 1.76258 +#ifndef NDEBUG
 1.76259 +  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
 1.76260 +    SrcList *pSrcList = pNC->pSrcList;
 1.76261 +    int i;
 1.76262 +    for(i=0; i<pNC->pSrcList->nSrc; i++){
 1.76263 +      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
 1.76264 +    }
 1.76265 +  }
 1.76266 +#endif
 1.76267 +  switch( pExpr->op ){
 1.76268 +
 1.76269 +#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
 1.76270 +    /* The special operator TK_ROW means use the rowid for the first
 1.76271 +    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
 1.76272 +    ** clause processing on UPDATE and DELETE statements.
 1.76273 +    */
 1.76274 +    case TK_ROW: {
 1.76275 +      SrcList *pSrcList = pNC->pSrcList;
 1.76276 +      struct SrcList_item *pItem;
 1.76277 +      assert( pSrcList && pSrcList->nSrc==1 );
 1.76278 +      pItem = pSrcList->a; 
 1.76279 +      pExpr->op = TK_COLUMN;
 1.76280 +      pExpr->pTab = pItem->pTab;
 1.76281 +      pExpr->iTable = pItem->iCursor;
 1.76282 +      pExpr->iColumn = -1;
 1.76283 +      pExpr->affinity = SQLITE_AFF_INTEGER;
 1.76284 +      break;
 1.76285 +    }
 1.76286 +#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
 1.76287 +
 1.76288 +    /* A lone identifier is the name of a column.
 1.76289 +    */
 1.76290 +    case TK_ID: {
 1.76291 +      return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
 1.76292 +    }
 1.76293 +  
 1.76294 +    /* A table name and column name:     ID.ID
 1.76295 +    ** Or a database, table and column:  ID.ID.ID
 1.76296 +    */
 1.76297 +    case TK_DOT: {
 1.76298 +      const char *zColumn;
 1.76299 +      const char *zTable;
 1.76300 +      const char *zDb;
 1.76301 +      Expr *pRight;
 1.76302 +
 1.76303 +      /* if( pSrcList==0 ) break; */
 1.76304 +      pRight = pExpr->pRight;
 1.76305 +      if( pRight->op==TK_ID ){
 1.76306 +        zDb = 0;
 1.76307 +        zTable = pExpr->pLeft->u.zToken;
 1.76308 +        zColumn = pRight->u.zToken;
 1.76309 +      }else{
 1.76310 +        assert( pRight->op==TK_DOT );
 1.76311 +        zDb = pExpr->pLeft->u.zToken;
 1.76312 +        zTable = pRight->pLeft->u.zToken;
 1.76313 +        zColumn = pRight->pRight->u.zToken;
 1.76314 +      }
 1.76315 +      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
 1.76316 +    }
 1.76317 +
 1.76318 +    /* Resolve function names
 1.76319 +    */
 1.76320 +    case TK_FUNCTION: {
 1.76321 +      ExprList *pList = pExpr->x.pList;    /* The argument list */
 1.76322 +      int n = pList ? pList->nExpr : 0;    /* Number of arguments */
 1.76323 +      int no_such_func = 0;       /* True if no such function exists */
 1.76324 +      int wrong_num_args = 0;     /* True if wrong number of arguments */
 1.76325 +      int is_agg = 0;             /* True if is an aggregate function */
 1.76326 +      int auth;                   /* Authorization to use the function */
 1.76327 +      int nId;                    /* Number of characters in function name */
 1.76328 +      const char *zId;            /* The function name. */
 1.76329 +      FuncDef *pDef;              /* Information about the function */
 1.76330 +      u8 enc = ENC(pParse->db);   /* The database encoding */
 1.76331 +
 1.76332 +      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
 1.76333 +      notValidPartIdxWhere(pParse, pNC, "functions");
 1.76334 +      zId = pExpr->u.zToken;
 1.76335 +      nId = sqlite3Strlen30(zId);
 1.76336 +      pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
 1.76337 +      if( pDef==0 ){
 1.76338 +        pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
 1.76339 +        if( pDef==0 ){
 1.76340 +          no_such_func = 1;
 1.76341 +        }else{
 1.76342 +          wrong_num_args = 1;
 1.76343 +        }
 1.76344 +      }else{
 1.76345 +        is_agg = pDef->xFunc==0;
 1.76346 +        if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
 1.76347 +          ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
 1.76348 +          if( n==2 ){
 1.76349 +            pExpr->iTable = exprProbability(pList->a[1].pExpr);
 1.76350 +            if( pExpr->iTable<0 ){
 1.76351 +              sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a "
 1.76352 +                                      "constant between 0.0 and 1.0");
 1.76353 +              pNC->nErr++;
 1.76354 +            }
 1.76355 +          }else{
 1.76356 +            /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is equivalent to
 1.76357 +            ** likelihood(X, 0.0625).
 1.76358 +            ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is short-hand for
 1.76359 +            ** likelihood(X,0.0625). */
 1.76360 +            pExpr->iTable = 62;  /* TUNING:  Default 2nd arg to unlikely() is 0.0625 */
 1.76361 +          }             
 1.76362 +        }
 1.76363 +      }
 1.76364 +#ifndef SQLITE_OMIT_AUTHORIZATION
 1.76365 +      if( pDef ){
 1.76366 +        auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
 1.76367 +        if( auth!=SQLITE_OK ){
 1.76368 +          if( auth==SQLITE_DENY ){
 1.76369 +            sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
 1.76370 +                                    pDef->zName);
 1.76371 +            pNC->nErr++;
 1.76372 +          }
 1.76373 +          pExpr->op = TK_NULL;
 1.76374 +          return WRC_Prune;
 1.76375 +        }
 1.76376 +        if( pDef->funcFlags & SQLITE_FUNC_CONSTANT ) ExprSetProperty(pExpr,EP_Constant);
 1.76377 +      }
 1.76378 +#endif
 1.76379 +      if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
 1.76380 +        sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
 1.76381 +        pNC->nErr++;
 1.76382 +        is_agg = 0;
 1.76383 +      }else if( no_such_func && pParse->db->init.busy==0 ){
 1.76384 +        sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
 1.76385 +        pNC->nErr++;
 1.76386 +      }else if( wrong_num_args ){
 1.76387 +        sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
 1.76388 +             nId, zId);
 1.76389 +        pNC->nErr++;
 1.76390 +      }
 1.76391 +      if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
 1.76392 +      sqlite3WalkExprList(pWalker, pList);
 1.76393 +      if( is_agg ){
 1.76394 +        NameContext *pNC2 = pNC;
 1.76395 +        pExpr->op = TK_AGG_FUNCTION;
 1.76396 +        pExpr->op2 = 0;
 1.76397 +        while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
 1.76398 +          pExpr->op2++;
 1.76399 +          pNC2 = pNC2->pNext;
 1.76400 +        }
 1.76401 +        if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
 1.76402 +        pNC->ncFlags |= NC_AllowAgg;
 1.76403 +      }
 1.76404 +      /* FIX ME:  Compute pExpr->affinity based on the expected return
 1.76405 +      ** type of the function 
 1.76406 +      */
 1.76407 +      return WRC_Prune;
 1.76408 +    }
 1.76409 +#ifndef SQLITE_OMIT_SUBQUERY
 1.76410 +    case TK_SELECT:
 1.76411 +    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
 1.76412 +#endif
 1.76413 +    case TK_IN: {
 1.76414 +      testcase( pExpr->op==TK_IN );
 1.76415 +      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
 1.76416 +        int nRef = pNC->nRef;
 1.76417 +        notValidCheckConstraint(pParse, pNC, "subqueries");
 1.76418 +        notValidPartIdxWhere(pParse, pNC, "subqueries");
 1.76419 +        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
 1.76420 +        assert( pNC->nRef>=nRef );
 1.76421 +        if( nRef!=pNC->nRef ){
 1.76422 +          ExprSetProperty(pExpr, EP_VarSelect);
 1.76423 +        }
 1.76424 +      }
 1.76425 +      break;
 1.76426 +    }
 1.76427 +    case TK_VARIABLE: {
 1.76428 +      notValidCheckConstraint(pParse, pNC, "parameters");
 1.76429 +      notValidPartIdxWhere(pParse, pNC, "parameters");
 1.76430 +      break;
 1.76431 +    }
 1.76432 +  }
 1.76433 +  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
 1.76434 +}
 1.76435 +
 1.76436 +/*
 1.76437 +** pEList is a list of expressions which are really the result set of the
 1.76438 +** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
 1.76439 +** This routine checks to see if pE is a simple identifier which corresponds
 1.76440 +** to the AS-name of one of the terms of the expression list.  If it is,
 1.76441 +** this routine return an integer between 1 and N where N is the number of
 1.76442 +** elements in pEList, corresponding to the matching entry.  If there is
 1.76443 +** no match, or if pE is not a simple identifier, then this routine
 1.76444 +** return 0.
 1.76445 +**
 1.76446 +** pEList has been resolved.  pE has not.
 1.76447 +*/
 1.76448 +static int resolveAsName(
 1.76449 +  Parse *pParse,     /* Parsing context for error messages */
 1.76450 +  ExprList *pEList,  /* List of expressions to scan */
 1.76451 +  Expr *pE           /* Expression we are trying to match */
 1.76452 +){
 1.76453 +  int i;             /* Loop counter */
 1.76454 +
 1.76455 +  UNUSED_PARAMETER(pParse);
 1.76456 +
 1.76457 +  if( pE->op==TK_ID ){
 1.76458 +    char *zCol = pE->u.zToken;
 1.76459 +    for(i=0; i<pEList->nExpr; i++){
 1.76460 +      char *zAs = pEList->a[i].zName;
 1.76461 +      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
 1.76462 +        return i+1;
 1.76463 +      }
 1.76464 +    }
 1.76465 +  }
 1.76466 +  return 0;
 1.76467 +}
 1.76468 +
 1.76469 +/*
 1.76470 +** pE is a pointer to an expression which is a single term in the
 1.76471 +** ORDER BY of a compound SELECT.  The expression has not been
 1.76472 +** name resolved.
 1.76473 +**
 1.76474 +** At the point this routine is called, we already know that the
 1.76475 +** ORDER BY term is not an integer index into the result set.  That
 1.76476 +** case is handled by the calling routine.
 1.76477 +**
 1.76478 +** Attempt to match pE against result set columns in the left-most
 1.76479 +** SELECT statement.  Return the index i of the matching column,
 1.76480 +** as an indication to the caller that it should sort by the i-th column.
 1.76481 +** The left-most column is 1.  In other words, the value returned is the
 1.76482 +** same integer value that would be used in the SQL statement to indicate
 1.76483 +** the column.
 1.76484 +**
 1.76485 +** If there is no match, return 0.  Return -1 if an error occurs.
 1.76486 +*/
 1.76487 +static int resolveOrderByTermToExprList(
 1.76488 +  Parse *pParse,     /* Parsing context for error messages */
 1.76489 +  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
 1.76490 +  Expr *pE           /* The specific ORDER BY term */
 1.76491 +){
 1.76492 +  int i;             /* Loop counter */
 1.76493 +  ExprList *pEList;  /* The columns of the result set */
 1.76494 +  NameContext nc;    /* Name context for resolving pE */
 1.76495 +  sqlite3 *db;       /* Database connection */
 1.76496 +  int rc;            /* Return code from subprocedures */
 1.76497 +  u8 savedSuppErr;   /* Saved value of db->suppressErr */
 1.76498 +
 1.76499 +  assert( sqlite3ExprIsInteger(pE, &i)==0 );
 1.76500 +  pEList = pSelect->pEList;
 1.76501 +
 1.76502 +  /* Resolve all names in the ORDER BY term expression
 1.76503 +  */
 1.76504 +  memset(&nc, 0, sizeof(nc));
 1.76505 +  nc.pParse = pParse;
 1.76506 +  nc.pSrcList = pSelect->pSrc;
 1.76507 +  nc.pEList = pEList;
 1.76508 +  nc.ncFlags = NC_AllowAgg;
 1.76509 +  nc.nErr = 0;
 1.76510 +  db = pParse->db;
 1.76511 +  savedSuppErr = db->suppressErr;
 1.76512 +  db->suppressErr = 1;
 1.76513 +  rc = sqlite3ResolveExprNames(&nc, pE);
 1.76514 +  db->suppressErr = savedSuppErr;
 1.76515 +  if( rc ) return 0;
 1.76516 +
 1.76517 +  /* Try to match the ORDER BY expression against an expression
 1.76518 +  ** in the result set.  Return an 1-based index of the matching
 1.76519 +  ** result-set entry.
 1.76520 +  */
 1.76521 +  for(i=0; i<pEList->nExpr; i++){
 1.76522 +    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
 1.76523 +      return i+1;
 1.76524 +    }
 1.76525 +  }
 1.76526 +
 1.76527 +  /* If no match, return 0. */
 1.76528 +  return 0;
 1.76529 +}
 1.76530 +
 1.76531 +/*
 1.76532 +** Generate an ORDER BY or GROUP BY term out-of-range error.
 1.76533 +*/
 1.76534 +static void resolveOutOfRangeError(
 1.76535 +  Parse *pParse,         /* The error context into which to write the error */
 1.76536 +  const char *zType,     /* "ORDER" or "GROUP" */
 1.76537 +  int i,                 /* The index (1-based) of the term out of range */
 1.76538 +  int mx                 /* Largest permissible value of i */
 1.76539 +){
 1.76540 +  sqlite3ErrorMsg(pParse, 
 1.76541 +    "%r %s BY term out of range - should be "
 1.76542 +    "between 1 and %d", i, zType, mx);
 1.76543 +}
 1.76544 +
 1.76545 +/*
 1.76546 +** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
 1.76547 +** each term of the ORDER BY clause is a constant integer between 1
 1.76548 +** and N where N is the number of columns in the compound SELECT.
 1.76549 +**
 1.76550 +** ORDER BY terms that are already an integer between 1 and N are
 1.76551 +** unmodified.  ORDER BY terms that are integers outside the range of
 1.76552 +** 1 through N generate an error.  ORDER BY terms that are expressions
 1.76553 +** are matched against result set expressions of compound SELECT
 1.76554 +** beginning with the left-most SELECT and working toward the right.
 1.76555 +** At the first match, the ORDER BY expression is transformed into
 1.76556 +** the integer column number.
 1.76557 +**
 1.76558 +** Return the number of errors seen.
 1.76559 +*/
 1.76560 +static int resolveCompoundOrderBy(
 1.76561 +  Parse *pParse,        /* Parsing context.  Leave error messages here */
 1.76562 +  Select *pSelect       /* The SELECT statement containing the ORDER BY */
 1.76563 +){
 1.76564 +  int i;
 1.76565 +  ExprList *pOrderBy;
 1.76566 +  ExprList *pEList;
 1.76567 +  sqlite3 *db;
 1.76568 +  int moreToDo = 1;
 1.76569 +
 1.76570 +  pOrderBy = pSelect->pOrderBy;
 1.76571 +  if( pOrderBy==0 ) return 0;
 1.76572 +  db = pParse->db;
 1.76573 +#if SQLITE_MAX_COLUMN
 1.76574 +  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
 1.76575 +    sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
 1.76576 +    return 1;
 1.76577 +  }
 1.76578 +#endif
 1.76579 +  for(i=0; i<pOrderBy->nExpr; i++){
 1.76580 +    pOrderBy->a[i].done = 0;
 1.76581 +  }
 1.76582 +  pSelect->pNext = 0;
 1.76583 +  while( pSelect->pPrior ){
 1.76584 +    pSelect->pPrior->pNext = pSelect;
 1.76585 +    pSelect = pSelect->pPrior;
 1.76586 +  }
 1.76587 +  while( pSelect && moreToDo ){
 1.76588 +    struct ExprList_item *pItem;
 1.76589 +    moreToDo = 0;
 1.76590 +    pEList = pSelect->pEList;
 1.76591 +    assert( pEList!=0 );
 1.76592 +    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
 1.76593 +      int iCol = -1;
 1.76594 +      Expr *pE, *pDup;
 1.76595 +      if( pItem->done ) continue;
 1.76596 +      pE = sqlite3ExprSkipCollate(pItem->pExpr);
 1.76597 +      if( sqlite3ExprIsInteger(pE, &iCol) ){
 1.76598 +        if( iCol<=0 || iCol>pEList->nExpr ){
 1.76599 +          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
 1.76600 +          return 1;
 1.76601 +        }
 1.76602 +      }else{
 1.76603 +        iCol = resolveAsName(pParse, pEList, pE);
 1.76604 +        if( iCol==0 ){
 1.76605 +          pDup = sqlite3ExprDup(db, pE, 0);
 1.76606 +          if( !db->mallocFailed ){
 1.76607 +            assert(pDup);
 1.76608 +            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
 1.76609 +          }
 1.76610 +          sqlite3ExprDelete(db, pDup);
 1.76611 +        }
 1.76612 +      }
 1.76613 +      if( iCol>0 ){
 1.76614 +        /* Convert the ORDER BY term into an integer column number iCol,
 1.76615 +        ** taking care to preserve the COLLATE clause if it exists */
 1.76616 +        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
 1.76617 +        if( pNew==0 ) return 1;
 1.76618 +        pNew->flags |= EP_IntValue;
 1.76619 +        pNew->u.iValue = iCol;
 1.76620 +        if( pItem->pExpr==pE ){
 1.76621 +          pItem->pExpr = pNew;
 1.76622 +        }else{
 1.76623 +          assert( pItem->pExpr->op==TK_COLLATE );
 1.76624 +          assert( pItem->pExpr->pLeft==pE );
 1.76625 +          pItem->pExpr->pLeft = pNew;
 1.76626 +        }
 1.76627 +        sqlite3ExprDelete(db, pE);
 1.76628 +        pItem->u.x.iOrderByCol = (u16)iCol;
 1.76629 +        pItem->done = 1;
 1.76630 +      }else{
 1.76631 +        moreToDo = 1;
 1.76632 +      }
 1.76633 +    }
 1.76634 +    pSelect = pSelect->pNext;
 1.76635 +  }
 1.76636 +  for(i=0; i<pOrderBy->nExpr; i++){
 1.76637 +    if( pOrderBy->a[i].done==0 ){
 1.76638 +      sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
 1.76639 +            "column in the result set", i+1);
 1.76640 +      return 1;
 1.76641 +    }
 1.76642 +  }
 1.76643 +  return 0;
 1.76644 +}
 1.76645 +
 1.76646 +/*
 1.76647 +** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
 1.76648 +** the SELECT statement pSelect.  If any term is reference to a
 1.76649 +** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
 1.76650 +** field) then convert that term into a copy of the corresponding result set
 1.76651 +** column.
 1.76652 +**
 1.76653 +** If any errors are detected, add an error message to pParse and
 1.76654 +** return non-zero.  Return zero if no errors are seen.
 1.76655 +*/
 1.76656 +SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
 1.76657 +  Parse *pParse,        /* Parsing context.  Leave error messages here */
 1.76658 +  Select *pSelect,      /* The SELECT statement containing the clause */
 1.76659 +  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
 1.76660 +  const char *zType     /* "ORDER" or "GROUP" */
 1.76661 +){
 1.76662 +  int i;
 1.76663 +  sqlite3 *db = pParse->db;
 1.76664 +  ExprList *pEList;
 1.76665 +  struct ExprList_item *pItem;
 1.76666 +
 1.76667 +  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
 1.76668 +#if SQLITE_MAX_COLUMN
 1.76669 +  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
 1.76670 +    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
 1.76671 +    return 1;
 1.76672 +  }
 1.76673 +#endif
 1.76674 +  pEList = pSelect->pEList;
 1.76675 +  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
 1.76676 +  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
 1.76677 +    if( pItem->u.x.iOrderByCol ){
 1.76678 +      if( pItem->u.x.iOrderByCol>pEList->nExpr ){
 1.76679 +        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
 1.76680 +        return 1;
 1.76681 +      }
 1.76682 +      resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr, zType,0);
 1.76683 +    }
 1.76684 +  }
 1.76685 +  return 0;
 1.76686 +}
 1.76687 +
 1.76688 +/*
 1.76689 +** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
 1.76690 +** The Name context of the SELECT statement is pNC.  zType is either
 1.76691 +** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
 1.76692 +**
 1.76693 +** This routine resolves each term of the clause into an expression.
 1.76694 +** If the order-by term is an integer I between 1 and N (where N is the
 1.76695 +** number of columns in the result set of the SELECT) then the expression
 1.76696 +** in the resolution is a copy of the I-th result-set expression.  If
 1.76697 +** the order-by term is an identifier that corresponds to the AS-name of
 1.76698 +** a result-set expression, then the term resolves to a copy of the
 1.76699 +** result-set expression.  Otherwise, the expression is resolved in
 1.76700 +** the usual way - using sqlite3ResolveExprNames().
 1.76701 +**
 1.76702 +** This routine returns the number of errors.  If errors occur, then
 1.76703 +** an appropriate error message might be left in pParse.  (OOM errors
 1.76704 +** excepted.)
 1.76705 +*/
 1.76706 +static int resolveOrderGroupBy(
 1.76707 +  NameContext *pNC,     /* The name context of the SELECT statement */
 1.76708 +  Select *pSelect,      /* The SELECT statement holding pOrderBy */
 1.76709 +  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
 1.76710 +  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
 1.76711 +){
 1.76712 +  int i, j;                      /* Loop counters */
 1.76713 +  int iCol;                      /* Column number */
 1.76714 +  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
 1.76715 +  Parse *pParse;                 /* Parsing context */
 1.76716 +  int nResult;                   /* Number of terms in the result set */
 1.76717 +
 1.76718 +  if( pOrderBy==0 ) return 0;
 1.76719 +  nResult = pSelect->pEList->nExpr;
 1.76720 +  pParse = pNC->pParse;
 1.76721 +  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
 1.76722 +    Expr *pE = pItem->pExpr;
 1.76723 +    Expr *pE2 = sqlite3ExprSkipCollate(pE);
 1.76724 +    if( zType[0]!='G' ){
 1.76725 +      iCol = resolveAsName(pParse, pSelect->pEList, pE2);
 1.76726 +      if( iCol>0 ){
 1.76727 +        /* If an AS-name match is found, mark this ORDER BY column as being
 1.76728 +        ** a copy of the iCol-th result-set column.  The subsequent call to
 1.76729 +        ** sqlite3ResolveOrderGroupBy() will convert the expression to a
 1.76730 +        ** copy of the iCol-th result-set expression. */
 1.76731 +        pItem->u.x.iOrderByCol = (u16)iCol;
 1.76732 +        continue;
 1.76733 +      }
 1.76734 +    }
 1.76735 +    if( sqlite3ExprIsInteger(pE2, &iCol) ){
 1.76736 +      /* The ORDER BY term is an integer constant.  Again, set the column
 1.76737 +      ** number so that sqlite3ResolveOrderGroupBy() will convert the
 1.76738 +      ** order-by term to a copy of the result-set expression */
 1.76739 +      if( iCol<1 || iCol>0xffff ){
 1.76740 +        resolveOutOfRangeError(pParse, zType, i+1, nResult);
 1.76741 +        return 1;
 1.76742 +      }
 1.76743 +      pItem->u.x.iOrderByCol = (u16)iCol;
 1.76744 +      continue;
 1.76745 +    }
 1.76746 +
 1.76747 +    /* Otherwise, treat the ORDER BY term as an ordinary expression */
 1.76748 +    pItem->u.x.iOrderByCol = 0;
 1.76749 +    if( sqlite3ResolveExprNames(pNC, pE) ){
 1.76750 +      return 1;
 1.76751 +    }
 1.76752 +    for(j=0; j<pSelect->pEList->nExpr; j++){
 1.76753 +      if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
 1.76754 +        pItem->u.x.iOrderByCol = j+1;
 1.76755 +      }
 1.76756 +    }
 1.76757 +  }
 1.76758 +  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
 1.76759 +}
 1.76760 +
 1.76761 +/*
 1.76762 +** Resolve names in the SELECT statement p and all of its descendents.
 1.76763 +*/
 1.76764 +static int resolveSelectStep(Walker *pWalker, Select *p){
 1.76765 +  NameContext *pOuterNC;  /* Context that contains this SELECT */
 1.76766 +  NameContext sNC;        /* Name context of this SELECT */
 1.76767 +  int isCompound;         /* True if p is a compound select */
 1.76768 +  int nCompound;          /* Number of compound terms processed so far */
 1.76769 +  Parse *pParse;          /* Parsing context */
 1.76770 +  ExprList *pEList;       /* Result set expression list */
 1.76771 +  int i;                  /* Loop counter */
 1.76772 +  ExprList *pGroupBy;     /* The GROUP BY clause */
 1.76773 +  Select *pLeftmost;      /* Left-most of SELECT of a compound */
 1.76774 +  sqlite3 *db;            /* Database connection */
 1.76775 +  
 1.76776 +
 1.76777 +  assert( p!=0 );
 1.76778 +  if( p->selFlags & SF_Resolved ){
 1.76779 +    return WRC_Prune;
 1.76780 +  }
 1.76781 +  pOuterNC = pWalker->u.pNC;
 1.76782 +  pParse = pWalker->pParse;
 1.76783 +  db = pParse->db;
 1.76784 +
 1.76785 +  /* Normally sqlite3SelectExpand() will be called first and will have
 1.76786 +  ** already expanded this SELECT.  However, if this is a subquery within
 1.76787 +  ** an expression, sqlite3ResolveExprNames() will be called without a
 1.76788 +  ** prior call to sqlite3SelectExpand().  When that happens, let
 1.76789 +  ** sqlite3SelectPrep() do all of the processing for this SELECT.
 1.76790 +  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
 1.76791 +  ** this routine in the correct order.
 1.76792 +  */
 1.76793 +  if( (p->selFlags & SF_Expanded)==0 ){
 1.76794 +    sqlite3SelectPrep(pParse, p, pOuterNC);
 1.76795 +    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
 1.76796 +  }
 1.76797 +
 1.76798 +  isCompound = p->pPrior!=0;
 1.76799 +  nCompound = 0;
 1.76800 +  pLeftmost = p;
 1.76801 +  while( p ){
 1.76802 +    assert( (p->selFlags & SF_Expanded)!=0 );
 1.76803 +    assert( (p->selFlags & SF_Resolved)==0 );
 1.76804 +    p->selFlags |= SF_Resolved;
 1.76805 +
 1.76806 +    /* Resolve the expressions in the LIMIT and OFFSET clauses. These
 1.76807 +    ** are not allowed to refer to any names, so pass an empty NameContext.
 1.76808 +    */
 1.76809 +    memset(&sNC, 0, sizeof(sNC));
 1.76810 +    sNC.pParse = pParse;
 1.76811 +    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
 1.76812 +        sqlite3ResolveExprNames(&sNC, p->pOffset) ){
 1.76813 +      return WRC_Abort;
 1.76814 +    }
 1.76815 +  
 1.76816 +    /* Recursively resolve names in all subqueries
 1.76817 +    */
 1.76818 +    for(i=0; i<p->pSrc->nSrc; i++){
 1.76819 +      struct SrcList_item *pItem = &p->pSrc->a[i];
 1.76820 +      if( pItem->pSelect ){
 1.76821 +        NameContext *pNC;         /* Used to iterate name contexts */
 1.76822 +        int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
 1.76823 +        const char *zSavedContext = pParse->zAuthContext;
 1.76824 +
 1.76825 +        /* Count the total number of references to pOuterNC and all of its
 1.76826 +        ** parent contexts. After resolving references to expressions in
 1.76827 +        ** pItem->pSelect, check if this value has changed. If so, then
 1.76828 +        ** SELECT statement pItem->pSelect must be correlated. Set the
 1.76829 +        ** pItem->isCorrelated flag if this is the case. */
 1.76830 +        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
 1.76831 +
 1.76832 +        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
 1.76833 +        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
 1.76834 +        pParse->zAuthContext = zSavedContext;
 1.76835 +        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
 1.76836 +
 1.76837 +        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
 1.76838 +        assert( pItem->isCorrelated==0 && nRef<=0 );
 1.76839 +        pItem->isCorrelated = (nRef!=0);
 1.76840 +      }
 1.76841 +    }
 1.76842 +  
 1.76843 +    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
 1.76844 +    ** resolve the result-set expression list.
 1.76845 +    */
 1.76846 +    sNC.ncFlags = NC_AllowAgg;
 1.76847 +    sNC.pSrcList = p->pSrc;
 1.76848 +    sNC.pNext = pOuterNC;
 1.76849 +  
 1.76850 +    /* Resolve names in the result set. */
 1.76851 +    pEList = p->pEList;
 1.76852 +    assert( pEList!=0 );
 1.76853 +    for(i=0; i<pEList->nExpr; i++){
 1.76854 +      Expr *pX = pEList->a[i].pExpr;
 1.76855 +      if( sqlite3ResolveExprNames(&sNC, pX) ){
 1.76856 +        return WRC_Abort;
 1.76857 +      }
 1.76858 +    }
 1.76859 +  
 1.76860 +    /* If there are no aggregate functions in the result-set, and no GROUP BY 
 1.76861 +    ** expression, do not allow aggregates in any of the other expressions.
 1.76862 +    */
 1.76863 +    assert( (p->selFlags & SF_Aggregate)==0 );
 1.76864 +    pGroupBy = p->pGroupBy;
 1.76865 +    if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
 1.76866 +      p->selFlags |= SF_Aggregate;
 1.76867 +    }else{
 1.76868 +      sNC.ncFlags &= ~NC_AllowAgg;
 1.76869 +    }
 1.76870 +  
 1.76871 +    /* If a HAVING clause is present, then there must be a GROUP BY clause.
 1.76872 +    */
 1.76873 +    if( p->pHaving && !pGroupBy ){
 1.76874 +      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
 1.76875 +      return WRC_Abort;
 1.76876 +    }
 1.76877 +  
 1.76878 +    /* Add the output column list to the name-context before parsing the
 1.76879 +    ** other expressions in the SELECT statement. This is so that
 1.76880 +    ** expressions in the WHERE clause (etc.) can refer to expressions by
 1.76881 +    ** aliases in the result set.
 1.76882 +    **
 1.76883 +    ** Minor point: If this is the case, then the expression will be
 1.76884 +    ** re-evaluated for each reference to it.
 1.76885 +    */
 1.76886 +    sNC.pEList = p->pEList;
 1.76887 +    if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
 1.76888 +    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
 1.76889 +
 1.76890 +    /* The ORDER BY and GROUP BY clauses may not refer to terms in
 1.76891 +    ** outer queries 
 1.76892 +    */
 1.76893 +    sNC.pNext = 0;
 1.76894 +    sNC.ncFlags |= NC_AllowAgg;
 1.76895 +
 1.76896 +    /* Process the ORDER BY clause for singleton SELECT statements.
 1.76897 +    ** The ORDER BY clause for compounds SELECT statements is handled
 1.76898 +    ** below, after all of the result-sets for all of the elements of
 1.76899 +    ** the compound have been resolved.
 1.76900 +    */
 1.76901 +    if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
 1.76902 +      return WRC_Abort;
 1.76903 +    }
 1.76904 +    if( db->mallocFailed ){
 1.76905 +      return WRC_Abort;
 1.76906 +    }
 1.76907 +  
 1.76908 +    /* Resolve the GROUP BY clause.  At the same time, make sure 
 1.76909 +    ** the GROUP BY clause does not contain aggregate functions.
 1.76910 +    */
 1.76911 +    if( pGroupBy ){
 1.76912 +      struct ExprList_item *pItem;
 1.76913 +    
 1.76914 +      if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
 1.76915 +        return WRC_Abort;
 1.76916 +      }
 1.76917 +      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
 1.76918 +        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
 1.76919 +          sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
 1.76920 +              "the GROUP BY clause");
 1.76921 +          return WRC_Abort;
 1.76922 +        }
 1.76923 +      }
 1.76924 +    }
 1.76925 +
 1.76926 +    /* Advance to the next term of the compound
 1.76927 +    */
 1.76928 +    p = p->pPrior;
 1.76929 +    nCompound++;
 1.76930 +  }
 1.76931 +
 1.76932 +  /* Resolve the ORDER BY on a compound SELECT after all terms of
 1.76933 +  ** the compound have been resolved.
 1.76934 +  */
 1.76935 +  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
 1.76936 +    return WRC_Abort;
 1.76937 +  }
 1.76938 +
 1.76939 +  return WRC_Prune;
 1.76940 +}
 1.76941 +
 1.76942 +/*
 1.76943 +** This routine walks an expression tree and resolves references to
 1.76944 +** table columns and result-set columns.  At the same time, do error
 1.76945 +** checking on function usage and set a flag if any aggregate functions
 1.76946 +** are seen.
 1.76947 +**
 1.76948 +** To resolve table columns references we look for nodes (or subtrees) of the 
 1.76949 +** form X.Y.Z or Y.Z or just Z where
 1.76950 +**
 1.76951 +**      X:   The name of a database.  Ex:  "main" or "temp" or
 1.76952 +**           the symbolic name assigned to an ATTACH-ed database.
 1.76953 +**
 1.76954 +**      Y:   The name of a table in a FROM clause.  Or in a trigger
 1.76955 +**           one of the special names "old" or "new".
 1.76956 +**
 1.76957 +**      Z:   The name of a column in table Y.
 1.76958 +**
 1.76959 +** The node at the root of the subtree is modified as follows:
 1.76960 +**
 1.76961 +**    Expr.op        Changed to TK_COLUMN
 1.76962 +**    Expr.pTab      Points to the Table object for X.Y
 1.76963 +**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
 1.76964 +**    Expr.iTable    The VDBE cursor number for X.Y
 1.76965 +**
 1.76966 +**
 1.76967 +** To resolve result-set references, look for expression nodes of the
 1.76968 +** form Z (with no X and Y prefix) where the Z matches the right-hand
 1.76969 +** size of an AS clause in the result-set of a SELECT.  The Z expression
 1.76970 +** is replaced by a copy of the left-hand side of the result-set expression.
 1.76971 +** Table-name and function resolution occurs on the substituted expression
 1.76972 +** tree.  For example, in:
 1.76973 +**
 1.76974 +**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
 1.76975 +**
 1.76976 +** The "x" term of the order by is replaced by "a+b" to render:
 1.76977 +**
 1.76978 +**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
 1.76979 +**
 1.76980 +** Function calls are checked to make sure that the function is 
 1.76981 +** defined and that the correct number of arguments are specified.
 1.76982 +** If the function is an aggregate function, then the NC_HasAgg flag is
 1.76983 +** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
 1.76984 +** If an expression contains aggregate functions then the EP_Agg
 1.76985 +** property on the expression is set.
 1.76986 +**
 1.76987 +** An error message is left in pParse if anything is amiss.  The number
 1.76988 +** if errors is returned.
 1.76989 +*/
 1.76990 +SQLITE_PRIVATE int sqlite3ResolveExprNames( 
 1.76991 +  NameContext *pNC,       /* Namespace to resolve expressions in. */
 1.76992 +  Expr *pExpr             /* The expression to be analyzed. */
 1.76993 +){
 1.76994 +  u8 savedHasAgg;
 1.76995 +  Walker w;
 1.76996 +
 1.76997 +  if( pExpr==0 ) return 0;
 1.76998 +#if SQLITE_MAX_EXPR_DEPTH>0
 1.76999 +  {
 1.77000 +    Parse *pParse = pNC->pParse;
 1.77001 +    if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
 1.77002 +      return 1;
 1.77003 +    }
 1.77004 +    pParse->nHeight += pExpr->nHeight;
 1.77005 +  }
 1.77006 +#endif
 1.77007 +  savedHasAgg = pNC->ncFlags & NC_HasAgg;
 1.77008 +  pNC->ncFlags &= ~NC_HasAgg;
 1.77009 +  memset(&w, 0, sizeof(w));
 1.77010 +  w.xExprCallback = resolveExprStep;
 1.77011 +  w.xSelectCallback = resolveSelectStep;
 1.77012 +  w.pParse = pNC->pParse;
 1.77013 +  w.u.pNC = pNC;
 1.77014 +  sqlite3WalkExpr(&w, pExpr);
 1.77015 +#if SQLITE_MAX_EXPR_DEPTH>0
 1.77016 +  pNC->pParse->nHeight -= pExpr->nHeight;
 1.77017 +#endif
 1.77018 +  if( pNC->nErr>0 || w.pParse->nErr>0 ){
 1.77019 +    ExprSetProperty(pExpr, EP_Error);
 1.77020 +  }
 1.77021 +  if( pNC->ncFlags & NC_HasAgg ){
 1.77022 +    ExprSetProperty(pExpr, EP_Agg);
 1.77023 +  }else if( savedHasAgg ){
 1.77024 +    pNC->ncFlags |= NC_HasAgg;
 1.77025 +  }
 1.77026 +  return ExprHasProperty(pExpr, EP_Error);
 1.77027 +}
 1.77028 +
 1.77029 +
 1.77030 +/*
 1.77031 +** Resolve all names in all expressions of a SELECT and in all
 1.77032 +** decendents of the SELECT, including compounds off of p->pPrior,
 1.77033 +** subqueries in expressions, and subqueries used as FROM clause
 1.77034 +** terms.
 1.77035 +**
 1.77036 +** See sqlite3ResolveExprNames() for a description of the kinds of
 1.77037 +** transformations that occur.
 1.77038 +**
 1.77039 +** All SELECT statements should have been expanded using
 1.77040 +** sqlite3SelectExpand() prior to invoking this routine.
 1.77041 +*/
 1.77042 +SQLITE_PRIVATE void sqlite3ResolveSelectNames(
 1.77043 +  Parse *pParse,         /* The parser context */
 1.77044 +  Select *p,             /* The SELECT statement being coded. */
 1.77045 +  NameContext *pOuterNC  /* Name context for parent SELECT statement */
 1.77046 +){
 1.77047 +  Walker w;
 1.77048 +
 1.77049 +  assert( p!=0 );
 1.77050 +  memset(&w, 0, sizeof(w));
 1.77051 +  w.xExprCallback = resolveExprStep;
 1.77052 +  w.xSelectCallback = resolveSelectStep;
 1.77053 +  w.pParse = pParse;
 1.77054 +  w.u.pNC = pOuterNC;
 1.77055 +  sqlite3WalkSelect(&w, p);
 1.77056 +}
 1.77057 +
 1.77058 +/*
 1.77059 +** Resolve names in expressions that can only reference a single table:
 1.77060 +**
 1.77061 +**    *   CHECK constraints
 1.77062 +**    *   WHERE clauses on partial indices
 1.77063 +**
 1.77064 +** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
 1.77065 +** is set to -1 and the Expr.iColumn value is set to the column number.
 1.77066 +**
 1.77067 +** Any errors cause an error message to be set in pParse.
 1.77068 +*/
 1.77069 +SQLITE_PRIVATE void sqlite3ResolveSelfReference(
 1.77070 +  Parse *pParse,      /* Parsing context */
 1.77071 +  Table *pTab,        /* The table being referenced */
 1.77072 +  int type,           /* NC_IsCheck or NC_PartIdx */
 1.77073 +  Expr *pExpr,        /* Expression to resolve.  May be NULL. */
 1.77074 +  ExprList *pList     /* Expression list to resolve.  May be NUL. */
 1.77075 +){
 1.77076 +  SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
 1.77077 +  NameContext sNC;                /* Name context for pParse->pNewTable */
 1.77078 +  int i;                          /* Loop counter */
 1.77079 +
 1.77080 +  assert( type==NC_IsCheck || type==NC_PartIdx );
 1.77081 +  memset(&sNC, 0, sizeof(sNC));
 1.77082 +  memset(&sSrc, 0, sizeof(sSrc));
 1.77083 +  sSrc.nSrc = 1;
 1.77084 +  sSrc.a[0].zName = pTab->zName;
 1.77085 +  sSrc.a[0].pTab = pTab;
 1.77086 +  sSrc.a[0].iCursor = -1;
 1.77087 +  sNC.pParse = pParse;
 1.77088 +  sNC.pSrcList = &sSrc;
 1.77089 +  sNC.ncFlags = type;
 1.77090 +  if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
 1.77091 +  if( pList ){
 1.77092 +    for(i=0; i<pList->nExpr; i++){
 1.77093 +      if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
 1.77094 +        return;
 1.77095 +      }
 1.77096 +    }
 1.77097 +  }
 1.77098 +}
 1.77099 +
 1.77100 +/************** End of resolve.c *********************************************/
 1.77101 +/************** Begin file expr.c ********************************************/
 1.77102 +/*
 1.77103 +** 2001 September 15
 1.77104 +**
 1.77105 +** The author disclaims copyright to this source code.  In place of
 1.77106 +** a legal notice, here is a blessing:
 1.77107 +**
 1.77108 +**    May you do good and not evil.
 1.77109 +**    May you find forgiveness for yourself and forgive others.
 1.77110 +**    May you share freely, never taking more than you give.
 1.77111 +**
 1.77112 +*************************************************************************
 1.77113 +** This file contains routines used for analyzing expressions and
 1.77114 +** for generating VDBE code that evaluates expressions in SQLite.
 1.77115 +*/
 1.77116 +
 1.77117 +/*
 1.77118 +** Return the 'affinity' of the expression pExpr if any.
 1.77119 +**
 1.77120 +** If pExpr is a column, a reference to a column via an 'AS' alias,
 1.77121 +** or a sub-select with a column as the return value, then the 
 1.77122 +** affinity of that column is returned. Otherwise, 0x00 is returned,
 1.77123 +** indicating no affinity for the expression.
 1.77124 +**
 1.77125 +** i.e. the WHERE clause expresssions in the following statements all
 1.77126 +** have an affinity:
 1.77127 +**
 1.77128 +** CREATE TABLE t1(a);
 1.77129 +** SELECT * FROM t1 WHERE a;
 1.77130 +** SELECT a AS b FROM t1 WHERE b;
 1.77131 +** SELECT * FROM t1 WHERE (select a from t1);
 1.77132 +*/
 1.77133 +SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
 1.77134 +  int op;
 1.77135 +  pExpr = sqlite3ExprSkipCollate(pExpr);
 1.77136 +  op = pExpr->op;
 1.77137 +  if( op==TK_SELECT ){
 1.77138 +    assert( pExpr->flags&EP_xIsSelect );
 1.77139 +    return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
 1.77140 +  }
 1.77141 +#ifndef SQLITE_OMIT_CAST
 1.77142 +  if( op==TK_CAST ){
 1.77143 +    assert( !ExprHasProperty(pExpr, EP_IntValue) );
 1.77144 +    return sqlite3AffinityType(pExpr->u.zToken, 0);
 1.77145 +  }
 1.77146 +#endif
 1.77147 +  if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
 1.77148 +   && pExpr->pTab!=0
 1.77149 +  ){
 1.77150 +    /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
 1.77151 +    ** a TK_COLUMN but was previously evaluated and cached in a register */
 1.77152 +    int j = pExpr->iColumn;
 1.77153 +    if( j<0 ) return SQLITE_AFF_INTEGER;
 1.77154 +    assert( pExpr->pTab && j<pExpr->pTab->nCol );
 1.77155 +    return pExpr->pTab->aCol[j].affinity;
 1.77156 +  }
 1.77157 +  return pExpr->affinity;
 1.77158 +}
 1.77159 +
 1.77160 +/*
 1.77161 +** Set the collating sequence for expression pExpr to be the collating
 1.77162 +** sequence named by pToken.   Return a pointer to a new Expr node that
 1.77163 +** implements the COLLATE operator.
 1.77164 +**
 1.77165 +** If a memory allocation error occurs, that fact is recorded in pParse->db
 1.77166 +** and the pExpr parameter is returned unchanged.
 1.77167 +*/
 1.77168 +SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){
 1.77169 +  if( pCollName->n>0 ){
 1.77170 +    Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
 1.77171 +    if( pNew ){
 1.77172 +      pNew->pLeft = pExpr;
 1.77173 +      pNew->flags |= EP_Collate|EP_Skip;
 1.77174 +      pExpr = pNew;
 1.77175 +    }
 1.77176 +  }
 1.77177 +  return pExpr;
 1.77178 +}
 1.77179 +SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
 1.77180 +  Token s;
 1.77181 +  assert( zC!=0 );
 1.77182 +  s.z = zC;
 1.77183 +  s.n = sqlite3Strlen30(s.z);
 1.77184 +  return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
 1.77185 +}
 1.77186 +
 1.77187 +/*
 1.77188 +** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
 1.77189 +** or likelihood() function at the root of an expression.
 1.77190 +*/
 1.77191 +SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
 1.77192 +  while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
 1.77193 +    if( ExprHasProperty(pExpr, EP_Unlikely) ){
 1.77194 +      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
 1.77195 +      assert( pExpr->x.pList->nExpr>0 );
 1.77196 +      assert( pExpr->op==TK_FUNCTION );
 1.77197 +      pExpr = pExpr->x.pList->a[0].pExpr;
 1.77198 +    }else{
 1.77199 +      assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
 1.77200 +      pExpr = pExpr->pLeft;
 1.77201 +    }
 1.77202 +  }   
 1.77203 +  return pExpr;
 1.77204 +}
 1.77205 +
 1.77206 +/*
 1.77207 +** Return the collation sequence for the expression pExpr. If
 1.77208 +** there is no defined collating sequence, return NULL.
 1.77209 +**
 1.77210 +** The collating sequence might be determined by a COLLATE operator
 1.77211 +** or by the presence of a column with a defined collating sequence.
 1.77212 +** COLLATE operators take first precedence.  Left operands take
 1.77213 +** precedence over right operands.
 1.77214 +*/
 1.77215 +SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
 1.77216 +  sqlite3 *db = pParse->db;
 1.77217 +  CollSeq *pColl = 0;
 1.77218 +  Expr *p = pExpr;
 1.77219 +  while( p ){
 1.77220 +    int op = p->op;
 1.77221 +    if( op==TK_CAST || op==TK_UPLUS ){
 1.77222 +      p = p->pLeft;
 1.77223 +      continue;
 1.77224 +    }
 1.77225 +    if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
 1.77226 +      pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
 1.77227 +      break;
 1.77228 +    }
 1.77229 +    if( p->pTab!=0
 1.77230 +     && (op==TK_AGG_COLUMN || op==TK_COLUMN
 1.77231 +          || op==TK_REGISTER || op==TK_TRIGGER)
 1.77232 +    ){
 1.77233 +      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
 1.77234 +      ** a TK_COLUMN but was previously evaluated and cached in a register */
 1.77235 +      int j = p->iColumn;
 1.77236 +      if( j>=0 ){
 1.77237 +        const char *zColl = p->pTab->aCol[j].zColl;
 1.77238 +        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
 1.77239 +      }
 1.77240 +      break;
 1.77241 +    }
 1.77242 +    if( p->flags & EP_Collate ){
 1.77243 +      if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
 1.77244 +        p = p->pLeft;
 1.77245 +      }else{
 1.77246 +        p = p->pRight;
 1.77247 +      }
 1.77248 +    }else{
 1.77249 +      break;
 1.77250 +    }
 1.77251 +  }
 1.77252 +  if( sqlite3CheckCollSeq(pParse, pColl) ){ 
 1.77253 +    pColl = 0;
 1.77254 +  }
 1.77255 +  return pColl;
 1.77256 +}
 1.77257 +
 1.77258 +/*
 1.77259 +** pExpr is an operand of a comparison operator.  aff2 is the
 1.77260 +** type affinity of the other operand.  This routine returns the
 1.77261 +** type affinity that should be used for the comparison operator.
 1.77262 +*/
 1.77263 +SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
 1.77264 +  char aff1 = sqlite3ExprAffinity(pExpr);
 1.77265 +  if( aff1 && aff2 ){
 1.77266 +    /* Both sides of the comparison are columns. If one has numeric
 1.77267 +    ** affinity, use that. Otherwise use no affinity.
 1.77268 +    */
 1.77269 +    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
 1.77270 +      return SQLITE_AFF_NUMERIC;
 1.77271 +    }else{
 1.77272 +      return SQLITE_AFF_NONE;
 1.77273 +    }
 1.77274 +  }else if( !aff1 && !aff2 ){
 1.77275 +    /* Neither side of the comparison is a column.  Compare the
 1.77276 +    ** results directly.
 1.77277 +    */
 1.77278 +    return SQLITE_AFF_NONE;
 1.77279 +  }else{
 1.77280 +    /* One side is a column, the other is not. Use the columns affinity. */
 1.77281 +    assert( aff1==0 || aff2==0 );
 1.77282 +    return (aff1 + aff2);
 1.77283 +  }
 1.77284 +}
 1.77285 +
 1.77286 +/*
 1.77287 +** pExpr is a comparison operator.  Return the type affinity that should
 1.77288 +** be applied to both operands prior to doing the comparison.
 1.77289 +*/
 1.77290 +static char comparisonAffinity(Expr *pExpr){
 1.77291 +  char aff;
 1.77292 +  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
 1.77293 +          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
 1.77294 +          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
 1.77295 +  assert( pExpr->pLeft );
 1.77296 +  aff = sqlite3ExprAffinity(pExpr->pLeft);
 1.77297 +  if( pExpr->pRight ){
 1.77298 +    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
 1.77299 +  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
 1.77300 +    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
 1.77301 +  }else if( !aff ){
 1.77302 +    aff = SQLITE_AFF_NONE;
 1.77303 +  }
 1.77304 +  return aff;
 1.77305 +}
 1.77306 +
 1.77307 +/*
 1.77308 +** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
 1.77309 +** idx_affinity is the affinity of an indexed column. Return true
 1.77310 +** if the index with affinity idx_affinity may be used to implement
 1.77311 +** the comparison in pExpr.
 1.77312 +*/
 1.77313 +SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
 1.77314 +  char aff = comparisonAffinity(pExpr);
 1.77315 +  switch( aff ){
 1.77316 +    case SQLITE_AFF_NONE:
 1.77317 +      return 1;
 1.77318 +    case SQLITE_AFF_TEXT:
 1.77319 +      return idx_affinity==SQLITE_AFF_TEXT;
 1.77320 +    default:
 1.77321 +      return sqlite3IsNumericAffinity(idx_affinity);
 1.77322 +  }
 1.77323 +}
 1.77324 +
 1.77325 +/*
 1.77326 +** Return the P5 value that should be used for a binary comparison
 1.77327 +** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
 1.77328 +*/
 1.77329 +static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
 1.77330 +  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
 1.77331 +  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
 1.77332 +  return aff;
 1.77333 +}
 1.77334 +
 1.77335 +/*
 1.77336 +** Return a pointer to the collation sequence that should be used by
 1.77337 +** a binary comparison operator comparing pLeft and pRight.
 1.77338 +**
 1.77339 +** If the left hand expression has a collating sequence type, then it is
 1.77340 +** used. Otherwise the collation sequence for the right hand expression
 1.77341 +** is used, or the default (BINARY) if neither expression has a collating
 1.77342 +** type.
 1.77343 +**
 1.77344 +** Argument pRight (but not pLeft) may be a null pointer. In this case,
 1.77345 +** it is not considered.
 1.77346 +*/
 1.77347 +SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
 1.77348 +  Parse *pParse, 
 1.77349 +  Expr *pLeft, 
 1.77350 +  Expr *pRight
 1.77351 +){
 1.77352 +  CollSeq *pColl;
 1.77353 +  assert( pLeft );
 1.77354 +  if( pLeft->flags & EP_Collate ){
 1.77355 +    pColl = sqlite3ExprCollSeq(pParse, pLeft);
 1.77356 +  }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
 1.77357 +    pColl = sqlite3ExprCollSeq(pParse, pRight);
 1.77358 +  }else{
 1.77359 +    pColl = sqlite3ExprCollSeq(pParse, pLeft);
 1.77360 +    if( !pColl ){
 1.77361 +      pColl = sqlite3ExprCollSeq(pParse, pRight);
 1.77362 +    }
 1.77363 +  }
 1.77364 +  return pColl;
 1.77365 +}
 1.77366 +
 1.77367 +/*
 1.77368 +** Generate code for a comparison operator.
 1.77369 +*/
 1.77370 +static int codeCompare(
 1.77371 +  Parse *pParse,    /* The parsing (and code generating) context */
 1.77372 +  Expr *pLeft,      /* The left operand */
 1.77373 +  Expr *pRight,     /* The right operand */
 1.77374 +  int opcode,       /* The comparison opcode */
 1.77375 +  int in1, int in2, /* Register holding operands */
 1.77376 +  int dest,         /* Jump here if true.  */
 1.77377 +  int jumpIfNull    /* If true, jump if either operand is NULL */
 1.77378 +){
 1.77379 +  int p5;
 1.77380 +  int addr;
 1.77381 +  CollSeq *p4;
 1.77382 +
 1.77383 +  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
 1.77384 +  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
 1.77385 +  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
 1.77386 +                           (void*)p4, P4_COLLSEQ);
 1.77387 +  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
 1.77388 +  return addr;
 1.77389 +}
 1.77390 +
 1.77391 +#if SQLITE_MAX_EXPR_DEPTH>0
 1.77392 +/*
 1.77393 +** Check that argument nHeight is less than or equal to the maximum
 1.77394 +** expression depth allowed. If it is not, leave an error message in
 1.77395 +** pParse.
 1.77396 +*/
 1.77397 +SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
 1.77398 +  int rc = SQLITE_OK;
 1.77399 +  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
 1.77400 +  if( nHeight>mxHeight ){
 1.77401 +    sqlite3ErrorMsg(pParse, 
 1.77402 +       "Expression tree is too large (maximum depth %d)", mxHeight
 1.77403 +    );
 1.77404 +    rc = SQLITE_ERROR;
 1.77405 +  }
 1.77406 +  return rc;
 1.77407 +}
 1.77408 +
 1.77409 +/* The following three functions, heightOfExpr(), heightOfExprList()
 1.77410 +** and heightOfSelect(), are used to determine the maximum height
 1.77411 +** of any expression tree referenced by the structure passed as the
 1.77412 +** first argument.
 1.77413 +**
 1.77414 +** If this maximum height is greater than the current value pointed
 1.77415 +** to by pnHeight, the second parameter, then set *pnHeight to that
 1.77416 +** value.
 1.77417 +*/
 1.77418 +static void heightOfExpr(Expr *p, int *pnHeight){
 1.77419 +  if( p ){
 1.77420 +    if( p->nHeight>*pnHeight ){
 1.77421 +      *pnHeight = p->nHeight;
 1.77422 +    }
 1.77423 +  }
 1.77424 +}
 1.77425 +static void heightOfExprList(ExprList *p, int *pnHeight){
 1.77426 +  if( p ){
 1.77427 +    int i;
 1.77428 +    for(i=0; i<p->nExpr; i++){
 1.77429 +      heightOfExpr(p->a[i].pExpr, pnHeight);
 1.77430 +    }
 1.77431 +  }
 1.77432 +}
 1.77433 +static void heightOfSelect(Select *p, int *pnHeight){
 1.77434 +  if( p ){
 1.77435 +    heightOfExpr(p->pWhere, pnHeight);
 1.77436 +    heightOfExpr(p->pHaving, pnHeight);
 1.77437 +    heightOfExpr(p->pLimit, pnHeight);
 1.77438 +    heightOfExpr(p->pOffset, pnHeight);
 1.77439 +    heightOfExprList(p->pEList, pnHeight);
 1.77440 +    heightOfExprList(p->pGroupBy, pnHeight);
 1.77441 +    heightOfExprList(p->pOrderBy, pnHeight);
 1.77442 +    heightOfSelect(p->pPrior, pnHeight);
 1.77443 +  }
 1.77444 +}
 1.77445 +
 1.77446 +/*
 1.77447 +** Set the Expr.nHeight variable in the structure passed as an 
 1.77448 +** argument. An expression with no children, Expr.pList or 
 1.77449 +** Expr.pSelect member has a height of 1. Any other expression
 1.77450 +** has a height equal to the maximum height of any other 
 1.77451 +** referenced Expr plus one.
 1.77452 +*/
 1.77453 +static void exprSetHeight(Expr *p){
 1.77454 +  int nHeight = 0;
 1.77455 +  heightOfExpr(p->pLeft, &nHeight);
 1.77456 +  heightOfExpr(p->pRight, &nHeight);
 1.77457 +  if( ExprHasProperty(p, EP_xIsSelect) ){
 1.77458 +    heightOfSelect(p->x.pSelect, &nHeight);
 1.77459 +  }else{
 1.77460 +    heightOfExprList(p->x.pList, &nHeight);
 1.77461 +  }
 1.77462 +  p->nHeight = nHeight + 1;
 1.77463 +}
 1.77464 +
 1.77465 +/*
 1.77466 +** Set the Expr.nHeight variable using the exprSetHeight() function. If
 1.77467 +** the height is greater than the maximum allowed expression depth,
 1.77468 +** leave an error in pParse.
 1.77469 +*/
 1.77470 +SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
 1.77471 +  exprSetHeight(p);
 1.77472 +  sqlite3ExprCheckHeight(pParse, p->nHeight);
 1.77473 +}
 1.77474 +
 1.77475 +/*
 1.77476 +** Return the maximum height of any expression tree referenced
 1.77477 +** by the select statement passed as an argument.
 1.77478 +*/
 1.77479 +SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
 1.77480 +  int nHeight = 0;
 1.77481 +  heightOfSelect(p, &nHeight);
 1.77482 +  return nHeight;
 1.77483 +}
 1.77484 +#else
 1.77485 +  #define exprSetHeight(y)
 1.77486 +#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
 1.77487 +
 1.77488 +/*
 1.77489 +** This routine is the core allocator for Expr nodes.
 1.77490 +**
 1.77491 +** Construct a new expression node and return a pointer to it.  Memory
 1.77492 +** for this node and for the pToken argument is a single allocation
 1.77493 +** obtained from sqlite3DbMalloc().  The calling function
 1.77494 +** is responsible for making sure the node eventually gets freed.
 1.77495 +**
 1.77496 +** If dequote is true, then the token (if it exists) is dequoted.
 1.77497 +** If dequote is false, no dequoting is performance.  The deQuote
 1.77498 +** parameter is ignored if pToken is NULL or if the token does not
 1.77499 +** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
 1.77500 +** then the EP_DblQuoted flag is set on the expression node.
 1.77501 +**
 1.77502 +** Special case:  If op==TK_INTEGER and pToken points to a string that
 1.77503 +** can be translated into a 32-bit integer, then the token is not
 1.77504 +** stored in u.zToken.  Instead, the integer values is written
 1.77505 +** into u.iValue and the EP_IntValue flag is set.  No extra storage
 1.77506 +** is allocated to hold the integer text and the dequote flag is ignored.
 1.77507 +*/
 1.77508 +SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
 1.77509 +  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
 1.77510 +  int op,                 /* Expression opcode */
 1.77511 +  const Token *pToken,    /* Token argument.  Might be NULL */
 1.77512 +  int dequote             /* True to dequote */
 1.77513 +){
 1.77514 +  Expr *pNew;
 1.77515 +  int nExtra = 0;
 1.77516 +  int iValue = 0;
 1.77517 +
 1.77518 +  if( pToken ){
 1.77519 +    if( op!=TK_INTEGER || pToken->z==0
 1.77520 +          || sqlite3GetInt32(pToken->z, &iValue)==0 ){
 1.77521 +      nExtra = pToken->n+1;
 1.77522 +      assert( iValue>=0 );
 1.77523 +    }
 1.77524 +  }
 1.77525 +  pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
 1.77526 +  if( pNew ){
 1.77527 +    pNew->op = (u8)op;
 1.77528 +    pNew->iAgg = -1;
 1.77529 +    if( pToken ){
 1.77530 +      if( nExtra==0 ){
 1.77531 +        pNew->flags |= EP_IntValue;
 1.77532 +        pNew->u.iValue = iValue;
 1.77533 +      }else{
 1.77534 +        int c;
 1.77535 +        pNew->u.zToken = (char*)&pNew[1];
 1.77536 +        assert( pToken->z!=0 || pToken->n==0 );
 1.77537 +        if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
 1.77538 +        pNew->u.zToken[pToken->n] = 0;
 1.77539 +        if( dequote && nExtra>=3 
 1.77540 +             && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
 1.77541 +          sqlite3Dequote(pNew->u.zToken);
 1.77542 +          if( c=='"' ) pNew->flags |= EP_DblQuoted;
 1.77543 +        }
 1.77544 +      }
 1.77545 +    }
 1.77546 +#if SQLITE_MAX_EXPR_DEPTH>0
 1.77547 +    pNew->nHeight = 1;
 1.77548 +#endif  
 1.77549 +  }
 1.77550 +  return pNew;
 1.77551 +}
 1.77552 +
 1.77553 +/*
 1.77554 +** Allocate a new expression node from a zero-terminated token that has
 1.77555 +** already been dequoted.
 1.77556 +*/
 1.77557 +SQLITE_PRIVATE Expr *sqlite3Expr(
 1.77558 +  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
 1.77559 +  int op,                 /* Expression opcode */
 1.77560 +  const char *zToken      /* Token argument.  Might be NULL */
 1.77561 +){
 1.77562 +  Token x;
 1.77563 +  x.z = zToken;
 1.77564 +  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
 1.77565 +  return sqlite3ExprAlloc(db, op, &x, 0);
 1.77566 +}
 1.77567 +
 1.77568 +/*
 1.77569 +** Attach subtrees pLeft and pRight to the Expr node pRoot.
 1.77570 +**
 1.77571 +** If pRoot==NULL that means that a memory allocation error has occurred.
 1.77572 +** In that case, delete the subtrees pLeft and pRight.
 1.77573 +*/
 1.77574 +SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
 1.77575 +  sqlite3 *db,
 1.77576 +  Expr *pRoot,
 1.77577 +  Expr *pLeft,
 1.77578 +  Expr *pRight
 1.77579 +){
 1.77580 +  if( pRoot==0 ){
 1.77581 +    assert( db->mallocFailed );
 1.77582 +    sqlite3ExprDelete(db, pLeft);
 1.77583 +    sqlite3ExprDelete(db, pRight);
 1.77584 +  }else{
 1.77585 +    if( pRight ){
 1.77586 +      pRoot->pRight = pRight;
 1.77587 +      pRoot->flags |= EP_Collate & pRight->flags;
 1.77588 +    }
 1.77589 +    if( pLeft ){
 1.77590 +      pRoot->pLeft = pLeft;
 1.77591 +      pRoot->flags |= EP_Collate & pLeft->flags;
 1.77592 +    }
 1.77593 +    exprSetHeight(pRoot);
 1.77594 +  }
 1.77595 +}
 1.77596 +
 1.77597 +/*
 1.77598 +** Allocate a Expr node which joins as many as two subtrees.
 1.77599 +**
 1.77600 +** One or both of the subtrees can be NULL.  Return a pointer to the new
 1.77601 +** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
 1.77602 +** free the subtrees and return NULL.
 1.77603 +*/
 1.77604 +SQLITE_PRIVATE Expr *sqlite3PExpr(
 1.77605 +  Parse *pParse,          /* Parsing context */
 1.77606 +  int op,                 /* Expression opcode */
 1.77607 +  Expr *pLeft,            /* Left operand */
 1.77608 +  Expr *pRight,           /* Right operand */
 1.77609 +  const Token *pToken     /* Argument token */
 1.77610 +){
 1.77611 +  Expr *p;
 1.77612 +  if( op==TK_AND && pLeft && pRight ){
 1.77613 +    /* Take advantage of short-circuit false optimization for AND */
 1.77614 +    p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
 1.77615 +  }else{
 1.77616 +    p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
 1.77617 +    sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
 1.77618 +  }
 1.77619 +  if( p ) {
 1.77620 +    sqlite3ExprCheckHeight(pParse, p->nHeight);
 1.77621 +  }
 1.77622 +  return p;
 1.77623 +}
 1.77624 +
 1.77625 +/*
 1.77626 +** If the expression is always either TRUE or FALSE (respectively),
 1.77627 +** then return 1.  If one cannot determine the truth value of the
 1.77628 +** expression at compile-time return 0.
 1.77629 +**
 1.77630 +** This is an optimization.  If is OK to return 0 here even if
 1.77631 +** the expression really is always false or false (a false negative).
 1.77632 +** But it is a bug to return 1 if the expression might have different
 1.77633 +** boolean values in different circumstances (a false positive.)
 1.77634 +**
 1.77635 +** Note that if the expression is part of conditional for a
 1.77636 +** LEFT JOIN, then we cannot determine at compile-time whether or not
 1.77637 +** is it true or false, so always return 0.
 1.77638 +*/
 1.77639 +static int exprAlwaysTrue(Expr *p){
 1.77640 +  int v = 0;
 1.77641 +  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
 1.77642 +  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
 1.77643 +  return v!=0;
 1.77644 +}
 1.77645 +static int exprAlwaysFalse(Expr *p){
 1.77646 +  int v = 0;
 1.77647 +  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
 1.77648 +  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
 1.77649 +  return v==0;
 1.77650 +}
 1.77651 +
 1.77652 +/*
 1.77653 +** Join two expressions using an AND operator.  If either expression is
 1.77654 +** NULL, then just return the other expression.
 1.77655 +**
 1.77656 +** If one side or the other of the AND is known to be false, then instead
 1.77657 +** of returning an AND expression, just return a constant expression with
 1.77658 +** a value of false.
 1.77659 +*/
 1.77660 +SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
 1.77661 +  if( pLeft==0 ){
 1.77662 +    return pRight;
 1.77663 +  }else if( pRight==0 ){
 1.77664 +    return pLeft;
 1.77665 +  }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
 1.77666 +    sqlite3ExprDelete(db, pLeft);
 1.77667 +    sqlite3ExprDelete(db, pRight);
 1.77668 +    return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
 1.77669 +  }else{
 1.77670 +    Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
 1.77671 +    sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
 1.77672 +    return pNew;
 1.77673 +  }
 1.77674 +}
 1.77675 +
 1.77676 +/*
 1.77677 +** Construct a new expression node for a function with multiple
 1.77678 +** arguments.
 1.77679 +*/
 1.77680 +SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
 1.77681 +  Expr *pNew;
 1.77682 +  sqlite3 *db = pParse->db;
 1.77683 +  assert( pToken );
 1.77684 +  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
 1.77685 +  if( pNew==0 ){
 1.77686 +    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
 1.77687 +    return 0;
 1.77688 +  }
 1.77689 +  pNew->x.pList = pList;
 1.77690 +  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
 1.77691 +  sqlite3ExprSetHeight(pParse, pNew);
 1.77692 +  return pNew;
 1.77693 +}
 1.77694 +
 1.77695 +/*
 1.77696 +** Assign a variable number to an expression that encodes a wildcard
 1.77697 +** in the original SQL statement.  
 1.77698 +**
 1.77699 +** Wildcards consisting of a single "?" are assigned the next sequential
 1.77700 +** variable number.
 1.77701 +**
 1.77702 +** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
 1.77703 +** sure "nnn" is not too be to avoid a denial of service attack when
 1.77704 +** the SQL statement comes from an external source.
 1.77705 +**
 1.77706 +** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
 1.77707 +** as the previous instance of the same wildcard.  Or if this is the first
 1.77708 +** instance of the wildcard, the next sequenial variable number is
 1.77709 +** assigned.
 1.77710 +*/
 1.77711 +SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
 1.77712 +  sqlite3 *db = pParse->db;
 1.77713 +  const char *z;
 1.77714 +
 1.77715 +  if( pExpr==0 ) return;
 1.77716 +  assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
 1.77717 +  z = pExpr->u.zToken;
 1.77718 +  assert( z!=0 );
 1.77719 +  assert( z[0]!=0 );
 1.77720 +  if( z[1]==0 ){
 1.77721 +    /* Wildcard of the form "?".  Assign the next variable number */
 1.77722 +    assert( z[0]=='?' );
 1.77723 +    pExpr->iColumn = (ynVar)(++pParse->nVar);
 1.77724 +  }else{
 1.77725 +    ynVar x = 0;
 1.77726 +    u32 n = sqlite3Strlen30(z);
 1.77727 +    if( z[0]=='?' ){
 1.77728 +      /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
 1.77729 +      ** use it as the variable number */
 1.77730 +      i64 i;
 1.77731 +      int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
 1.77732 +      pExpr->iColumn = x = (ynVar)i;
 1.77733 +      testcase( i==0 );
 1.77734 +      testcase( i==1 );
 1.77735 +      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
 1.77736 +      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
 1.77737 +      if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
 1.77738 +        sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
 1.77739 +            db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
 1.77740 +        x = 0;
 1.77741 +      }
 1.77742 +      if( i>pParse->nVar ){
 1.77743 +        pParse->nVar = (int)i;
 1.77744 +      }
 1.77745 +    }else{
 1.77746 +      /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
 1.77747 +      ** number as the prior appearance of the same name, or if the name
 1.77748 +      ** has never appeared before, reuse the same variable number
 1.77749 +      */
 1.77750 +      ynVar i;
 1.77751 +      for(i=0; i<pParse->nzVar; i++){
 1.77752 +        if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
 1.77753 +          pExpr->iColumn = x = (ynVar)i+1;
 1.77754 +          break;
 1.77755 +        }
 1.77756 +      }
 1.77757 +      if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
 1.77758 +    }
 1.77759 +    if( x>0 ){
 1.77760 +      if( x>pParse->nzVar ){
 1.77761 +        char **a;
 1.77762 +        a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
 1.77763 +        if( a==0 ) return;  /* Error reported through db->mallocFailed */
 1.77764 +        pParse->azVar = a;
 1.77765 +        memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
 1.77766 +        pParse->nzVar = x;
 1.77767 +      }
 1.77768 +      if( z[0]!='?' || pParse->azVar[x-1]==0 ){
 1.77769 +        sqlite3DbFree(db, pParse->azVar[x-1]);
 1.77770 +        pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
 1.77771 +      }
 1.77772 +    }
 1.77773 +  } 
 1.77774 +  if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
 1.77775 +    sqlite3ErrorMsg(pParse, "too many SQL variables");
 1.77776 +  }
 1.77777 +}
 1.77778 +
 1.77779 +/*
 1.77780 +** Recursively delete an expression tree.
 1.77781 +*/
 1.77782 +SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
 1.77783 +  if( p==0 ) return;
 1.77784 +  /* Sanity check: Assert that the IntValue is non-negative if it exists */
 1.77785 +  assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
 1.77786 +  if( !ExprHasProperty(p, EP_TokenOnly) ){
 1.77787 +    /* The Expr.x union is never used at the same time as Expr.pRight */
 1.77788 +    assert( p->x.pList==0 || p->pRight==0 );
 1.77789 +    sqlite3ExprDelete(db, p->pLeft);
 1.77790 +    sqlite3ExprDelete(db, p->pRight);
 1.77791 +    if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
 1.77792 +    if( ExprHasProperty(p, EP_xIsSelect) ){
 1.77793 +      sqlite3SelectDelete(db, p->x.pSelect);
 1.77794 +    }else{
 1.77795 +      sqlite3ExprListDelete(db, p->x.pList);
 1.77796 +    }
 1.77797 +  }
 1.77798 +  if( !ExprHasProperty(p, EP_Static) ){
 1.77799 +    sqlite3DbFree(db, p);
 1.77800 +  }
 1.77801 +}
 1.77802 +
 1.77803 +/*
 1.77804 +** Return the number of bytes allocated for the expression structure 
 1.77805 +** passed as the first argument. This is always one of EXPR_FULLSIZE,
 1.77806 +** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
 1.77807 +*/
 1.77808 +static int exprStructSize(Expr *p){
 1.77809 +  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
 1.77810 +  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
 1.77811 +  return EXPR_FULLSIZE;
 1.77812 +}
 1.77813 +
 1.77814 +/*
 1.77815 +** The dupedExpr*Size() routines each return the number of bytes required
 1.77816 +** to store a copy of an expression or expression tree.  They differ in
 1.77817 +** how much of the tree is measured.
 1.77818 +**
 1.77819 +**     dupedExprStructSize()     Size of only the Expr structure 
 1.77820 +**     dupedExprNodeSize()       Size of Expr + space for token
 1.77821 +**     dupedExprSize()           Expr + token + subtree components
 1.77822 +**
 1.77823 +***************************************************************************
 1.77824 +**
 1.77825 +** The dupedExprStructSize() function returns two values OR-ed together:  
 1.77826 +** (1) the space required for a copy of the Expr structure only and 
 1.77827 +** (2) the EP_xxx flags that indicate what the structure size should be.
 1.77828 +** The return values is always one of:
 1.77829 +**
 1.77830 +**      EXPR_FULLSIZE
 1.77831 +**      EXPR_REDUCEDSIZE   | EP_Reduced
 1.77832 +**      EXPR_TOKENONLYSIZE | EP_TokenOnly
 1.77833 +**
 1.77834 +** The size of the structure can be found by masking the return value
 1.77835 +** of this routine with 0xfff.  The flags can be found by masking the
 1.77836 +** return value with EP_Reduced|EP_TokenOnly.
 1.77837 +**
 1.77838 +** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
 1.77839 +** (unreduced) Expr objects as they or originally constructed by the parser.
 1.77840 +** During expression analysis, extra information is computed and moved into
 1.77841 +** later parts of teh Expr object and that extra information might get chopped
 1.77842 +** off if the expression is reduced.  Note also that it does not work to
 1.77843 +** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
 1.77844 +** to reduce a pristine expression tree from the parser.  The implementation
 1.77845 +** of dupedExprStructSize() contain multiple assert() statements that attempt
 1.77846 +** to enforce this constraint.
 1.77847 +*/
 1.77848 +static int dupedExprStructSize(Expr *p, int flags){
 1.77849 +  int nSize;
 1.77850 +  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
 1.77851 +  assert( EXPR_FULLSIZE<=0xfff );
 1.77852 +  assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
 1.77853 +  if( 0==(flags&EXPRDUP_REDUCE) ){
 1.77854 +    nSize = EXPR_FULLSIZE;
 1.77855 +  }else{
 1.77856 +    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
 1.77857 +    assert( !ExprHasProperty(p, EP_FromJoin) ); 
 1.77858 +    assert( !ExprHasProperty(p, EP_MemToken) );
 1.77859 +    assert( !ExprHasProperty(p, EP_NoReduce) );
 1.77860 +    if( p->pLeft || p->x.pList ){
 1.77861 +      nSize = EXPR_REDUCEDSIZE | EP_Reduced;
 1.77862 +    }else{
 1.77863 +      assert( p->pRight==0 );
 1.77864 +      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
 1.77865 +    }
 1.77866 +  }
 1.77867 +  return nSize;
 1.77868 +}
 1.77869 +
 1.77870 +/*
 1.77871 +** This function returns the space in bytes required to store the copy 
 1.77872 +** of the Expr structure and a copy of the Expr.u.zToken string (if that
 1.77873 +** string is defined.)
 1.77874 +*/
 1.77875 +static int dupedExprNodeSize(Expr *p, int flags){
 1.77876 +  int nByte = dupedExprStructSize(p, flags) & 0xfff;
 1.77877 +  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
 1.77878 +    nByte += sqlite3Strlen30(p->u.zToken)+1;
 1.77879 +  }
 1.77880 +  return ROUND8(nByte);
 1.77881 +}
 1.77882 +
 1.77883 +/*
 1.77884 +** Return the number of bytes required to create a duplicate of the 
 1.77885 +** expression passed as the first argument. The second argument is a
 1.77886 +** mask containing EXPRDUP_XXX flags.
 1.77887 +**
 1.77888 +** The value returned includes space to create a copy of the Expr struct
 1.77889 +** itself and the buffer referred to by Expr.u.zToken, if any.
 1.77890 +**
 1.77891 +** If the EXPRDUP_REDUCE flag is set, then the return value includes 
 1.77892 +** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
 1.77893 +** and Expr.pRight variables (but not for any structures pointed to or 
 1.77894 +** descended from the Expr.x.pList or Expr.x.pSelect variables).
 1.77895 +*/
 1.77896 +static int dupedExprSize(Expr *p, int flags){
 1.77897 +  int nByte = 0;
 1.77898 +  if( p ){
 1.77899 +    nByte = dupedExprNodeSize(p, flags);
 1.77900 +    if( flags&EXPRDUP_REDUCE ){
 1.77901 +      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
 1.77902 +    }
 1.77903 +  }
 1.77904 +  return nByte;
 1.77905 +}
 1.77906 +
 1.77907 +/*
 1.77908 +** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
 1.77909 +** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
 1.77910 +** to store the copy of expression p, the copies of p->u.zToken
 1.77911 +** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
 1.77912 +** if any. Before returning, *pzBuffer is set to the first byte passed the
 1.77913 +** portion of the buffer copied into by this function.
 1.77914 +*/
 1.77915 +static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
 1.77916 +  Expr *pNew = 0;                      /* Value to return */
 1.77917 +  if( p ){
 1.77918 +    const int isReduced = (flags&EXPRDUP_REDUCE);
 1.77919 +    u8 *zAlloc;
 1.77920 +    u32 staticFlag = 0;
 1.77921 +
 1.77922 +    assert( pzBuffer==0 || isReduced );
 1.77923 +
 1.77924 +    /* Figure out where to write the new Expr structure. */
 1.77925 +    if( pzBuffer ){
 1.77926 +      zAlloc = *pzBuffer;
 1.77927 +      staticFlag = EP_Static;
 1.77928 +    }else{
 1.77929 +      zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
 1.77930 +    }
 1.77931 +    pNew = (Expr *)zAlloc;
 1.77932 +
 1.77933 +    if( pNew ){
 1.77934 +      /* Set nNewSize to the size allocated for the structure pointed to
 1.77935 +      ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
 1.77936 +      ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
 1.77937 +      ** by the copy of the p->u.zToken string (if any).
 1.77938 +      */
 1.77939 +      const unsigned nStructSize = dupedExprStructSize(p, flags);
 1.77940 +      const int nNewSize = nStructSize & 0xfff;
 1.77941 +      int nToken;
 1.77942 +      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
 1.77943 +        nToken = sqlite3Strlen30(p->u.zToken) + 1;
 1.77944 +      }else{
 1.77945 +        nToken = 0;
 1.77946 +      }
 1.77947 +      if( isReduced ){
 1.77948 +        assert( ExprHasProperty(p, EP_Reduced)==0 );
 1.77949 +        memcpy(zAlloc, p, nNewSize);
 1.77950 +      }else{
 1.77951 +        int nSize = exprStructSize(p);
 1.77952 +        memcpy(zAlloc, p, nSize);
 1.77953 +        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
 1.77954 +      }
 1.77955 +
 1.77956 +      /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
 1.77957 +      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
 1.77958 +      pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
 1.77959 +      pNew->flags |= staticFlag;
 1.77960 +
 1.77961 +      /* Copy the p->u.zToken string, if any. */
 1.77962 +      if( nToken ){
 1.77963 +        char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
 1.77964 +        memcpy(zToken, p->u.zToken, nToken);
 1.77965 +      }
 1.77966 +
 1.77967 +      if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
 1.77968 +        /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
 1.77969 +        if( ExprHasProperty(p, EP_xIsSelect) ){
 1.77970 +          pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
 1.77971 +        }else{
 1.77972 +          pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
 1.77973 +        }
 1.77974 +      }
 1.77975 +
 1.77976 +      /* Fill in pNew->pLeft and pNew->pRight. */
 1.77977 +      if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
 1.77978 +        zAlloc += dupedExprNodeSize(p, flags);
 1.77979 +        if( ExprHasProperty(pNew, EP_Reduced) ){
 1.77980 +          pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
 1.77981 +          pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
 1.77982 +        }
 1.77983 +        if( pzBuffer ){
 1.77984 +          *pzBuffer = zAlloc;
 1.77985 +        }
 1.77986 +      }else{
 1.77987 +        if( !ExprHasProperty(p, EP_TokenOnly) ){
 1.77988 +          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
 1.77989 +          pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
 1.77990 +        }
 1.77991 +      }
 1.77992 +
 1.77993 +    }
 1.77994 +  }
 1.77995 +  return pNew;
 1.77996 +}
 1.77997 +
 1.77998 +/*
 1.77999 +** Create and return a deep copy of the object passed as the second 
 1.78000 +** argument. If an OOM condition is encountered, NULL is returned
 1.78001 +** and the db->mallocFailed flag set.
 1.78002 +*/
 1.78003 +#ifndef SQLITE_OMIT_CTE
 1.78004 +static With *withDup(sqlite3 *db, With *p){
 1.78005 +  With *pRet = 0;
 1.78006 +  if( p ){
 1.78007 +    int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
 1.78008 +    pRet = sqlite3DbMallocZero(db, nByte);
 1.78009 +    if( pRet ){
 1.78010 +      int i;
 1.78011 +      pRet->nCte = p->nCte;
 1.78012 +      for(i=0; i<p->nCte; i++){
 1.78013 +        pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
 1.78014 +        pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
 1.78015 +        pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
 1.78016 +      }
 1.78017 +    }
 1.78018 +  }
 1.78019 +  return pRet;
 1.78020 +}
 1.78021 +#else
 1.78022 +# define withDup(x,y) 0
 1.78023 +#endif
 1.78024 +
 1.78025 +/*
 1.78026 +** The following group of routines make deep copies of expressions,
 1.78027 +** expression lists, ID lists, and select statements.  The copies can
 1.78028 +** be deleted (by being passed to their respective ...Delete() routines)
 1.78029 +** without effecting the originals.
 1.78030 +**
 1.78031 +** The expression list, ID, and source lists return by sqlite3ExprListDup(),
 1.78032 +** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
 1.78033 +** by subsequent calls to sqlite*ListAppend() routines.
 1.78034 +**
 1.78035 +** Any tables that the SrcList might point to are not duplicated.
 1.78036 +**
 1.78037 +** The flags parameter contains a combination of the EXPRDUP_XXX flags.
 1.78038 +** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
 1.78039 +** truncated version of the usual Expr structure that will be stored as
 1.78040 +** part of the in-memory representation of the database schema.
 1.78041 +*/
 1.78042 +SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
 1.78043 +  return exprDup(db, p, flags, 0);
 1.78044 +}
 1.78045 +SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
 1.78046 +  ExprList *pNew;
 1.78047 +  struct ExprList_item *pItem, *pOldItem;
 1.78048 +  int i;
 1.78049 +  if( p==0 ) return 0;
 1.78050 +  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
 1.78051 +  if( pNew==0 ) return 0;
 1.78052 +  pNew->iECursor = 0;
 1.78053 +  pNew->nExpr = i = p->nExpr;
 1.78054 +  if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
 1.78055 +  pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
 1.78056 +  if( pItem==0 ){
 1.78057 +    sqlite3DbFree(db, pNew);
 1.78058 +    return 0;
 1.78059 +  } 
 1.78060 +  pOldItem = p->a;
 1.78061 +  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
 1.78062 +    Expr *pOldExpr = pOldItem->pExpr;
 1.78063 +    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
 1.78064 +    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
 1.78065 +    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
 1.78066 +    pItem->sortOrder = pOldItem->sortOrder;
 1.78067 +    pItem->done = 0;
 1.78068 +    pItem->bSpanIsTab = pOldItem->bSpanIsTab;
 1.78069 +    pItem->u = pOldItem->u;
 1.78070 +  }
 1.78071 +  return pNew;
 1.78072 +}
 1.78073 +
 1.78074 +/*
 1.78075 +** If cursors, triggers, views and subqueries are all omitted from
 1.78076 +** the build, then none of the following routines, except for 
 1.78077 +** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
 1.78078 +** called with a NULL argument.
 1.78079 +*/
 1.78080 +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
 1.78081 + || !defined(SQLITE_OMIT_SUBQUERY)
 1.78082 +SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
 1.78083 +  SrcList *pNew;
 1.78084 +  int i;
 1.78085 +  int nByte;
 1.78086 +  if( p==0 ) return 0;
 1.78087 +  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
 1.78088 +  pNew = sqlite3DbMallocRaw(db, nByte );
 1.78089 +  if( pNew==0 ) return 0;
 1.78090 +  pNew->nSrc = pNew->nAlloc = p->nSrc;
 1.78091 +  for(i=0; i<p->nSrc; i++){
 1.78092 +    struct SrcList_item *pNewItem = &pNew->a[i];
 1.78093 +    struct SrcList_item *pOldItem = &p->a[i];
 1.78094 +    Table *pTab;
 1.78095 +    pNewItem->pSchema = pOldItem->pSchema;
 1.78096 +    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
 1.78097 +    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
 1.78098 +    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
 1.78099 +    pNewItem->jointype = pOldItem->jointype;
 1.78100 +    pNewItem->iCursor = pOldItem->iCursor;
 1.78101 +    pNewItem->addrFillSub = pOldItem->addrFillSub;
 1.78102 +    pNewItem->regReturn = pOldItem->regReturn;
 1.78103 +    pNewItem->isCorrelated = pOldItem->isCorrelated;
 1.78104 +    pNewItem->viaCoroutine = pOldItem->viaCoroutine;
 1.78105 +    pNewItem->isRecursive = pOldItem->isRecursive;
 1.78106 +    pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
 1.78107 +    pNewItem->notIndexed = pOldItem->notIndexed;
 1.78108 +    pNewItem->pIndex = pOldItem->pIndex;
 1.78109 +    pTab = pNewItem->pTab = pOldItem->pTab;
 1.78110 +    if( pTab ){
 1.78111 +      pTab->nRef++;
 1.78112 +    }
 1.78113 +    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
 1.78114 +    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
 1.78115 +    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
 1.78116 +    pNewItem->colUsed = pOldItem->colUsed;
 1.78117 +  }
 1.78118 +  return pNew;
 1.78119 +}
 1.78120 +SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
 1.78121 +  IdList *pNew;
 1.78122 +  int i;
 1.78123 +  if( p==0 ) return 0;
 1.78124 +  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
 1.78125 +  if( pNew==0 ) return 0;
 1.78126 +  pNew->nId = p->nId;
 1.78127 +  pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
 1.78128 +  if( pNew->a==0 ){
 1.78129 +    sqlite3DbFree(db, pNew);
 1.78130 +    return 0;
 1.78131 +  }
 1.78132 +  /* Note that because the size of the allocation for p->a[] is not
 1.78133 +  ** necessarily a power of two, sqlite3IdListAppend() may not be called
 1.78134 +  ** on the duplicate created by this function. */
 1.78135 +  for(i=0; i<p->nId; i++){
 1.78136 +    struct IdList_item *pNewItem = &pNew->a[i];
 1.78137 +    struct IdList_item *pOldItem = &p->a[i];
 1.78138 +    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
 1.78139 +    pNewItem->idx = pOldItem->idx;
 1.78140 +  }
 1.78141 +  return pNew;
 1.78142 +}
 1.78143 +SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
 1.78144 +  Select *pNew, *pPrior;
 1.78145 +  if( p==0 ) return 0;
 1.78146 +  pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
 1.78147 +  if( pNew==0 ) return 0;
 1.78148 +  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
 1.78149 +  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
 1.78150 +  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
 1.78151 +  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
 1.78152 +  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
 1.78153 +  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
 1.78154 +  pNew->op = p->op;
 1.78155 +  pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
 1.78156 +  if( pPrior ) pPrior->pNext = pNew;
 1.78157 +  pNew->pNext = 0;
 1.78158 +  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
 1.78159 +  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
 1.78160 +  pNew->iLimit = 0;
 1.78161 +  pNew->iOffset = 0;
 1.78162 +  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
 1.78163 +  pNew->addrOpenEphm[0] = -1;
 1.78164 +  pNew->addrOpenEphm[1] = -1;
 1.78165 +  pNew->addrOpenEphm[2] = -1;
 1.78166 +  pNew->nSelectRow = p->nSelectRow;
 1.78167 +  pNew->pWith = withDup(db, p->pWith);
 1.78168 +  return pNew;
 1.78169 +}
 1.78170 +#else
 1.78171 +SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
 1.78172 +  assert( p==0 );
 1.78173 +  return 0;
 1.78174 +}
 1.78175 +#endif
 1.78176 +
 1.78177 +
 1.78178 +/*
 1.78179 +** Add a new element to the end of an expression list.  If pList is
 1.78180 +** initially NULL, then create a new expression list.
 1.78181 +**
 1.78182 +** If a memory allocation error occurs, the entire list is freed and
 1.78183 +** NULL is returned.  If non-NULL is returned, then it is guaranteed
 1.78184 +** that the new entry was successfully appended.
 1.78185 +*/
 1.78186 +SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
 1.78187 +  Parse *pParse,          /* Parsing context */
 1.78188 +  ExprList *pList,        /* List to which to append. Might be NULL */
 1.78189 +  Expr *pExpr             /* Expression to be appended. Might be NULL */
 1.78190 +){
 1.78191 +  sqlite3 *db = pParse->db;
 1.78192 +  if( pList==0 ){
 1.78193 +    pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
 1.78194 +    if( pList==0 ){
 1.78195 +      goto no_mem;
 1.78196 +    }
 1.78197 +    pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
 1.78198 +    if( pList->a==0 ) goto no_mem;
 1.78199 +  }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
 1.78200 +    struct ExprList_item *a;
 1.78201 +    assert( pList->nExpr>0 );
 1.78202 +    a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
 1.78203 +    if( a==0 ){
 1.78204 +      goto no_mem;
 1.78205 +    }
 1.78206 +    pList->a = a;
 1.78207 +  }
 1.78208 +  assert( pList->a!=0 );
 1.78209 +  if( 1 ){
 1.78210 +    struct ExprList_item *pItem = &pList->a[pList->nExpr++];
 1.78211 +    memset(pItem, 0, sizeof(*pItem));
 1.78212 +    pItem->pExpr = pExpr;
 1.78213 +  }
 1.78214 +  return pList;
 1.78215 +
 1.78216 +no_mem:     
 1.78217 +  /* Avoid leaking memory if malloc has failed. */
 1.78218 +  sqlite3ExprDelete(db, pExpr);
 1.78219 +  sqlite3ExprListDelete(db, pList);
 1.78220 +  return 0;
 1.78221 +}
 1.78222 +
 1.78223 +/*
 1.78224 +** Set the ExprList.a[].zName element of the most recently added item
 1.78225 +** on the expression list.
 1.78226 +**
 1.78227 +** pList might be NULL following an OOM error.  But pName should never be
 1.78228 +** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
 1.78229 +** is set.
 1.78230 +*/
 1.78231 +SQLITE_PRIVATE void sqlite3ExprListSetName(
 1.78232 +  Parse *pParse,          /* Parsing context */
 1.78233 +  ExprList *pList,        /* List to which to add the span. */
 1.78234 +  Token *pName,           /* Name to be added */
 1.78235 +  int dequote             /* True to cause the name to be dequoted */
 1.78236 +){
 1.78237 +  assert( pList!=0 || pParse->db->mallocFailed!=0 );
 1.78238 +  if( pList ){
 1.78239 +    struct ExprList_item *pItem;
 1.78240 +    assert( pList->nExpr>0 );
 1.78241 +    pItem = &pList->a[pList->nExpr-1];
 1.78242 +    assert( pItem->zName==0 );
 1.78243 +    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
 1.78244 +    if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
 1.78245 +  }
 1.78246 +}
 1.78247 +
 1.78248 +/*
 1.78249 +** Set the ExprList.a[].zSpan element of the most recently added item
 1.78250 +** on the expression list.
 1.78251 +**
 1.78252 +** pList might be NULL following an OOM error.  But pSpan should never be
 1.78253 +** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
 1.78254 +** is set.
 1.78255 +*/
 1.78256 +SQLITE_PRIVATE void sqlite3ExprListSetSpan(
 1.78257 +  Parse *pParse,          /* Parsing context */
 1.78258 +  ExprList *pList,        /* List to which to add the span. */
 1.78259 +  ExprSpan *pSpan         /* The span to be added */
 1.78260 +){
 1.78261 +  sqlite3 *db = pParse->db;
 1.78262 +  assert( pList!=0 || db->mallocFailed!=0 );
 1.78263 +  if( pList ){
 1.78264 +    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
 1.78265 +    assert( pList->nExpr>0 );
 1.78266 +    assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
 1.78267 +    sqlite3DbFree(db, pItem->zSpan);
 1.78268 +    pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
 1.78269 +                                    (int)(pSpan->zEnd - pSpan->zStart));
 1.78270 +  }
 1.78271 +}
 1.78272 +
 1.78273 +/*
 1.78274 +** If the expression list pEList contains more than iLimit elements,
 1.78275 +** leave an error message in pParse.
 1.78276 +*/
 1.78277 +SQLITE_PRIVATE void sqlite3ExprListCheckLength(
 1.78278 +  Parse *pParse,
 1.78279 +  ExprList *pEList,
 1.78280 +  const char *zObject
 1.78281 +){
 1.78282 +  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
 1.78283 +  testcase( pEList && pEList->nExpr==mx );
 1.78284 +  testcase( pEList && pEList->nExpr==mx+1 );
 1.78285 +  if( pEList && pEList->nExpr>mx ){
 1.78286 +    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
 1.78287 +  }
 1.78288 +}
 1.78289 +
 1.78290 +/*
 1.78291 +** Delete an entire expression list.
 1.78292 +*/
 1.78293 +SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
 1.78294 +  int i;
 1.78295 +  struct ExprList_item *pItem;
 1.78296 +  if( pList==0 ) return;
 1.78297 +  assert( pList->a!=0 || pList->nExpr==0 );
 1.78298 +  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
 1.78299 +    sqlite3ExprDelete(db, pItem->pExpr);
 1.78300 +    sqlite3DbFree(db, pItem->zName);
 1.78301 +    sqlite3DbFree(db, pItem->zSpan);
 1.78302 +  }
 1.78303 +  sqlite3DbFree(db, pList->a);
 1.78304 +  sqlite3DbFree(db, pList);
 1.78305 +}
 1.78306 +
 1.78307 +/*
 1.78308 +** These routines are Walker callbacks.  Walker.u.pi is a pointer
 1.78309 +** to an integer.  These routines are checking an expression to see
 1.78310 +** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
 1.78311 +** not constant.
 1.78312 +**
 1.78313 +** These callback routines are used to implement the following:
 1.78314 +**
 1.78315 +**     sqlite3ExprIsConstant()
 1.78316 +**     sqlite3ExprIsConstantNotJoin()
 1.78317 +**     sqlite3ExprIsConstantOrFunction()
 1.78318 +**
 1.78319 +*/
 1.78320 +static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
 1.78321 +
 1.78322 +  /* If pWalker->u.i is 3 then any term of the expression that comes from
 1.78323 +  ** the ON or USING clauses of a join disqualifies the expression
 1.78324 +  ** from being considered constant. */
 1.78325 +  if( pWalker->u.i==3 && ExprHasProperty(pExpr, EP_FromJoin) ){
 1.78326 +    pWalker->u.i = 0;
 1.78327 +    return WRC_Abort;
 1.78328 +  }
 1.78329 +
 1.78330 +  switch( pExpr->op ){
 1.78331 +    /* Consider functions to be constant if all their arguments are constant
 1.78332 +    ** and either pWalker->u.i==2 or the function as the SQLITE_FUNC_CONST
 1.78333 +    ** flag. */
 1.78334 +    case TK_FUNCTION:
 1.78335 +      if( pWalker->u.i==2 || ExprHasProperty(pExpr,EP_Constant) ){
 1.78336 +        return WRC_Continue;
 1.78337 +      }
 1.78338 +      /* Fall through */
 1.78339 +    case TK_ID:
 1.78340 +    case TK_COLUMN:
 1.78341 +    case TK_AGG_FUNCTION:
 1.78342 +    case TK_AGG_COLUMN:
 1.78343 +      testcase( pExpr->op==TK_ID );
 1.78344 +      testcase( pExpr->op==TK_COLUMN );
 1.78345 +      testcase( pExpr->op==TK_AGG_FUNCTION );
 1.78346 +      testcase( pExpr->op==TK_AGG_COLUMN );
 1.78347 +      pWalker->u.i = 0;
 1.78348 +      return WRC_Abort;
 1.78349 +    default:
 1.78350 +      testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
 1.78351 +      testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
 1.78352 +      return WRC_Continue;
 1.78353 +  }
 1.78354 +}
 1.78355 +static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
 1.78356 +  UNUSED_PARAMETER(NotUsed);
 1.78357 +  pWalker->u.i = 0;
 1.78358 +  return WRC_Abort;
 1.78359 +}
 1.78360 +static int exprIsConst(Expr *p, int initFlag){
 1.78361 +  Walker w;
 1.78362 +  memset(&w, 0, sizeof(w));
 1.78363 +  w.u.i = initFlag;
 1.78364 +  w.xExprCallback = exprNodeIsConstant;
 1.78365 +  w.xSelectCallback = selectNodeIsConstant;
 1.78366 +  sqlite3WalkExpr(&w, p);
 1.78367 +  return w.u.i;
 1.78368 +}
 1.78369 +
 1.78370 +/*
 1.78371 +** Walk an expression tree.  Return 1 if the expression is constant
 1.78372 +** and 0 if it involves variables or function calls.
 1.78373 +**
 1.78374 +** For the purposes of this function, a double-quoted string (ex: "abc")
 1.78375 +** is considered a variable but a single-quoted string (ex: 'abc') is
 1.78376 +** a constant.
 1.78377 +*/
 1.78378 +SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
 1.78379 +  return exprIsConst(p, 1);
 1.78380 +}
 1.78381 +
 1.78382 +/*
 1.78383 +** Walk an expression tree.  Return 1 if the expression is constant
 1.78384 +** that does no originate from the ON or USING clauses of a join.
 1.78385 +** Return 0 if it involves variables or function calls or terms from
 1.78386 +** an ON or USING clause.
 1.78387 +*/
 1.78388 +SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
 1.78389 +  return exprIsConst(p, 3);
 1.78390 +}
 1.78391 +
 1.78392 +/*
 1.78393 +** Walk an expression tree.  Return 1 if the expression is constant
 1.78394 +** or a function call with constant arguments.  Return and 0 if there
 1.78395 +** are any variables.
 1.78396 +**
 1.78397 +** For the purposes of this function, a double-quoted string (ex: "abc")
 1.78398 +** is considered a variable but a single-quoted string (ex: 'abc') is
 1.78399 +** a constant.
 1.78400 +*/
 1.78401 +SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
 1.78402 +  return exprIsConst(p, 2);
 1.78403 +}
 1.78404 +
 1.78405 +/*
 1.78406 +** If the expression p codes a constant integer that is small enough
 1.78407 +** to fit in a 32-bit integer, return 1 and put the value of the integer
 1.78408 +** in *pValue.  If the expression is not an integer or if it is too big
 1.78409 +** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
 1.78410 +*/
 1.78411 +SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
 1.78412 +  int rc = 0;
 1.78413 +
 1.78414 +  /* If an expression is an integer literal that fits in a signed 32-bit
 1.78415 +  ** integer, then the EP_IntValue flag will have already been set */
 1.78416 +  assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
 1.78417 +           || sqlite3GetInt32(p->u.zToken, &rc)==0 );
 1.78418 +
 1.78419 +  if( p->flags & EP_IntValue ){
 1.78420 +    *pValue = p->u.iValue;
 1.78421 +    return 1;
 1.78422 +  }
 1.78423 +  switch( p->op ){
 1.78424 +    case TK_UPLUS: {
 1.78425 +      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
 1.78426 +      break;
 1.78427 +    }
 1.78428 +    case TK_UMINUS: {
 1.78429 +      int v;
 1.78430 +      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
 1.78431 +        assert( v!=(-2147483647-1) );
 1.78432 +        *pValue = -v;
 1.78433 +        rc = 1;
 1.78434 +      }
 1.78435 +      break;
 1.78436 +    }
 1.78437 +    default: break;
 1.78438 +  }
 1.78439 +  return rc;
 1.78440 +}
 1.78441 +
 1.78442 +/*
 1.78443 +** Return FALSE if there is no chance that the expression can be NULL.
 1.78444 +**
 1.78445 +** If the expression might be NULL or if the expression is too complex
 1.78446 +** to tell return TRUE.  
 1.78447 +**
 1.78448 +** This routine is used as an optimization, to skip OP_IsNull opcodes
 1.78449 +** when we know that a value cannot be NULL.  Hence, a false positive
 1.78450 +** (returning TRUE when in fact the expression can never be NULL) might
 1.78451 +** be a small performance hit but is otherwise harmless.  On the other
 1.78452 +** hand, a false negative (returning FALSE when the result could be NULL)
 1.78453 +** will likely result in an incorrect answer.  So when in doubt, return
 1.78454 +** TRUE.
 1.78455 +*/
 1.78456 +SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
 1.78457 +  u8 op;
 1.78458 +  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
 1.78459 +  op = p->op;
 1.78460 +  if( op==TK_REGISTER ) op = p->op2;
 1.78461 +  switch( op ){
 1.78462 +    case TK_INTEGER:
 1.78463 +    case TK_STRING:
 1.78464 +    case TK_FLOAT:
 1.78465 +    case TK_BLOB:
 1.78466 +      return 0;
 1.78467 +    default:
 1.78468 +      return 1;
 1.78469 +  }
 1.78470 +}
 1.78471 +
 1.78472 +/*
 1.78473 +** Return TRUE if the given expression is a constant which would be
 1.78474 +** unchanged by OP_Affinity with the affinity given in the second
 1.78475 +** argument.
 1.78476 +**
 1.78477 +** This routine is used to determine if the OP_Affinity operation
 1.78478 +** can be omitted.  When in doubt return FALSE.  A false negative
 1.78479 +** is harmless.  A false positive, however, can result in the wrong
 1.78480 +** answer.
 1.78481 +*/
 1.78482 +SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
 1.78483 +  u8 op;
 1.78484 +  if( aff==SQLITE_AFF_NONE ) return 1;
 1.78485 +  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
 1.78486 +  op = p->op;
 1.78487 +  if( op==TK_REGISTER ) op = p->op2;
 1.78488 +  switch( op ){
 1.78489 +    case TK_INTEGER: {
 1.78490 +      return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
 1.78491 +    }
 1.78492 +    case TK_FLOAT: {
 1.78493 +      return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
 1.78494 +    }
 1.78495 +    case TK_STRING: {
 1.78496 +      return aff==SQLITE_AFF_TEXT;
 1.78497 +    }
 1.78498 +    case TK_BLOB: {
 1.78499 +      return 1;
 1.78500 +    }
 1.78501 +    case TK_COLUMN: {
 1.78502 +      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
 1.78503 +      return p->iColumn<0
 1.78504 +          && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
 1.78505 +    }
 1.78506 +    default: {
 1.78507 +      return 0;
 1.78508 +    }
 1.78509 +  }
 1.78510 +}
 1.78511 +
 1.78512 +/*
 1.78513 +** Return TRUE if the given string is a row-id column name.
 1.78514 +*/
 1.78515 +SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
 1.78516 +  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
 1.78517 +  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
 1.78518 +  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
 1.78519 +  return 0;
 1.78520 +}
 1.78521 +
 1.78522 +/*
 1.78523 +** Return true if we are able to the IN operator optimization on a
 1.78524 +** query of the form
 1.78525 +**
 1.78526 +**       x IN (SELECT ...)
 1.78527 +**
 1.78528 +** Where the SELECT... clause is as specified by the parameter to this
 1.78529 +** routine.
 1.78530 +**
 1.78531 +** The Select object passed in has already been preprocessed and no
 1.78532 +** errors have been found.
 1.78533 +*/
 1.78534 +#ifndef SQLITE_OMIT_SUBQUERY
 1.78535 +static int isCandidateForInOpt(Select *p){
 1.78536 +  SrcList *pSrc;
 1.78537 +  ExprList *pEList;
 1.78538 +  Table *pTab;
 1.78539 +  if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
 1.78540 +  if( p->pPrior ) return 0;              /* Not a compound SELECT */
 1.78541 +  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
 1.78542 +    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
 1.78543 +    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
 1.78544 +    return 0; /* No DISTINCT keyword and no aggregate functions */
 1.78545 +  }
 1.78546 +  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
 1.78547 +  if( p->pLimit ) return 0;              /* Has no LIMIT clause */
 1.78548 +  assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
 1.78549 +  if( p->pWhere ) return 0;              /* Has no WHERE clause */
 1.78550 +  pSrc = p->pSrc;
 1.78551 +  assert( pSrc!=0 );
 1.78552 +  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
 1.78553 +  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
 1.78554 +  pTab = pSrc->a[0].pTab;
 1.78555 +  if( NEVER(pTab==0) ) return 0;
 1.78556 +  assert( pTab->pSelect==0 );            /* FROM clause is not a view */
 1.78557 +  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
 1.78558 +  pEList = p->pEList;
 1.78559 +  if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
 1.78560 +  if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
 1.78561 +  return 1;
 1.78562 +}
 1.78563 +#endif /* SQLITE_OMIT_SUBQUERY */
 1.78564 +
 1.78565 +/*
 1.78566 +** Code an OP_Once instruction and allocate space for its flag. Return the 
 1.78567 +** address of the new instruction.
 1.78568 +*/
 1.78569 +SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
 1.78570 +  Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
 1.78571 +  return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
 1.78572 +}
 1.78573 +
 1.78574 +/*
 1.78575 +** This function is used by the implementation of the IN (...) operator.
 1.78576 +** The pX parameter is the expression on the RHS of the IN operator, which
 1.78577 +** might be either a list of expressions or a subquery.
 1.78578 +**
 1.78579 +** The job of this routine is to find or create a b-tree object that can
 1.78580 +** be used either to test for membership in the RHS set or to iterate through
 1.78581 +** all members of the RHS set, skipping duplicates.
 1.78582 +**
 1.78583 +** A cursor is opened on the b-tree object that the RHS of the IN operator
 1.78584 +** and pX->iTable is set to the index of that cursor.
 1.78585 +**
 1.78586 +** The returned value of this function indicates the b-tree type, as follows:
 1.78587 +**
 1.78588 +**   IN_INDEX_ROWID      - The cursor was opened on a database table.
 1.78589 +**   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
 1.78590 +**   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
 1.78591 +**   IN_INDEX_EPH        - The cursor was opened on a specially created and
 1.78592 +**                         populated epheremal table.
 1.78593 +**
 1.78594 +** An existing b-tree might be used if the RHS expression pX is a simple
 1.78595 +** subquery such as:
 1.78596 +**
 1.78597 +**     SELECT <column> FROM <table>
 1.78598 +**
 1.78599 +** If the RHS of the IN operator is a list or a more complex subquery, then
 1.78600 +** an ephemeral table might need to be generated from the RHS and then
 1.78601 +** pX->iTable made to point to the ephermeral table instead of an
 1.78602 +** existing table.  
 1.78603 +**
 1.78604 +** If the prNotFound parameter is 0, then the b-tree will be used to iterate
 1.78605 +** through the set members, skipping any duplicates. In this case an
 1.78606 +** epheremal table must be used unless the selected <column> is guaranteed
 1.78607 +** to be unique - either because it is an INTEGER PRIMARY KEY or it
 1.78608 +** has a UNIQUE constraint or UNIQUE index.
 1.78609 +**
 1.78610 +** If the prNotFound parameter is not 0, then the b-tree will be used 
 1.78611 +** for fast set membership tests. In this case an epheremal table must 
 1.78612 +** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
 1.78613 +** be found with <column> as its left-most column.
 1.78614 +**
 1.78615 +** When the b-tree is being used for membership tests, the calling function
 1.78616 +** needs to know whether or not the structure contains an SQL NULL 
 1.78617 +** value in order to correctly evaluate expressions like "X IN (Y, Z)".
 1.78618 +** If there is any chance that the (...) might contain a NULL value at
 1.78619 +** runtime, then a register is allocated and the register number written
 1.78620 +** to *prNotFound. If there is no chance that the (...) contains a
 1.78621 +** NULL value, then *prNotFound is left unchanged.
 1.78622 +**
 1.78623 +** If a register is allocated and its location stored in *prNotFound, then
 1.78624 +** its initial value is NULL.  If the (...) does not remain constant
 1.78625 +** for the duration of the query (i.e. the SELECT within the (...)
 1.78626 +** is a correlated subquery) then the value of the allocated register is
 1.78627 +** reset to NULL each time the subquery is rerun. This allows the
 1.78628 +** caller to use vdbe code equivalent to the following:
 1.78629 +**
 1.78630 +**   if( register==NULL ){
 1.78631 +**     has_null = <test if data structure contains null>
 1.78632 +**     register = 1
 1.78633 +**   }
 1.78634 +**
 1.78635 +** in order to avoid running the <test if data structure contains null>
 1.78636 +** test more often than is necessary.
 1.78637 +*/
 1.78638 +#ifndef SQLITE_OMIT_SUBQUERY
 1.78639 +SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
 1.78640 +  Select *p;                            /* SELECT to the right of IN operator */
 1.78641 +  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
 1.78642 +  int iTab = pParse->nTab++;            /* Cursor of the RHS table */
 1.78643 +  int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
 1.78644 +  Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
 1.78645 +
 1.78646 +  assert( pX->op==TK_IN );
 1.78647 +
 1.78648 +  /* Check to see if an existing table or index can be used to
 1.78649 +  ** satisfy the query.  This is preferable to generating a new 
 1.78650 +  ** ephemeral table.
 1.78651 +  */
 1.78652 +  p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
 1.78653 +  if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
 1.78654 +    sqlite3 *db = pParse->db;              /* Database connection */
 1.78655 +    Table *pTab;                           /* Table <table>. */
 1.78656 +    Expr *pExpr;                           /* Expression <column> */
 1.78657 +    i16 iCol;                              /* Index of column <column> */
 1.78658 +    i16 iDb;                               /* Database idx for pTab */
 1.78659 +
 1.78660 +    assert( p );                        /* Because of isCandidateForInOpt(p) */
 1.78661 +    assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
 1.78662 +    assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
 1.78663 +    assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
 1.78664 +    pTab = p->pSrc->a[0].pTab;
 1.78665 +    pExpr = p->pEList->a[0].pExpr;
 1.78666 +    iCol = (i16)pExpr->iColumn;
 1.78667 +   
 1.78668 +    /* Code an OP_Transaction and OP_TableLock for <table>. */
 1.78669 +    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
 1.78670 +    sqlite3CodeVerifySchema(pParse, iDb);
 1.78671 +    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
 1.78672 +
 1.78673 +    /* This function is only called from two places. In both cases the vdbe
 1.78674 +    ** has already been allocated. So assume sqlite3GetVdbe() is always
 1.78675 +    ** successful here.
 1.78676 +    */
 1.78677 +    assert(v);
 1.78678 +    if( iCol<0 ){
 1.78679 +      int iAddr = sqlite3CodeOnce(pParse);
 1.78680 +      VdbeCoverage(v);
 1.78681 +
 1.78682 +      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
 1.78683 +      eType = IN_INDEX_ROWID;
 1.78684 +
 1.78685 +      sqlite3VdbeJumpHere(v, iAddr);
 1.78686 +    }else{
 1.78687 +      Index *pIdx;                         /* Iterator variable */
 1.78688 +
 1.78689 +      /* The collation sequence used by the comparison. If an index is to
 1.78690 +      ** be used in place of a temp-table, it must be ordered according
 1.78691 +      ** to this collation sequence.  */
 1.78692 +      CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
 1.78693 +
 1.78694 +      /* Check that the affinity that will be used to perform the 
 1.78695 +      ** comparison is the same as the affinity of the column. If
 1.78696 +      ** it is not, it is not possible to use any index.
 1.78697 +      */
 1.78698 +      int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
 1.78699 +
 1.78700 +      for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
 1.78701 +        if( (pIdx->aiColumn[0]==iCol)
 1.78702 +         && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
 1.78703 +         && (!mustBeUnique || (pIdx->nKeyCol==1 && pIdx->onError!=OE_None))
 1.78704 +        ){
 1.78705 +          int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
 1.78706 +          sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
 1.78707 +          sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
 1.78708 +          VdbeComment((v, "%s", pIdx->zName));
 1.78709 +          assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
 1.78710 +          eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
 1.78711 +
 1.78712 +          if( prNotFound && !pTab->aCol[iCol].notNull ){
 1.78713 +            *prNotFound = ++pParse->nMem;
 1.78714 +            sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
 1.78715 +          }
 1.78716 +          sqlite3VdbeJumpHere(v, iAddr);
 1.78717 +        }
 1.78718 +      }
 1.78719 +    }
 1.78720 +  }
 1.78721 +
 1.78722 +  if( eType==0 ){
 1.78723 +    /* Could not found an existing table or index to use as the RHS b-tree.
 1.78724 +    ** We will have to generate an ephemeral table to do the job.
 1.78725 +    */
 1.78726 +    u32 savedNQueryLoop = pParse->nQueryLoop;
 1.78727 +    int rMayHaveNull = 0;
 1.78728 +    eType = IN_INDEX_EPH;
 1.78729 +    if( prNotFound ){
 1.78730 +      *prNotFound = rMayHaveNull = ++pParse->nMem;
 1.78731 +      sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
 1.78732 +    }else{
 1.78733 +      testcase( pParse->nQueryLoop>0 );
 1.78734 +      pParse->nQueryLoop = 0;
 1.78735 +      if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
 1.78736 +        eType = IN_INDEX_ROWID;
 1.78737 +      }
 1.78738 +    }
 1.78739 +    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
 1.78740 +    pParse->nQueryLoop = savedNQueryLoop;
 1.78741 +  }else{
 1.78742 +    pX->iTable = iTab;
 1.78743 +  }
 1.78744 +  return eType;
 1.78745 +}
 1.78746 +#endif
 1.78747 +
 1.78748 +/*
 1.78749 +** Generate code for scalar subqueries used as a subquery expression, EXISTS,
 1.78750 +** or IN operators.  Examples:
 1.78751 +**
 1.78752 +**     (SELECT a FROM b)          -- subquery
 1.78753 +**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
 1.78754 +**     x IN (4,5,11)              -- IN operator with list on right-hand side
 1.78755 +**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
 1.78756 +**
 1.78757 +** The pExpr parameter describes the expression that contains the IN
 1.78758 +** operator or subquery.
 1.78759 +**
 1.78760 +** If parameter isRowid is non-zero, then expression pExpr is guaranteed
 1.78761 +** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
 1.78762 +** to some integer key column of a table B-Tree. In this case, use an
 1.78763 +** intkey B-Tree to store the set of IN(...) values instead of the usual
 1.78764 +** (slower) variable length keys B-Tree.
 1.78765 +**
 1.78766 +** If rMayHaveNull is non-zero, that means that the operation is an IN
 1.78767 +** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
 1.78768 +** Furthermore, the IN is in a WHERE clause and that we really want
 1.78769 +** to iterate over the RHS of the IN operator in order to quickly locate
 1.78770 +** all corresponding LHS elements.  All this routine does is initialize
 1.78771 +** the register given by rMayHaveNull to NULL.  Calling routines will take
 1.78772 +** care of changing this register value to non-NULL if the RHS is NULL-free.
 1.78773 +**
 1.78774 +** If rMayHaveNull is zero, that means that the subquery is being used
 1.78775 +** for membership testing only.  There is no need to initialize any
 1.78776 +** registers to indicate the presence or absence of NULLs on the RHS.
 1.78777 +**
 1.78778 +** For a SELECT or EXISTS operator, return the register that holds the
 1.78779 +** result.  For IN operators or if an error occurs, the return value is 0.
 1.78780 +*/
 1.78781 +#ifndef SQLITE_OMIT_SUBQUERY
 1.78782 +SQLITE_PRIVATE int sqlite3CodeSubselect(
 1.78783 +  Parse *pParse,          /* Parsing context */
 1.78784 +  Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
 1.78785 +  int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
 1.78786 +  int isRowid             /* If true, LHS of IN operator is a rowid */
 1.78787 +){
 1.78788 +  int testAddr = -1;                      /* One-time test address */
 1.78789 +  int rReg = 0;                           /* Register storing resulting */
 1.78790 +  Vdbe *v = sqlite3GetVdbe(pParse);
 1.78791 +  if( NEVER(v==0) ) return 0;
 1.78792 +  sqlite3ExprCachePush(pParse);
 1.78793 +
 1.78794 +  /* This code must be run in its entirety every time it is encountered
 1.78795 +  ** if any of the following is true:
 1.78796 +  **
 1.78797 +  **    *  The right-hand side is a correlated subquery
 1.78798 +  **    *  The right-hand side is an expression list containing variables
 1.78799 +  **    *  We are inside a trigger
 1.78800 +  **
 1.78801 +  ** If all of the above are false, then we can run this code just once
 1.78802 +  ** save the results, and reuse the same result on subsequent invocations.
 1.78803 +  */
 1.78804 +  if( !ExprHasProperty(pExpr, EP_VarSelect) ){
 1.78805 +    testAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
 1.78806 +  }
 1.78807 +
 1.78808 +#ifndef SQLITE_OMIT_EXPLAIN
 1.78809 +  if( pParse->explain==2 ){
 1.78810 +    char *zMsg = sqlite3MPrintf(
 1.78811 +        pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
 1.78812 +        pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
 1.78813 +    );
 1.78814 +    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
 1.78815 +  }
 1.78816 +#endif
 1.78817 +
 1.78818 +  switch( pExpr->op ){
 1.78819 +    case TK_IN: {
 1.78820 +      char affinity;              /* Affinity of the LHS of the IN */
 1.78821 +      int addr;                   /* Address of OP_OpenEphemeral instruction */
 1.78822 +      Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
 1.78823 +      KeyInfo *pKeyInfo = 0;      /* Key information */
 1.78824 +
 1.78825 +      if( rMayHaveNull ){
 1.78826 +        sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
 1.78827 +      }
 1.78828 +
 1.78829 +      affinity = sqlite3ExprAffinity(pLeft);
 1.78830 +
 1.78831 +      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
 1.78832 +      ** expression it is handled the same way.  An ephemeral table is 
 1.78833 +      ** filled with single-field index keys representing the results
 1.78834 +      ** from the SELECT or the <exprlist>.
 1.78835 +      **
 1.78836 +      ** If the 'x' expression is a column value, or the SELECT...
 1.78837 +      ** statement returns a column value, then the affinity of that
 1.78838 +      ** column is used to build the index keys. If both 'x' and the
 1.78839 +      ** SELECT... statement are columns, then numeric affinity is used
 1.78840 +      ** if either column has NUMERIC or INTEGER affinity. If neither
 1.78841 +      ** 'x' nor the SELECT... statement are columns, then numeric affinity
 1.78842 +      ** is used.
 1.78843 +      */
 1.78844 +      pExpr->iTable = pParse->nTab++;
 1.78845 +      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
 1.78846 +      pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
 1.78847 +
 1.78848 +      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
 1.78849 +        /* Case 1:     expr IN (SELECT ...)
 1.78850 +        **
 1.78851 +        ** Generate code to write the results of the select into the temporary
 1.78852 +        ** table allocated and opened above.
 1.78853 +        */
 1.78854 +        SelectDest dest;
 1.78855 +        ExprList *pEList;
 1.78856 +
 1.78857 +        assert( !isRowid );
 1.78858 +        sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
 1.78859 +        dest.affSdst = (u8)affinity;
 1.78860 +        assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
 1.78861 +        pExpr->x.pSelect->iLimit = 0;
 1.78862 +        testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
 1.78863 +        if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
 1.78864 +          sqlite3KeyInfoUnref(pKeyInfo);
 1.78865 +          return 0;
 1.78866 +        }
 1.78867 +        pEList = pExpr->x.pSelect->pEList;
 1.78868 +        assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
 1.78869 +        assert( pEList!=0 );
 1.78870 +        assert( pEList->nExpr>0 );
 1.78871 +        assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
 1.78872 +        pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
 1.78873 +                                                         pEList->a[0].pExpr);
 1.78874 +      }else if( ALWAYS(pExpr->x.pList!=0) ){
 1.78875 +        /* Case 2:     expr IN (exprlist)
 1.78876 +        **
 1.78877 +        ** For each expression, build an index key from the evaluation and
 1.78878 +        ** store it in the temporary table. If <expr> is a column, then use
 1.78879 +        ** that columns affinity when building index keys. If <expr> is not
 1.78880 +        ** a column, use numeric affinity.
 1.78881 +        */
 1.78882 +        int i;
 1.78883 +        ExprList *pList = pExpr->x.pList;
 1.78884 +        struct ExprList_item *pItem;
 1.78885 +        int r1, r2, r3;
 1.78886 +
 1.78887 +        if( !affinity ){
 1.78888 +          affinity = SQLITE_AFF_NONE;
 1.78889 +        }
 1.78890 +        if( pKeyInfo ){
 1.78891 +          assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
 1.78892 +          pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
 1.78893 +        }
 1.78894 +
 1.78895 +        /* Loop through each expression in <exprlist>. */
 1.78896 +        r1 = sqlite3GetTempReg(pParse);
 1.78897 +        r2 = sqlite3GetTempReg(pParse);
 1.78898 +        sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
 1.78899 +        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
 1.78900 +          Expr *pE2 = pItem->pExpr;
 1.78901 +          int iValToIns;
 1.78902 +
 1.78903 +          /* If the expression is not constant then we will need to
 1.78904 +          ** disable the test that was generated above that makes sure
 1.78905 +          ** this code only executes once.  Because for a non-constant
 1.78906 +          ** expression we need to rerun this code each time.
 1.78907 +          */
 1.78908 +          if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
 1.78909 +            sqlite3VdbeChangeToNoop(v, testAddr);
 1.78910 +            testAddr = -1;
 1.78911 +          }
 1.78912 +
 1.78913 +          /* Evaluate the expression and insert it into the temp table */
 1.78914 +          if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
 1.78915 +            sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
 1.78916 +          }else{
 1.78917 +            r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
 1.78918 +            if( isRowid ){
 1.78919 +              sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
 1.78920 +                                sqlite3VdbeCurrentAddr(v)+2);
 1.78921 +              VdbeCoverage(v);
 1.78922 +              sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
 1.78923 +            }else{
 1.78924 +              sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
 1.78925 +              sqlite3ExprCacheAffinityChange(pParse, r3, 1);
 1.78926 +              sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
 1.78927 +            }
 1.78928 +          }
 1.78929 +        }
 1.78930 +        sqlite3ReleaseTempReg(pParse, r1);
 1.78931 +        sqlite3ReleaseTempReg(pParse, r2);
 1.78932 +      }
 1.78933 +      if( pKeyInfo ){
 1.78934 +        sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
 1.78935 +      }
 1.78936 +      break;
 1.78937 +    }
 1.78938 +
 1.78939 +    case TK_EXISTS:
 1.78940 +    case TK_SELECT:
 1.78941 +    default: {
 1.78942 +      /* If this has to be a scalar SELECT.  Generate code to put the
 1.78943 +      ** value of this select in a memory cell and record the number
 1.78944 +      ** of the memory cell in iColumn.  If this is an EXISTS, write
 1.78945 +      ** an integer 0 (not exists) or 1 (exists) into a memory cell
 1.78946 +      ** and record that memory cell in iColumn.
 1.78947 +      */
 1.78948 +      Select *pSel;                         /* SELECT statement to encode */
 1.78949 +      SelectDest dest;                      /* How to deal with SELECt result */
 1.78950 +
 1.78951 +      testcase( pExpr->op==TK_EXISTS );
 1.78952 +      testcase( pExpr->op==TK_SELECT );
 1.78953 +      assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
 1.78954 +
 1.78955 +      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
 1.78956 +      pSel = pExpr->x.pSelect;
 1.78957 +      sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
 1.78958 +      if( pExpr->op==TK_SELECT ){
 1.78959 +        dest.eDest = SRT_Mem;
 1.78960 +        sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
 1.78961 +        VdbeComment((v, "Init subquery result"));
 1.78962 +      }else{
 1.78963 +        dest.eDest = SRT_Exists;
 1.78964 +        sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
 1.78965 +        VdbeComment((v, "Init EXISTS result"));
 1.78966 +      }
 1.78967 +      sqlite3ExprDelete(pParse->db, pSel->pLimit);
 1.78968 +      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
 1.78969 +                                  &sqlite3IntTokens[1]);
 1.78970 +      pSel->iLimit = 0;
 1.78971 +      if( sqlite3Select(pParse, pSel, &dest) ){
 1.78972 +        return 0;
 1.78973 +      }
 1.78974 +      rReg = dest.iSDParm;
 1.78975 +      ExprSetVVAProperty(pExpr, EP_NoReduce);
 1.78976 +      break;
 1.78977 +    }
 1.78978 +  }
 1.78979 +
 1.78980 +  if( testAddr>=0 ){
 1.78981 +    sqlite3VdbeJumpHere(v, testAddr);
 1.78982 +  }
 1.78983 +  sqlite3ExprCachePop(pParse, 1);
 1.78984 +
 1.78985 +  return rReg;
 1.78986 +}
 1.78987 +#endif /* SQLITE_OMIT_SUBQUERY */
 1.78988 +
 1.78989 +#ifndef SQLITE_OMIT_SUBQUERY
 1.78990 +/*
 1.78991 +** Generate code for an IN expression.
 1.78992 +**
 1.78993 +**      x IN (SELECT ...)
 1.78994 +**      x IN (value, value, ...)
 1.78995 +**
 1.78996 +** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
 1.78997 +** is an array of zero or more values.  The expression is true if the LHS is
 1.78998 +** contained within the RHS.  The value of the expression is unknown (NULL)
 1.78999 +** if the LHS is NULL or if the LHS is not contained within the RHS and the
 1.79000 +** RHS contains one or more NULL values.
 1.79001 +**
 1.79002 +** This routine generates code will jump to destIfFalse if the LHS is not 
 1.79003 +** contained within the RHS.  If due to NULLs we cannot determine if the LHS
 1.79004 +** is contained in the RHS then jump to destIfNull.  If the LHS is contained
 1.79005 +** within the RHS then fall through.
 1.79006 +*/
 1.79007 +static void sqlite3ExprCodeIN(
 1.79008 +  Parse *pParse,        /* Parsing and code generating context */
 1.79009 +  Expr *pExpr,          /* The IN expression */
 1.79010 +  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
 1.79011 +  int destIfNull        /* Jump here if the results are unknown due to NULLs */
 1.79012 +){
 1.79013 +  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
 1.79014 +  char affinity;        /* Comparison affinity to use */
 1.79015 +  int eType;            /* Type of the RHS */
 1.79016 +  int r1;               /* Temporary use register */
 1.79017 +  Vdbe *v;              /* Statement under construction */
 1.79018 +
 1.79019 +  /* Compute the RHS.   After this step, the table with cursor
 1.79020 +  ** pExpr->iTable will contains the values that make up the RHS.
 1.79021 +  */
 1.79022 +  v = pParse->pVdbe;
 1.79023 +  assert( v!=0 );       /* OOM detected prior to this routine */
 1.79024 +  VdbeNoopComment((v, "begin IN expr"));
 1.79025 +  eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
 1.79026 +
 1.79027 +  /* Figure out the affinity to use to create a key from the results
 1.79028 +  ** of the expression. affinityStr stores a static string suitable for
 1.79029 +  ** P4 of OP_MakeRecord.
 1.79030 +  */
 1.79031 +  affinity = comparisonAffinity(pExpr);
 1.79032 +
 1.79033 +  /* Code the LHS, the <expr> from "<expr> IN (...)".
 1.79034 +  */
 1.79035 +  sqlite3ExprCachePush(pParse);
 1.79036 +  r1 = sqlite3GetTempReg(pParse);
 1.79037 +  sqlite3ExprCode(pParse, pExpr->pLeft, r1);
 1.79038 +
 1.79039 +  /* If the LHS is NULL, then the result is either false or NULL depending
 1.79040 +  ** on whether the RHS is empty or not, respectively.
 1.79041 +  */
 1.79042 +  if( destIfNull==destIfFalse ){
 1.79043 +    /* Shortcut for the common case where the false and NULL outcomes are
 1.79044 +    ** the same. */
 1.79045 +    sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
 1.79046 +  }else{
 1.79047 +    int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
 1.79048 +    sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
 1.79049 +    VdbeCoverage(v);
 1.79050 +    sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
 1.79051 +    sqlite3VdbeJumpHere(v, addr1);
 1.79052 +  }
 1.79053 +
 1.79054 +  if( eType==IN_INDEX_ROWID ){
 1.79055 +    /* In this case, the RHS is the ROWID of table b-tree
 1.79056 +    */
 1.79057 +    sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
 1.79058 +    sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
 1.79059 +    VdbeCoverage(v);
 1.79060 +  }else{
 1.79061 +    /* In this case, the RHS is an index b-tree.
 1.79062 +    */
 1.79063 +    sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
 1.79064 +
 1.79065 +    /* If the set membership test fails, then the result of the 
 1.79066 +    ** "x IN (...)" expression must be either 0 or NULL. If the set
 1.79067 +    ** contains no NULL values, then the result is 0. If the set 
 1.79068 +    ** contains one or more NULL values, then the result of the
 1.79069 +    ** expression is also NULL.
 1.79070 +    */
 1.79071 +    if( rRhsHasNull==0 || destIfFalse==destIfNull ){
 1.79072 +      /* This branch runs if it is known at compile time that the RHS
 1.79073 +      ** cannot contain NULL values. This happens as the result
 1.79074 +      ** of a "NOT NULL" constraint in the database schema.
 1.79075 +      **
 1.79076 +      ** Also run this branch if NULL is equivalent to FALSE
 1.79077 +      ** for this particular IN operator.
 1.79078 +      */
 1.79079 +      sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
 1.79080 +      VdbeCoverage(v);
 1.79081 +    }else{
 1.79082 +      /* In this branch, the RHS of the IN might contain a NULL and
 1.79083 +      ** the presence of a NULL on the RHS makes a difference in the
 1.79084 +      ** outcome.
 1.79085 +      */
 1.79086 +      int j1, j2;
 1.79087 +
 1.79088 +      /* First check to see if the LHS is contained in the RHS.  If so,
 1.79089 +      ** then the presence of NULLs in the RHS does not matter, so jump
 1.79090 +      ** over all of the code that follows.
 1.79091 +      */
 1.79092 +      j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
 1.79093 +      VdbeCoverage(v);
 1.79094 +
 1.79095 +      /* Here we begin generating code that runs if the LHS is not
 1.79096 +      ** contained within the RHS.  Generate additional code that
 1.79097 +      ** tests the RHS for NULLs.  If the RHS contains a NULL then
 1.79098 +      ** jump to destIfNull.  If there are no NULLs in the RHS then
 1.79099 +      ** jump to destIfFalse.
 1.79100 +      */
 1.79101 +      sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull); VdbeCoverage(v);
 1.79102 +      sqlite3VdbeAddOp2(v, OP_IfNot, rRhsHasNull, destIfFalse); VdbeCoverage(v);
 1.79103 +      j2 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
 1.79104 +      VdbeCoverage(v);
 1.79105 +      sqlite3VdbeAddOp2(v, OP_Integer, 0, rRhsHasNull);
 1.79106 +      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
 1.79107 +      sqlite3VdbeJumpHere(v, j2);
 1.79108 +      sqlite3VdbeAddOp2(v, OP_Integer, 1, rRhsHasNull);
 1.79109 +      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
 1.79110 +
 1.79111 +      /* The OP_Found at the top of this branch jumps here when true, 
 1.79112 +      ** causing the overall IN expression evaluation to fall through.
 1.79113 +      */
 1.79114 +      sqlite3VdbeJumpHere(v, j1);
 1.79115 +    }
 1.79116 +  }
 1.79117 +  sqlite3ReleaseTempReg(pParse, r1);
 1.79118 +  sqlite3ExprCachePop(pParse, 1);
 1.79119 +  VdbeComment((v, "end IN expr"));
 1.79120 +}
 1.79121 +#endif /* SQLITE_OMIT_SUBQUERY */
 1.79122 +
 1.79123 +/*
 1.79124 +** Duplicate an 8-byte value
 1.79125 +*/
 1.79126 +static char *dup8bytes(Vdbe *v, const char *in){
 1.79127 +  char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
 1.79128 +  if( out ){
 1.79129 +    memcpy(out, in, 8);
 1.79130 +  }
 1.79131 +  return out;
 1.79132 +}
 1.79133 +
 1.79134 +#ifndef SQLITE_OMIT_FLOATING_POINT
 1.79135 +/*
 1.79136 +** Generate an instruction that will put the floating point
 1.79137 +** value described by z[0..n-1] into register iMem.
 1.79138 +**
 1.79139 +** The z[] string will probably not be zero-terminated.  But the 
 1.79140 +** z[n] character is guaranteed to be something that does not look
 1.79141 +** like the continuation of the number.
 1.79142 +*/
 1.79143 +static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
 1.79144 +  if( ALWAYS(z!=0) ){
 1.79145 +    double value;
 1.79146 +    char *zV;
 1.79147 +    sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
 1.79148 +    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
 1.79149 +    if( negateFlag ) value = -value;
 1.79150 +    zV = dup8bytes(v, (char*)&value);
 1.79151 +    sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
 1.79152 +  }
 1.79153 +}
 1.79154 +#endif
 1.79155 +
 1.79156 +
 1.79157 +/*
 1.79158 +** Generate an instruction that will put the integer describe by
 1.79159 +** text z[0..n-1] into register iMem.
 1.79160 +**
 1.79161 +** Expr.u.zToken is always UTF8 and zero-terminated.
 1.79162 +*/
 1.79163 +static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
 1.79164 +  Vdbe *v = pParse->pVdbe;
 1.79165 +  if( pExpr->flags & EP_IntValue ){
 1.79166 +    int i = pExpr->u.iValue;
 1.79167 +    assert( i>=0 );
 1.79168 +    if( negFlag ) i = -i;
 1.79169 +    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
 1.79170 +  }else{
 1.79171 +    int c;
 1.79172 +    i64 value;
 1.79173 +    const char *z = pExpr->u.zToken;
 1.79174 +    assert( z!=0 );
 1.79175 +    c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
 1.79176 +    if( c==0 || (c==2 && negFlag) ){
 1.79177 +      char *zV;
 1.79178 +      if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
 1.79179 +      zV = dup8bytes(v, (char*)&value);
 1.79180 +      sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
 1.79181 +    }else{
 1.79182 +#ifdef SQLITE_OMIT_FLOATING_POINT
 1.79183 +      sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
 1.79184 +#else
 1.79185 +      codeReal(v, z, negFlag, iMem);
 1.79186 +#endif
 1.79187 +    }
 1.79188 +  }
 1.79189 +}
 1.79190 +
 1.79191 +/*
 1.79192 +** Clear a cache entry.
 1.79193 +*/
 1.79194 +static void cacheEntryClear(Parse *pParse, struct yColCache *p){
 1.79195 +  if( p->tempReg ){
 1.79196 +    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
 1.79197 +      pParse->aTempReg[pParse->nTempReg++] = p->iReg;
 1.79198 +    }
 1.79199 +    p->tempReg = 0;
 1.79200 +  }
 1.79201 +}
 1.79202 +
 1.79203 +
 1.79204 +/*
 1.79205 +** Record in the column cache that a particular column from a
 1.79206 +** particular table is stored in a particular register.
 1.79207 +*/
 1.79208 +SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
 1.79209 +  int i;
 1.79210 +  int minLru;
 1.79211 +  int idxLru;
 1.79212 +  struct yColCache *p;
 1.79213 +
 1.79214 +  assert( iReg>0 );  /* Register numbers are always positive */
 1.79215 +  assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
 1.79216 +
 1.79217 +  /* The SQLITE_ColumnCache flag disables the column cache.  This is used
 1.79218 +  ** for testing only - to verify that SQLite always gets the same answer
 1.79219 +  ** with and without the column cache.
 1.79220 +  */
 1.79221 +  if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
 1.79222 +
 1.79223 +  /* First replace any existing entry.
 1.79224 +  **
 1.79225 +  ** Actually, the way the column cache is currently used, we are guaranteed
 1.79226 +  ** that the object will never already be in cache.  Verify this guarantee.
 1.79227 +  */
 1.79228 +#ifndef NDEBUG
 1.79229 +  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
 1.79230 +    assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
 1.79231 +  }
 1.79232 +#endif
 1.79233 +
 1.79234 +  /* Find an empty slot and replace it */
 1.79235 +  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
 1.79236 +    if( p->iReg==0 ){
 1.79237 +      p->iLevel = pParse->iCacheLevel;
 1.79238 +      p->iTable = iTab;
 1.79239 +      p->iColumn = iCol;
 1.79240 +      p->iReg = iReg;
 1.79241 +      p->tempReg = 0;
 1.79242 +      p->lru = pParse->iCacheCnt++;
 1.79243 +      return;
 1.79244 +    }
 1.79245 +  }
 1.79246 +
 1.79247 +  /* Replace the last recently used */
 1.79248 +  minLru = 0x7fffffff;
 1.79249 +  idxLru = -1;
 1.79250 +  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
 1.79251 +    if( p->lru<minLru ){
 1.79252 +      idxLru = i;
 1.79253 +      minLru = p->lru;
 1.79254 +    }
 1.79255 +  }
 1.79256 +  if( ALWAYS(idxLru>=0) ){
 1.79257 +    p = &pParse->aColCache[idxLru];
 1.79258 +    p->iLevel = pParse->iCacheLevel;
 1.79259 +    p->iTable = iTab;
 1.79260 +    p->iColumn = iCol;
 1.79261 +    p->iReg = iReg;
 1.79262 +    p->tempReg = 0;
 1.79263 +    p->lru = pParse->iCacheCnt++;
 1.79264 +    return;
 1.79265 +  }
 1.79266 +}
 1.79267 +
 1.79268 +/*
 1.79269 +** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
 1.79270 +** Purge the range of registers from the column cache.
 1.79271 +*/
 1.79272 +SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
 1.79273 +  int i;
 1.79274 +  int iLast = iReg + nReg - 1;
 1.79275 +  struct yColCache *p;
 1.79276 +  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
 1.79277 +    int r = p->iReg;
 1.79278 +    if( r>=iReg && r<=iLast ){
 1.79279 +      cacheEntryClear(pParse, p);
 1.79280 +      p->iReg = 0;
 1.79281 +    }
 1.79282 +  }
 1.79283 +}
 1.79284 +
 1.79285 +/*
 1.79286 +** Remember the current column cache context.  Any new entries added
 1.79287 +** added to the column cache after this call are removed when the
 1.79288 +** corresponding pop occurs.
 1.79289 +*/
 1.79290 +SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
 1.79291 +  pParse->iCacheLevel++;
 1.79292 +#ifdef SQLITE_DEBUG
 1.79293 +  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
 1.79294 +    printf("PUSH to %d\n", pParse->iCacheLevel);
 1.79295 +  }
 1.79296 +#endif
 1.79297 +}
 1.79298 +
 1.79299 +/*
 1.79300 +** Remove from the column cache any entries that were added since the
 1.79301 +** the previous N Push operations.  In other words, restore the cache
 1.79302 +** to the state it was in N Pushes ago.
 1.79303 +*/
 1.79304 +SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
 1.79305 +  int i;
 1.79306 +  struct yColCache *p;
 1.79307 +  assert( N>0 );
 1.79308 +  assert( pParse->iCacheLevel>=N );
 1.79309 +  pParse->iCacheLevel -= N;
 1.79310 +#ifdef SQLITE_DEBUG
 1.79311 +  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
 1.79312 +    printf("POP  to %d\n", pParse->iCacheLevel);
 1.79313 +  }
 1.79314 +#endif
 1.79315 +  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
 1.79316 +    if( p->iReg && p->iLevel>pParse->iCacheLevel ){
 1.79317 +      cacheEntryClear(pParse, p);
 1.79318 +      p->iReg = 0;
 1.79319 +    }
 1.79320 +  }
 1.79321 +}
 1.79322 +
 1.79323 +/*
 1.79324 +** When a cached column is reused, make sure that its register is
 1.79325 +** no longer available as a temp register.  ticket #3879:  that same
 1.79326 +** register might be in the cache in multiple places, so be sure to
 1.79327 +** get them all.
 1.79328 +*/
 1.79329 +static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
 1.79330 +  int i;
 1.79331 +  struct yColCache *p;
 1.79332 +  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
 1.79333 +    if( p->iReg==iReg ){
 1.79334 +      p->tempReg = 0;
 1.79335 +    }
 1.79336 +  }
 1.79337 +}
 1.79338 +
 1.79339 +/*
 1.79340 +** Generate code to extract the value of the iCol-th column of a table.
 1.79341 +*/
 1.79342 +SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
 1.79343 +  Vdbe *v,        /* The VDBE under construction */
 1.79344 +  Table *pTab,    /* The table containing the value */
 1.79345 +  int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
 1.79346 +  int iCol,       /* Index of the column to extract */
 1.79347 +  int regOut      /* Extract the value into this register */
 1.79348 +){
 1.79349 +  if( iCol<0 || iCol==pTab->iPKey ){
 1.79350 +    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
 1.79351 +  }else{
 1.79352 +    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
 1.79353 +    int x = iCol;
 1.79354 +    if( !HasRowid(pTab) ){
 1.79355 +      x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
 1.79356 +    }
 1.79357 +    sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
 1.79358 +  }
 1.79359 +  if( iCol>=0 ){
 1.79360 +    sqlite3ColumnDefault(v, pTab, iCol, regOut);
 1.79361 +  }
 1.79362 +}
 1.79363 +
 1.79364 +/*
 1.79365 +** Generate code that will extract the iColumn-th column from
 1.79366 +** table pTab and store the column value in a register.  An effort
 1.79367 +** is made to store the column value in register iReg, but this is
 1.79368 +** not guaranteed.  The location of the column value is returned.
 1.79369 +**
 1.79370 +** There must be an open cursor to pTab in iTable when this routine
 1.79371 +** is called.  If iColumn<0 then code is generated that extracts the rowid.
 1.79372 +*/
 1.79373 +SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
 1.79374 +  Parse *pParse,   /* Parsing and code generating context */
 1.79375 +  Table *pTab,     /* Description of the table we are reading from */
 1.79376 +  int iColumn,     /* Index of the table column */
 1.79377 +  int iTable,      /* The cursor pointing to the table */
 1.79378 +  int iReg,        /* Store results here */
 1.79379 +  u8 p5            /* P5 value for OP_Column */
 1.79380 +){
 1.79381 +  Vdbe *v = pParse->pVdbe;
 1.79382 +  int i;
 1.79383 +  struct yColCache *p;
 1.79384 +
 1.79385 +  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
 1.79386 +    if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
 1.79387 +      p->lru = pParse->iCacheCnt++;
 1.79388 +      sqlite3ExprCachePinRegister(pParse, p->iReg);
 1.79389 +      return p->iReg;
 1.79390 +    }
 1.79391 +  }  
 1.79392 +  assert( v!=0 );
 1.79393 +  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
 1.79394 +  if( p5 ){
 1.79395 +    sqlite3VdbeChangeP5(v, p5);
 1.79396 +  }else{   
 1.79397 +    sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
 1.79398 +  }
 1.79399 +  return iReg;
 1.79400 +}
 1.79401 +
 1.79402 +/*
 1.79403 +** Clear all column cache entries.
 1.79404 +*/
 1.79405 +SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
 1.79406 +  int i;
 1.79407 +  struct yColCache *p;
 1.79408 +
 1.79409 +#if SQLITE_DEBUG
 1.79410 +  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
 1.79411 +    printf("CLEAR\n");
 1.79412 +  }
 1.79413 +#endif
 1.79414 +  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
 1.79415 +    if( p->iReg ){
 1.79416 +      cacheEntryClear(pParse, p);
 1.79417 +      p->iReg = 0;
 1.79418 +    }
 1.79419 +  }
 1.79420 +}
 1.79421 +
 1.79422 +/*
 1.79423 +** Record the fact that an affinity change has occurred on iCount
 1.79424 +** registers starting with iStart.
 1.79425 +*/
 1.79426 +SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
 1.79427 +  sqlite3ExprCacheRemove(pParse, iStart, iCount);
 1.79428 +}
 1.79429 +
 1.79430 +/*
 1.79431 +** Generate code to move content from registers iFrom...iFrom+nReg-1
 1.79432 +** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
 1.79433 +*/
 1.79434 +SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
 1.79435 +  int i;
 1.79436 +  struct yColCache *p;
 1.79437 +  assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
 1.79438 +  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1);
 1.79439 +  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
 1.79440 +    int x = p->iReg;
 1.79441 +    if( x>=iFrom && x<iFrom+nReg ){
 1.79442 +      p->iReg += iTo-iFrom;
 1.79443 +    }
 1.79444 +  }
 1.79445 +}
 1.79446 +
 1.79447 +#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
 1.79448 +/*
 1.79449 +** Return true if any register in the range iFrom..iTo (inclusive)
 1.79450 +** is used as part of the column cache.
 1.79451 +**
 1.79452 +** This routine is used within assert() and testcase() macros only
 1.79453 +** and does not appear in a normal build.
 1.79454 +*/
 1.79455 +static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
 1.79456 +  int i;
 1.79457 +  struct yColCache *p;
 1.79458 +  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
 1.79459 +    int r = p->iReg;
 1.79460 +    if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
 1.79461 +  }
 1.79462 +  return 0;
 1.79463 +}
 1.79464 +#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
 1.79465 +
 1.79466 +/*
 1.79467 +** Convert an expression node to a TK_REGISTER
 1.79468 +*/
 1.79469 +static void exprToRegister(Expr *p, int iReg){
 1.79470 +  p->op2 = p->op;
 1.79471 +  p->op = TK_REGISTER;
 1.79472 +  p->iTable = iReg;
 1.79473 +  ExprClearProperty(p, EP_Skip);
 1.79474 +}
 1.79475 +
 1.79476 +/*
 1.79477 +** Generate code into the current Vdbe to evaluate the given
 1.79478 +** expression.  Attempt to store the results in register "target".
 1.79479 +** Return the register where results are stored.
 1.79480 +**
 1.79481 +** With this routine, there is no guarantee that results will
 1.79482 +** be stored in target.  The result might be stored in some other
 1.79483 +** register if it is convenient to do so.  The calling function
 1.79484 +** must check the return code and move the results to the desired
 1.79485 +** register.
 1.79486 +*/
 1.79487 +SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
 1.79488 +  Vdbe *v = pParse->pVdbe;  /* The VM under construction */
 1.79489 +  int op;                   /* The opcode being coded */
 1.79490 +  int inReg = target;       /* Results stored in register inReg */
 1.79491 +  int regFree1 = 0;         /* If non-zero free this temporary register */
 1.79492 +  int regFree2 = 0;         /* If non-zero free this temporary register */
 1.79493 +  int r1, r2, r3, r4;       /* Various register numbers */
 1.79494 +  sqlite3 *db = pParse->db; /* The database connection */
 1.79495 +  Expr tempX;               /* Temporary expression node */
 1.79496 +
 1.79497 +  assert( target>0 && target<=pParse->nMem );
 1.79498 +  if( v==0 ){
 1.79499 +    assert( pParse->db->mallocFailed );
 1.79500 +    return 0;
 1.79501 +  }
 1.79502 +
 1.79503 +  if( pExpr==0 ){
 1.79504 +    op = TK_NULL;
 1.79505 +  }else{
 1.79506 +    op = pExpr->op;
 1.79507 +  }
 1.79508 +  switch( op ){
 1.79509 +    case TK_AGG_COLUMN: {
 1.79510 +      AggInfo *pAggInfo = pExpr->pAggInfo;
 1.79511 +      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
 1.79512 +      if( !pAggInfo->directMode ){
 1.79513 +        assert( pCol->iMem>0 );
 1.79514 +        inReg = pCol->iMem;
 1.79515 +        break;
 1.79516 +      }else if( pAggInfo->useSortingIdx ){
 1.79517 +        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
 1.79518 +                              pCol->iSorterColumn, target);
 1.79519 +        break;
 1.79520 +      }
 1.79521 +      /* Otherwise, fall thru into the TK_COLUMN case */
 1.79522 +    }
 1.79523 +    case TK_COLUMN: {
 1.79524 +      int iTab = pExpr->iTable;
 1.79525 +      if( iTab<0 ){
 1.79526 +        if( pParse->ckBase>0 ){
 1.79527 +          /* Generating CHECK constraints or inserting into partial index */
 1.79528 +          inReg = pExpr->iColumn + pParse->ckBase;
 1.79529 +          break;
 1.79530 +        }else{
 1.79531 +          /* Deleting from a partial index */
 1.79532 +          iTab = pParse->iPartIdxTab;
 1.79533 +        }
 1.79534 +      }
 1.79535 +      inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
 1.79536 +                               pExpr->iColumn, iTab, target,
 1.79537 +                               pExpr->op2);
 1.79538 +      break;
 1.79539 +    }
 1.79540 +    case TK_INTEGER: {
 1.79541 +      codeInteger(pParse, pExpr, 0, target);
 1.79542 +      break;
 1.79543 +    }
 1.79544 +#ifndef SQLITE_OMIT_FLOATING_POINT
 1.79545 +    case TK_FLOAT: {
 1.79546 +      assert( !ExprHasProperty(pExpr, EP_IntValue) );
 1.79547 +      codeReal(v, pExpr->u.zToken, 0, target);
 1.79548 +      break;
 1.79549 +    }
 1.79550 +#endif
 1.79551 +    case TK_STRING: {
 1.79552 +      assert( !ExprHasProperty(pExpr, EP_IntValue) );
 1.79553 +      sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
 1.79554 +      break;
 1.79555 +    }
 1.79556 +    case TK_NULL: {
 1.79557 +      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
 1.79558 +      break;
 1.79559 +    }
 1.79560 +#ifndef SQLITE_OMIT_BLOB_LITERAL
 1.79561 +    case TK_BLOB: {
 1.79562 +      int n;
 1.79563 +      const char *z;
 1.79564 +      char *zBlob;
 1.79565 +      assert( !ExprHasProperty(pExpr, EP_IntValue) );
 1.79566 +      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
 1.79567 +      assert( pExpr->u.zToken[1]=='\'' );
 1.79568 +      z = &pExpr->u.zToken[2];
 1.79569 +      n = sqlite3Strlen30(z) - 1;
 1.79570 +      assert( z[n]=='\'' );
 1.79571 +      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
 1.79572 +      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
 1.79573 +      break;
 1.79574 +    }
 1.79575 +#endif
 1.79576 +    case TK_VARIABLE: {
 1.79577 +      assert( !ExprHasProperty(pExpr, EP_IntValue) );
 1.79578 +      assert( pExpr->u.zToken!=0 );
 1.79579 +      assert( pExpr->u.zToken[0]!=0 );
 1.79580 +      sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
 1.79581 +      if( pExpr->u.zToken[1]!=0 ){
 1.79582 +        assert( pExpr->u.zToken[0]=='?' 
 1.79583 +             || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
 1.79584 +        sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
 1.79585 +      }
 1.79586 +      break;
 1.79587 +    }
 1.79588 +    case TK_REGISTER: {
 1.79589 +      inReg = pExpr->iTable;
 1.79590 +      break;
 1.79591 +    }
 1.79592 +    case TK_AS: {
 1.79593 +      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
 1.79594 +      break;
 1.79595 +    }
 1.79596 +#ifndef SQLITE_OMIT_CAST
 1.79597 +    case TK_CAST: {
 1.79598 +      /* Expressions of the form:   CAST(pLeft AS token) */
 1.79599 +      int aff, to_op;
 1.79600 +      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
 1.79601 +      assert( !ExprHasProperty(pExpr, EP_IntValue) );
 1.79602 +      aff = sqlite3AffinityType(pExpr->u.zToken, 0);
 1.79603 +      to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
 1.79604 +      assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
 1.79605 +      assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
 1.79606 +      assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
 1.79607 +      assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
 1.79608 +      assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
 1.79609 +      testcase( to_op==OP_ToText );
 1.79610 +      testcase( to_op==OP_ToBlob );
 1.79611 +      testcase( to_op==OP_ToNumeric );
 1.79612 +      testcase( to_op==OP_ToInt );
 1.79613 +      testcase( to_op==OP_ToReal );
 1.79614 +      if( inReg!=target ){
 1.79615 +        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
 1.79616 +        inReg = target;
 1.79617 +      }
 1.79618 +      sqlite3VdbeAddOp1(v, to_op, inReg);
 1.79619 +      testcase( usedAsColumnCache(pParse, inReg, inReg) );
 1.79620 +      sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
 1.79621 +      break;
 1.79622 +    }
 1.79623 +#endif /* SQLITE_OMIT_CAST */
 1.79624 +    case TK_LT:
 1.79625 +    case TK_LE:
 1.79626 +    case TK_GT:
 1.79627 +    case TK_GE:
 1.79628 +    case TK_NE:
 1.79629 +    case TK_EQ: {
 1.79630 +      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
 1.79631 +      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
 1.79632 +      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
 1.79633 +                  r1, r2, inReg, SQLITE_STOREP2);
 1.79634 +      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
 1.79635 +      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
 1.79636 +      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
 1.79637 +      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
 1.79638 +      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
 1.79639 +      assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
 1.79640 +      testcase( regFree1==0 );
 1.79641 +      testcase( regFree2==0 );
 1.79642 +      break;
 1.79643 +    }
 1.79644 +    case TK_IS:
 1.79645 +    case TK_ISNOT: {
 1.79646 +      testcase( op==TK_IS );
 1.79647 +      testcase( op==TK_ISNOT );
 1.79648 +      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
 1.79649 +      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
 1.79650 +      op = (op==TK_IS) ? TK_EQ : TK_NE;
 1.79651 +      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
 1.79652 +                  r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
 1.79653 +      VdbeCoverageIf(v, op==TK_EQ);
 1.79654 +      VdbeCoverageIf(v, op==TK_NE);
 1.79655 +      testcase( regFree1==0 );
 1.79656 +      testcase( regFree2==0 );
 1.79657 +      break;
 1.79658 +    }
 1.79659 +    case TK_AND:
 1.79660 +    case TK_OR:
 1.79661 +    case TK_PLUS:
 1.79662 +    case TK_STAR:
 1.79663 +    case TK_MINUS:
 1.79664 +    case TK_REM:
 1.79665 +    case TK_BITAND:
 1.79666 +    case TK_BITOR:
 1.79667 +    case TK_SLASH:
 1.79668 +    case TK_LSHIFT:
 1.79669 +    case TK_RSHIFT: 
 1.79670 +    case TK_CONCAT: {
 1.79671 +      assert( TK_AND==OP_And );            testcase( op==TK_AND );
 1.79672 +      assert( TK_OR==OP_Or );              testcase( op==TK_OR );
 1.79673 +      assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
 1.79674 +      assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
 1.79675 +      assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
 1.79676 +      assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
 1.79677 +      assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
 1.79678 +      assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
 1.79679 +      assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
 1.79680 +      assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
 1.79681 +      assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
 1.79682 +      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
 1.79683 +      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
 1.79684 +      sqlite3VdbeAddOp3(v, op, r2, r1, target);
 1.79685 +      testcase( regFree1==0 );
 1.79686 +      testcase( regFree2==0 );
 1.79687 +      break;
 1.79688 +    }
 1.79689 +    case TK_UMINUS: {
 1.79690 +      Expr *pLeft = pExpr->pLeft;
 1.79691 +      assert( pLeft );
 1.79692 +      if( pLeft->op==TK_INTEGER ){
 1.79693 +        codeInteger(pParse, pLeft, 1, target);
 1.79694 +#ifndef SQLITE_OMIT_FLOATING_POINT
 1.79695 +      }else if( pLeft->op==TK_FLOAT ){
 1.79696 +        assert( !ExprHasProperty(pExpr, EP_IntValue) );
 1.79697 +        codeReal(v, pLeft->u.zToken, 1, target);
 1.79698 +#endif
 1.79699 +      }else{
 1.79700 +        tempX.op = TK_INTEGER;
 1.79701 +        tempX.flags = EP_IntValue|EP_TokenOnly;
 1.79702 +        tempX.u.iValue = 0;
 1.79703 +        r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
 1.79704 +        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
 1.79705 +        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
 1.79706 +        testcase( regFree2==0 );
 1.79707 +      }
 1.79708 +      inReg = target;
 1.79709 +      break;
 1.79710 +    }
 1.79711 +    case TK_BITNOT:
 1.79712 +    case TK_NOT: {
 1.79713 +      assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
 1.79714 +      assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
 1.79715 +      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
 1.79716 +      testcase( regFree1==0 );
 1.79717 +      inReg = target;
 1.79718 +      sqlite3VdbeAddOp2(v, op, r1, inReg);
 1.79719 +      break;
 1.79720 +    }
 1.79721 +    case TK_ISNULL:
 1.79722 +    case TK_NOTNULL: {
 1.79723 +      int addr;
 1.79724 +      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
 1.79725 +      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
 1.79726 +      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
 1.79727 +      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
 1.79728 +      testcase( regFree1==0 );
 1.79729 +      addr = sqlite3VdbeAddOp1(v, op, r1);
 1.79730 +      VdbeCoverageIf(v, op==TK_ISNULL);
 1.79731 +      VdbeCoverageIf(v, op==TK_NOTNULL);
 1.79732 +      sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
 1.79733 +      sqlite3VdbeJumpHere(v, addr);
 1.79734 +      break;
 1.79735 +    }
 1.79736 +    case TK_AGG_FUNCTION: {
 1.79737 +      AggInfo *pInfo = pExpr->pAggInfo;
 1.79738 +      if( pInfo==0 ){
 1.79739 +        assert( !ExprHasProperty(pExpr, EP_IntValue) );
 1.79740 +        sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
 1.79741 +      }else{
 1.79742 +        inReg = pInfo->aFunc[pExpr->iAgg].iMem;
 1.79743 +      }
 1.79744 +      break;
 1.79745 +    }
 1.79746 +    case TK_FUNCTION: {
 1.79747 +      ExprList *pFarg;       /* List of function arguments */
 1.79748 +      int nFarg;             /* Number of function arguments */
 1.79749 +      FuncDef *pDef;         /* The function definition object */
 1.79750 +      int nId;               /* Length of the function name in bytes */
 1.79751 +      const char *zId;       /* The function name */
 1.79752 +      u32 constMask = 0;     /* Mask of function arguments that are constant */
 1.79753 +      int i;                 /* Loop counter */
 1.79754 +      u8 enc = ENC(db);      /* The text encoding used by this database */
 1.79755 +      CollSeq *pColl = 0;    /* A collating sequence */
 1.79756 +
 1.79757 +      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
 1.79758 +      if( ExprHasProperty(pExpr, EP_TokenOnly) ){
 1.79759 +        pFarg = 0;
 1.79760 +      }else{
 1.79761 +        pFarg = pExpr->x.pList;
 1.79762 +      }
 1.79763 +      nFarg = pFarg ? pFarg->nExpr : 0;
 1.79764 +      assert( !ExprHasProperty(pExpr, EP_IntValue) );
 1.79765 +      zId = pExpr->u.zToken;
 1.79766 +      nId = sqlite3Strlen30(zId);
 1.79767 +      pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
 1.79768 +      if( pDef==0 ){
 1.79769 +        sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
 1.79770 +        break;
 1.79771 +      }
 1.79772 +
 1.79773 +      /* Attempt a direct implementation of the built-in COALESCE() and
 1.79774 +      ** IFNULL() functions.  This avoids unnecessary evalation of
 1.79775 +      ** arguments past the first non-NULL argument.
 1.79776 +      */
 1.79777 +      if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
 1.79778 +        int endCoalesce = sqlite3VdbeMakeLabel(v);
 1.79779 +        assert( nFarg>=2 );
 1.79780 +        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
 1.79781 +        for(i=1; i<nFarg; i++){
 1.79782 +          sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
 1.79783 +          VdbeCoverage(v);
 1.79784 +          sqlite3ExprCacheRemove(pParse, target, 1);
 1.79785 +          sqlite3ExprCachePush(pParse);
 1.79786 +          sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
 1.79787 +          sqlite3ExprCachePop(pParse, 1);
 1.79788 +        }
 1.79789 +        sqlite3VdbeResolveLabel(v, endCoalesce);
 1.79790 +        break;
 1.79791 +      }
 1.79792 +
 1.79793 +      /* The UNLIKELY() function is a no-op.  The result is the value
 1.79794 +      ** of the first argument.
 1.79795 +      */
 1.79796 +      if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
 1.79797 +        assert( nFarg>=1 );
 1.79798 +        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
 1.79799 +        break;
 1.79800 +      }
 1.79801 +
 1.79802 +      for(i=0; i<nFarg; i++){
 1.79803 +        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
 1.79804 +          testcase( i==31 );
 1.79805 +          constMask |= MASKBIT32(i);
 1.79806 +        }
 1.79807 +        if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
 1.79808 +          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
 1.79809 +        }
 1.79810 +      }
 1.79811 +      if( pFarg ){
 1.79812 +        if( constMask ){
 1.79813 +          r1 = pParse->nMem+1;
 1.79814 +          pParse->nMem += nFarg;
 1.79815 +        }else{
 1.79816 +          r1 = sqlite3GetTempRange(pParse, nFarg);
 1.79817 +        }
 1.79818 +
 1.79819 +        /* For length() and typeof() functions with a column argument,
 1.79820 +        ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
 1.79821 +        ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
 1.79822 +        ** loading.
 1.79823 +        */
 1.79824 +        if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
 1.79825 +          u8 exprOp;
 1.79826 +          assert( nFarg==1 );
 1.79827 +          assert( pFarg->a[0].pExpr!=0 );
 1.79828 +          exprOp = pFarg->a[0].pExpr->op;
 1.79829 +          if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
 1.79830 +            assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
 1.79831 +            assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
 1.79832 +            testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
 1.79833 +            pFarg->a[0].pExpr->op2 = 
 1.79834 +                  pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
 1.79835 +          }
 1.79836 +        }
 1.79837 +
 1.79838 +        sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
 1.79839 +        sqlite3ExprCodeExprList(pParse, pFarg, r1, 
 1.79840 +                                SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
 1.79841 +        sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
 1.79842 +      }else{
 1.79843 +        r1 = 0;
 1.79844 +      }
 1.79845 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.79846 +      /* Possibly overload the function if the first argument is
 1.79847 +      ** a virtual table column.
 1.79848 +      **
 1.79849 +      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
 1.79850 +      ** second argument, not the first, as the argument to test to
 1.79851 +      ** see if it is a column in a virtual table.  This is done because
 1.79852 +      ** the left operand of infix functions (the operand we want to
 1.79853 +      ** control overloading) ends up as the second argument to the
 1.79854 +      ** function.  The expression "A glob B" is equivalent to 
 1.79855 +      ** "glob(B,A).  We want to use the A in "A glob B" to test
 1.79856 +      ** for function overloading.  But we use the B term in "glob(B,A)".
 1.79857 +      */
 1.79858 +      if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
 1.79859 +        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
 1.79860 +      }else if( nFarg>0 ){
 1.79861 +        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
 1.79862 +      }
 1.79863 +#endif
 1.79864 +      if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
 1.79865 +        if( !pColl ) pColl = db->pDfltColl; 
 1.79866 +        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
 1.79867 +      }
 1.79868 +      sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
 1.79869 +                        (char*)pDef, P4_FUNCDEF);
 1.79870 +      sqlite3VdbeChangeP5(v, (u8)nFarg);
 1.79871 +      if( nFarg && constMask==0 ){
 1.79872 +        sqlite3ReleaseTempRange(pParse, r1, nFarg);
 1.79873 +      }
 1.79874 +      break;
 1.79875 +    }
 1.79876 +#ifndef SQLITE_OMIT_SUBQUERY
 1.79877 +    case TK_EXISTS:
 1.79878 +    case TK_SELECT: {
 1.79879 +      testcase( op==TK_EXISTS );
 1.79880 +      testcase( op==TK_SELECT );
 1.79881 +      inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
 1.79882 +      break;
 1.79883 +    }
 1.79884 +    case TK_IN: {
 1.79885 +      int destIfFalse = sqlite3VdbeMakeLabel(v);
 1.79886 +      int destIfNull = sqlite3VdbeMakeLabel(v);
 1.79887 +      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
 1.79888 +      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
 1.79889 +      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
 1.79890 +      sqlite3VdbeResolveLabel(v, destIfFalse);
 1.79891 +      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
 1.79892 +      sqlite3VdbeResolveLabel(v, destIfNull);
 1.79893 +      break;
 1.79894 +    }
 1.79895 +#endif /* SQLITE_OMIT_SUBQUERY */
 1.79896 +
 1.79897 +
 1.79898 +    /*
 1.79899 +    **    x BETWEEN y AND z
 1.79900 +    **
 1.79901 +    ** This is equivalent to
 1.79902 +    **
 1.79903 +    **    x>=y AND x<=z
 1.79904 +    **
 1.79905 +    ** X is stored in pExpr->pLeft.
 1.79906 +    ** Y is stored in pExpr->pList->a[0].pExpr.
 1.79907 +    ** Z is stored in pExpr->pList->a[1].pExpr.
 1.79908 +    */
 1.79909 +    case TK_BETWEEN: {
 1.79910 +      Expr *pLeft = pExpr->pLeft;
 1.79911 +      struct ExprList_item *pLItem = pExpr->x.pList->a;
 1.79912 +      Expr *pRight = pLItem->pExpr;
 1.79913 +
 1.79914 +      r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
 1.79915 +      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
 1.79916 +      testcase( regFree1==0 );
 1.79917 +      testcase( regFree2==0 );
 1.79918 +      r3 = sqlite3GetTempReg(pParse);
 1.79919 +      r4 = sqlite3GetTempReg(pParse);
 1.79920 +      codeCompare(pParse, pLeft, pRight, OP_Ge,
 1.79921 +                  r1, r2, r3, SQLITE_STOREP2);  VdbeCoverage(v);
 1.79922 +      pLItem++;
 1.79923 +      pRight = pLItem->pExpr;
 1.79924 +      sqlite3ReleaseTempReg(pParse, regFree2);
 1.79925 +      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
 1.79926 +      testcase( regFree2==0 );
 1.79927 +      codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
 1.79928 +      VdbeCoverage(v);
 1.79929 +      sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
 1.79930 +      sqlite3ReleaseTempReg(pParse, r3);
 1.79931 +      sqlite3ReleaseTempReg(pParse, r4);
 1.79932 +      break;
 1.79933 +    }
 1.79934 +    case TK_COLLATE: 
 1.79935 +    case TK_UPLUS: {
 1.79936 +      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
 1.79937 +      break;
 1.79938 +    }
 1.79939 +
 1.79940 +    case TK_TRIGGER: {
 1.79941 +      /* If the opcode is TK_TRIGGER, then the expression is a reference
 1.79942 +      ** to a column in the new.* or old.* pseudo-tables available to
 1.79943 +      ** trigger programs. In this case Expr.iTable is set to 1 for the
 1.79944 +      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
 1.79945 +      ** is set to the column of the pseudo-table to read, or to -1 to
 1.79946 +      ** read the rowid field.
 1.79947 +      **
 1.79948 +      ** The expression is implemented using an OP_Param opcode. The p1
 1.79949 +      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
 1.79950 +      ** to reference another column of the old.* pseudo-table, where 
 1.79951 +      ** i is the index of the column. For a new.rowid reference, p1 is
 1.79952 +      ** set to (n+1), where n is the number of columns in each pseudo-table.
 1.79953 +      ** For a reference to any other column in the new.* pseudo-table, p1
 1.79954 +      ** is set to (n+2+i), where n and i are as defined previously. For
 1.79955 +      ** example, if the table on which triggers are being fired is
 1.79956 +      ** declared as:
 1.79957 +      **
 1.79958 +      **   CREATE TABLE t1(a, b);
 1.79959 +      **
 1.79960 +      ** Then p1 is interpreted as follows:
 1.79961 +      **
 1.79962 +      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
 1.79963 +      **   p1==1   ->    old.a         p1==4   ->    new.a
 1.79964 +      **   p1==2   ->    old.b         p1==5   ->    new.b       
 1.79965 +      */
 1.79966 +      Table *pTab = pExpr->pTab;
 1.79967 +      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
 1.79968 +
 1.79969 +      assert( pExpr->iTable==0 || pExpr->iTable==1 );
 1.79970 +      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
 1.79971 +      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
 1.79972 +      assert( p1>=0 && p1<(pTab->nCol*2+2) );
 1.79973 +
 1.79974 +      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
 1.79975 +      VdbeComment((v, "%s.%s -> $%d",
 1.79976 +        (pExpr->iTable ? "new" : "old"),
 1.79977 +        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
 1.79978 +        target
 1.79979 +      ));
 1.79980 +
 1.79981 +#ifndef SQLITE_OMIT_FLOATING_POINT
 1.79982 +      /* If the column has REAL affinity, it may currently be stored as an
 1.79983 +      ** integer. Use OP_RealAffinity to make sure it is really real.  */
 1.79984 +      if( pExpr->iColumn>=0 
 1.79985 +       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
 1.79986 +      ){
 1.79987 +        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
 1.79988 +      }
 1.79989 +#endif
 1.79990 +      break;
 1.79991 +    }
 1.79992 +
 1.79993 +
 1.79994 +    /*
 1.79995 +    ** Form A:
 1.79996 +    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
 1.79997 +    **
 1.79998 +    ** Form B:
 1.79999 +    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
 1.80000 +    **
 1.80001 +    ** Form A is can be transformed into the equivalent form B as follows:
 1.80002 +    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
 1.80003 +    **        WHEN x=eN THEN rN ELSE y END
 1.80004 +    **
 1.80005 +    ** X (if it exists) is in pExpr->pLeft.
 1.80006 +    ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
 1.80007 +    ** odd.  The Y is also optional.  If the number of elements in x.pList
 1.80008 +    ** is even, then Y is omitted and the "otherwise" result is NULL.
 1.80009 +    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
 1.80010 +    **
 1.80011 +    ** The result of the expression is the Ri for the first matching Ei,
 1.80012 +    ** or if there is no matching Ei, the ELSE term Y, or if there is
 1.80013 +    ** no ELSE term, NULL.
 1.80014 +    */
 1.80015 +    default: assert( op==TK_CASE ); {
 1.80016 +      int endLabel;                     /* GOTO label for end of CASE stmt */
 1.80017 +      int nextCase;                     /* GOTO label for next WHEN clause */
 1.80018 +      int nExpr;                        /* 2x number of WHEN terms */
 1.80019 +      int i;                            /* Loop counter */
 1.80020 +      ExprList *pEList;                 /* List of WHEN terms */
 1.80021 +      struct ExprList_item *aListelem;  /* Array of WHEN terms */
 1.80022 +      Expr opCompare;                   /* The X==Ei expression */
 1.80023 +      Expr *pX;                         /* The X expression */
 1.80024 +      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
 1.80025 +      VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
 1.80026 +
 1.80027 +      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
 1.80028 +      assert(pExpr->x.pList->nExpr > 0);
 1.80029 +      pEList = pExpr->x.pList;
 1.80030 +      aListelem = pEList->a;
 1.80031 +      nExpr = pEList->nExpr;
 1.80032 +      endLabel = sqlite3VdbeMakeLabel(v);
 1.80033 +      if( (pX = pExpr->pLeft)!=0 ){
 1.80034 +        tempX = *pX;
 1.80035 +        testcase( pX->op==TK_COLUMN );
 1.80036 +        exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
 1.80037 +        testcase( regFree1==0 );
 1.80038 +        opCompare.op = TK_EQ;
 1.80039 +        opCompare.pLeft = &tempX;
 1.80040 +        pTest = &opCompare;
 1.80041 +        /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
 1.80042 +        ** The value in regFree1 might get SCopy-ed into the file result.
 1.80043 +        ** So make sure that the regFree1 register is not reused for other
 1.80044 +        ** purposes and possibly overwritten.  */
 1.80045 +        regFree1 = 0;
 1.80046 +      }
 1.80047 +      for(i=0; i<nExpr-1; i=i+2){
 1.80048 +        sqlite3ExprCachePush(pParse);
 1.80049 +        if( pX ){
 1.80050 +          assert( pTest!=0 );
 1.80051 +          opCompare.pRight = aListelem[i].pExpr;
 1.80052 +        }else{
 1.80053 +          pTest = aListelem[i].pExpr;
 1.80054 +        }
 1.80055 +        nextCase = sqlite3VdbeMakeLabel(v);
 1.80056 +        testcase( pTest->op==TK_COLUMN );
 1.80057 +        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
 1.80058 +        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
 1.80059 +        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
 1.80060 +        sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
 1.80061 +        sqlite3ExprCachePop(pParse, 1);
 1.80062 +        sqlite3VdbeResolveLabel(v, nextCase);
 1.80063 +      }
 1.80064 +      if( (nExpr&1)!=0 ){
 1.80065 +        sqlite3ExprCachePush(pParse);
 1.80066 +        sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
 1.80067 +        sqlite3ExprCachePop(pParse, 1);
 1.80068 +      }else{
 1.80069 +        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
 1.80070 +      }
 1.80071 +      assert( db->mallocFailed || pParse->nErr>0 
 1.80072 +           || pParse->iCacheLevel==iCacheLevel );
 1.80073 +      sqlite3VdbeResolveLabel(v, endLabel);
 1.80074 +      break;
 1.80075 +    }
 1.80076 +#ifndef SQLITE_OMIT_TRIGGER
 1.80077 +    case TK_RAISE: {
 1.80078 +      assert( pExpr->affinity==OE_Rollback 
 1.80079 +           || pExpr->affinity==OE_Abort
 1.80080 +           || pExpr->affinity==OE_Fail
 1.80081 +           || pExpr->affinity==OE_Ignore
 1.80082 +      );
 1.80083 +      if( !pParse->pTriggerTab ){
 1.80084 +        sqlite3ErrorMsg(pParse,
 1.80085 +                       "RAISE() may only be used within a trigger-program");
 1.80086 +        return 0;
 1.80087 +      }
 1.80088 +      if( pExpr->affinity==OE_Abort ){
 1.80089 +        sqlite3MayAbort(pParse);
 1.80090 +      }
 1.80091 +      assert( !ExprHasProperty(pExpr, EP_IntValue) );
 1.80092 +      if( pExpr->affinity==OE_Ignore ){
 1.80093 +        sqlite3VdbeAddOp4(
 1.80094 +            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
 1.80095 +        VdbeCoverage(v);
 1.80096 +      }else{
 1.80097 +        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
 1.80098 +                              pExpr->affinity, pExpr->u.zToken, 0, 0);
 1.80099 +      }
 1.80100 +
 1.80101 +      break;
 1.80102 +    }
 1.80103 +#endif
 1.80104 +  }
 1.80105 +  sqlite3ReleaseTempReg(pParse, regFree1);
 1.80106 +  sqlite3ReleaseTempReg(pParse, regFree2);
 1.80107 +  return inReg;
 1.80108 +}
 1.80109 +
 1.80110 +/*
 1.80111 +** Factor out the code of the given expression to initialization time.
 1.80112 +*/
 1.80113 +SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
 1.80114 +  Parse *pParse,    /* Parsing context */
 1.80115 +  Expr *pExpr,      /* The expression to code when the VDBE initializes */
 1.80116 +  int regDest,      /* Store the value in this register */
 1.80117 +  u8 reusable       /* True if this expression is reusable */
 1.80118 +){
 1.80119 +  ExprList *p;
 1.80120 +  assert( ConstFactorOk(pParse) );
 1.80121 +  p = pParse->pConstExpr;
 1.80122 +  pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
 1.80123 +  p = sqlite3ExprListAppend(pParse, p, pExpr);
 1.80124 +  if( p ){
 1.80125 +     struct ExprList_item *pItem = &p->a[p->nExpr-1];
 1.80126 +     pItem->u.iConstExprReg = regDest;
 1.80127 +     pItem->reusable = reusable;
 1.80128 +  }
 1.80129 +  pParse->pConstExpr = p;
 1.80130 +}
 1.80131 +
 1.80132 +/*
 1.80133 +** Generate code to evaluate an expression and store the results
 1.80134 +** into a register.  Return the register number where the results
 1.80135 +** are stored.
 1.80136 +**
 1.80137 +** If the register is a temporary register that can be deallocated,
 1.80138 +** then write its number into *pReg.  If the result register is not
 1.80139 +** a temporary, then set *pReg to zero.
 1.80140 +**
 1.80141 +** If pExpr is a constant, then this routine might generate this
 1.80142 +** code to fill the register in the initialization section of the
 1.80143 +** VDBE program, in order to factor it out of the evaluation loop.
 1.80144 +*/
 1.80145 +SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
 1.80146 +  int r2;
 1.80147 +  pExpr = sqlite3ExprSkipCollate(pExpr);
 1.80148 +  if( ConstFactorOk(pParse)
 1.80149 +   && pExpr->op!=TK_REGISTER
 1.80150 +   && sqlite3ExprIsConstantNotJoin(pExpr)
 1.80151 +  ){
 1.80152 +    ExprList *p = pParse->pConstExpr;
 1.80153 +    int i;
 1.80154 +    *pReg  = 0;
 1.80155 +    if( p ){
 1.80156 +      struct ExprList_item *pItem;
 1.80157 +      for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
 1.80158 +        if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
 1.80159 +          return pItem->u.iConstExprReg;
 1.80160 +        }
 1.80161 +      }
 1.80162 +    }
 1.80163 +    r2 = ++pParse->nMem;
 1.80164 +    sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
 1.80165 +  }else{
 1.80166 +    int r1 = sqlite3GetTempReg(pParse);
 1.80167 +    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
 1.80168 +    if( r2==r1 ){
 1.80169 +      *pReg = r1;
 1.80170 +    }else{
 1.80171 +      sqlite3ReleaseTempReg(pParse, r1);
 1.80172 +      *pReg = 0;
 1.80173 +    }
 1.80174 +  }
 1.80175 +  return r2;
 1.80176 +}
 1.80177 +
 1.80178 +/*
 1.80179 +** Generate code that will evaluate expression pExpr and store the
 1.80180 +** results in register target.  The results are guaranteed to appear
 1.80181 +** in register target.
 1.80182 +*/
 1.80183 +SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
 1.80184 +  int inReg;
 1.80185 +
 1.80186 +  assert( target>0 && target<=pParse->nMem );
 1.80187 +  if( pExpr && pExpr->op==TK_REGISTER ){
 1.80188 +    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
 1.80189 +  }else{
 1.80190 +    inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
 1.80191 +    assert( pParse->pVdbe || pParse->db->mallocFailed );
 1.80192 +    if( inReg!=target && pParse->pVdbe ){
 1.80193 +      sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
 1.80194 +    }
 1.80195 +  }
 1.80196 +}
 1.80197 +
 1.80198 +/*
 1.80199 +** Generate code that will evaluate expression pExpr and store the
 1.80200 +** results in register target.  The results are guaranteed to appear
 1.80201 +** in register target.  If the expression is constant, then this routine
 1.80202 +** might choose to code the expression at initialization time.
 1.80203 +*/
 1.80204 +SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
 1.80205 +  if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
 1.80206 +    sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
 1.80207 +  }else{
 1.80208 +    sqlite3ExprCode(pParse, pExpr, target);
 1.80209 +  }
 1.80210 +}
 1.80211 +
 1.80212 +/*
 1.80213 +** Generate code that evalutes the given expression and puts the result
 1.80214 +** in register target.
 1.80215 +**
 1.80216 +** Also make a copy of the expression results into another "cache" register
 1.80217 +** and modify the expression so that the next time it is evaluated,
 1.80218 +** the result is a copy of the cache register.
 1.80219 +**
 1.80220 +** This routine is used for expressions that are used multiple 
 1.80221 +** times.  They are evaluated once and the results of the expression
 1.80222 +** are reused.
 1.80223 +*/
 1.80224 +SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
 1.80225 +  Vdbe *v = pParse->pVdbe;
 1.80226 +  int iMem;
 1.80227 +
 1.80228 +  assert( target>0 );
 1.80229 +  assert( pExpr->op!=TK_REGISTER );
 1.80230 +  sqlite3ExprCode(pParse, pExpr, target);
 1.80231 +  iMem = ++pParse->nMem;
 1.80232 +  sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
 1.80233 +  exprToRegister(pExpr, iMem);
 1.80234 +}
 1.80235 +
 1.80236 +#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
 1.80237 +/*
 1.80238 +** Generate a human-readable explanation of an expression tree.
 1.80239 +*/
 1.80240 +SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
 1.80241 +  int op;                   /* The opcode being coded */
 1.80242 +  const char *zBinOp = 0;   /* Binary operator */
 1.80243 +  const char *zUniOp = 0;   /* Unary operator */
 1.80244 +  if( pExpr==0 ){
 1.80245 +    op = TK_NULL;
 1.80246 +  }else{
 1.80247 +    op = pExpr->op;
 1.80248 +  }
 1.80249 +  switch( op ){
 1.80250 +    case TK_AGG_COLUMN: {
 1.80251 +      sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
 1.80252 +            pExpr->iTable, pExpr->iColumn);
 1.80253 +      break;
 1.80254 +    }
 1.80255 +    case TK_COLUMN: {
 1.80256 +      if( pExpr->iTable<0 ){
 1.80257 +        /* This only happens when coding check constraints */
 1.80258 +        sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
 1.80259 +      }else{
 1.80260 +        sqlite3ExplainPrintf(pOut, "{%d:%d}",
 1.80261 +                             pExpr->iTable, pExpr->iColumn);
 1.80262 +      }
 1.80263 +      break;
 1.80264 +    }
 1.80265 +    case TK_INTEGER: {
 1.80266 +      if( pExpr->flags & EP_IntValue ){
 1.80267 +        sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
 1.80268 +      }else{
 1.80269 +        sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
 1.80270 +      }
 1.80271 +      break;
 1.80272 +    }
 1.80273 +#ifndef SQLITE_OMIT_FLOATING_POINT
 1.80274 +    case TK_FLOAT: {
 1.80275 +      sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
 1.80276 +      break;
 1.80277 +    }
 1.80278 +#endif
 1.80279 +    case TK_STRING: {
 1.80280 +      sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
 1.80281 +      break;
 1.80282 +    }
 1.80283 +    case TK_NULL: {
 1.80284 +      sqlite3ExplainPrintf(pOut,"NULL");
 1.80285 +      break;
 1.80286 +    }
 1.80287 +#ifndef SQLITE_OMIT_BLOB_LITERAL
 1.80288 +    case TK_BLOB: {
 1.80289 +      sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
 1.80290 +      break;
 1.80291 +    }
 1.80292 +#endif
 1.80293 +    case TK_VARIABLE: {
 1.80294 +      sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
 1.80295 +                           pExpr->u.zToken, pExpr->iColumn);
 1.80296 +      break;
 1.80297 +    }
 1.80298 +    case TK_REGISTER: {
 1.80299 +      sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
 1.80300 +      break;
 1.80301 +    }
 1.80302 +    case TK_AS: {
 1.80303 +      sqlite3ExplainExpr(pOut, pExpr->pLeft);
 1.80304 +      break;
 1.80305 +    }
 1.80306 +#ifndef SQLITE_OMIT_CAST
 1.80307 +    case TK_CAST: {
 1.80308 +      /* Expressions of the form:   CAST(pLeft AS token) */
 1.80309 +      const char *zAff = "unk";
 1.80310 +      switch( sqlite3AffinityType(pExpr->u.zToken, 0) ){
 1.80311 +        case SQLITE_AFF_TEXT:    zAff = "TEXT";     break;
 1.80312 +        case SQLITE_AFF_NONE:    zAff = "NONE";     break;
 1.80313 +        case SQLITE_AFF_NUMERIC: zAff = "NUMERIC";  break;
 1.80314 +        case SQLITE_AFF_INTEGER: zAff = "INTEGER";  break;
 1.80315 +        case SQLITE_AFF_REAL:    zAff = "REAL";     break;
 1.80316 +      }
 1.80317 +      sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
 1.80318 +      sqlite3ExplainExpr(pOut, pExpr->pLeft);
 1.80319 +      sqlite3ExplainPrintf(pOut, ")");
 1.80320 +      break;
 1.80321 +    }
 1.80322 +#endif /* SQLITE_OMIT_CAST */
 1.80323 +    case TK_LT:      zBinOp = "LT";     break;
 1.80324 +    case TK_LE:      zBinOp = "LE";     break;
 1.80325 +    case TK_GT:      zBinOp = "GT";     break;
 1.80326 +    case TK_GE:      zBinOp = "GE";     break;
 1.80327 +    case TK_NE:      zBinOp = "NE";     break;
 1.80328 +    case TK_EQ:      zBinOp = "EQ";     break;
 1.80329 +    case TK_IS:      zBinOp = "IS";     break;
 1.80330 +    case TK_ISNOT:   zBinOp = "ISNOT";  break;
 1.80331 +    case TK_AND:     zBinOp = "AND";    break;
 1.80332 +    case TK_OR:      zBinOp = "OR";     break;
 1.80333 +    case TK_PLUS:    zBinOp = "ADD";    break;
 1.80334 +    case TK_STAR:    zBinOp = "MUL";    break;
 1.80335 +    case TK_MINUS:   zBinOp = "SUB";    break;
 1.80336 +    case TK_REM:     zBinOp = "REM";    break;
 1.80337 +    case TK_BITAND:  zBinOp = "BITAND"; break;
 1.80338 +    case TK_BITOR:   zBinOp = "BITOR";  break;
 1.80339 +    case TK_SLASH:   zBinOp = "DIV";    break;
 1.80340 +    case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
 1.80341 +    case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
 1.80342 +    case TK_CONCAT:  zBinOp = "CONCAT"; break;
 1.80343 +
 1.80344 +    case TK_UMINUS:  zUniOp = "UMINUS"; break;
 1.80345 +    case TK_UPLUS:   zUniOp = "UPLUS";  break;
 1.80346 +    case TK_BITNOT:  zUniOp = "BITNOT"; break;
 1.80347 +    case TK_NOT:     zUniOp = "NOT";    break;
 1.80348 +    case TK_ISNULL:  zUniOp = "ISNULL"; break;
 1.80349 +    case TK_NOTNULL: zUniOp = "NOTNULL"; break;
 1.80350 +
 1.80351 +    case TK_COLLATE: {
 1.80352 +      sqlite3ExplainExpr(pOut, pExpr->pLeft);
 1.80353 +      sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken);
 1.80354 +      break;
 1.80355 +    }
 1.80356 +
 1.80357 +    case TK_AGG_FUNCTION:
 1.80358 +    case TK_FUNCTION: {
 1.80359 +      ExprList *pFarg;       /* List of function arguments */
 1.80360 +      if( ExprHasProperty(pExpr, EP_TokenOnly) ){
 1.80361 +        pFarg = 0;
 1.80362 +      }else{
 1.80363 +        pFarg = pExpr->x.pList;
 1.80364 +      }
 1.80365 +      if( op==TK_AGG_FUNCTION ){
 1.80366 +        sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
 1.80367 +                             pExpr->op2, pExpr->u.zToken);
 1.80368 +      }else{
 1.80369 +        sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
 1.80370 +      }
 1.80371 +      if( pFarg ){
 1.80372 +        sqlite3ExplainExprList(pOut, pFarg);
 1.80373 +      }
 1.80374 +      sqlite3ExplainPrintf(pOut, ")");
 1.80375 +      break;
 1.80376 +    }
 1.80377 +#ifndef SQLITE_OMIT_SUBQUERY
 1.80378 +    case TK_EXISTS: {
 1.80379 +      sqlite3ExplainPrintf(pOut, "EXISTS(");
 1.80380 +      sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
 1.80381 +      sqlite3ExplainPrintf(pOut,")");
 1.80382 +      break;
 1.80383 +    }
 1.80384 +    case TK_SELECT: {
 1.80385 +      sqlite3ExplainPrintf(pOut, "(");
 1.80386 +      sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
 1.80387 +      sqlite3ExplainPrintf(pOut, ")");
 1.80388 +      break;
 1.80389 +    }
 1.80390 +    case TK_IN: {
 1.80391 +      sqlite3ExplainPrintf(pOut, "IN(");
 1.80392 +      sqlite3ExplainExpr(pOut, pExpr->pLeft);
 1.80393 +      sqlite3ExplainPrintf(pOut, ",");
 1.80394 +      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
 1.80395 +        sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
 1.80396 +      }else{
 1.80397 +        sqlite3ExplainExprList(pOut, pExpr->x.pList);
 1.80398 +      }
 1.80399 +      sqlite3ExplainPrintf(pOut, ")");
 1.80400 +      break;
 1.80401 +    }
 1.80402 +#endif /* SQLITE_OMIT_SUBQUERY */
 1.80403 +
 1.80404 +    /*
 1.80405 +    **    x BETWEEN y AND z
 1.80406 +    **
 1.80407 +    ** This is equivalent to
 1.80408 +    **
 1.80409 +    **    x>=y AND x<=z
 1.80410 +    **
 1.80411 +    ** X is stored in pExpr->pLeft.
 1.80412 +    ** Y is stored in pExpr->pList->a[0].pExpr.
 1.80413 +    ** Z is stored in pExpr->pList->a[1].pExpr.
 1.80414 +    */
 1.80415 +    case TK_BETWEEN: {
 1.80416 +      Expr *pX = pExpr->pLeft;
 1.80417 +      Expr *pY = pExpr->x.pList->a[0].pExpr;
 1.80418 +      Expr *pZ = pExpr->x.pList->a[1].pExpr;
 1.80419 +      sqlite3ExplainPrintf(pOut, "BETWEEN(");
 1.80420 +      sqlite3ExplainExpr(pOut, pX);
 1.80421 +      sqlite3ExplainPrintf(pOut, ",");
 1.80422 +      sqlite3ExplainExpr(pOut, pY);
 1.80423 +      sqlite3ExplainPrintf(pOut, ",");
 1.80424 +      sqlite3ExplainExpr(pOut, pZ);
 1.80425 +      sqlite3ExplainPrintf(pOut, ")");
 1.80426 +      break;
 1.80427 +    }
 1.80428 +    case TK_TRIGGER: {
 1.80429 +      /* If the opcode is TK_TRIGGER, then the expression is a reference
 1.80430 +      ** to a column in the new.* or old.* pseudo-tables available to
 1.80431 +      ** trigger programs. In this case Expr.iTable is set to 1 for the
 1.80432 +      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
 1.80433 +      ** is set to the column of the pseudo-table to read, or to -1 to
 1.80434 +      ** read the rowid field.
 1.80435 +      */
 1.80436 +      sqlite3ExplainPrintf(pOut, "%s(%d)", 
 1.80437 +          pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
 1.80438 +      break;
 1.80439 +    }
 1.80440 +    case TK_CASE: {
 1.80441 +      sqlite3ExplainPrintf(pOut, "CASE(");
 1.80442 +      sqlite3ExplainExpr(pOut, pExpr->pLeft);
 1.80443 +      sqlite3ExplainPrintf(pOut, ",");
 1.80444 +      sqlite3ExplainExprList(pOut, pExpr->x.pList);
 1.80445 +      break;
 1.80446 +    }
 1.80447 +#ifndef SQLITE_OMIT_TRIGGER
 1.80448 +    case TK_RAISE: {
 1.80449 +      const char *zType = "unk";
 1.80450 +      switch( pExpr->affinity ){
 1.80451 +        case OE_Rollback:   zType = "rollback";  break;
 1.80452 +        case OE_Abort:      zType = "abort";     break;
 1.80453 +        case OE_Fail:       zType = "fail";      break;
 1.80454 +        case OE_Ignore:     zType = "ignore";    break;
 1.80455 +      }
 1.80456 +      sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
 1.80457 +      break;
 1.80458 +    }
 1.80459 +#endif
 1.80460 +  }
 1.80461 +  if( zBinOp ){
 1.80462 +    sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
 1.80463 +    sqlite3ExplainExpr(pOut, pExpr->pLeft);
 1.80464 +    sqlite3ExplainPrintf(pOut,",");
 1.80465 +    sqlite3ExplainExpr(pOut, pExpr->pRight);
 1.80466 +    sqlite3ExplainPrintf(pOut,")");
 1.80467 +  }else if( zUniOp ){
 1.80468 +    sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
 1.80469 +    sqlite3ExplainExpr(pOut, pExpr->pLeft);
 1.80470 +    sqlite3ExplainPrintf(pOut,")");
 1.80471 +  }
 1.80472 +}
 1.80473 +#endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
 1.80474 +
 1.80475 +#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
 1.80476 +/*
 1.80477 +** Generate a human-readable explanation of an expression list.
 1.80478 +*/
 1.80479 +SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
 1.80480 +  int i;
 1.80481 +  if( pList==0 || pList->nExpr==0 ){
 1.80482 +    sqlite3ExplainPrintf(pOut, "(empty-list)");
 1.80483 +    return;
 1.80484 +  }else if( pList->nExpr==1 ){
 1.80485 +    sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
 1.80486 +  }else{
 1.80487 +    sqlite3ExplainPush(pOut);
 1.80488 +    for(i=0; i<pList->nExpr; i++){
 1.80489 +      sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
 1.80490 +      sqlite3ExplainPush(pOut);
 1.80491 +      sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
 1.80492 +      sqlite3ExplainPop(pOut);
 1.80493 +      if( pList->a[i].zName ){
 1.80494 +        sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
 1.80495 +      }
 1.80496 +      if( pList->a[i].bSpanIsTab ){
 1.80497 +        sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
 1.80498 +      }
 1.80499 +      if( i<pList->nExpr-1 ){
 1.80500 +        sqlite3ExplainNL(pOut);
 1.80501 +      }
 1.80502 +    }
 1.80503 +    sqlite3ExplainPop(pOut);
 1.80504 +  }
 1.80505 +}
 1.80506 +#endif /* SQLITE_DEBUG */
 1.80507 +
 1.80508 +/*
 1.80509 +** Generate code that pushes the value of every element of the given
 1.80510 +** expression list into a sequence of registers beginning at target.
 1.80511 +**
 1.80512 +** Return the number of elements evaluated.
 1.80513 +**
 1.80514 +** The SQLITE_ECEL_DUP flag prevents the arguments from being
 1.80515 +** filled using OP_SCopy.  OP_Copy must be used instead.
 1.80516 +**
 1.80517 +** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
 1.80518 +** factored out into initialization code.
 1.80519 +*/
 1.80520 +SQLITE_PRIVATE int sqlite3ExprCodeExprList(
 1.80521 +  Parse *pParse,     /* Parsing context */
 1.80522 +  ExprList *pList,   /* The expression list to be coded */
 1.80523 +  int target,        /* Where to write results */
 1.80524 +  u8 flags           /* SQLITE_ECEL_* flags */
 1.80525 +){
 1.80526 +  struct ExprList_item *pItem;
 1.80527 +  int i, n;
 1.80528 +  u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
 1.80529 +  assert( pList!=0 );
 1.80530 +  assert( target>0 );
 1.80531 +  assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
 1.80532 +  n = pList->nExpr;
 1.80533 +  if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
 1.80534 +  for(pItem=pList->a, i=0; i<n; i++, pItem++){
 1.80535 +    Expr *pExpr = pItem->pExpr;
 1.80536 +    if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
 1.80537 +      sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
 1.80538 +    }else{
 1.80539 +      int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
 1.80540 +      if( inReg!=target+i ){
 1.80541 +        VdbeOp *pOp;
 1.80542 +        Vdbe *v = pParse->pVdbe;
 1.80543 +        if( copyOp==OP_Copy
 1.80544 +         && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
 1.80545 +         && pOp->p1+pOp->p3+1==inReg
 1.80546 +         && pOp->p2+pOp->p3+1==target+i
 1.80547 +        ){
 1.80548 +          pOp->p3++;
 1.80549 +        }else{
 1.80550 +          sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
 1.80551 +        }
 1.80552 +      }
 1.80553 +    }
 1.80554 +  }
 1.80555 +  return n;
 1.80556 +}
 1.80557 +
 1.80558 +/*
 1.80559 +** Generate code for a BETWEEN operator.
 1.80560 +**
 1.80561 +**    x BETWEEN y AND z
 1.80562 +**
 1.80563 +** The above is equivalent to 
 1.80564 +**
 1.80565 +**    x>=y AND x<=z
 1.80566 +**
 1.80567 +** Code it as such, taking care to do the common subexpression
 1.80568 +** elementation of x.
 1.80569 +*/
 1.80570 +static void exprCodeBetween(
 1.80571 +  Parse *pParse,    /* Parsing and code generating context */
 1.80572 +  Expr *pExpr,      /* The BETWEEN expression */
 1.80573 +  int dest,         /* Jump here if the jump is taken */
 1.80574 +  int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
 1.80575 +  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
 1.80576 +){
 1.80577 +  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
 1.80578 +  Expr compLeft;    /* The  x>=y  term */
 1.80579 +  Expr compRight;   /* The  x<=z  term */
 1.80580 +  Expr exprX;       /* The  x  subexpression */
 1.80581 +  int regFree1 = 0; /* Temporary use register */
 1.80582 +
 1.80583 +  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
 1.80584 +  exprX = *pExpr->pLeft;
 1.80585 +  exprAnd.op = TK_AND;
 1.80586 +  exprAnd.pLeft = &compLeft;
 1.80587 +  exprAnd.pRight = &compRight;
 1.80588 +  compLeft.op = TK_GE;
 1.80589 +  compLeft.pLeft = &exprX;
 1.80590 +  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
 1.80591 +  compRight.op = TK_LE;
 1.80592 +  compRight.pLeft = &exprX;
 1.80593 +  compRight.pRight = pExpr->x.pList->a[1].pExpr;
 1.80594 +  exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
 1.80595 +  if( jumpIfTrue ){
 1.80596 +    sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
 1.80597 +  }else{
 1.80598 +    sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
 1.80599 +  }
 1.80600 +  sqlite3ReleaseTempReg(pParse, regFree1);
 1.80601 +
 1.80602 +  /* Ensure adequate test coverage */
 1.80603 +  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
 1.80604 +  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
 1.80605 +  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
 1.80606 +  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
 1.80607 +  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
 1.80608 +  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
 1.80609 +  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
 1.80610 +  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
 1.80611 +}
 1.80612 +
 1.80613 +/*
 1.80614 +** Generate code for a boolean expression such that a jump is made
 1.80615 +** to the label "dest" if the expression is true but execution
 1.80616 +** continues straight thru if the expression is false.
 1.80617 +**
 1.80618 +** If the expression evaluates to NULL (neither true nor false), then
 1.80619 +** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
 1.80620 +**
 1.80621 +** This code depends on the fact that certain token values (ex: TK_EQ)
 1.80622 +** are the same as opcode values (ex: OP_Eq) that implement the corresponding
 1.80623 +** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
 1.80624 +** the make process cause these values to align.  Assert()s in the code
 1.80625 +** below verify that the numbers are aligned correctly.
 1.80626 +*/
 1.80627 +SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
 1.80628 +  Vdbe *v = pParse->pVdbe;
 1.80629 +  int op = 0;
 1.80630 +  int regFree1 = 0;
 1.80631 +  int regFree2 = 0;
 1.80632 +  int r1, r2;
 1.80633 +
 1.80634 +  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
 1.80635 +  if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
 1.80636 +  if( NEVER(pExpr==0) ) return;  /* No way this can happen */
 1.80637 +  op = pExpr->op;
 1.80638 +  switch( op ){
 1.80639 +    case TK_AND: {
 1.80640 +      int d2 = sqlite3VdbeMakeLabel(v);
 1.80641 +      testcase( jumpIfNull==0 );
 1.80642 +      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
 1.80643 +      sqlite3ExprCachePush(pParse);
 1.80644 +      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
 1.80645 +      sqlite3VdbeResolveLabel(v, d2);
 1.80646 +      sqlite3ExprCachePop(pParse, 1);
 1.80647 +      break;
 1.80648 +    }
 1.80649 +    case TK_OR: {
 1.80650 +      testcase( jumpIfNull==0 );
 1.80651 +      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
 1.80652 +      sqlite3ExprCachePush(pParse);
 1.80653 +      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
 1.80654 +      sqlite3ExprCachePop(pParse, 1);
 1.80655 +      break;
 1.80656 +    }
 1.80657 +    case TK_NOT: {
 1.80658 +      testcase( jumpIfNull==0 );
 1.80659 +      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
 1.80660 +      break;
 1.80661 +    }
 1.80662 +    case TK_LT:
 1.80663 +    case TK_LE:
 1.80664 +    case TK_GT:
 1.80665 +    case TK_GE:
 1.80666 +    case TK_NE:
 1.80667 +    case TK_EQ: {
 1.80668 +      testcase( jumpIfNull==0 );
 1.80669 +      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
 1.80670 +      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
 1.80671 +      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
 1.80672 +                  r1, r2, dest, jumpIfNull);
 1.80673 +      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
 1.80674 +      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
 1.80675 +      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
 1.80676 +      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
 1.80677 +      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
 1.80678 +      assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
 1.80679 +      testcase( regFree1==0 );
 1.80680 +      testcase( regFree2==0 );
 1.80681 +      break;
 1.80682 +    }
 1.80683 +    case TK_IS:
 1.80684 +    case TK_ISNOT: {
 1.80685 +      testcase( op==TK_IS );
 1.80686 +      testcase( op==TK_ISNOT );
 1.80687 +      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
 1.80688 +      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
 1.80689 +      op = (op==TK_IS) ? TK_EQ : TK_NE;
 1.80690 +      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
 1.80691 +                  r1, r2, dest, SQLITE_NULLEQ);
 1.80692 +      VdbeCoverageIf(v, op==TK_EQ);
 1.80693 +      VdbeCoverageIf(v, op==TK_NE);
 1.80694 +      testcase( regFree1==0 );
 1.80695 +      testcase( regFree2==0 );
 1.80696 +      break;
 1.80697 +    }
 1.80698 +    case TK_ISNULL:
 1.80699 +    case TK_NOTNULL: {
 1.80700 +      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
 1.80701 +      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
 1.80702 +      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
 1.80703 +      sqlite3VdbeAddOp2(v, op, r1, dest);
 1.80704 +      VdbeCoverageIf(v, op==TK_ISNULL);
 1.80705 +      VdbeCoverageIf(v, op==TK_NOTNULL);
 1.80706 +      testcase( regFree1==0 );
 1.80707 +      break;
 1.80708 +    }
 1.80709 +    case TK_BETWEEN: {
 1.80710 +      testcase( jumpIfNull==0 );
 1.80711 +      exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
 1.80712 +      break;
 1.80713 +    }
 1.80714 +#ifndef SQLITE_OMIT_SUBQUERY
 1.80715 +    case TK_IN: {
 1.80716 +      int destIfFalse = sqlite3VdbeMakeLabel(v);
 1.80717 +      int destIfNull = jumpIfNull ? dest : destIfFalse;
 1.80718 +      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
 1.80719 +      sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
 1.80720 +      sqlite3VdbeResolveLabel(v, destIfFalse);
 1.80721 +      break;
 1.80722 +    }
 1.80723 +#endif
 1.80724 +    default: {
 1.80725 +      if( exprAlwaysTrue(pExpr) ){
 1.80726 +        sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
 1.80727 +      }else if( exprAlwaysFalse(pExpr) ){
 1.80728 +        /* No-op */
 1.80729 +      }else{
 1.80730 +        r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
 1.80731 +        sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
 1.80732 +        VdbeCoverage(v);
 1.80733 +        testcase( regFree1==0 );
 1.80734 +        testcase( jumpIfNull==0 );
 1.80735 +      }
 1.80736 +      break;
 1.80737 +    }
 1.80738 +  }
 1.80739 +  sqlite3ReleaseTempReg(pParse, regFree1);
 1.80740 +  sqlite3ReleaseTempReg(pParse, regFree2);  
 1.80741 +}
 1.80742 +
 1.80743 +/*
 1.80744 +** Generate code for a boolean expression such that a jump is made
 1.80745 +** to the label "dest" if the expression is false but execution
 1.80746 +** continues straight thru if the expression is true.
 1.80747 +**
 1.80748 +** If the expression evaluates to NULL (neither true nor false) then
 1.80749 +** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
 1.80750 +** is 0.
 1.80751 +*/
 1.80752 +SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
 1.80753 +  Vdbe *v = pParse->pVdbe;
 1.80754 +  int op = 0;
 1.80755 +  int regFree1 = 0;
 1.80756 +  int regFree2 = 0;
 1.80757 +  int r1, r2;
 1.80758 +
 1.80759 +  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
 1.80760 +  if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
 1.80761 +  if( pExpr==0 )    return;
 1.80762 +
 1.80763 +  /* The value of pExpr->op and op are related as follows:
 1.80764 +  **
 1.80765 +  **       pExpr->op            op
 1.80766 +  **       ---------          ----------
 1.80767 +  **       TK_ISNULL          OP_NotNull
 1.80768 +  **       TK_NOTNULL         OP_IsNull
 1.80769 +  **       TK_NE              OP_Eq
 1.80770 +  **       TK_EQ              OP_Ne
 1.80771 +  **       TK_GT              OP_Le
 1.80772 +  **       TK_LE              OP_Gt
 1.80773 +  **       TK_GE              OP_Lt
 1.80774 +  **       TK_LT              OP_Ge
 1.80775 +  **
 1.80776 +  ** For other values of pExpr->op, op is undefined and unused.
 1.80777 +  ** The value of TK_ and OP_ constants are arranged such that we
 1.80778 +  ** can compute the mapping above using the following expression.
 1.80779 +  ** Assert()s verify that the computation is correct.
 1.80780 +  */
 1.80781 +  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
 1.80782 +
 1.80783 +  /* Verify correct alignment of TK_ and OP_ constants
 1.80784 +  */
 1.80785 +  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
 1.80786 +  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
 1.80787 +  assert( pExpr->op!=TK_NE || op==OP_Eq );
 1.80788 +  assert( pExpr->op!=TK_EQ || op==OP_Ne );
 1.80789 +  assert( pExpr->op!=TK_LT || op==OP_Ge );
 1.80790 +  assert( pExpr->op!=TK_LE || op==OP_Gt );
 1.80791 +  assert( pExpr->op!=TK_GT || op==OP_Le );
 1.80792 +  assert( pExpr->op!=TK_GE || op==OP_Lt );
 1.80793 +
 1.80794 +  switch( pExpr->op ){
 1.80795 +    case TK_AND: {
 1.80796 +      testcase( jumpIfNull==0 );
 1.80797 +      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
 1.80798 +      sqlite3ExprCachePush(pParse);
 1.80799 +      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
 1.80800 +      sqlite3ExprCachePop(pParse, 1);
 1.80801 +      break;
 1.80802 +    }
 1.80803 +    case TK_OR: {
 1.80804 +      int d2 = sqlite3VdbeMakeLabel(v);
 1.80805 +      testcase( jumpIfNull==0 );
 1.80806 +      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
 1.80807 +      sqlite3ExprCachePush(pParse);
 1.80808 +      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
 1.80809 +      sqlite3VdbeResolveLabel(v, d2);
 1.80810 +      sqlite3ExprCachePop(pParse, 1);
 1.80811 +      break;
 1.80812 +    }
 1.80813 +    case TK_NOT: {
 1.80814 +      testcase( jumpIfNull==0 );
 1.80815 +      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
 1.80816 +      break;
 1.80817 +    }
 1.80818 +    case TK_LT:
 1.80819 +    case TK_LE:
 1.80820 +    case TK_GT:
 1.80821 +    case TK_GE:
 1.80822 +    case TK_NE:
 1.80823 +    case TK_EQ: {
 1.80824 +      testcase( jumpIfNull==0 );
 1.80825 +      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
 1.80826 +      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
 1.80827 +      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
 1.80828 +                  r1, r2, dest, jumpIfNull);
 1.80829 +      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
 1.80830 +      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
 1.80831 +      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
 1.80832 +      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
 1.80833 +      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
 1.80834 +      assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
 1.80835 +      testcase( regFree1==0 );
 1.80836 +      testcase( regFree2==0 );
 1.80837 +      break;
 1.80838 +    }
 1.80839 +    case TK_IS:
 1.80840 +    case TK_ISNOT: {
 1.80841 +      testcase( pExpr->op==TK_IS );
 1.80842 +      testcase( pExpr->op==TK_ISNOT );
 1.80843 +      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
 1.80844 +      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
 1.80845 +      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
 1.80846 +      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
 1.80847 +                  r1, r2, dest, SQLITE_NULLEQ);
 1.80848 +      VdbeCoverageIf(v, op==TK_EQ);
 1.80849 +      VdbeCoverageIf(v, op==TK_NE);
 1.80850 +      testcase( regFree1==0 );
 1.80851 +      testcase( regFree2==0 );
 1.80852 +      break;
 1.80853 +    }
 1.80854 +    case TK_ISNULL:
 1.80855 +    case TK_NOTNULL: {
 1.80856 +      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
 1.80857 +      sqlite3VdbeAddOp2(v, op, r1, dest);
 1.80858 +      testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
 1.80859 +      testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
 1.80860 +      testcase( regFree1==0 );
 1.80861 +      break;
 1.80862 +    }
 1.80863 +    case TK_BETWEEN: {
 1.80864 +      testcase( jumpIfNull==0 );
 1.80865 +      exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
 1.80866 +      break;
 1.80867 +    }
 1.80868 +#ifndef SQLITE_OMIT_SUBQUERY
 1.80869 +    case TK_IN: {
 1.80870 +      if( jumpIfNull ){
 1.80871 +        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
 1.80872 +      }else{
 1.80873 +        int destIfNull = sqlite3VdbeMakeLabel(v);
 1.80874 +        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
 1.80875 +        sqlite3VdbeResolveLabel(v, destIfNull);
 1.80876 +      }
 1.80877 +      break;
 1.80878 +    }
 1.80879 +#endif
 1.80880 +    default: {
 1.80881 +      if( exprAlwaysFalse(pExpr) ){
 1.80882 +        sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
 1.80883 +      }else if( exprAlwaysTrue(pExpr) ){
 1.80884 +        /* no-op */
 1.80885 +      }else{
 1.80886 +        r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
 1.80887 +        sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
 1.80888 +        VdbeCoverage(v);
 1.80889 +        testcase( regFree1==0 );
 1.80890 +        testcase( jumpIfNull==0 );
 1.80891 +      }
 1.80892 +      break;
 1.80893 +    }
 1.80894 +  }
 1.80895 +  sqlite3ReleaseTempReg(pParse, regFree1);
 1.80896 +  sqlite3ReleaseTempReg(pParse, regFree2);
 1.80897 +}
 1.80898 +
 1.80899 +/*
 1.80900 +** Do a deep comparison of two expression trees.  Return 0 if the two
 1.80901 +** expressions are completely identical.  Return 1 if they differ only
 1.80902 +** by a COLLATE operator at the top level.  Return 2 if there are differences
 1.80903 +** other than the top-level COLLATE operator.
 1.80904 +**
 1.80905 +** If any subelement of pB has Expr.iTable==(-1) then it is allowed
 1.80906 +** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
 1.80907 +**
 1.80908 +** The pA side might be using TK_REGISTER.  If that is the case and pB is
 1.80909 +** not using TK_REGISTER but is otherwise equivalent, then still return 0.
 1.80910 +**
 1.80911 +** Sometimes this routine will return 2 even if the two expressions
 1.80912 +** really are equivalent.  If we cannot prove that the expressions are
 1.80913 +** identical, we return 2 just to be safe.  So if this routine
 1.80914 +** returns 2, then you do not really know for certain if the two
 1.80915 +** expressions are the same.  But if you get a 0 or 1 return, then you
 1.80916 +** can be sure the expressions are the same.  In the places where
 1.80917 +** this routine is used, it does not hurt to get an extra 2 - that
 1.80918 +** just might result in some slightly slower code.  But returning
 1.80919 +** an incorrect 0 or 1 could lead to a malfunction.
 1.80920 +*/
 1.80921 +SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
 1.80922 +  u32 combinedFlags;
 1.80923 +  if( pA==0 || pB==0 ){
 1.80924 +    return pB==pA ? 0 : 2;
 1.80925 +  }
 1.80926 +  combinedFlags = pA->flags | pB->flags;
 1.80927 +  if( combinedFlags & EP_IntValue ){
 1.80928 +    if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
 1.80929 +      return 0;
 1.80930 +    }
 1.80931 +    return 2;
 1.80932 +  }
 1.80933 +  if( pA->op!=pB->op ){
 1.80934 +    if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
 1.80935 +      return 1;
 1.80936 +    }
 1.80937 +    if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
 1.80938 +      return 1;
 1.80939 +    }
 1.80940 +    return 2;
 1.80941 +  }
 1.80942 +  if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken ){
 1.80943 +    if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
 1.80944 +      return pA->op==TK_COLLATE ? 1 : 2;
 1.80945 +    }
 1.80946 +  }
 1.80947 +  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
 1.80948 +  if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
 1.80949 +    if( combinedFlags & EP_xIsSelect ) return 2;
 1.80950 +    if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
 1.80951 +    if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
 1.80952 +    if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
 1.80953 +    if( ALWAYS((combinedFlags & EP_Reduced)==0) ){
 1.80954 +      if( pA->iColumn!=pB->iColumn ) return 2;
 1.80955 +      if( pA->iTable!=pB->iTable 
 1.80956 +       && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
 1.80957 +    }
 1.80958 +  }
 1.80959 +  return 0;
 1.80960 +}
 1.80961 +
 1.80962 +/*
 1.80963 +** Compare two ExprList objects.  Return 0 if they are identical and 
 1.80964 +** non-zero if they differ in any way.
 1.80965 +**
 1.80966 +** If any subelement of pB has Expr.iTable==(-1) then it is allowed
 1.80967 +** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
 1.80968 +**
 1.80969 +** This routine might return non-zero for equivalent ExprLists.  The
 1.80970 +** only consequence will be disabled optimizations.  But this routine
 1.80971 +** must never return 0 if the two ExprList objects are different, or
 1.80972 +** a malfunction will result.
 1.80973 +**
 1.80974 +** Two NULL pointers are considered to be the same.  But a NULL pointer
 1.80975 +** always differs from a non-NULL pointer.
 1.80976 +*/
 1.80977 +SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
 1.80978 +  int i;
 1.80979 +  if( pA==0 && pB==0 ) return 0;
 1.80980 +  if( pA==0 || pB==0 ) return 1;
 1.80981 +  if( pA->nExpr!=pB->nExpr ) return 1;
 1.80982 +  for(i=0; i<pA->nExpr; i++){
 1.80983 +    Expr *pExprA = pA->a[i].pExpr;
 1.80984 +    Expr *pExprB = pB->a[i].pExpr;
 1.80985 +    if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
 1.80986 +    if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
 1.80987 +  }
 1.80988 +  return 0;
 1.80989 +}
 1.80990 +
 1.80991 +/*
 1.80992 +** Return true if we can prove the pE2 will always be true if pE1 is
 1.80993 +** true.  Return false if we cannot complete the proof or if pE2 might
 1.80994 +** be false.  Examples:
 1.80995 +**
 1.80996 +**     pE1: x==5       pE2: x==5             Result: true
 1.80997 +**     pE1: x>0        pE2: x==5             Result: false
 1.80998 +**     pE1: x=21       pE2: x=21 OR y=43     Result: true
 1.80999 +**     pE1: x!=123     pE2: x IS NOT NULL    Result: true
 1.81000 +**     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
 1.81001 +**     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
 1.81002 +**     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
 1.81003 +**
 1.81004 +** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
 1.81005 +** Expr.iTable<0 then assume a table number given by iTab.
 1.81006 +**
 1.81007 +** When in doubt, return false.  Returning true might give a performance
 1.81008 +** improvement.  Returning false might cause a performance reduction, but
 1.81009 +** it will always give the correct answer and is hence always safe.
 1.81010 +*/
 1.81011 +SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
 1.81012 +  if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
 1.81013 +    return 1;
 1.81014 +  }
 1.81015 +  if( pE2->op==TK_OR
 1.81016 +   && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
 1.81017 +             || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
 1.81018 +  ){
 1.81019 +    return 1;
 1.81020 +  }
 1.81021 +  if( pE2->op==TK_NOTNULL
 1.81022 +   && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
 1.81023 +   && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
 1.81024 +  ){
 1.81025 +    return 1;
 1.81026 +  }
 1.81027 +  return 0;
 1.81028 +}
 1.81029 +
 1.81030 +/*
 1.81031 +** An instance of the following structure is used by the tree walker
 1.81032 +** to count references to table columns in the arguments of an 
 1.81033 +** aggregate function, in order to implement the
 1.81034 +** sqlite3FunctionThisSrc() routine.
 1.81035 +*/
 1.81036 +struct SrcCount {
 1.81037 +  SrcList *pSrc;   /* One particular FROM clause in a nested query */
 1.81038 +  int nThis;       /* Number of references to columns in pSrcList */
 1.81039 +  int nOther;      /* Number of references to columns in other FROM clauses */
 1.81040 +};
 1.81041 +
 1.81042 +/*
 1.81043 +** Count the number of references to columns.
 1.81044 +*/
 1.81045 +static int exprSrcCount(Walker *pWalker, Expr *pExpr){
 1.81046 +  /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
 1.81047 +  ** is always called before sqlite3ExprAnalyzeAggregates() and so the
 1.81048 +  ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
 1.81049 +  ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
 1.81050 +  ** NEVER() will need to be removed. */
 1.81051 +  if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
 1.81052 +    int i;
 1.81053 +    struct SrcCount *p = pWalker->u.pSrcCount;
 1.81054 +    SrcList *pSrc = p->pSrc;
 1.81055 +    for(i=0; i<pSrc->nSrc; i++){
 1.81056 +      if( pExpr->iTable==pSrc->a[i].iCursor ) break;
 1.81057 +    }
 1.81058 +    if( i<pSrc->nSrc ){
 1.81059 +      p->nThis++;
 1.81060 +    }else{
 1.81061 +      p->nOther++;
 1.81062 +    }
 1.81063 +  }
 1.81064 +  return WRC_Continue;
 1.81065 +}
 1.81066 +
 1.81067 +/*
 1.81068 +** Determine if any of the arguments to the pExpr Function reference
 1.81069 +** pSrcList.  Return true if they do.  Also return true if the function
 1.81070 +** has no arguments or has only constant arguments.  Return false if pExpr
 1.81071 +** references columns but not columns of tables found in pSrcList.
 1.81072 +*/
 1.81073 +SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
 1.81074 +  Walker w;
 1.81075 +  struct SrcCount cnt;
 1.81076 +  assert( pExpr->op==TK_AGG_FUNCTION );
 1.81077 +  memset(&w, 0, sizeof(w));
 1.81078 +  w.xExprCallback = exprSrcCount;
 1.81079 +  w.u.pSrcCount = &cnt;
 1.81080 +  cnt.pSrc = pSrcList;
 1.81081 +  cnt.nThis = 0;
 1.81082 +  cnt.nOther = 0;
 1.81083 +  sqlite3WalkExprList(&w, pExpr->x.pList);
 1.81084 +  return cnt.nThis>0 || cnt.nOther==0;
 1.81085 +}
 1.81086 +
 1.81087 +/*
 1.81088 +** Add a new element to the pAggInfo->aCol[] array.  Return the index of
 1.81089 +** the new element.  Return a negative number if malloc fails.
 1.81090 +*/
 1.81091 +static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
 1.81092 +  int i;
 1.81093 +  pInfo->aCol = sqlite3ArrayAllocate(
 1.81094 +       db,
 1.81095 +       pInfo->aCol,
 1.81096 +       sizeof(pInfo->aCol[0]),
 1.81097 +       &pInfo->nColumn,
 1.81098 +       &i
 1.81099 +  );
 1.81100 +  return i;
 1.81101 +}    
 1.81102 +
 1.81103 +/*
 1.81104 +** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
 1.81105 +** the new element.  Return a negative number if malloc fails.
 1.81106 +*/
 1.81107 +static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
 1.81108 +  int i;
 1.81109 +  pInfo->aFunc = sqlite3ArrayAllocate(
 1.81110 +       db, 
 1.81111 +       pInfo->aFunc,
 1.81112 +       sizeof(pInfo->aFunc[0]),
 1.81113 +       &pInfo->nFunc,
 1.81114 +       &i
 1.81115 +  );
 1.81116 +  return i;
 1.81117 +}    
 1.81118 +
 1.81119 +/*
 1.81120 +** This is the xExprCallback for a tree walker.  It is used to
 1.81121 +** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
 1.81122 +** for additional information.
 1.81123 +*/
 1.81124 +static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
 1.81125 +  int i;
 1.81126 +  NameContext *pNC = pWalker->u.pNC;
 1.81127 +  Parse *pParse = pNC->pParse;
 1.81128 +  SrcList *pSrcList = pNC->pSrcList;
 1.81129 +  AggInfo *pAggInfo = pNC->pAggInfo;
 1.81130 +
 1.81131 +  switch( pExpr->op ){
 1.81132 +    case TK_AGG_COLUMN:
 1.81133 +    case TK_COLUMN: {
 1.81134 +      testcase( pExpr->op==TK_AGG_COLUMN );
 1.81135 +      testcase( pExpr->op==TK_COLUMN );
 1.81136 +      /* Check to see if the column is in one of the tables in the FROM
 1.81137 +      ** clause of the aggregate query */
 1.81138 +      if( ALWAYS(pSrcList!=0) ){
 1.81139 +        struct SrcList_item *pItem = pSrcList->a;
 1.81140 +        for(i=0; i<pSrcList->nSrc; i++, pItem++){
 1.81141 +          struct AggInfo_col *pCol;
 1.81142 +          assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
 1.81143 +          if( pExpr->iTable==pItem->iCursor ){
 1.81144 +            /* If we reach this point, it means that pExpr refers to a table
 1.81145 +            ** that is in the FROM clause of the aggregate query.  
 1.81146 +            **
 1.81147 +            ** Make an entry for the column in pAggInfo->aCol[] if there
 1.81148 +            ** is not an entry there already.
 1.81149 +            */
 1.81150 +            int k;
 1.81151 +            pCol = pAggInfo->aCol;
 1.81152 +            for(k=0; k<pAggInfo->nColumn; k++, pCol++){
 1.81153 +              if( pCol->iTable==pExpr->iTable &&
 1.81154 +                  pCol->iColumn==pExpr->iColumn ){
 1.81155 +                break;
 1.81156 +              }
 1.81157 +            }
 1.81158 +            if( (k>=pAggInfo->nColumn)
 1.81159 +             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
 1.81160 +            ){
 1.81161 +              pCol = &pAggInfo->aCol[k];
 1.81162 +              pCol->pTab = pExpr->pTab;
 1.81163 +              pCol->iTable = pExpr->iTable;
 1.81164 +              pCol->iColumn = pExpr->iColumn;
 1.81165 +              pCol->iMem = ++pParse->nMem;
 1.81166 +              pCol->iSorterColumn = -1;
 1.81167 +              pCol->pExpr = pExpr;
 1.81168 +              if( pAggInfo->pGroupBy ){
 1.81169 +                int j, n;
 1.81170 +                ExprList *pGB = pAggInfo->pGroupBy;
 1.81171 +                struct ExprList_item *pTerm = pGB->a;
 1.81172 +                n = pGB->nExpr;
 1.81173 +                for(j=0; j<n; j++, pTerm++){
 1.81174 +                  Expr *pE = pTerm->pExpr;
 1.81175 +                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
 1.81176 +                      pE->iColumn==pExpr->iColumn ){
 1.81177 +                    pCol->iSorterColumn = j;
 1.81178 +                    break;
 1.81179 +                  }
 1.81180 +                }
 1.81181 +              }
 1.81182 +              if( pCol->iSorterColumn<0 ){
 1.81183 +                pCol->iSorterColumn = pAggInfo->nSortingColumn++;
 1.81184 +              }
 1.81185 +            }
 1.81186 +            /* There is now an entry for pExpr in pAggInfo->aCol[] (either
 1.81187 +            ** because it was there before or because we just created it).
 1.81188 +            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
 1.81189 +            ** pAggInfo->aCol[] entry.
 1.81190 +            */
 1.81191 +            ExprSetVVAProperty(pExpr, EP_NoReduce);
 1.81192 +            pExpr->pAggInfo = pAggInfo;
 1.81193 +            pExpr->op = TK_AGG_COLUMN;
 1.81194 +            pExpr->iAgg = (i16)k;
 1.81195 +            break;
 1.81196 +          } /* endif pExpr->iTable==pItem->iCursor */
 1.81197 +        } /* end loop over pSrcList */
 1.81198 +      }
 1.81199 +      return WRC_Prune;
 1.81200 +    }
 1.81201 +    case TK_AGG_FUNCTION: {
 1.81202 +      if( (pNC->ncFlags & NC_InAggFunc)==0
 1.81203 +       && pWalker->walkerDepth==pExpr->op2
 1.81204 +      ){
 1.81205 +        /* Check to see if pExpr is a duplicate of another aggregate 
 1.81206 +        ** function that is already in the pAggInfo structure
 1.81207 +        */
 1.81208 +        struct AggInfo_func *pItem = pAggInfo->aFunc;
 1.81209 +        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
 1.81210 +          if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
 1.81211 +            break;
 1.81212 +          }
 1.81213 +        }
 1.81214 +        if( i>=pAggInfo->nFunc ){
 1.81215 +          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
 1.81216 +          */
 1.81217 +          u8 enc = ENC(pParse->db);
 1.81218 +          i = addAggInfoFunc(pParse->db, pAggInfo);
 1.81219 +          if( i>=0 ){
 1.81220 +            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
 1.81221 +            pItem = &pAggInfo->aFunc[i];
 1.81222 +            pItem->pExpr = pExpr;
 1.81223 +            pItem->iMem = ++pParse->nMem;
 1.81224 +            assert( !ExprHasProperty(pExpr, EP_IntValue) );
 1.81225 +            pItem->pFunc = sqlite3FindFunction(pParse->db,
 1.81226 +                   pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
 1.81227 +                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
 1.81228 +            if( pExpr->flags & EP_Distinct ){
 1.81229 +              pItem->iDistinct = pParse->nTab++;
 1.81230 +            }else{
 1.81231 +              pItem->iDistinct = -1;
 1.81232 +            }
 1.81233 +          }
 1.81234 +        }
 1.81235 +        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
 1.81236 +        */
 1.81237 +        assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
 1.81238 +        ExprSetVVAProperty(pExpr, EP_NoReduce);
 1.81239 +        pExpr->iAgg = (i16)i;
 1.81240 +        pExpr->pAggInfo = pAggInfo;
 1.81241 +        return WRC_Prune;
 1.81242 +      }else{
 1.81243 +        return WRC_Continue;
 1.81244 +      }
 1.81245 +    }
 1.81246 +  }
 1.81247 +  return WRC_Continue;
 1.81248 +}
 1.81249 +static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
 1.81250 +  UNUSED_PARAMETER(pWalker);
 1.81251 +  UNUSED_PARAMETER(pSelect);
 1.81252 +  return WRC_Continue;
 1.81253 +}
 1.81254 +
 1.81255 +/*
 1.81256 +** Analyze the pExpr expression looking for aggregate functions and
 1.81257 +** for variables that need to be added to AggInfo object that pNC->pAggInfo
 1.81258 +** points to.  Additional entries are made on the AggInfo object as
 1.81259 +** necessary.
 1.81260 +**
 1.81261 +** This routine should only be called after the expression has been
 1.81262 +** analyzed by sqlite3ResolveExprNames().
 1.81263 +*/
 1.81264 +SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
 1.81265 +  Walker w;
 1.81266 +  memset(&w, 0, sizeof(w));
 1.81267 +  w.xExprCallback = analyzeAggregate;
 1.81268 +  w.xSelectCallback = analyzeAggregatesInSelect;
 1.81269 +  w.u.pNC = pNC;
 1.81270 +  assert( pNC->pSrcList!=0 );
 1.81271 +  sqlite3WalkExpr(&w, pExpr);
 1.81272 +}
 1.81273 +
 1.81274 +/*
 1.81275 +** Call sqlite3ExprAnalyzeAggregates() for every expression in an
 1.81276 +** expression list.  Return the number of errors.
 1.81277 +**
 1.81278 +** If an error is found, the analysis is cut short.
 1.81279 +*/
 1.81280 +SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
 1.81281 +  struct ExprList_item *pItem;
 1.81282 +  int i;
 1.81283 +  if( pList ){
 1.81284 +    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
 1.81285 +      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
 1.81286 +    }
 1.81287 +  }
 1.81288 +}
 1.81289 +
 1.81290 +/*
 1.81291 +** Allocate a single new register for use to hold some intermediate result.
 1.81292 +*/
 1.81293 +SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
 1.81294 +  if( pParse->nTempReg==0 ){
 1.81295 +    return ++pParse->nMem;
 1.81296 +  }
 1.81297 +  return pParse->aTempReg[--pParse->nTempReg];
 1.81298 +}
 1.81299 +
 1.81300 +/*
 1.81301 +** Deallocate a register, making available for reuse for some other
 1.81302 +** purpose.
 1.81303 +**
 1.81304 +** If a register is currently being used by the column cache, then
 1.81305 +** the dallocation is deferred until the column cache line that uses
 1.81306 +** the register becomes stale.
 1.81307 +*/
 1.81308 +SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
 1.81309 +  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
 1.81310 +    int i;
 1.81311 +    struct yColCache *p;
 1.81312 +    for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
 1.81313 +      if( p->iReg==iReg ){
 1.81314 +        p->tempReg = 1;
 1.81315 +        return;
 1.81316 +      }
 1.81317 +    }
 1.81318 +    pParse->aTempReg[pParse->nTempReg++] = iReg;
 1.81319 +  }
 1.81320 +}
 1.81321 +
 1.81322 +/*
 1.81323 +** Allocate or deallocate a block of nReg consecutive registers
 1.81324 +*/
 1.81325 +SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
 1.81326 +  int i, n;
 1.81327 +  i = pParse->iRangeReg;
 1.81328 +  n = pParse->nRangeReg;
 1.81329 +  if( nReg<=n ){
 1.81330 +    assert( !usedAsColumnCache(pParse, i, i+n-1) );
 1.81331 +    pParse->iRangeReg += nReg;
 1.81332 +    pParse->nRangeReg -= nReg;
 1.81333 +  }else{
 1.81334 +    i = pParse->nMem+1;
 1.81335 +    pParse->nMem += nReg;
 1.81336 +  }
 1.81337 +  return i;
 1.81338 +}
 1.81339 +SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
 1.81340 +  sqlite3ExprCacheRemove(pParse, iReg, nReg);
 1.81341 +  if( nReg>pParse->nRangeReg ){
 1.81342 +    pParse->nRangeReg = nReg;
 1.81343 +    pParse->iRangeReg = iReg;
 1.81344 +  }
 1.81345 +}
 1.81346 +
 1.81347 +/*
 1.81348 +** Mark all temporary registers as being unavailable for reuse.
 1.81349 +*/
 1.81350 +SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
 1.81351 +  pParse->nTempReg = 0;
 1.81352 +  pParse->nRangeReg = 0;
 1.81353 +}
 1.81354 +
 1.81355 +/************** End of expr.c ************************************************/
 1.81356 +/************** Begin file alter.c *******************************************/
 1.81357 +/*
 1.81358 +** 2005 February 15
 1.81359 +**
 1.81360 +** The author disclaims copyright to this source code.  In place of
 1.81361 +** a legal notice, here is a blessing:
 1.81362 +**
 1.81363 +**    May you do good and not evil.
 1.81364 +**    May you find forgiveness for yourself and forgive others.
 1.81365 +**    May you share freely, never taking more than you give.
 1.81366 +**
 1.81367 +*************************************************************************
 1.81368 +** This file contains C code routines that used to generate VDBE code
 1.81369 +** that implements the ALTER TABLE command.
 1.81370 +*/
 1.81371 +
 1.81372 +/*
 1.81373 +** The code in this file only exists if we are not omitting the
 1.81374 +** ALTER TABLE logic from the build.
 1.81375 +*/
 1.81376 +#ifndef SQLITE_OMIT_ALTERTABLE
 1.81377 +
 1.81378 +
 1.81379 +/*
 1.81380 +** This function is used by SQL generated to implement the 
 1.81381 +** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
 1.81382 +** CREATE INDEX command. The second is a table name. The table name in 
 1.81383 +** the CREATE TABLE or CREATE INDEX statement is replaced with the third
 1.81384 +** argument and the result returned. Examples:
 1.81385 +**
 1.81386 +** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
 1.81387 +**     -> 'CREATE TABLE def(a, b, c)'
 1.81388 +**
 1.81389 +** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
 1.81390 +**     -> 'CREATE INDEX i ON def(a, b, c)'
 1.81391 +*/
 1.81392 +static void renameTableFunc(
 1.81393 +  sqlite3_context *context,
 1.81394 +  int NotUsed,
 1.81395 +  sqlite3_value **argv
 1.81396 +){
 1.81397 +  unsigned char const *zSql = sqlite3_value_text(argv[0]);
 1.81398 +  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
 1.81399 +
 1.81400 +  int token;
 1.81401 +  Token tname;
 1.81402 +  unsigned char const *zCsr = zSql;
 1.81403 +  int len = 0;
 1.81404 +  char *zRet;
 1.81405 +
 1.81406 +  sqlite3 *db = sqlite3_context_db_handle(context);
 1.81407 +
 1.81408 +  UNUSED_PARAMETER(NotUsed);
 1.81409 +
 1.81410 +  /* The principle used to locate the table name in the CREATE TABLE 
 1.81411 +  ** statement is that the table name is the first non-space token that
 1.81412 +  ** is immediately followed by a TK_LP or TK_USING token.
 1.81413 +  */
 1.81414 +  if( zSql ){
 1.81415 +    do {
 1.81416 +      if( !*zCsr ){
 1.81417 +        /* Ran out of input before finding an opening bracket. Return NULL. */
 1.81418 +        return;
 1.81419 +      }
 1.81420 +
 1.81421 +      /* Store the token that zCsr points to in tname. */
 1.81422 +      tname.z = (char*)zCsr;
 1.81423 +      tname.n = len;
 1.81424 +
 1.81425 +      /* Advance zCsr to the next token. Store that token type in 'token',
 1.81426 +      ** and its length in 'len' (to be used next iteration of this loop).
 1.81427 +      */
 1.81428 +      do {
 1.81429 +        zCsr += len;
 1.81430 +        len = sqlite3GetToken(zCsr, &token);
 1.81431 +      } while( token==TK_SPACE );
 1.81432 +      assert( len>0 );
 1.81433 +    } while( token!=TK_LP && token!=TK_USING );
 1.81434 +
 1.81435 +    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
 1.81436 +       zSql, zTableName, tname.z+tname.n);
 1.81437 +    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
 1.81438 +  }
 1.81439 +}
 1.81440 +
 1.81441 +/*
 1.81442 +** This C function implements an SQL user function that is used by SQL code
 1.81443 +** generated by the ALTER TABLE ... RENAME command to modify the definition
 1.81444 +** of any foreign key constraints that use the table being renamed as the 
 1.81445 +** parent table. It is passed three arguments:
 1.81446 +**
 1.81447 +**   1) The complete text of the CREATE TABLE statement being modified,
 1.81448 +**   2) The old name of the table being renamed, and
 1.81449 +**   3) The new name of the table being renamed.
 1.81450 +**
 1.81451 +** It returns the new CREATE TABLE statement. For example:
 1.81452 +**
 1.81453 +**   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
 1.81454 +**       -> 'CREATE TABLE t1(a REFERENCES t3)'
 1.81455 +*/
 1.81456 +#ifndef SQLITE_OMIT_FOREIGN_KEY
 1.81457 +static void renameParentFunc(
 1.81458 +  sqlite3_context *context,
 1.81459 +  int NotUsed,
 1.81460 +  sqlite3_value **argv
 1.81461 +){
 1.81462 +  sqlite3 *db = sqlite3_context_db_handle(context);
 1.81463 +  char *zOutput = 0;
 1.81464 +  char *zResult;
 1.81465 +  unsigned char const *zInput = sqlite3_value_text(argv[0]);
 1.81466 +  unsigned char const *zOld = sqlite3_value_text(argv[1]);
 1.81467 +  unsigned char const *zNew = sqlite3_value_text(argv[2]);
 1.81468 +
 1.81469 +  unsigned const char *z;         /* Pointer to token */
 1.81470 +  int n;                          /* Length of token z */
 1.81471 +  int token;                      /* Type of token */
 1.81472 +
 1.81473 +  UNUSED_PARAMETER(NotUsed);
 1.81474 +  for(z=zInput; *z; z=z+n){
 1.81475 +    n = sqlite3GetToken(z, &token);
 1.81476 +    if( token==TK_REFERENCES ){
 1.81477 +      char *zParent;
 1.81478 +      do {
 1.81479 +        z += n;
 1.81480 +        n = sqlite3GetToken(z, &token);
 1.81481 +      }while( token==TK_SPACE );
 1.81482 +
 1.81483 +      zParent = sqlite3DbStrNDup(db, (const char *)z, n);
 1.81484 +      if( zParent==0 ) break;
 1.81485 +      sqlite3Dequote(zParent);
 1.81486 +      if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
 1.81487 +        char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
 1.81488 +            (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
 1.81489 +        );
 1.81490 +        sqlite3DbFree(db, zOutput);
 1.81491 +        zOutput = zOut;
 1.81492 +        zInput = &z[n];
 1.81493 +      }
 1.81494 +      sqlite3DbFree(db, zParent);
 1.81495 +    }
 1.81496 +  }
 1.81497 +
 1.81498 +  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
 1.81499 +  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
 1.81500 +  sqlite3DbFree(db, zOutput);
 1.81501 +}
 1.81502 +#endif
 1.81503 +
 1.81504 +#ifndef SQLITE_OMIT_TRIGGER
 1.81505 +/* This function is used by SQL generated to implement the
 1.81506 +** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
 1.81507 +** statement. The second is a table name. The table name in the CREATE 
 1.81508 +** TRIGGER statement is replaced with the third argument and the result 
 1.81509 +** returned. This is analagous to renameTableFunc() above, except for CREATE
 1.81510 +** TRIGGER, not CREATE INDEX and CREATE TABLE.
 1.81511 +*/
 1.81512 +static void renameTriggerFunc(
 1.81513 +  sqlite3_context *context,
 1.81514 +  int NotUsed,
 1.81515 +  sqlite3_value **argv
 1.81516 +){
 1.81517 +  unsigned char const *zSql = sqlite3_value_text(argv[0]);
 1.81518 +  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
 1.81519 +
 1.81520 +  int token;
 1.81521 +  Token tname;
 1.81522 +  int dist = 3;
 1.81523 +  unsigned char const *zCsr = zSql;
 1.81524 +  int len = 0;
 1.81525 +  char *zRet;
 1.81526 +  sqlite3 *db = sqlite3_context_db_handle(context);
 1.81527 +
 1.81528 +  UNUSED_PARAMETER(NotUsed);
 1.81529 +
 1.81530 +  /* The principle used to locate the table name in the CREATE TRIGGER 
 1.81531 +  ** statement is that the table name is the first token that is immediatedly
 1.81532 +  ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
 1.81533 +  ** of TK_WHEN, TK_BEGIN or TK_FOR.
 1.81534 +  */
 1.81535 +  if( zSql ){
 1.81536 +    do {
 1.81537 +
 1.81538 +      if( !*zCsr ){
 1.81539 +        /* Ran out of input before finding the table name. Return NULL. */
 1.81540 +        return;
 1.81541 +      }
 1.81542 +
 1.81543 +      /* Store the token that zCsr points to in tname. */
 1.81544 +      tname.z = (char*)zCsr;
 1.81545 +      tname.n = len;
 1.81546 +
 1.81547 +      /* Advance zCsr to the next token. Store that token type in 'token',
 1.81548 +      ** and its length in 'len' (to be used next iteration of this loop).
 1.81549 +      */
 1.81550 +      do {
 1.81551 +        zCsr += len;
 1.81552 +        len = sqlite3GetToken(zCsr, &token);
 1.81553 +      }while( token==TK_SPACE );
 1.81554 +      assert( len>0 );
 1.81555 +
 1.81556 +      /* Variable 'dist' stores the number of tokens read since the most
 1.81557 +      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
 1.81558 +      ** token is read and 'dist' equals 2, the condition stated above
 1.81559 +      ** to be met.
 1.81560 +      **
 1.81561 +      ** Note that ON cannot be a database, table or column name, so
 1.81562 +      ** there is no need to worry about syntax like 
 1.81563 +      ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
 1.81564 +      */
 1.81565 +      dist++;
 1.81566 +      if( token==TK_DOT || token==TK_ON ){
 1.81567 +        dist = 0;
 1.81568 +      }
 1.81569 +    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
 1.81570 +
 1.81571 +    /* Variable tname now contains the token that is the old table-name
 1.81572 +    ** in the CREATE TRIGGER statement.
 1.81573 +    */
 1.81574 +    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
 1.81575 +       zSql, zTableName, tname.z+tname.n);
 1.81576 +    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
 1.81577 +  }
 1.81578 +}
 1.81579 +#endif   /* !SQLITE_OMIT_TRIGGER */
 1.81580 +
 1.81581 +/*
 1.81582 +** Register built-in functions used to help implement ALTER TABLE
 1.81583 +*/
 1.81584 +SQLITE_PRIVATE void sqlite3AlterFunctions(void){
 1.81585 +  static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
 1.81586 +    FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
 1.81587 +#ifndef SQLITE_OMIT_TRIGGER
 1.81588 +    FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
 1.81589 +#endif
 1.81590 +#ifndef SQLITE_OMIT_FOREIGN_KEY
 1.81591 +    FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
 1.81592 +#endif
 1.81593 +  };
 1.81594 +  int i;
 1.81595 +  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
 1.81596 +  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
 1.81597 +
 1.81598 +  for(i=0; i<ArraySize(aAlterTableFuncs); i++){
 1.81599 +    sqlite3FuncDefInsert(pHash, &aFunc[i]);
 1.81600 +  }
 1.81601 +}
 1.81602 +
 1.81603 +/*
 1.81604 +** This function is used to create the text of expressions of the form:
 1.81605 +**
 1.81606 +**   name=<constant1> OR name=<constant2> OR ...
 1.81607 +**
 1.81608 +** If argument zWhere is NULL, then a pointer string containing the text 
 1.81609 +** "name=<constant>" is returned, where <constant> is the quoted version
 1.81610 +** of the string passed as argument zConstant. The returned buffer is
 1.81611 +** allocated using sqlite3DbMalloc(). It is the responsibility of the
 1.81612 +** caller to ensure that it is eventually freed.
 1.81613 +**
 1.81614 +** If argument zWhere is not NULL, then the string returned is 
 1.81615 +** "<where> OR name=<constant>", where <where> is the contents of zWhere.
 1.81616 +** In this case zWhere is passed to sqlite3DbFree() before returning.
 1.81617 +** 
 1.81618 +*/
 1.81619 +static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
 1.81620 +  char *zNew;
 1.81621 +  if( !zWhere ){
 1.81622 +    zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
 1.81623 +  }else{
 1.81624 +    zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
 1.81625 +    sqlite3DbFree(db, zWhere);
 1.81626 +  }
 1.81627 +  return zNew;
 1.81628 +}
 1.81629 +
 1.81630 +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
 1.81631 +/*
 1.81632 +** Generate the text of a WHERE expression which can be used to select all
 1.81633 +** tables that have foreign key constraints that refer to table pTab (i.e.
 1.81634 +** constraints for which pTab is the parent table) from the sqlite_master
 1.81635 +** table.
 1.81636 +*/
 1.81637 +static char *whereForeignKeys(Parse *pParse, Table *pTab){
 1.81638 +  FKey *p;
 1.81639 +  char *zWhere = 0;
 1.81640 +  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
 1.81641 +    zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
 1.81642 +  }
 1.81643 +  return zWhere;
 1.81644 +}
 1.81645 +#endif
 1.81646 +
 1.81647 +/*
 1.81648 +** Generate the text of a WHERE expression which can be used to select all
 1.81649 +** temporary triggers on table pTab from the sqlite_temp_master table. If
 1.81650 +** table pTab has no temporary triggers, or is itself stored in the 
 1.81651 +** temporary database, NULL is returned.
 1.81652 +*/
 1.81653 +static char *whereTempTriggers(Parse *pParse, Table *pTab){
 1.81654 +  Trigger *pTrig;
 1.81655 +  char *zWhere = 0;
 1.81656 +  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
 1.81657 +
 1.81658 +  /* If the table is not located in the temp-db (in which case NULL is 
 1.81659 +  ** returned, loop through the tables list of triggers. For each trigger
 1.81660 +  ** that is not part of the temp-db schema, add a clause to the WHERE 
 1.81661 +  ** expression being built up in zWhere.
 1.81662 +  */
 1.81663 +  if( pTab->pSchema!=pTempSchema ){
 1.81664 +    sqlite3 *db = pParse->db;
 1.81665 +    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
 1.81666 +      if( pTrig->pSchema==pTempSchema ){
 1.81667 +        zWhere = whereOrName(db, zWhere, pTrig->zName);
 1.81668 +      }
 1.81669 +    }
 1.81670 +  }
 1.81671 +  if( zWhere ){
 1.81672 +    char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
 1.81673 +    sqlite3DbFree(pParse->db, zWhere);
 1.81674 +    zWhere = zNew;
 1.81675 +  }
 1.81676 +  return zWhere;
 1.81677 +}
 1.81678 +
 1.81679 +/*
 1.81680 +** Generate code to drop and reload the internal representation of table
 1.81681 +** pTab from the database, including triggers and temporary triggers.
 1.81682 +** Argument zName is the name of the table in the database schema at
 1.81683 +** the time the generated code is executed. This can be different from
 1.81684 +** pTab->zName if this function is being called to code part of an 
 1.81685 +** "ALTER TABLE RENAME TO" statement.
 1.81686 +*/
 1.81687 +static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
 1.81688 +  Vdbe *v;
 1.81689 +  char *zWhere;
 1.81690 +  int iDb;                   /* Index of database containing pTab */
 1.81691 +#ifndef SQLITE_OMIT_TRIGGER
 1.81692 +  Trigger *pTrig;
 1.81693 +#endif
 1.81694 +
 1.81695 +  v = sqlite3GetVdbe(pParse);
 1.81696 +  if( NEVER(v==0) ) return;
 1.81697 +  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
 1.81698 +  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
 1.81699 +  assert( iDb>=0 );
 1.81700 +
 1.81701 +#ifndef SQLITE_OMIT_TRIGGER
 1.81702 +  /* Drop any table triggers from the internal schema. */
 1.81703 +  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
 1.81704 +    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
 1.81705 +    assert( iTrigDb==iDb || iTrigDb==1 );
 1.81706 +    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
 1.81707 +  }
 1.81708 +#endif
 1.81709 +
 1.81710 +  /* Drop the table and index from the internal schema.  */
 1.81711 +  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
 1.81712 +
 1.81713 +  /* Reload the table, index and permanent trigger schemas. */
 1.81714 +  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
 1.81715 +  if( !zWhere ) return;
 1.81716 +  sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
 1.81717 +
 1.81718 +#ifndef SQLITE_OMIT_TRIGGER
 1.81719 +  /* Now, if the table is not stored in the temp database, reload any temp 
 1.81720 +  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
 1.81721 +  */
 1.81722 +  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
 1.81723 +    sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
 1.81724 +  }
 1.81725 +#endif
 1.81726 +}
 1.81727 +
 1.81728 +/*
 1.81729 +** Parameter zName is the name of a table that is about to be altered
 1.81730 +** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
 1.81731 +** If the table is a system table, this function leaves an error message
 1.81732 +** in pParse->zErr (system tables may not be altered) and returns non-zero.
 1.81733 +**
 1.81734 +** Or, if zName is not a system table, zero is returned.
 1.81735 +*/
 1.81736 +static int isSystemTable(Parse *pParse, const char *zName){
 1.81737 +  if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
 1.81738 +    sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
 1.81739 +    return 1;
 1.81740 +  }
 1.81741 +  return 0;
 1.81742 +}
 1.81743 +
 1.81744 +/*
 1.81745 +** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
 1.81746 +** command. 
 1.81747 +*/
 1.81748 +SQLITE_PRIVATE void sqlite3AlterRenameTable(
 1.81749 +  Parse *pParse,            /* Parser context. */
 1.81750 +  SrcList *pSrc,            /* The table to rename. */
 1.81751 +  Token *pName              /* The new table name. */
 1.81752 +){
 1.81753 +  int iDb;                  /* Database that contains the table */
 1.81754 +  char *zDb;                /* Name of database iDb */
 1.81755 +  Table *pTab;              /* Table being renamed */
 1.81756 +  char *zName = 0;          /* NULL-terminated version of pName */ 
 1.81757 +  sqlite3 *db = pParse->db; /* Database connection */
 1.81758 +  int nTabName;             /* Number of UTF-8 characters in zTabName */
 1.81759 +  const char *zTabName;     /* Original name of the table */
 1.81760 +  Vdbe *v;
 1.81761 +#ifndef SQLITE_OMIT_TRIGGER
 1.81762 +  char *zWhere = 0;         /* Where clause to locate temp triggers */
 1.81763 +#endif
 1.81764 +  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
 1.81765 +  int savedDbFlags;         /* Saved value of db->flags */
 1.81766 +
 1.81767 +  savedDbFlags = db->flags;  
 1.81768 +  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
 1.81769 +  assert( pSrc->nSrc==1 );
 1.81770 +  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
 1.81771 +
 1.81772 +  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
 1.81773 +  if( !pTab ) goto exit_rename_table;
 1.81774 +  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
 1.81775 +  zDb = db->aDb[iDb].zName;
 1.81776 +  db->flags |= SQLITE_PreferBuiltin;
 1.81777 +
 1.81778 +  /* Get a NULL terminated version of the new table name. */
 1.81779 +  zName = sqlite3NameFromToken(db, pName);
 1.81780 +  if( !zName ) goto exit_rename_table;
 1.81781 +
 1.81782 +  /* Check that a table or index named 'zName' does not already exist
 1.81783 +  ** in database iDb. If so, this is an error.
 1.81784 +  */
 1.81785 +  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
 1.81786 +    sqlite3ErrorMsg(pParse, 
 1.81787 +        "there is already another table or index with this name: %s", zName);
 1.81788 +    goto exit_rename_table;
 1.81789 +  }
 1.81790 +
 1.81791 +  /* Make sure it is not a system table being altered, or a reserved name
 1.81792 +  ** that the table is being renamed to.
 1.81793 +  */
 1.81794 +  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
 1.81795 +    goto exit_rename_table;
 1.81796 +  }
 1.81797 +  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
 1.81798 +    exit_rename_table;
 1.81799 +  }
 1.81800 +
 1.81801 +#ifndef SQLITE_OMIT_VIEW
 1.81802 +  if( pTab->pSelect ){
 1.81803 +    sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
 1.81804 +    goto exit_rename_table;
 1.81805 +  }
 1.81806 +#endif
 1.81807 +
 1.81808 +#ifndef SQLITE_OMIT_AUTHORIZATION
 1.81809 +  /* Invoke the authorization callback. */
 1.81810 +  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
 1.81811 +    goto exit_rename_table;
 1.81812 +  }
 1.81813 +#endif
 1.81814 +
 1.81815 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.81816 +  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
 1.81817 +    goto exit_rename_table;
 1.81818 +  }
 1.81819 +  if( IsVirtual(pTab) ){
 1.81820 +    pVTab = sqlite3GetVTable(db, pTab);
 1.81821 +    if( pVTab->pVtab->pModule->xRename==0 ){
 1.81822 +      pVTab = 0;
 1.81823 +    }
 1.81824 +  }
 1.81825 +#endif
 1.81826 +
 1.81827 +  /* Begin a transaction for database iDb. 
 1.81828 +  ** Then modify the schema cookie (since the ALTER TABLE modifies the
 1.81829 +  ** schema). Open a statement transaction if the table is a virtual
 1.81830 +  ** table.
 1.81831 +  */
 1.81832 +  v = sqlite3GetVdbe(pParse);
 1.81833 +  if( v==0 ){
 1.81834 +    goto exit_rename_table;
 1.81835 +  }
 1.81836 +  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
 1.81837 +  sqlite3ChangeCookie(pParse, iDb);
 1.81838 +
 1.81839 +  /* If this is a virtual table, invoke the xRename() function if
 1.81840 +  ** one is defined. The xRename() callback will modify the names
 1.81841 +  ** of any resources used by the v-table implementation (including other
 1.81842 +  ** SQLite tables) that are identified by the name of the virtual table.
 1.81843 +  */
 1.81844 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.81845 +  if( pVTab ){
 1.81846 +    int i = ++pParse->nMem;
 1.81847 +    sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
 1.81848 +    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
 1.81849 +    sqlite3MayAbort(pParse);
 1.81850 +  }
 1.81851 +#endif
 1.81852 +
 1.81853 +  /* figure out how many UTF-8 characters are in zName */
 1.81854 +  zTabName = pTab->zName;
 1.81855 +  nTabName = sqlite3Utf8CharLen(zTabName, -1);
 1.81856 +
 1.81857 +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
 1.81858 +  if( db->flags&SQLITE_ForeignKeys ){
 1.81859 +    /* If foreign-key support is enabled, rewrite the CREATE TABLE 
 1.81860 +    ** statements corresponding to all child tables of foreign key constraints
 1.81861 +    ** for which the renamed table is the parent table.  */
 1.81862 +    if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
 1.81863 +      sqlite3NestedParse(pParse, 
 1.81864 +          "UPDATE \"%w\".%s SET "
 1.81865 +              "sql = sqlite_rename_parent(sql, %Q, %Q) "
 1.81866 +              "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
 1.81867 +      sqlite3DbFree(db, zWhere);
 1.81868 +    }
 1.81869 +  }
 1.81870 +#endif
 1.81871 +
 1.81872 +  /* Modify the sqlite_master table to use the new table name. */
 1.81873 +  sqlite3NestedParse(pParse,
 1.81874 +      "UPDATE %Q.%s SET "
 1.81875 +#ifdef SQLITE_OMIT_TRIGGER
 1.81876 +          "sql = sqlite_rename_table(sql, %Q), "
 1.81877 +#else
 1.81878 +          "sql = CASE "
 1.81879 +            "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
 1.81880 +            "ELSE sqlite_rename_table(sql, %Q) END, "
 1.81881 +#endif
 1.81882 +          "tbl_name = %Q, "
 1.81883 +          "name = CASE "
 1.81884 +            "WHEN type='table' THEN %Q "
 1.81885 +            "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
 1.81886 +             "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
 1.81887 +            "ELSE name END "
 1.81888 +      "WHERE tbl_name=%Q COLLATE nocase AND "
 1.81889 +          "(type='table' OR type='index' OR type='trigger');", 
 1.81890 +      zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
 1.81891 +#ifndef SQLITE_OMIT_TRIGGER
 1.81892 +      zName,
 1.81893 +#endif
 1.81894 +      zName, nTabName, zTabName
 1.81895 +  );
 1.81896 +
 1.81897 +#ifndef SQLITE_OMIT_AUTOINCREMENT
 1.81898 +  /* If the sqlite_sequence table exists in this database, then update 
 1.81899 +  ** it with the new table name.
 1.81900 +  */
 1.81901 +  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
 1.81902 +    sqlite3NestedParse(pParse,
 1.81903 +        "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
 1.81904 +        zDb, zName, pTab->zName);
 1.81905 +  }
 1.81906 +#endif
 1.81907 +
 1.81908 +#ifndef SQLITE_OMIT_TRIGGER
 1.81909 +  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
 1.81910 +  ** table. Don't do this if the table being ALTERed is itself located in
 1.81911 +  ** the temp database.
 1.81912 +  */
 1.81913 +  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
 1.81914 +    sqlite3NestedParse(pParse, 
 1.81915 +        "UPDATE sqlite_temp_master SET "
 1.81916 +            "sql = sqlite_rename_trigger(sql, %Q), "
 1.81917 +            "tbl_name = %Q "
 1.81918 +            "WHERE %s;", zName, zName, zWhere);
 1.81919 +    sqlite3DbFree(db, zWhere);
 1.81920 +  }
 1.81921 +#endif
 1.81922 +
 1.81923 +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
 1.81924 +  if( db->flags&SQLITE_ForeignKeys ){
 1.81925 +    FKey *p;
 1.81926 +    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
 1.81927 +      Table *pFrom = p->pFrom;
 1.81928 +      if( pFrom!=pTab ){
 1.81929 +        reloadTableSchema(pParse, p->pFrom, pFrom->zName);
 1.81930 +      }
 1.81931 +    }
 1.81932 +  }
 1.81933 +#endif
 1.81934 +
 1.81935 +  /* Drop and reload the internal table schema. */
 1.81936 +  reloadTableSchema(pParse, pTab, zName);
 1.81937 +
 1.81938 +exit_rename_table:
 1.81939 +  sqlite3SrcListDelete(db, pSrc);
 1.81940 +  sqlite3DbFree(db, zName);
 1.81941 +  db->flags = savedDbFlags;
 1.81942 +}
 1.81943 +
 1.81944 +
 1.81945 +/*
 1.81946 +** Generate code to make sure the file format number is at least minFormat.
 1.81947 +** The generated code will increase the file format number if necessary.
 1.81948 +*/
 1.81949 +SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
 1.81950 +  Vdbe *v;
 1.81951 +  v = sqlite3GetVdbe(pParse);
 1.81952 +  /* The VDBE should have been allocated before this routine is called.
 1.81953 +  ** If that allocation failed, we would have quit before reaching this
 1.81954 +  ** point */
 1.81955 +  if( ALWAYS(v) ){
 1.81956 +    int r1 = sqlite3GetTempReg(pParse);
 1.81957 +    int r2 = sqlite3GetTempReg(pParse);
 1.81958 +    int j1;
 1.81959 +    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
 1.81960 +    sqlite3VdbeUsesBtree(v, iDb);
 1.81961 +    sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
 1.81962 +    j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
 1.81963 +    sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v);
 1.81964 +    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
 1.81965 +    sqlite3VdbeJumpHere(v, j1);
 1.81966 +    sqlite3ReleaseTempReg(pParse, r1);
 1.81967 +    sqlite3ReleaseTempReg(pParse, r2);
 1.81968 +  }
 1.81969 +}
 1.81970 +
 1.81971 +/*
 1.81972 +** This function is called after an "ALTER TABLE ... ADD" statement
 1.81973 +** has been parsed. Argument pColDef contains the text of the new
 1.81974 +** column definition.
 1.81975 +**
 1.81976 +** The Table structure pParse->pNewTable was extended to include
 1.81977 +** the new column during parsing.
 1.81978 +*/
 1.81979 +SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
 1.81980 +  Table *pNew;              /* Copy of pParse->pNewTable */
 1.81981 +  Table *pTab;              /* Table being altered */
 1.81982 +  int iDb;                  /* Database number */
 1.81983 +  const char *zDb;          /* Database name */
 1.81984 +  const char *zTab;         /* Table name */
 1.81985 +  char *zCol;               /* Null-terminated column definition */
 1.81986 +  Column *pCol;             /* The new column */
 1.81987 +  Expr *pDflt;              /* Default value for the new column */
 1.81988 +  sqlite3 *db;              /* The database connection; */
 1.81989 +
 1.81990 +  db = pParse->db;
 1.81991 +  if( pParse->nErr || db->mallocFailed ) return;
 1.81992 +  pNew = pParse->pNewTable;
 1.81993 +  assert( pNew );
 1.81994 +
 1.81995 +  assert( sqlite3BtreeHoldsAllMutexes(db) );
 1.81996 +  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
 1.81997 +  zDb = db->aDb[iDb].zName;
 1.81998 +  zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
 1.81999 +  pCol = &pNew->aCol[pNew->nCol-1];
 1.82000 +  pDflt = pCol->pDflt;
 1.82001 +  pTab = sqlite3FindTable(db, zTab, zDb);
 1.82002 +  assert( pTab );
 1.82003 +
 1.82004 +#ifndef SQLITE_OMIT_AUTHORIZATION
 1.82005 +  /* Invoke the authorization callback. */
 1.82006 +  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
 1.82007 +    return;
 1.82008 +  }
 1.82009 +#endif
 1.82010 +
 1.82011 +  /* If the default value for the new column was specified with a 
 1.82012 +  ** literal NULL, then set pDflt to 0. This simplifies checking
 1.82013 +  ** for an SQL NULL default below.
 1.82014 +  */
 1.82015 +  if( pDflt && pDflt->op==TK_NULL ){
 1.82016 +    pDflt = 0;
 1.82017 +  }
 1.82018 +
 1.82019 +  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
 1.82020 +  ** If there is a NOT NULL constraint, then the default value for the
 1.82021 +  ** column must not be NULL.
 1.82022 +  */
 1.82023 +  if( pCol->colFlags & COLFLAG_PRIMKEY ){
 1.82024 +    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
 1.82025 +    return;
 1.82026 +  }
 1.82027 +  if( pNew->pIndex ){
 1.82028 +    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
 1.82029 +    return;
 1.82030 +  }
 1.82031 +  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
 1.82032 +    sqlite3ErrorMsg(pParse, 
 1.82033 +        "Cannot add a REFERENCES column with non-NULL default value");
 1.82034 +    return;
 1.82035 +  }
 1.82036 +  if( pCol->notNull && !pDflt ){
 1.82037 +    sqlite3ErrorMsg(pParse, 
 1.82038 +        "Cannot add a NOT NULL column with default value NULL");
 1.82039 +    return;
 1.82040 +  }
 1.82041 +
 1.82042 +  /* Ensure the default expression is something that sqlite3ValueFromExpr()
 1.82043 +  ** can handle (i.e. not CURRENT_TIME etc.)
 1.82044 +  */
 1.82045 +  if( pDflt ){
 1.82046 +    sqlite3_value *pVal = 0;
 1.82047 +    if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
 1.82048 +      db->mallocFailed = 1;
 1.82049 +      return;
 1.82050 +    }
 1.82051 +    if( !pVal ){
 1.82052 +      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
 1.82053 +      return;
 1.82054 +    }
 1.82055 +    sqlite3ValueFree(pVal);
 1.82056 +  }
 1.82057 +
 1.82058 +  /* Modify the CREATE TABLE statement. */
 1.82059 +  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
 1.82060 +  if( zCol ){
 1.82061 +    char *zEnd = &zCol[pColDef->n-1];
 1.82062 +    int savedDbFlags = db->flags;
 1.82063 +    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
 1.82064 +      *zEnd-- = '\0';
 1.82065 +    }
 1.82066 +    db->flags |= SQLITE_PreferBuiltin;
 1.82067 +    sqlite3NestedParse(pParse, 
 1.82068 +        "UPDATE \"%w\".%s SET "
 1.82069 +          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
 1.82070 +        "WHERE type = 'table' AND name = %Q", 
 1.82071 +      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
 1.82072 +      zTab
 1.82073 +    );
 1.82074 +    sqlite3DbFree(db, zCol);
 1.82075 +    db->flags = savedDbFlags;
 1.82076 +  }
 1.82077 +
 1.82078 +  /* If the default value of the new column is NULL, then set the file
 1.82079 +  ** format to 2. If the default value of the new column is not NULL,
 1.82080 +  ** the file format becomes 3.
 1.82081 +  */
 1.82082 +  sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
 1.82083 +
 1.82084 +  /* Reload the schema of the modified table. */
 1.82085 +  reloadTableSchema(pParse, pTab, pTab->zName);
 1.82086 +}
 1.82087 +
 1.82088 +/*
 1.82089 +** This function is called by the parser after the table-name in
 1.82090 +** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
 1.82091 +** pSrc is the full-name of the table being altered.
 1.82092 +**
 1.82093 +** This routine makes a (partial) copy of the Table structure
 1.82094 +** for the table being altered and sets Parse.pNewTable to point
 1.82095 +** to it. Routines called by the parser as the column definition
 1.82096 +** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
 1.82097 +** the copy. The copy of the Table structure is deleted by tokenize.c 
 1.82098 +** after parsing is finished.
 1.82099 +**
 1.82100 +** Routine sqlite3AlterFinishAddColumn() will be called to complete
 1.82101 +** coding the "ALTER TABLE ... ADD" statement.
 1.82102 +*/
 1.82103 +SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
 1.82104 +  Table *pNew;
 1.82105 +  Table *pTab;
 1.82106 +  Vdbe *v;
 1.82107 +  int iDb;
 1.82108 +  int i;
 1.82109 +  int nAlloc;
 1.82110 +  sqlite3 *db = pParse->db;
 1.82111 +
 1.82112 +  /* Look up the table being altered. */
 1.82113 +  assert( pParse->pNewTable==0 );
 1.82114 +  assert( sqlite3BtreeHoldsAllMutexes(db) );
 1.82115 +  if( db->mallocFailed ) goto exit_begin_add_column;
 1.82116 +  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
 1.82117 +  if( !pTab ) goto exit_begin_add_column;
 1.82118 +
 1.82119 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.82120 +  if( IsVirtual(pTab) ){
 1.82121 +    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
 1.82122 +    goto exit_begin_add_column;
 1.82123 +  }
 1.82124 +#endif
 1.82125 +
 1.82126 +  /* Make sure this is not an attempt to ALTER a view. */
 1.82127 +  if( pTab->pSelect ){
 1.82128 +    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
 1.82129 +    goto exit_begin_add_column;
 1.82130 +  }
 1.82131 +  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
 1.82132 +    goto exit_begin_add_column;
 1.82133 +  }
 1.82134 +
 1.82135 +  assert( pTab->addColOffset>0 );
 1.82136 +  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
 1.82137 +
 1.82138 +  /* Put a copy of the Table struct in Parse.pNewTable for the
 1.82139 +  ** sqlite3AddColumn() function and friends to modify.  But modify
 1.82140 +  ** the name by adding an "sqlite_altertab_" prefix.  By adding this
 1.82141 +  ** prefix, we insure that the name will not collide with an existing
 1.82142 +  ** table because user table are not allowed to have the "sqlite_"
 1.82143 +  ** prefix on their name.
 1.82144 +  */
 1.82145 +  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
 1.82146 +  if( !pNew ) goto exit_begin_add_column;
 1.82147 +  pParse->pNewTable = pNew;
 1.82148 +  pNew->nRef = 1;
 1.82149 +  pNew->nCol = pTab->nCol;
 1.82150 +  assert( pNew->nCol>0 );
 1.82151 +  nAlloc = (((pNew->nCol-1)/8)*8)+8;
 1.82152 +  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
 1.82153 +  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
 1.82154 +  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
 1.82155 +  if( !pNew->aCol || !pNew->zName ){
 1.82156 +    db->mallocFailed = 1;
 1.82157 +    goto exit_begin_add_column;
 1.82158 +  }
 1.82159 +  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
 1.82160 +  for(i=0; i<pNew->nCol; i++){
 1.82161 +    Column *pCol = &pNew->aCol[i];
 1.82162 +    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
 1.82163 +    pCol->zColl = 0;
 1.82164 +    pCol->zType = 0;
 1.82165 +    pCol->pDflt = 0;
 1.82166 +    pCol->zDflt = 0;
 1.82167 +  }
 1.82168 +  pNew->pSchema = db->aDb[iDb].pSchema;
 1.82169 +  pNew->addColOffset = pTab->addColOffset;
 1.82170 +  pNew->nRef = 1;
 1.82171 +
 1.82172 +  /* Begin a transaction and increment the schema cookie.  */
 1.82173 +  sqlite3BeginWriteOperation(pParse, 0, iDb);
 1.82174 +  v = sqlite3GetVdbe(pParse);
 1.82175 +  if( !v ) goto exit_begin_add_column;
 1.82176 +  sqlite3ChangeCookie(pParse, iDb);
 1.82177 +
 1.82178 +exit_begin_add_column:
 1.82179 +  sqlite3SrcListDelete(db, pSrc);
 1.82180 +  return;
 1.82181 +}
 1.82182 +#endif  /* SQLITE_ALTER_TABLE */
 1.82183 +
 1.82184 +/************** End of alter.c ***********************************************/
 1.82185 +/************** Begin file analyze.c *****************************************/
 1.82186 +/*
 1.82187 +** 2005-07-08
 1.82188 +**
 1.82189 +** The author disclaims copyright to this source code.  In place of
 1.82190 +** a legal notice, here is a blessing:
 1.82191 +**
 1.82192 +**    May you do good and not evil.
 1.82193 +**    May you find forgiveness for yourself and forgive others.
 1.82194 +**    May you share freely, never taking more than you give.
 1.82195 +**
 1.82196 +*************************************************************************
 1.82197 +** This file contains code associated with the ANALYZE command.
 1.82198 +**
 1.82199 +** The ANALYZE command gather statistics about the content of tables
 1.82200 +** and indices.  These statistics are made available to the query planner
 1.82201 +** to help it make better decisions about how to perform queries.
 1.82202 +**
 1.82203 +** The following system tables are or have been supported:
 1.82204 +**
 1.82205 +**    CREATE TABLE sqlite_stat1(tbl, idx, stat);
 1.82206 +**    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
 1.82207 +**    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
 1.82208 +**    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
 1.82209 +**
 1.82210 +** Additional tables might be added in future releases of SQLite.
 1.82211 +** The sqlite_stat2 table is not created or used unless the SQLite version
 1.82212 +** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
 1.82213 +** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
 1.82214 +** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
 1.82215 +** created and used by SQLite versions 3.7.9 and later and with
 1.82216 +** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
 1.82217 +** is a superset of sqlite_stat2.  The sqlite_stat4 is an enhanced
 1.82218 +** version of sqlite_stat3 and is only available when compiled with
 1.82219 +** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later.  It is
 1.82220 +** not possible to enable both STAT3 and STAT4 at the same time.  If they
 1.82221 +** are both enabled, then STAT4 takes precedence.
 1.82222 +**
 1.82223 +** For most applications, sqlite_stat1 provides all the statisics required
 1.82224 +** for the query planner to make good choices.
 1.82225 +**
 1.82226 +** Format of sqlite_stat1:
 1.82227 +**
 1.82228 +** There is normally one row per index, with the index identified by the
 1.82229 +** name in the idx column.  The tbl column is the name of the table to
 1.82230 +** which the index belongs.  In each such row, the stat column will be
 1.82231 +** a string consisting of a list of integers.  The first integer in this
 1.82232 +** list is the number of rows in the index.  (This is the same as the
 1.82233 +** number of rows in the table, except for partial indices.)  The second
 1.82234 +** integer is the average number of rows in the index that have the same
 1.82235 +** value in the first column of the index.  The third integer is the average
 1.82236 +** number of rows in the index that have the same value for the first two
 1.82237 +** columns.  The N-th integer (for N>1) is the average number of rows in 
 1.82238 +** the index which have the same value for the first N-1 columns.  For
 1.82239 +** a K-column index, there will be K+1 integers in the stat column.  If
 1.82240 +** the index is unique, then the last integer will be 1.
 1.82241 +**
 1.82242 +** The list of integers in the stat column can optionally be followed
 1.82243 +** by the keyword "unordered".  The "unordered" keyword, if it is present,
 1.82244 +** must be separated from the last integer by a single space.  If the
 1.82245 +** "unordered" keyword is present, then the query planner assumes that
 1.82246 +** the index is unordered and will not use the index for a range query.
 1.82247 +** 
 1.82248 +** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
 1.82249 +** column contains a single integer which is the (estimated) number of
 1.82250 +** rows in the table identified by sqlite_stat1.tbl.
 1.82251 +**
 1.82252 +** Format of sqlite_stat2:
 1.82253 +**
 1.82254 +** The sqlite_stat2 is only created and is only used if SQLite is compiled
 1.82255 +** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
 1.82256 +** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
 1.82257 +** about the distribution of keys within an index.  The index is identified by
 1.82258 +** the "idx" column and the "tbl" column is the name of the table to which
 1.82259 +** the index belongs.  There are usually 10 rows in the sqlite_stat2
 1.82260 +** table for each index.
 1.82261 +**
 1.82262 +** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
 1.82263 +** inclusive are samples of the left-most key value in the index taken at
 1.82264 +** evenly spaced points along the index.  Let the number of samples be S
 1.82265 +** (10 in the standard build) and let C be the number of rows in the index.
 1.82266 +** Then the sampled rows are given by:
 1.82267 +**
 1.82268 +**     rownumber = (i*C*2 + C)/(S*2)
 1.82269 +**
 1.82270 +** For i between 0 and S-1.  Conceptually, the index space is divided into
 1.82271 +** S uniform buckets and the samples are the middle row from each bucket.
 1.82272 +**
 1.82273 +** The format for sqlite_stat2 is recorded here for legacy reference.  This
 1.82274 +** version of SQLite does not support sqlite_stat2.  It neither reads nor
 1.82275 +** writes the sqlite_stat2 table.  This version of SQLite only supports
 1.82276 +** sqlite_stat3.
 1.82277 +**
 1.82278 +** Format for sqlite_stat3:
 1.82279 +**
 1.82280 +** The sqlite_stat3 format is a subset of sqlite_stat4.  Hence, the
 1.82281 +** sqlite_stat4 format will be described first.  Further information
 1.82282 +** about sqlite_stat3 follows the sqlite_stat4 description.
 1.82283 +**
 1.82284 +** Format for sqlite_stat4:
 1.82285 +**
 1.82286 +** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
 1.82287 +** to aid the query planner in choosing good indices based on the values
 1.82288 +** that indexed columns are compared against in the WHERE clauses of
 1.82289 +** queries.
 1.82290 +**
 1.82291 +** The sqlite_stat4 table contains multiple entries for each index.
 1.82292 +** The idx column names the index and the tbl column is the table of the
 1.82293 +** index.  If the idx and tbl columns are the same, then the sample is
 1.82294 +** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the
 1.82295 +** binary encoding of a key from the index.  The nEq column is a
 1.82296 +** list of integers.  The first integer is the approximate number
 1.82297 +** of entries in the index whose left-most column exactly matches
 1.82298 +** the left-most column of the sample.  The second integer in nEq
 1.82299 +** is the approximate number of entries in the index where the
 1.82300 +** first two columns match the first two columns of the sample.
 1.82301 +** And so forth.  nLt is another list of integers that show the approximate
 1.82302 +** number of entries that are strictly less than the sample.  The first
 1.82303 +** integer in nLt contains the number of entries in the index where the
 1.82304 +** left-most column is less than the left-most column of the sample.
 1.82305 +** The K-th integer in the nLt entry is the number of index entries 
 1.82306 +** where the first K columns are less than the first K columns of the
 1.82307 +** sample.  The nDLt column is like nLt except that it contains the 
 1.82308 +** number of distinct entries in the index that are less than the
 1.82309 +** sample.
 1.82310 +**
 1.82311 +** There can be an arbitrary number of sqlite_stat4 entries per index.
 1.82312 +** The ANALYZE command will typically generate sqlite_stat4 tables
 1.82313 +** that contain between 10 and 40 samples which are distributed across
 1.82314 +** the key space, though not uniformly, and which include samples with
 1.82315 +** large nEq values.
 1.82316 +**
 1.82317 +** Format for sqlite_stat3 redux:
 1.82318 +**
 1.82319 +** The sqlite_stat3 table is like sqlite_stat4 except that it only
 1.82320 +** looks at the left-most column of the index.  The sqlite_stat3.sample
 1.82321 +** column contains the actual value of the left-most column instead
 1.82322 +** of a blob encoding of the complete index key as is found in
 1.82323 +** sqlite_stat4.sample.  The nEq, nLt, and nDLt entries of sqlite_stat3
 1.82324 +** all contain just a single integer which is the same as the first
 1.82325 +** integer in the equivalent columns in sqlite_stat4.
 1.82326 +*/
 1.82327 +#ifndef SQLITE_OMIT_ANALYZE
 1.82328 +
 1.82329 +#if defined(SQLITE_ENABLE_STAT4)
 1.82330 +# define IsStat4     1
 1.82331 +# define IsStat3     0
 1.82332 +#elif defined(SQLITE_ENABLE_STAT3)
 1.82333 +# define IsStat4     0
 1.82334 +# define IsStat3     1
 1.82335 +#else
 1.82336 +# define IsStat4     0
 1.82337 +# define IsStat3     0
 1.82338 +# undef SQLITE_STAT4_SAMPLES
 1.82339 +# define SQLITE_STAT4_SAMPLES 1
 1.82340 +#endif
 1.82341 +#define IsStat34    (IsStat3+IsStat4)  /* 1 for STAT3 or STAT4. 0 otherwise */
 1.82342 +
 1.82343 +/*
 1.82344 +** This routine generates code that opens the sqlite_statN tables.
 1.82345 +** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now
 1.82346 +** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when
 1.82347 +** appropriate compile-time options are provided.
 1.82348 +**
 1.82349 +** If the sqlite_statN tables do not previously exist, it is created.
 1.82350 +**
 1.82351 +** Argument zWhere may be a pointer to a buffer containing a table name,
 1.82352 +** or it may be a NULL pointer. If it is not NULL, then all entries in
 1.82353 +** the sqlite_statN tables associated with the named table are deleted.
 1.82354 +** If zWhere==0, then code is generated to delete all stat table entries.
 1.82355 +*/
 1.82356 +static void openStatTable(
 1.82357 +  Parse *pParse,          /* Parsing context */
 1.82358 +  int iDb,                /* The database we are looking in */
 1.82359 +  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
 1.82360 +  const char *zWhere,     /* Delete entries for this table or index */
 1.82361 +  const char *zWhereType  /* Either "tbl" or "idx" */
 1.82362 +){
 1.82363 +  static const struct {
 1.82364 +    const char *zName;
 1.82365 +    const char *zCols;
 1.82366 +  } aTable[] = {
 1.82367 +    { "sqlite_stat1", "tbl,idx,stat" },
 1.82368 +#if defined(SQLITE_ENABLE_STAT4)
 1.82369 +    { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
 1.82370 +    { "sqlite_stat3", 0 },
 1.82371 +#elif defined(SQLITE_ENABLE_STAT3)
 1.82372 +    { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
 1.82373 +    { "sqlite_stat4", 0 },
 1.82374 +#else
 1.82375 +    { "sqlite_stat3", 0 },
 1.82376 +    { "sqlite_stat4", 0 },
 1.82377 +#endif
 1.82378 +  };
 1.82379 +  int i;
 1.82380 +  sqlite3 *db = pParse->db;
 1.82381 +  Db *pDb;
 1.82382 +  Vdbe *v = sqlite3GetVdbe(pParse);
 1.82383 +  int aRoot[ArraySize(aTable)];
 1.82384 +  u8 aCreateTbl[ArraySize(aTable)];
 1.82385 +
 1.82386 +  if( v==0 ) return;
 1.82387 +  assert( sqlite3BtreeHoldsAllMutexes(db) );
 1.82388 +  assert( sqlite3VdbeDb(v)==db );
 1.82389 +  pDb = &db->aDb[iDb];
 1.82390 +
 1.82391 +  /* Create new statistic tables if they do not exist, or clear them
 1.82392 +  ** if they do already exist.
 1.82393 +  */
 1.82394 +  for(i=0; i<ArraySize(aTable); i++){
 1.82395 +    const char *zTab = aTable[i].zName;
 1.82396 +    Table *pStat;
 1.82397 +    if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
 1.82398 +      if( aTable[i].zCols ){
 1.82399 +        /* The sqlite_statN table does not exist. Create it. Note that a 
 1.82400 +        ** side-effect of the CREATE TABLE statement is to leave the rootpage 
 1.82401 +        ** of the new table in register pParse->regRoot. This is important 
 1.82402 +        ** because the OpenWrite opcode below will be needing it. */
 1.82403 +        sqlite3NestedParse(pParse,
 1.82404 +            "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
 1.82405 +        );
 1.82406 +        aRoot[i] = pParse->regRoot;
 1.82407 +        aCreateTbl[i] = OPFLAG_P2ISREG;
 1.82408 +      }
 1.82409 +    }else{
 1.82410 +      /* The table already exists. If zWhere is not NULL, delete all entries 
 1.82411 +      ** associated with the table zWhere. If zWhere is NULL, delete the
 1.82412 +      ** entire contents of the table. */
 1.82413 +      aRoot[i] = pStat->tnum;
 1.82414 +      aCreateTbl[i] = 0;
 1.82415 +      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
 1.82416 +      if( zWhere ){
 1.82417 +        sqlite3NestedParse(pParse,
 1.82418 +           "DELETE FROM %Q.%s WHERE %s=%Q",
 1.82419 +           pDb->zName, zTab, zWhereType, zWhere
 1.82420 +        );
 1.82421 +      }else{
 1.82422 +        /* The sqlite_stat[134] table already exists.  Delete all rows. */
 1.82423 +        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
 1.82424 +      }
 1.82425 +    }
 1.82426 +  }
 1.82427 +
 1.82428 +  /* Open the sqlite_stat[134] tables for writing. */
 1.82429 +  for(i=0; aTable[i].zCols; i++){
 1.82430 +    assert( i<ArraySize(aTable) );
 1.82431 +    sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
 1.82432 +    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
 1.82433 +  }
 1.82434 +}
 1.82435 +
 1.82436 +/*
 1.82437 +** Recommended number of samples for sqlite_stat4
 1.82438 +*/
 1.82439 +#ifndef SQLITE_STAT4_SAMPLES
 1.82440 +# define SQLITE_STAT4_SAMPLES 24
 1.82441 +#endif
 1.82442 +
 1.82443 +/*
 1.82444 +** Three SQL functions - stat_init(), stat_push(), and stat_get() -
 1.82445 +** share an instance of the following structure to hold their state
 1.82446 +** information.
 1.82447 +*/
 1.82448 +typedef struct Stat4Accum Stat4Accum;
 1.82449 +typedef struct Stat4Sample Stat4Sample;
 1.82450 +struct Stat4Sample {
 1.82451 +  tRowcnt *anEq;                  /* sqlite_stat4.nEq */
 1.82452 +  tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
 1.82453 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.82454 +  tRowcnt *anLt;                  /* sqlite_stat4.nLt */
 1.82455 +  union {
 1.82456 +    i64 iRowid;                     /* Rowid in main table of the key */
 1.82457 +    u8 *aRowid;                     /* Key for WITHOUT ROWID tables */
 1.82458 +  } u;
 1.82459 +  u32 nRowid;                     /* Sizeof aRowid[] */
 1.82460 +  u8 isPSample;                   /* True if a periodic sample */
 1.82461 +  int iCol;                       /* If !isPSample, the reason for inclusion */
 1.82462 +  u32 iHash;                      /* Tiebreaker hash */
 1.82463 +#endif
 1.82464 +};                                                    
 1.82465 +struct Stat4Accum {
 1.82466 +  tRowcnt nRow;             /* Number of rows in the entire table */
 1.82467 +  tRowcnt nPSample;         /* How often to do a periodic sample */
 1.82468 +  int nCol;                 /* Number of columns in index + rowid */
 1.82469 +  int mxSample;             /* Maximum number of samples to accumulate */
 1.82470 +  Stat4Sample current;      /* Current row as a Stat4Sample */
 1.82471 +  u32 iPrn;                 /* Pseudo-random number used for sampling */
 1.82472 +  Stat4Sample *aBest;       /* Array of nCol best samples */
 1.82473 +  int iMin;                 /* Index in a[] of entry with minimum score */
 1.82474 +  int nSample;              /* Current number of samples */
 1.82475 +  int iGet;                 /* Index of current sample accessed by stat_get() */
 1.82476 +  Stat4Sample *a;           /* Array of mxSample Stat4Sample objects */
 1.82477 +  sqlite3 *db;              /* Database connection, for malloc() */
 1.82478 +};
 1.82479 +
 1.82480 +/* Reclaim memory used by a Stat4Sample
 1.82481 +*/
 1.82482 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.82483 +static void sampleClear(sqlite3 *db, Stat4Sample *p){
 1.82484 +  assert( db!=0 );
 1.82485 +  if( p->nRowid ){
 1.82486 +    sqlite3DbFree(db, p->u.aRowid);
 1.82487 +    p->nRowid = 0;
 1.82488 +  }
 1.82489 +}
 1.82490 +#endif
 1.82491 +
 1.82492 +/* Initialize the BLOB value of a ROWID
 1.82493 +*/
 1.82494 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.82495 +static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
 1.82496 +  assert( db!=0 );
 1.82497 +  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
 1.82498 +  p->u.aRowid = sqlite3DbMallocRaw(db, n);
 1.82499 +  if( p->u.aRowid ){
 1.82500 +    p->nRowid = n;
 1.82501 +    memcpy(p->u.aRowid, pData, n);
 1.82502 +  }else{
 1.82503 +    p->nRowid = 0;
 1.82504 +  }
 1.82505 +}
 1.82506 +#endif
 1.82507 +
 1.82508 +/* Initialize the INTEGER value of a ROWID.
 1.82509 +*/
 1.82510 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.82511 +static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
 1.82512 +  assert( db!=0 );
 1.82513 +  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
 1.82514 +  p->nRowid = 0;
 1.82515 +  p->u.iRowid = iRowid;
 1.82516 +}
 1.82517 +#endif
 1.82518 +
 1.82519 +
 1.82520 +/*
 1.82521 +** Copy the contents of object (*pFrom) into (*pTo).
 1.82522 +*/
 1.82523 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.82524 +static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
 1.82525 +  pTo->isPSample = pFrom->isPSample;
 1.82526 +  pTo->iCol = pFrom->iCol;
 1.82527 +  pTo->iHash = pFrom->iHash;
 1.82528 +  memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
 1.82529 +  memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
 1.82530 +  memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
 1.82531 +  if( pFrom->nRowid ){
 1.82532 +    sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
 1.82533 +  }else{
 1.82534 +    sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
 1.82535 +  }
 1.82536 +}
 1.82537 +#endif
 1.82538 +
 1.82539 +/*
 1.82540 +** Reclaim all memory of a Stat4Accum structure.
 1.82541 +*/
 1.82542 +static void stat4Destructor(void *pOld){
 1.82543 +  Stat4Accum *p = (Stat4Accum*)pOld;
 1.82544 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.82545 +  int i;
 1.82546 +  for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
 1.82547 +  for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
 1.82548 +  sampleClear(p->db, &p->current);
 1.82549 +#endif
 1.82550 +  sqlite3DbFree(p->db, p);
 1.82551 +}
 1.82552 +
 1.82553 +/*
 1.82554 +** Implementation of the stat_init(N,C) SQL function. The two parameters
 1.82555 +** are the number of rows in the table or index (C) and the number of columns
 1.82556 +** in the index (N).  The second argument (C) is only used for STAT3 and STAT4.
 1.82557 +**
 1.82558 +** This routine allocates the Stat4Accum object in heap memory. The return 
 1.82559 +** value is a pointer to the the Stat4Accum object encoded as a blob (i.e. 
 1.82560 +** the size of the blob is sizeof(void*) bytes). 
 1.82561 +*/
 1.82562 +static void statInit(
 1.82563 +  sqlite3_context *context,
 1.82564 +  int argc,
 1.82565 +  sqlite3_value **argv
 1.82566 +){
 1.82567 +  Stat4Accum *p;
 1.82568 +  int nCol;                       /* Number of columns in index being sampled */
 1.82569 +  int nColUp;                     /* nCol rounded up for alignment */
 1.82570 +  int n;                          /* Bytes of space to allocate */
 1.82571 +  sqlite3 *db;                    /* Database connection */
 1.82572 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.82573 +  int mxSample = SQLITE_STAT4_SAMPLES;
 1.82574 +#endif
 1.82575 +
 1.82576 +  /* Decode the three function arguments */
 1.82577 +  UNUSED_PARAMETER(argc);
 1.82578 +  nCol = sqlite3_value_int(argv[0]);
 1.82579 +  assert( nCol>1 );               /* >1 because it includes the rowid column */
 1.82580 +  nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
 1.82581 +
 1.82582 +  /* Allocate the space required for the Stat4Accum object */
 1.82583 +  n = sizeof(*p) 
 1.82584 +    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anEq */
 1.82585 +    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anDLt */
 1.82586 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.82587 +    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anLt */
 1.82588 +    + sizeof(Stat4Sample)*(nCol+mxSample)     /* Stat4Accum.aBest[], a[] */
 1.82589 +    + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
 1.82590 +#endif
 1.82591 +  ;
 1.82592 +  db = sqlite3_context_db_handle(context);
 1.82593 +  p = sqlite3DbMallocZero(db, n);
 1.82594 +  if( p==0 ){
 1.82595 +    sqlite3_result_error_nomem(context);
 1.82596 +    return;
 1.82597 +  }
 1.82598 +
 1.82599 +  p->db = db;
 1.82600 +  p->nRow = 0;
 1.82601 +  p->nCol = nCol;
 1.82602 +  p->current.anDLt = (tRowcnt*)&p[1];
 1.82603 +  p->current.anEq = &p->current.anDLt[nColUp];
 1.82604 +
 1.82605 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.82606 +  {
 1.82607 +    u8 *pSpace;                     /* Allocated space not yet assigned */
 1.82608 +    int i;                          /* Used to iterate through p->aSample[] */
 1.82609 +
 1.82610 +    p->iGet = -1;
 1.82611 +    p->mxSample = mxSample;
 1.82612 +    p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[1])/(mxSample/3+1) + 1);
 1.82613 +    p->current.anLt = &p->current.anEq[nColUp];
 1.82614 +    p->iPrn = nCol*0x689e962d ^ sqlite3_value_int(argv[1])*0xd0944565;
 1.82615 +  
 1.82616 +    /* Set up the Stat4Accum.a[] and aBest[] arrays */
 1.82617 +    p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
 1.82618 +    p->aBest = &p->a[mxSample];
 1.82619 +    pSpace = (u8*)(&p->a[mxSample+nCol]);
 1.82620 +    for(i=0; i<(mxSample+nCol); i++){
 1.82621 +      p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
 1.82622 +      p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
 1.82623 +      p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
 1.82624 +    }
 1.82625 +    assert( (pSpace - (u8*)p)==n );
 1.82626 +  
 1.82627 +    for(i=0; i<nCol; i++){
 1.82628 +      p->aBest[i].iCol = i;
 1.82629 +    }
 1.82630 +  }
 1.82631 +#endif
 1.82632 +
 1.82633 +  /* Return a pointer to the allocated object to the caller */
 1.82634 +  sqlite3_result_blob(context, p, sizeof(p), stat4Destructor);
 1.82635 +}
 1.82636 +static const FuncDef statInitFuncdef = {
 1.82637 +  1+IsStat34,      /* nArg */
 1.82638 +  SQLITE_UTF8,     /* funcFlags */
 1.82639 +  0,               /* pUserData */
 1.82640 +  0,               /* pNext */
 1.82641 +  statInit,        /* xFunc */
 1.82642 +  0,               /* xStep */
 1.82643 +  0,               /* xFinalize */
 1.82644 +  "stat_init",     /* zName */
 1.82645 +  0,               /* pHash */
 1.82646 +  0                /* pDestructor */
 1.82647 +};
 1.82648 +
 1.82649 +#ifdef SQLITE_ENABLE_STAT4
 1.82650 +/*
 1.82651 +** pNew and pOld are both candidate non-periodic samples selected for 
 1.82652 +** the same column (pNew->iCol==pOld->iCol). Ignoring this column and 
 1.82653 +** considering only any trailing columns and the sample hash value, this
 1.82654 +** function returns true if sample pNew is to be preferred over pOld.
 1.82655 +** In other words, if we assume that the cardinalities of the selected
 1.82656 +** column for pNew and pOld are equal, is pNew to be preferred over pOld.
 1.82657 +**
 1.82658 +** This function assumes that for each argument sample, the contents of
 1.82659 +** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid. 
 1.82660 +*/
 1.82661 +static int sampleIsBetterPost(
 1.82662 +  Stat4Accum *pAccum, 
 1.82663 +  Stat4Sample *pNew, 
 1.82664 +  Stat4Sample *pOld
 1.82665 +){
 1.82666 +  int nCol = pAccum->nCol;
 1.82667 +  int i;
 1.82668 +  assert( pNew->iCol==pOld->iCol );
 1.82669 +  for(i=pNew->iCol+1; i<nCol; i++){
 1.82670 +    if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
 1.82671 +    if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
 1.82672 +  }
 1.82673 +  if( pNew->iHash>pOld->iHash ) return 1;
 1.82674 +  return 0;
 1.82675 +}
 1.82676 +#endif
 1.82677 +
 1.82678 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.82679 +/*
 1.82680 +** Return true if pNew is to be preferred over pOld.
 1.82681 +**
 1.82682 +** This function assumes that for each argument sample, the contents of
 1.82683 +** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid. 
 1.82684 +*/
 1.82685 +static int sampleIsBetter(
 1.82686 +  Stat4Accum *pAccum, 
 1.82687 +  Stat4Sample *pNew, 
 1.82688 +  Stat4Sample *pOld
 1.82689 +){
 1.82690 +  tRowcnt nEqNew = pNew->anEq[pNew->iCol];
 1.82691 +  tRowcnt nEqOld = pOld->anEq[pOld->iCol];
 1.82692 +
 1.82693 +  assert( pOld->isPSample==0 && pNew->isPSample==0 );
 1.82694 +  assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
 1.82695 +
 1.82696 +  if( (nEqNew>nEqOld) ) return 1;
 1.82697 +#ifdef SQLITE_ENABLE_STAT4
 1.82698 +  if( nEqNew==nEqOld ){
 1.82699 +    if( pNew->iCol<pOld->iCol ) return 1;
 1.82700 +    return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
 1.82701 +  }
 1.82702 +  return 0;
 1.82703 +#else
 1.82704 +  return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
 1.82705 +#endif
 1.82706 +}
 1.82707 +
 1.82708 +/*
 1.82709 +** Copy the contents of sample *pNew into the p->a[] array. If necessary,
 1.82710 +** remove the least desirable sample from p->a[] to make room.
 1.82711 +*/
 1.82712 +static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
 1.82713 +  Stat4Sample *pSample = 0;
 1.82714 +  int i;
 1.82715 +
 1.82716 +  assert( IsStat4 || nEqZero==0 );
 1.82717 +
 1.82718 +#ifdef SQLITE_ENABLE_STAT4
 1.82719 +  if( pNew->isPSample==0 ){
 1.82720 +    Stat4Sample *pUpgrade = 0;
 1.82721 +    assert( pNew->anEq[pNew->iCol]>0 );
 1.82722 +
 1.82723 +    /* This sample is being added because the prefix that ends in column 
 1.82724 +    ** iCol occurs many times in the table. However, if we have already
 1.82725 +    ** added a sample that shares this prefix, there is no need to add
 1.82726 +    ** this one. Instead, upgrade the priority of the highest priority
 1.82727 +    ** existing sample that shares this prefix.  */
 1.82728 +    for(i=p->nSample-1; i>=0; i--){
 1.82729 +      Stat4Sample *pOld = &p->a[i];
 1.82730 +      if( pOld->anEq[pNew->iCol]==0 ){
 1.82731 +        if( pOld->isPSample ) return;
 1.82732 +        assert( pOld->iCol>pNew->iCol );
 1.82733 +        assert( sampleIsBetter(p, pNew, pOld) );
 1.82734 +        if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
 1.82735 +          pUpgrade = pOld;
 1.82736 +        }
 1.82737 +      }
 1.82738 +    }
 1.82739 +    if( pUpgrade ){
 1.82740 +      pUpgrade->iCol = pNew->iCol;
 1.82741 +      pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
 1.82742 +      goto find_new_min;
 1.82743 +    }
 1.82744 +  }
 1.82745 +#endif
 1.82746 +
 1.82747 +  /* If necessary, remove sample iMin to make room for the new sample. */
 1.82748 +  if( p->nSample>=p->mxSample ){
 1.82749 +    Stat4Sample *pMin = &p->a[p->iMin];
 1.82750 +    tRowcnt *anEq = pMin->anEq;
 1.82751 +    tRowcnt *anLt = pMin->anLt;
 1.82752 +    tRowcnt *anDLt = pMin->anDLt;
 1.82753 +    sampleClear(p->db, pMin);
 1.82754 +    memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
 1.82755 +    pSample = &p->a[p->nSample-1];
 1.82756 +    pSample->nRowid = 0;
 1.82757 +    pSample->anEq = anEq;
 1.82758 +    pSample->anDLt = anDLt;
 1.82759 +    pSample->anLt = anLt;
 1.82760 +    p->nSample = p->mxSample-1;
 1.82761 +  }
 1.82762 +
 1.82763 +  /* The "rows less-than" for the rowid column must be greater than that
 1.82764 +  ** for the last sample in the p->a[] array. Otherwise, the samples would
 1.82765 +  ** be out of order. */
 1.82766 +#ifdef SQLITE_ENABLE_STAT4
 1.82767 +  assert( p->nSample==0 
 1.82768 +       || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
 1.82769 +#endif
 1.82770 +
 1.82771 +  /* Insert the new sample */
 1.82772 +  pSample = &p->a[p->nSample];
 1.82773 +  sampleCopy(p, pSample, pNew);
 1.82774 +  p->nSample++;
 1.82775 +
 1.82776 +  /* Zero the first nEqZero entries in the anEq[] array. */
 1.82777 +  memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
 1.82778 +
 1.82779 +#ifdef SQLITE_ENABLE_STAT4
 1.82780 + find_new_min:
 1.82781 +#endif
 1.82782 +  if( p->nSample>=p->mxSample ){
 1.82783 +    int iMin = -1;
 1.82784 +    for(i=0; i<p->mxSample; i++){
 1.82785 +      if( p->a[i].isPSample ) continue;
 1.82786 +      if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
 1.82787 +        iMin = i;
 1.82788 +      }
 1.82789 +    }
 1.82790 +    assert( iMin>=0 );
 1.82791 +    p->iMin = iMin;
 1.82792 +  }
 1.82793 +}
 1.82794 +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
 1.82795 +
 1.82796 +/*
 1.82797 +** Field iChng of the index being scanned has changed. So at this point
 1.82798 +** p->current contains a sample that reflects the previous row of the
 1.82799 +** index. The value of anEq[iChng] and subsequent anEq[] elements are
 1.82800 +** correct at this point.
 1.82801 +*/
 1.82802 +static void samplePushPrevious(Stat4Accum *p, int iChng){
 1.82803 +#ifdef SQLITE_ENABLE_STAT4
 1.82804 +  int i;
 1.82805 +
 1.82806 +  /* Check if any samples from the aBest[] array should be pushed
 1.82807 +  ** into IndexSample.a[] at this point.  */
 1.82808 +  for(i=(p->nCol-2); i>=iChng; i--){
 1.82809 +    Stat4Sample *pBest = &p->aBest[i];
 1.82810 +    pBest->anEq[i] = p->current.anEq[i];
 1.82811 +    if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
 1.82812 +      sampleInsert(p, pBest, i);
 1.82813 +    }
 1.82814 +  }
 1.82815 +
 1.82816 +  /* Update the anEq[] fields of any samples already collected. */
 1.82817 +  for(i=p->nSample-1; i>=0; i--){
 1.82818 +    int j;
 1.82819 +    for(j=iChng; j<p->nCol; j++){
 1.82820 +      if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
 1.82821 +    }
 1.82822 +  }
 1.82823 +#endif
 1.82824 +
 1.82825 +#if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
 1.82826 +  if( iChng==0 ){
 1.82827 +    tRowcnt nLt = p->current.anLt[0];
 1.82828 +    tRowcnt nEq = p->current.anEq[0];
 1.82829 +
 1.82830 +    /* Check if this is to be a periodic sample. If so, add it. */
 1.82831 +    if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
 1.82832 +      p->current.isPSample = 1;
 1.82833 +      sampleInsert(p, &p->current, 0);
 1.82834 +      p->current.isPSample = 0;
 1.82835 +    }else 
 1.82836 +
 1.82837 +    /* Or if it is a non-periodic sample. Add it in this case too. */
 1.82838 +    if( p->nSample<p->mxSample 
 1.82839 +     || sampleIsBetter(p, &p->current, &p->a[p->iMin]) 
 1.82840 +    ){
 1.82841 +      sampleInsert(p, &p->current, 0);
 1.82842 +    }
 1.82843 +  }
 1.82844 +#endif
 1.82845 +
 1.82846 +#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
 1.82847 +  UNUSED_PARAMETER( p );
 1.82848 +  UNUSED_PARAMETER( iChng );
 1.82849 +#endif
 1.82850 +}
 1.82851 +
 1.82852 +/*
 1.82853 +** Implementation of the stat_push SQL function:  stat_push(P,C,R)
 1.82854 +** Arguments:
 1.82855 +**
 1.82856 +**    P     Pointer to the Stat4Accum object created by stat_init()
 1.82857 +**    C     Index of left-most column to differ from previous row
 1.82858 +**    R     Rowid for the current row.  Might be a key record for
 1.82859 +**          WITHOUT ROWID tables.
 1.82860 +**
 1.82861 +** The SQL function always returns NULL.
 1.82862 +**
 1.82863 +** The R parameter is only used for STAT3 and STAT4
 1.82864 +*/
 1.82865 +static void statPush(
 1.82866 +  sqlite3_context *context,
 1.82867 +  int argc,
 1.82868 +  sqlite3_value **argv
 1.82869 +){
 1.82870 +  int i;
 1.82871 +
 1.82872 +  /* The three function arguments */
 1.82873 +  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
 1.82874 +  int iChng = sqlite3_value_int(argv[1]);
 1.82875 +
 1.82876 +  UNUSED_PARAMETER( argc );
 1.82877 +  UNUSED_PARAMETER( context );
 1.82878 +  assert( p->nCol>1 );        /* Includes rowid field */
 1.82879 +  assert( iChng<p->nCol );
 1.82880 +
 1.82881 +  if( p->nRow==0 ){
 1.82882 +    /* This is the first call to this function. Do initialization. */
 1.82883 +    for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
 1.82884 +  }else{
 1.82885 +    /* Second and subsequent calls get processed here */
 1.82886 +    samplePushPrevious(p, iChng);
 1.82887 +
 1.82888 +    /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
 1.82889 +    ** to the current row of the index. */
 1.82890 +    for(i=0; i<iChng; i++){
 1.82891 +      p->current.anEq[i]++;
 1.82892 +    }
 1.82893 +    for(i=iChng; i<p->nCol; i++){
 1.82894 +      p->current.anDLt[i]++;
 1.82895 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.82896 +      p->current.anLt[i] += p->current.anEq[i];
 1.82897 +#endif
 1.82898 +      p->current.anEq[i] = 1;
 1.82899 +    }
 1.82900 +  }
 1.82901 +  p->nRow++;
 1.82902 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.82903 +  if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
 1.82904 +    sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
 1.82905 +  }else{
 1.82906 +    sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
 1.82907 +                                       sqlite3_value_blob(argv[2]));
 1.82908 +  }
 1.82909 +  p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
 1.82910 +#endif
 1.82911 +
 1.82912 +#ifdef SQLITE_ENABLE_STAT4
 1.82913 +  {
 1.82914 +    tRowcnt nLt = p->current.anLt[p->nCol-1];
 1.82915 +
 1.82916 +    /* Check if this is to be a periodic sample. If so, add it. */
 1.82917 +    if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
 1.82918 +      p->current.isPSample = 1;
 1.82919 +      p->current.iCol = 0;
 1.82920 +      sampleInsert(p, &p->current, p->nCol-1);
 1.82921 +      p->current.isPSample = 0;
 1.82922 +    }
 1.82923 +
 1.82924 +    /* Update the aBest[] array. */
 1.82925 +    for(i=0; i<(p->nCol-1); i++){
 1.82926 +      p->current.iCol = i;
 1.82927 +      if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
 1.82928 +        sampleCopy(p, &p->aBest[i], &p->current);
 1.82929 +      }
 1.82930 +    }
 1.82931 +  }
 1.82932 +#endif
 1.82933 +}
 1.82934 +static const FuncDef statPushFuncdef = {
 1.82935 +  2+IsStat34,      /* nArg */
 1.82936 +  SQLITE_UTF8,     /* funcFlags */
 1.82937 +  0,               /* pUserData */
 1.82938 +  0,               /* pNext */
 1.82939 +  statPush,        /* xFunc */
 1.82940 +  0,               /* xStep */
 1.82941 +  0,               /* xFinalize */
 1.82942 +  "stat_push",     /* zName */
 1.82943 +  0,               /* pHash */
 1.82944 +  0                /* pDestructor */
 1.82945 +};
 1.82946 +
 1.82947 +#define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
 1.82948 +#define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
 1.82949 +#define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
 1.82950 +#define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
 1.82951 +#define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
 1.82952 +
 1.82953 +/*
 1.82954 +** Implementation of the stat_get(P,J) SQL function.  This routine is
 1.82955 +** used to query the results.  Content is returned for parameter J
 1.82956 +** which is one of the STAT_GET_xxxx values defined above.
 1.82957 +**
 1.82958 +** If neither STAT3 nor STAT4 are enabled, then J is always
 1.82959 +** STAT_GET_STAT1 and is hence omitted and this routine becomes
 1.82960 +** a one-parameter function, stat_get(P), that always returns the
 1.82961 +** stat1 table entry information.
 1.82962 +*/
 1.82963 +static void statGet(
 1.82964 +  sqlite3_context *context,
 1.82965 +  int argc,
 1.82966 +  sqlite3_value **argv
 1.82967 +){
 1.82968 +  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
 1.82969 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.82970 +  /* STAT3 and STAT4 have a parameter on this routine. */
 1.82971 +  int eCall = sqlite3_value_int(argv[1]);
 1.82972 +  assert( argc==2 );
 1.82973 +  assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ 
 1.82974 +       || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
 1.82975 +       || eCall==STAT_GET_NDLT 
 1.82976 +  );
 1.82977 +  if( eCall==STAT_GET_STAT1 )
 1.82978 +#else
 1.82979 +  assert( argc==1 );
 1.82980 +#endif
 1.82981 +  {
 1.82982 +    /* Return the value to store in the "stat" column of the sqlite_stat1
 1.82983 +    ** table for this index.
 1.82984 +    **
 1.82985 +    ** The value is a string composed of a list of integers describing 
 1.82986 +    ** the index. The first integer in the list is the total number of 
 1.82987 +    ** entries in the index. There is one additional integer in the list 
 1.82988 +    ** for each indexed column. This additional integer is an estimate of
 1.82989 +    ** the number of rows matched by a stabbing query on the index using
 1.82990 +    ** a key with the corresponding number of fields. In other words,
 1.82991 +    ** if the index is on columns (a,b) and the sqlite_stat1 value is 
 1.82992 +    ** "100 10 2", then SQLite estimates that:
 1.82993 +    **
 1.82994 +    **   * the index contains 100 rows,
 1.82995 +    **   * "WHERE a=?" matches 10 rows, and
 1.82996 +    **   * "WHERE a=? AND b=?" matches 2 rows.
 1.82997 +    **
 1.82998 +    ** If D is the count of distinct values and K is the total number of 
 1.82999 +    ** rows, then each estimate is computed as:
 1.83000 +    **
 1.83001 +    **        I = (K+D-1)/D
 1.83002 +    */
 1.83003 +    char *z;
 1.83004 +    int i;
 1.83005 +
 1.83006 +    char *zRet = sqlite3MallocZero(p->nCol * 25);
 1.83007 +    if( zRet==0 ){
 1.83008 +      sqlite3_result_error_nomem(context);
 1.83009 +      return;
 1.83010 +    }
 1.83011 +
 1.83012 +    sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
 1.83013 +    z = zRet + sqlite3Strlen30(zRet);
 1.83014 +    for(i=0; i<(p->nCol-1); i++){
 1.83015 +      u64 nDistinct = p->current.anDLt[i] + 1;
 1.83016 +      u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
 1.83017 +      sqlite3_snprintf(24, z, " %llu", iVal);
 1.83018 +      z += sqlite3Strlen30(z);
 1.83019 +      assert( p->current.anEq[i] );
 1.83020 +    }
 1.83021 +    assert( z[0]=='\0' && z>zRet );
 1.83022 +
 1.83023 +    sqlite3_result_text(context, zRet, -1, sqlite3_free);
 1.83024 +  }
 1.83025 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.83026 +  else if( eCall==STAT_GET_ROWID ){
 1.83027 +    if( p->iGet<0 ){
 1.83028 +      samplePushPrevious(p, 0);
 1.83029 +      p->iGet = 0;
 1.83030 +    }
 1.83031 +    if( p->iGet<p->nSample ){
 1.83032 +      Stat4Sample *pS = p->a + p->iGet;
 1.83033 +      if( pS->nRowid==0 ){
 1.83034 +        sqlite3_result_int64(context, pS->u.iRowid);
 1.83035 +      }else{
 1.83036 +        sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
 1.83037 +                            SQLITE_TRANSIENT);
 1.83038 +      }
 1.83039 +    }
 1.83040 +  }else{
 1.83041 +    tRowcnt *aCnt = 0;
 1.83042 +
 1.83043 +    assert( p->iGet<p->nSample );
 1.83044 +    switch( eCall ){
 1.83045 +      case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
 1.83046 +      case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
 1.83047 +      default: {
 1.83048 +        aCnt = p->a[p->iGet].anDLt; 
 1.83049 +        p->iGet++;
 1.83050 +        break;
 1.83051 +      }
 1.83052 +    }
 1.83053 +
 1.83054 +    if( IsStat3 ){
 1.83055 +      sqlite3_result_int64(context, (i64)aCnt[0]);
 1.83056 +    }else{
 1.83057 +      char *zRet = sqlite3MallocZero(p->nCol * 25);
 1.83058 +      if( zRet==0 ){
 1.83059 +        sqlite3_result_error_nomem(context);
 1.83060 +      }else{
 1.83061 +        int i;
 1.83062 +        char *z = zRet;
 1.83063 +        for(i=0; i<p->nCol; i++){
 1.83064 +          sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
 1.83065 +          z += sqlite3Strlen30(z);
 1.83066 +        }
 1.83067 +        assert( z[0]=='\0' && z>zRet );
 1.83068 +        z[-1] = '\0';
 1.83069 +        sqlite3_result_text(context, zRet, -1, sqlite3_free);
 1.83070 +      }
 1.83071 +    }
 1.83072 +  }
 1.83073 +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
 1.83074 +#ifndef SQLITE_DEBUG
 1.83075 +  UNUSED_PARAMETER( argc );
 1.83076 +#endif
 1.83077 +}
 1.83078 +static const FuncDef statGetFuncdef = {
 1.83079 +  1+IsStat34,      /* nArg */
 1.83080 +  SQLITE_UTF8,     /* funcFlags */
 1.83081 +  0,               /* pUserData */
 1.83082 +  0,               /* pNext */
 1.83083 +  statGet,         /* xFunc */
 1.83084 +  0,               /* xStep */
 1.83085 +  0,               /* xFinalize */
 1.83086 +  "stat_get",      /* zName */
 1.83087 +  0,               /* pHash */
 1.83088 +  0                /* pDestructor */
 1.83089 +};
 1.83090 +
 1.83091 +static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
 1.83092 +  assert( regOut!=regStat4 && regOut!=regStat4+1 );
 1.83093 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.83094 +  sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
 1.83095 +#elif SQLITE_DEBUG
 1.83096 +  assert( iParam==STAT_GET_STAT1 );
 1.83097 +#else
 1.83098 +  UNUSED_PARAMETER( iParam );
 1.83099 +#endif
 1.83100 +  sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
 1.83101 +  sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
 1.83102 +  sqlite3VdbeChangeP5(v, 1 + IsStat34);
 1.83103 +}
 1.83104 +
 1.83105 +/*
 1.83106 +** Generate code to do an analysis of all indices associated with
 1.83107 +** a single table.
 1.83108 +*/
 1.83109 +static void analyzeOneTable(
 1.83110 +  Parse *pParse,   /* Parser context */
 1.83111 +  Table *pTab,     /* Table whose indices are to be analyzed */
 1.83112 +  Index *pOnlyIdx, /* If not NULL, only analyze this one index */
 1.83113 +  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
 1.83114 +  int iMem,        /* Available memory locations begin here */
 1.83115 +  int iTab         /* Next available cursor */
 1.83116 +){
 1.83117 +  sqlite3 *db = pParse->db;    /* Database handle */
 1.83118 +  Index *pIdx;                 /* An index to being analyzed */
 1.83119 +  int iIdxCur;                 /* Cursor open on index being analyzed */
 1.83120 +  int iTabCur;                 /* Table cursor */
 1.83121 +  Vdbe *v;                     /* The virtual machine being built up */
 1.83122 +  int i;                       /* Loop counter */
 1.83123 +  int jZeroRows = -1;          /* Jump from here if number of rows is zero */
 1.83124 +  int iDb;                     /* Index of database containing pTab */
 1.83125 +  u8 needTableCnt = 1;         /* True to count the table */
 1.83126 +  int regNewRowid = iMem++;    /* Rowid for the inserted record */
 1.83127 +  int regStat4 = iMem++;       /* Register to hold Stat4Accum object */
 1.83128 +  int regChng = iMem++;        /* Index of changed index field */
 1.83129 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.83130 +  int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
 1.83131 +#endif
 1.83132 +  int regTemp = iMem++;        /* Temporary use register */
 1.83133 +  int regTabname = iMem++;     /* Register containing table name */
 1.83134 +  int regIdxname = iMem++;     /* Register containing index name */
 1.83135 +  int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
 1.83136 +  int regPrev = iMem;          /* MUST BE LAST (see below) */
 1.83137 +
 1.83138 +  pParse->nMem = MAX(pParse->nMem, iMem);
 1.83139 +  v = sqlite3GetVdbe(pParse);
 1.83140 +  if( v==0 || NEVER(pTab==0) ){
 1.83141 +    return;
 1.83142 +  }
 1.83143 +  if( pTab->tnum==0 ){
 1.83144 +    /* Do not gather statistics on views or virtual tables */
 1.83145 +    return;
 1.83146 +  }
 1.83147 +  if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
 1.83148 +    /* Do not gather statistics on system tables */
 1.83149 +    return;
 1.83150 +  }
 1.83151 +  assert( sqlite3BtreeHoldsAllMutexes(db) );
 1.83152 +  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
 1.83153 +  assert( iDb>=0 );
 1.83154 +  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 1.83155 +#ifndef SQLITE_OMIT_AUTHORIZATION
 1.83156 +  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
 1.83157 +      db->aDb[iDb].zName ) ){
 1.83158 +    return;
 1.83159 +  }
 1.83160 +#endif
 1.83161 +
 1.83162 +  /* Establish a read-lock on the table at the shared-cache level. 
 1.83163 +  ** Open a read-only cursor on the table. Also allocate a cursor number
 1.83164 +  ** to use for scanning indexes (iIdxCur). No index cursor is opened at
 1.83165 +  ** this time though.  */
 1.83166 +  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
 1.83167 +  iTabCur = iTab++;
 1.83168 +  iIdxCur = iTab++;
 1.83169 +  pParse->nTab = MAX(pParse->nTab, iTab);
 1.83170 +  sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
 1.83171 +  sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
 1.83172 +
 1.83173 +  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
 1.83174 +    int nCol;                     /* Number of columns indexed by pIdx */
 1.83175 +    int *aGotoChng;               /* Array of jump instruction addresses */
 1.83176 +    int addrRewind;               /* Address of "OP_Rewind iIdxCur" */
 1.83177 +    int addrGotoChng0;            /* Address of "Goto addr_chng_0" */
 1.83178 +    int addrNextRow;              /* Address of "next_row:" */
 1.83179 +    const char *zIdxName;         /* Name of the index */
 1.83180 +
 1.83181 +    if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
 1.83182 +    if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
 1.83183 +    VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
 1.83184 +    nCol = pIdx->nKeyCol;
 1.83185 +    aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*(nCol+1));
 1.83186 +    if( aGotoChng==0 ) continue;
 1.83187 +
 1.83188 +    /* Populate the register containing the index name. */
 1.83189 +    if( pIdx->autoIndex==2 && !HasRowid(pTab) ){
 1.83190 +      zIdxName = pTab->zName;
 1.83191 +    }else{
 1.83192 +      zIdxName = pIdx->zName;
 1.83193 +    }
 1.83194 +    sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, zIdxName, 0);
 1.83195 +
 1.83196 +    /*
 1.83197 +    ** Pseudo-code for loop that calls stat_push():
 1.83198 +    **
 1.83199 +    **   Rewind csr
 1.83200 +    **   if eof(csr) goto end_of_scan;
 1.83201 +    **   regChng = 0
 1.83202 +    **   goto chng_addr_0;
 1.83203 +    **
 1.83204 +    **  next_row:
 1.83205 +    **   regChng = 0
 1.83206 +    **   if( idx(0) != regPrev(0) ) goto chng_addr_0
 1.83207 +    **   regChng = 1
 1.83208 +    **   if( idx(1) != regPrev(1) ) goto chng_addr_1
 1.83209 +    **   ...
 1.83210 +    **   regChng = N
 1.83211 +    **   goto chng_addr_N
 1.83212 +    **
 1.83213 +    **  chng_addr_0:
 1.83214 +    **   regPrev(0) = idx(0)
 1.83215 +    **  chng_addr_1:
 1.83216 +    **   regPrev(1) = idx(1)
 1.83217 +    **  ...
 1.83218 +    **
 1.83219 +    **  chng_addr_N:
 1.83220 +    **   regRowid = idx(rowid)
 1.83221 +    **   stat_push(P, regChng, regRowid)
 1.83222 +    **   Next csr
 1.83223 +    **   if !eof(csr) goto next_row;
 1.83224 +    **
 1.83225 +    **  end_of_scan:
 1.83226 +    */
 1.83227 +
 1.83228 +    /* Make sure there are enough memory cells allocated to accommodate 
 1.83229 +    ** the regPrev array and a trailing rowid (the rowid slot is required
 1.83230 +    ** when building a record to insert into the sample column of 
 1.83231 +    ** the sqlite_stat4 table.  */
 1.83232 +    pParse->nMem = MAX(pParse->nMem, regPrev+nCol);
 1.83233 +
 1.83234 +    /* Open a read-only cursor on the index being analyzed. */
 1.83235 +    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
 1.83236 +    sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
 1.83237 +    sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
 1.83238 +    VdbeComment((v, "%s", pIdx->zName));
 1.83239 +
 1.83240 +    /* Invoke the stat_init() function. The arguments are:
 1.83241 +    ** 
 1.83242 +    **    (1) the number of columns in the index including the rowid,
 1.83243 +    **    (2) the number of rows in the index,
 1.83244 +    **
 1.83245 +    ** The second argument is only used for STAT3 and STAT4
 1.83246 +    */
 1.83247 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.83248 +    sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+2);
 1.83249 +#endif
 1.83250 +    sqlite3VdbeAddOp2(v, OP_Integer, nCol+1, regStat4+1);
 1.83251 +    sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
 1.83252 +    sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
 1.83253 +    sqlite3VdbeChangeP5(v, 1+IsStat34);
 1.83254 +
 1.83255 +    /* Implementation of the following:
 1.83256 +    **
 1.83257 +    **   Rewind csr
 1.83258 +    **   if eof(csr) goto end_of_scan;
 1.83259 +    **   regChng = 0
 1.83260 +    **   goto next_push_0;
 1.83261 +    **
 1.83262 +    */
 1.83263 +    addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
 1.83264 +    VdbeCoverage(v);
 1.83265 +    sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
 1.83266 +    addrGotoChng0 = sqlite3VdbeAddOp0(v, OP_Goto);
 1.83267 +
 1.83268 +    /*
 1.83269 +    **  next_row:
 1.83270 +    **   regChng = 0
 1.83271 +    **   if( idx(0) != regPrev(0) ) goto chng_addr_0
 1.83272 +    **   regChng = 1
 1.83273 +    **   if( idx(1) != regPrev(1) ) goto chng_addr_1
 1.83274 +    **   ...
 1.83275 +    **   regChng = N
 1.83276 +    **   goto chng_addr_N
 1.83277 +    */
 1.83278 +    addrNextRow = sqlite3VdbeCurrentAddr(v);
 1.83279 +    for(i=0; i<nCol; i++){
 1.83280 +      char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
 1.83281 +      sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
 1.83282 +      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
 1.83283 +      aGotoChng[i] = 
 1.83284 +      sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
 1.83285 +      sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
 1.83286 +      VdbeCoverage(v);
 1.83287 +    }
 1.83288 +    sqlite3VdbeAddOp2(v, OP_Integer, nCol, regChng);
 1.83289 +    aGotoChng[nCol] = sqlite3VdbeAddOp0(v, OP_Goto);
 1.83290 +
 1.83291 +    /*
 1.83292 +    **  chng_addr_0:
 1.83293 +    **   regPrev(0) = idx(0)
 1.83294 +    **  chng_addr_1:
 1.83295 +    **   regPrev(1) = idx(1)
 1.83296 +    **  ...
 1.83297 +    */
 1.83298 +    sqlite3VdbeJumpHere(v, addrGotoChng0);
 1.83299 +    for(i=0; i<nCol; i++){
 1.83300 +      sqlite3VdbeJumpHere(v, aGotoChng[i]);
 1.83301 +      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
 1.83302 +    }
 1.83303 +
 1.83304 +    /*
 1.83305 +    **  chng_addr_N:
 1.83306 +    **   regRowid = idx(rowid)            // STAT34 only
 1.83307 +    **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT34 only
 1.83308 +    **   Next csr
 1.83309 +    **   if !eof(csr) goto next_row;
 1.83310 +    */
 1.83311 +    sqlite3VdbeJumpHere(v, aGotoChng[nCol]);
 1.83312 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.83313 +    assert( regRowid==(regStat4+2) );
 1.83314 +    if( HasRowid(pTab) ){
 1.83315 +      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
 1.83316 +    }else{
 1.83317 +      Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
 1.83318 +      int j, k, regKey;
 1.83319 +      regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
 1.83320 +      for(j=0; j<pPk->nKeyCol; j++){
 1.83321 +        k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
 1.83322 +        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
 1.83323 +        VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
 1.83324 +      }
 1.83325 +      sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
 1.83326 +      sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
 1.83327 +    }
 1.83328 +#endif
 1.83329 +    assert( regChng==(regStat4+1) );
 1.83330 +    sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
 1.83331 +    sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
 1.83332 +    sqlite3VdbeChangeP5(v, 2+IsStat34);
 1.83333 +    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
 1.83334 +
 1.83335 +    /* Add the entry to the stat1 table. */
 1.83336 +    callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
 1.83337 +    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
 1.83338 +    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
 1.83339 +    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
 1.83340 +    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
 1.83341 +
 1.83342 +    /* Add the entries to the stat3 or stat4 table. */
 1.83343 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.83344 +    {
 1.83345 +      int regEq = regStat1;
 1.83346 +      int regLt = regStat1+1;
 1.83347 +      int regDLt = regStat1+2;
 1.83348 +      int regSample = regStat1+3;
 1.83349 +      int regCol = regStat1+4;
 1.83350 +      int regSampleRowid = regCol + nCol;
 1.83351 +      int addrNext;
 1.83352 +      int addrIsNull;
 1.83353 +      u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
 1.83354 +
 1.83355 +      pParse->nMem = MAX(pParse->nMem, regCol+nCol+1);
 1.83356 +
 1.83357 +      addrNext = sqlite3VdbeCurrentAddr(v);
 1.83358 +      callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
 1.83359 +      addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
 1.83360 +      VdbeCoverage(v);
 1.83361 +      callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
 1.83362 +      callStatGet(v, regStat4, STAT_GET_NLT, regLt);
 1.83363 +      callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
 1.83364 +      sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
 1.83365 +      /* We know that the regSampleRowid row exists because it was read by
 1.83366 +      ** the previous loop.  Thus the not-found jump of seekOp will never
 1.83367 +      ** be taken */
 1.83368 +      VdbeCoverageNeverTaken(v);
 1.83369 +#ifdef SQLITE_ENABLE_STAT3
 1.83370 +      sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, 
 1.83371 +                                      pIdx->aiColumn[0], regSample);
 1.83372 +#else
 1.83373 +      for(i=0; i<nCol; i++){
 1.83374 +        i16 iCol = pIdx->aiColumn[i];
 1.83375 +        sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
 1.83376 +      }
 1.83377 +      sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol+1, regSample);
 1.83378 +#endif
 1.83379 +      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
 1.83380 +      sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
 1.83381 +      sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
 1.83382 +      sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
 1.83383 +      sqlite3VdbeJumpHere(v, addrIsNull);
 1.83384 +    }
 1.83385 +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
 1.83386 +
 1.83387 +    /* End of analysis */
 1.83388 +    sqlite3VdbeJumpHere(v, addrRewind);
 1.83389 +    sqlite3DbFree(db, aGotoChng);
 1.83390 +  }
 1.83391 +
 1.83392 +
 1.83393 +  /* Create a single sqlite_stat1 entry containing NULL as the index
 1.83394 +  ** name and the row count as the content.
 1.83395 +  */
 1.83396 +  if( pOnlyIdx==0 && needTableCnt ){
 1.83397 +    VdbeComment((v, "%s", pTab->zName));
 1.83398 +    sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
 1.83399 +    jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
 1.83400 +    sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
 1.83401 +    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
 1.83402 +    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
 1.83403 +    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
 1.83404 +    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
 1.83405 +    sqlite3VdbeJumpHere(v, jZeroRows);
 1.83406 +  }
 1.83407 +}
 1.83408 +
 1.83409 +
 1.83410 +/*
 1.83411 +** Generate code that will cause the most recent index analysis to
 1.83412 +** be loaded into internal hash tables where is can be used.
 1.83413 +*/
 1.83414 +static void loadAnalysis(Parse *pParse, int iDb){
 1.83415 +  Vdbe *v = sqlite3GetVdbe(pParse);
 1.83416 +  if( v ){
 1.83417 +    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
 1.83418 +  }
 1.83419 +}
 1.83420 +
 1.83421 +/*
 1.83422 +** Generate code that will do an analysis of an entire database
 1.83423 +*/
 1.83424 +static void analyzeDatabase(Parse *pParse, int iDb){
 1.83425 +  sqlite3 *db = pParse->db;
 1.83426 +  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
 1.83427 +  HashElem *k;
 1.83428 +  int iStatCur;
 1.83429 +  int iMem;
 1.83430 +  int iTab;
 1.83431 +
 1.83432 +  sqlite3BeginWriteOperation(pParse, 0, iDb);
 1.83433 +  iStatCur = pParse->nTab;
 1.83434 +  pParse->nTab += 3;
 1.83435 +  openStatTable(pParse, iDb, iStatCur, 0, 0);
 1.83436 +  iMem = pParse->nMem+1;
 1.83437 +  iTab = pParse->nTab;
 1.83438 +  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 1.83439 +  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
 1.83440 +    Table *pTab = (Table*)sqliteHashData(k);
 1.83441 +    analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
 1.83442 +  }
 1.83443 +  loadAnalysis(pParse, iDb);
 1.83444 +}
 1.83445 +
 1.83446 +/*
 1.83447 +** Generate code that will do an analysis of a single table in
 1.83448 +** a database.  If pOnlyIdx is not NULL then it is a single index
 1.83449 +** in pTab that should be analyzed.
 1.83450 +*/
 1.83451 +static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
 1.83452 +  int iDb;
 1.83453 +  int iStatCur;
 1.83454 +
 1.83455 +  assert( pTab!=0 );
 1.83456 +  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
 1.83457 +  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
 1.83458 +  sqlite3BeginWriteOperation(pParse, 0, iDb);
 1.83459 +  iStatCur = pParse->nTab;
 1.83460 +  pParse->nTab += 3;
 1.83461 +  if( pOnlyIdx ){
 1.83462 +    openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
 1.83463 +  }else{
 1.83464 +    openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
 1.83465 +  }
 1.83466 +  analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
 1.83467 +  loadAnalysis(pParse, iDb);
 1.83468 +}
 1.83469 +
 1.83470 +/*
 1.83471 +** Generate code for the ANALYZE command.  The parser calls this routine
 1.83472 +** when it recognizes an ANALYZE command.
 1.83473 +**
 1.83474 +**        ANALYZE                            -- 1
 1.83475 +**        ANALYZE  <database>                -- 2
 1.83476 +**        ANALYZE  ?<database>.?<tablename>  -- 3
 1.83477 +**
 1.83478 +** Form 1 causes all indices in all attached databases to be analyzed.
 1.83479 +** Form 2 analyzes all indices the single database named.
 1.83480 +** Form 3 analyzes all indices associated with the named table.
 1.83481 +*/
 1.83482 +SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
 1.83483 +  sqlite3 *db = pParse->db;
 1.83484 +  int iDb;
 1.83485 +  int i;
 1.83486 +  char *z, *zDb;
 1.83487 +  Table *pTab;
 1.83488 +  Index *pIdx;
 1.83489 +  Token *pTableName;
 1.83490 +
 1.83491 +  /* Read the database schema. If an error occurs, leave an error message
 1.83492 +  ** and code in pParse and return NULL. */
 1.83493 +  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
 1.83494 +  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
 1.83495 +    return;
 1.83496 +  }
 1.83497 +
 1.83498 +  assert( pName2!=0 || pName1==0 );
 1.83499 +  if( pName1==0 ){
 1.83500 +    /* Form 1:  Analyze everything */
 1.83501 +    for(i=0; i<db->nDb; i++){
 1.83502 +      if( i==1 ) continue;  /* Do not analyze the TEMP database */
 1.83503 +      analyzeDatabase(pParse, i);
 1.83504 +    }
 1.83505 +  }else if( pName2->n==0 ){
 1.83506 +    /* Form 2:  Analyze the database or table named */
 1.83507 +    iDb = sqlite3FindDb(db, pName1);
 1.83508 +    if( iDb>=0 ){
 1.83509 +      analyzeDatabase(pParse, iDb);
 1.83510 +    }else{
 1.83511 +      z = sqlite3NameFromToken(db, pName1);
 1.83512 +      if( z ){
 1.83513 +        if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
 1.83514 +          analyzeTable(pParse, pIdx->pTable, pIdx);
 1.83515 +        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
 1.83516 +          analyzeTable(pParse, pTab, 0);
 1.83517 +        }
 1.83518 +        sqlite3DbFree(db, z);
 1.83519 +      }
 1.83520 +    }
 1.83521 +  }else{
 1.83522 +    /* Form 3: Analyze the fully qualified table name */
 1.83523 +    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
 1.83524 +    if( iDb>=0 ){
 1.83525 +      zDb = db->aDb[iDb].zName;
 1.83526 +      z = sqlite3NameFromToken(db, pTableName);
 1.83527 +      if( z ){
 1.83528 +        if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
 1.83529 +          analyzeTable(pParse, pIdx->pTable, pIdx);
 1.83530 +        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
 1.83531 +          analyzeTable(pParse, pTab, 0);
 1.83532 +        }
 1.83533 +        sqlite3DbFree(db, z);
 1.83534 +      }
 1.83535 +    }   
 1.83536 +  }
 1.83537 +}
 1.83538 +
 1.83539 +/*
 1.83540 +** Used to pass information from the analyzer reader through to the
 1.83541 +** callback routine.
 1.83542 +*/
 1.83543 +typedef struct analysisInfo analysisInfo;
 1.83544 +struct analysisInfo {
 1.83545 +  sqlite3 *db;
 1.83546 +  const char *zDatabase;
 1.83547 +};
 1.83548 +
 1.83549 +/*
 1.83550 +** The first argument points to a nul-terminated string containing a
 1.83551 +** list of space separated integers. Read the first nOut of these into
 1.83552 +** the array aOut[].
 1.83553 +*/
 1.83554 +static void decodeIntArray(
 1.83555 +  char *zIntArray,       /* String containing int array to decode */
 1.83556 +  int nOut,              /* Number of slots in aOut[] */
 1.83557 +  tRowcnt *aOut,         /* Store integers here */
 1.83558 +  Index *pIndex          /* Handle extra flags for this index, if not NULL */
 1.83559 +){
 1.83560 +  char *z = zIntArray;
 1.83561 +  int c;
 1.83562 +  int i;
 1.83563 +  tRowcnt v;
 1.83564 +
 1.83565 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.83566 +  if( z==0 ) z = "";
 1.83567 +#else
 1.83568 +  if( NEVER(z==0) ) z = "";
 1.83569 +#endif
 1.83570 +  for(i=0; *z && i<nOut; i++){
 1.83571 +    v = 0;
 1.83572 +    while( (c=z[0])>='0' && c<='9' ){
 1.83573 +      v = v*10 + c - '0';
 1.83574 +      z++;
 1.83575 +    }
 1.83576 +    aOut[i] = v;
 1.83577 +    if( *z==' ' ) z++;
 1.83578 +  }
 1.83579 +#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
 1.83580 +  assert( pIndex!=0 );
 1.83581 +#else
 1.83582 +  if( pIndex )
 1.83583 +#endif
 1.83584 +  {
 1.83585 +    if( strcmp(z, "unordered")==0 ){
 1.83586 +      pIndex->bUnordered = 1;
 1.83587 +    }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
 1.83588 +      int v32 = 0;
 1.83589 +      sqlite3GetInt32(z+3, &v32);
 1.83590 +      pIndex->szIdxRow = sqlite3LogEst(v32);
 1.83591 +    }
 1.83592 +  }
 1.83593 +}
 1.83594 +
 1.83595 +/*
 1.83596 +** This callback is invoked once for each index when reading the
 1.83597 +** sqlite_stat1 table.  
 1.83598 +**
 1.83599 +**     argv[0] = name of the table
 1.83600 +**     argv[1] = name of the index (might be NULL)
 1.83601 +**     argv[2] = results of analysis - on integer for each column
 1.83602 +**
 1.83603 +** Entries for which argv[1]==NULL simply record the number of rows in
 1.83604 +** the table.
 1.83605 +*/
 1.83606 +static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
 1.83607 +  analysisInfo *pInfo = (analysisInfo*)pData;
 1.83608 +  Index *pIndex;
 1.83609 +  Table *pTable;
 1.83610 +  const char *z;
 1.83611 +
 1.83612 +  assert( argc==3 );
 1.83613 +  UNUSED_PARAMETER2(NotUsed, argc);
 1.83614 +
 1.83615 +  if( argv==0 || argv[0]==0 || argv[2]==0 ){
 1.83616 +    return 0;
 1.83617 +  }
 1.83618 +  pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
 1.83619 +  if( pTable==0 ){
 1.83620 +    return 0;
 1.83621 +  }
 1.83622 +  if( argv[1]==0 ){
 1.83623 +    pIndex = 0;
 1.83624 +  }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
 1.83625 +    pIndex = sqlite3PrimaryKeyIndex(pTable);
 1.83626 +  }else{
 1.83627 +    pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
 1.83628 +  }
 1.83629 +  z = argv[2];
 1.83630 +
 1.83631 +  if( pIndex ){
 1.83632 +    decodeIntArray((char*)z, pIndex->nKeyCol+1, pIndex->aiRowEst, pIndex);
 1.83633 +    if( pIndex->pPartIdxWhere==0 ) pTable->nRowEst = pIndex->aiRowEst[0];
 1.83634 +  }else{
 1.83635 +    Index fakeIdx;
 1.83636 +    fakeIdx.szIdxRow = pTable->szTabRow;
 1.83637 +    decodeIntArray((char*)z, 1, &pTable->nRowEst, &fakeIdx);
 1.83638 +    pTable->szTabRow = fakeIdx.szIdxRow;
 1.83639 +  }
 1.83640 +
 1.83641 +  return 0;
 1.83642 +}
 1.83643 +
 1.83644 +/*
 1.83645 +** If the Index.aSample variable is not NULL, delete the aSample[] array
 1.83646 +** and its contents.
 1.83647 +*/
 1.83648 +SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
 1.83649 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.83650 +  if( pIdx->aSample ){
 1.83651 +    int j;
 1.83652 +    for(j=0; j<pIdx->nSample; j++){
 1.83653 +      IndexSample *p = &pIdx->aSample[j];
 1.83654 +      sqlite3DbFree(db, p->p);
 1.83655 +    }
 1.83656 +    sqlite3DbFree(db, pIdx->aSample);
 1.83657 +  }
 1.83658 +  if( db && db->pnBytesFreed==0 ){
 1.83659 +    pIdx->nSample = 0;
 1.83660 +    pIdx->aSample = 0;
 1.83661 +  }
 1.83662 +#else
 1.83663 +  UNUSED_PARAMETER(db);
 1.83664 +  UNUSED_PARAMETER(pIdx);
 1.83665 +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
 1.83666 +}
 1.83667 +
 1.83668 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.83669 +/*
 1.83670 +** Populate the pIdx->aAvgEq[] array based on the samples currently
 1.83671 +** stored in pIdx->aSample[]. 
 1.83672 +*/
 1.83673 +static void initAvgEq(Index *pIdx){
 1.83674 +  if( pIdx ){
 1.83675 +    IndexSample *aSample = pIdx->aSample;
 1.83676 +    IndexSample *pFinal = &aSample[pIdx->nSample-1];
 1.83677 +    int iCol;
 1.83678 +    for(iCol=0; iCol<pIdx->nKeyCol; iCol++){
 1.83679 +      int i;                    /* Used to iterate through samples */
 1.83680 +      tRowcnt sumEq = 0;        /* Sum of the nEq values */
 1.83681 +      tRowcnt nSum = 0;         /* Number of terms contributing to sumEq */
 1.83682 +      tRowcnt avgEq = 0;
 1.83683 +      tRowcnt nDLt = pFinal->anDLt[iCol];
 1.83684 +
 1.83685 +      /* Set nSum to the number of distinct (iCol+1) field prefixes that
 1.83686 +      ** occur in the stat4 table for this index before pFinal. Set
 1.83687 +      ** sumEq to the sum of the nEq values for column iCol for the same
 1.83688 +      ** set (adding the value only once where there exist dupicate 
 1.83689 +      ** prefixes).  */
 1.83690 +      for(i=0; i<(pIdx->nSample-1); i++){
 1.83691 +        if( aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] ){
 1.83692 +          sumEq += aSample[i].anEq[iCol];
 1.83693 +          nSum++;
 1.83694 +        }
 1.83695 +      }
 1.83696 +      if( nDLt>nSum ){
 1.83697 +        avgEq = (pFinal->anLt[iCol] - sumEq)/(nDLt - nSum);
 1.83698 +      }
 1.83699 +      if( avgEq==0 ) avgEq = 1;
 1.83700 +      pIdx->aAvgEq[iCol] = avgEq;
 1.83701 +      if( pIdx->nSampleCol==1 ) break;
 1.83702 +    }
 1.83703 +  }
 1.83704 +}
 1.83705 +
 1.83706 +/*
 1.83707 +** Look up an index by name.  Or, if the name of a WITHOUT ROWID table
 1.83708 +** is supplied instead, find the PRIMARY KEY index for that table.
 1.83709 +*/
 1.83710 +static Index *findIndexOrPrimaryKey(
 1.83711 +  sqlite3 *db,
 1.83712 +  const char *zName,
 1.83713 +  const char *zDb
 1.83714 +){
 1.83715 +  Index *pIdx = sqlite3FindIndex(db, zName, zDb);
 1.83716 +  if( pIdx==0 ){
 1.83717 +    Table *pTab = sqlite3FindTable(db, zName, zDb);
 1.83718 +    if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
 1.83719 +  }
 1.83720 +  return pIdx;
 1.83721 +}
 1.83722 +
 1.83723 +/*
 1.83724 +** Load the content from either the sqlite_stat4 or sqlite_stat3 table 
 1.83725 +** into the relevant Index.aSample[] arrays.
 1.83726 +**
 1.83727 +** Arguments zSql1 and zSql2 must point to SQL statements that return
 1.83728 +** data equivalent to the following (statements are different for stat3,
 1.83729 +** see the caller of this function for details):
 1.83730 +**
 1.83731 +**    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
 1.83732 +**    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
 1.83733 +**
 1.83734 +** where %Q is replaced with the database name before the SQL is executed.
 1.83735 +*/
 1.83736 +static int loadStatTbl(
 1.83737 +  sqlite3 *db,                  /* Database handle */
 1.83738 +  int bStat3,                   /* Assume single column records only */
 1.83739 +  const char *zSql1,            /* SQL statement 1 (see above) */
 1.83740 +  const char *zSql2,            /* SQL statement 2 (see above) */
 1.83741 +  const char *zDb               /* Database name (e.g. "main") */
 1.83742 +){
 1.83743 +  int rc;                       /* Result codes from subroutines */
 1.83744 +  sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
 1.83745 +  char *zSql;                   /* Text of the SQL statement */
 1.83746 +  Index *pPrevIdx = 0;          /* Previous index in the loop */
 1.83747 +  IndexSample *pSample;         /* A slot in pIdx->aSample[] */
 1.83748 +
 1.83749 +  assert( db->lookaside.bEnabled==0 );
 1.83750 +  zSql = sqlite3MPrintf(db, zSql1, zDb);
 1.83751 +  if( !zSql ){
 1.83752 +    return SQLITE_NOMEM;
 1.83753 +  }
 1.83754 +  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
 1.83755 +  sqlite3DbFree(db, zSql);
 1.83756 +  if( rc ) return rc;
 1.83757 +
 1.83758 +  while( sqlite3_step(pStmt)==SQLITE_ROW ){
 1.83759 +    int nIdxCol = 1;              /* Number of columns in stat4 records */
 1.83760 +    int nAvgCol = 1;              /* Number of entries in Index.aAvgEq */
 1.83761 +
 1.83762 +    char *zIndex;   /* Index name */
 1.83763 +    Index *pIdx;    /* Pointer to the index object */
 1.83764 +    int nSample;    /* Number of samples */
 1.83765 +    int nByte;      /* Bytes of space required */
 1.83766 +    int i;          /* Bytes of space required */
 1.83767 +    tRowcnt *pSpace;
 1.83768 +
 1.83769 +    zIndex = (char *)sqlite3_column_text(pStmt, 0);
 1.83770 +    if( zIndex==0 ) continue;
 1.83771 +    nSample = sqlite3_column_int(pStmt, 1);
 1.83772 +    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
 1.83773 +    assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
 1.83774 +    /* Index.nSample is non-zero at this point if data has already been
 1.83775 +    ** loaded from the stat4 table. In this case ignore stat3 data.  */
 1.83776 +    if( pIdx==0 || pIdx->nSample ) continue;
 1.83777 +    if( bStat3==0 ){
 1.83778 +      nIdxCol = pIdx->nKeyCol+1;
 1.83779 +      nAvgCol = pIdx->nKeyCol;
 1.83780 +    }
 1.83781 +    pIdx->nSampleCol = nIdxCol;
 1.83782 +    nByte = sizeof(IndexSample) * nSample;
 1.83783 +    nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
 1.83784 +    nByte += nAvgCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
 1.83785 +
 1.83786 +    pIdx->aSample = sqlite3DbMallocZero(db, nByte);
 1.83787 +    if( pIdx->aSample==0 ){
 1.83788 +      sqlite3_finalize(pStmt);
 1.83789 +      return SQLITE_NOMEM;
 1.83790 +    }
 1.83791 +    pSpace = (tRowcnt*)&pIdx->aSample[nSample];
 1.83792 +    pIdx->aAvgEq = pSpace; pSpace += nAvgCol;
 1.83793 +    for(i=0; i<nSample; i++){
 1.83794 +      pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
 1.83795 +      pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
 1.83796 +      pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
 1.83797 +    }
 1.83798 +    assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
 1.83799 +  }
 1.83800 +  rc = sqlite3_finalize(pStmt);
 1.83801 +  if( rc ) return rc;
 1.83802 +
 1.83803 +  zSql = sqlite3MPrintf(db, zSql2, zDb);
 1.83804 +  if( !zSql ){
 1.83805 +    return SQLITE_NOMEM;
 1.83806 +  }
 1.83807 +  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
 1.83808 +  sqlite3DbFree(db, zSql);
 1.83809 +  if( rc ) return rc;
 1.83810 +
 1.83811 +  while( sqlite3_step(pStmt)==SQLITE_ROW ){
 1.83812 +    char *zIndex;                 /* Index name */
 1.83813 +    Index *pIdx;                  /* Pointer to the index object */
 1.83814 +    int nCol = 1;                 /* Number of columns in index */
 1.83815 +
 1.83816 +    zIndex = (char *)sqlite3_column_text(pStmt, 0);
 1.83817 +    if( zIndex==0 ) continue;
 1.83818 +    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
 1.83819 +    if( pIdx==0 ) continue;
 1.83820 +    /* This next condition is true if data has already been loaded from 
 1.83821 +    ** the sqlite_stat4 table. In this case ignore stat3 data.  */
 1.83822 +    nCol = pIdx->nSampleCol;
 1.83823 +    if( bStat3 && nCol>1 ) continue;
 1.83824 +    if( pIdx!=pPrevIdx ){
 1.83825 +      initAvgEq(pPrevIdx);
 1.83826 +      pPrevIdx = pIdx;
 1.83827 +    }
 1.83828 +    pSample = &pIdx->aSample[pIdx->nSample];
 1.83829 +    decodeIntArray((char*)sqlite3_column_text(pStmt,1), nCol, pSample->anEq, 0);
 1.83830 +    decodeIntArray((char*)sqlite3_column_text(pStmt,2), nCol, pSample->anLt, 0);
 1.83831 +    decodeIntArray((char*)sqlite3_column_text(pStmt,3), nCol, pSample->anDLt,0);
 1.83832 +
 1.83833 +    /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
 1.83834 +    ** This is in case the sample record is corrupted. In that case, the
 1.83835 +    ** sqlite3VdbeRecordCompare() may read up to two varints past the
 1.83836 +    ** end of the allocated buffer before it realizes it is dealing with
 1.83837 +    ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
 1.83838 +    ** a buffer overread.  */
 1.83839 +    pSample->n = sqlite3_column_bytes(pStmt, 4);
 1.83840 +    pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
 1.83841 +    if( pSample->p==0 ){
 1.83842 +      sqlite3_finalize(pStmt);
 1.83843 +      return SQLITE_NOMEM;
 1.83844 +    }
 1.83845 +    memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
 1.83846 +    pIdx->nSample++;
 1.83847 +  }
 1.83848 +  rc = sqlite3_finalize(pStmt);
 1.83849 +  if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
 1.83850 +  return rc;
 1.83851 +}
 1.83852 +
 1.83853 +/*
 1.83854 +** Load content from the sqlite_stat4 and sqlite_stat3 tables into 
 1.83855 +** the Index.aSample[] arrays of all indices.
 1.83856 +*/
 1.83857 +static int loadStat4(sqlite3 *db, const char *zDb){
 1.83858 +  int rc = SQLITE_OK;             /* Result codes from subroutines */
 1.83859 +
 1.83860 +  assert( db->lookaside.bEnabled==0 );
 1.83861 +  if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
 1.83862 +    rc = loadStatTbl(db, 0,
 1.83863 +      "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx", 
 1.83864 +      "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
 1.83865 +      zDb
 1.83866 +    );
 1.83867 +  }
 1.83868 +
 1.83869 +  if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
 1.83870 +    rc = loadStatTbl(db, 1,
 1.83871 +      "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx", 
 1.83872 +      "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
 1.83873 +      zDb
 1.83874 +    );
 1.83875 +  }
 1.83876 +
 1.83877 +  return rc;
 1.83878 +}
 1.83879 +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
 1.83880 +
 1.83881 +/*
 1.83882 +** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
 1.83883 +** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
 1.83884 +** arrays. The contents of sqlite_stat3/4 are used to populate the
 1.83885 +** Index.aSample[] arrays.
 1.83886 +**
 1.83887 +** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
 1.83888 +** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined 
 1.83889 +** during compilation and the sqlite_stat3/4 table is present, no data is 
 1.83890 +** read from it.
 1.83891 +**
 1.83892 +** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the 
 1.83893 +** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
 1.83894 +** returned. However, in this case, data is read from the sqlite_stat1
 1.83895 +** table (if it is present) before returning.
 1.83896 +**
 1.83897 +** If an OOM error occurs, this function always sets db->mallocFailed.
 1.83898 +** This means if the caller does not care about other errors, the return
 1.83899 +** code may be ignored.
 1.83900 +*/
 1.83901 +SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
 1.83902 +  analysisInfo sInfo;
 1.83903 +  HashElem *i;
 1.83904 +  char *zSql;
 1.83905 +  int rc;
 1.83906 +
 1.83907 +  assert( iDb>=0 && iDb<db->nDb );
 1.83908 +  assert( db->aDb[iDb].pBt!=0 );
 1.83909 +
 1.83910 +  /* Clear any prior statistics */
 1.83911 +  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 1.83912 +  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
 1.83913 +    Index *pIdx = sqliteHashData(i);
 1.83914 +    sqlite3DefaultRowEst(pIdx);
 1.83915 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.83916 +    sqlite3DeleteIndexSamples(db, pIdx);
 1.83917 +    pIdx->aSample = 0;
 1.83918 +#endif
 1.83919 +  }
 1.83920 +
 1.83921 +  /* Check to make sure the sqlite_stat1 table exists */
 1.83922 +  sInfo.db = db;
 1.83923 +  sInfo.zDatabase = db->aDb[iDb].zName;
 1.83924 +  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
 1.83925 +    return SQLITE_ERROR;
 1.83926 +  }
 1.83927 +
 1.83928 +  /* Load new statistics out of the sqlite_stat1 table */
 1.83929 +  zSql = sqlite3MPrintf(db, 
 1.83930 +      "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
 1.83931 +  if( zSql==0 ){
 1.83932 +    rc = SQLITE_NOMEM;
 1.83933 +  }else{
 1.83934 +    rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
 1.83935 +    sqlite3DbFree(db, zSql);
 1.83936 +  }
 1.83937 +
 1.83938 +
 1.83939 +  /* Load the statistics from the sqlite_stat4 table. */
 1.83940 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 1.83941 +  if( rc==SQLITE_OK ){
 1.83942 +    int lookasideEnabled = db->lookaside.bEnabled;
 1.83943 +    db->lookaside.bEnabled = 0;
 1.83944 +    rc = loadStat4(db, sInfo.zDatabase);
 1.83945 +    db->lookaside.bEnabled = lookasideEnabled;
 1.83946 +  }
 1.83947 +#endif
 1.83948 +
 1.83949 +  if( rc==SQLITE_NOMEM ){
 1.83950 +    db->mallocFailed = 1;
 1.83951 +  }
 1.83952 +  return rc;
 1.83953 +}
 1.83954 +
 1.83955 +
 1.83956 +#endif /* SQLITE_OMIT_ANALYZE */
 1.83957 +
 1.83958 +/************** End of analyze.c *********************************************/
 1.83959 +/************** Begin file attach.c ******************************************/
 1.83960 +/*
 1.83961 +** 2003 April 6
 1.83962 +**
 1.83963 +** The author disclaims copyright to this source code.  In place of
 1.83964 +** a legal notice, here is a blessing:
 1.83965 +**
 1.83966 +**    May you do good and not evil.
 1.83967 +**    May you find forgiveness for yourself and forgive others.
 1.83968 +**    May you share freely, never taking more than you give.
 1.83969 +**
 1.83970 +*************************************************************************
 1.83971 +** This file contains code used to implement the ATTACH and DETACH commands.
 1.83972 +*/
 1.83973 +
 1.83974 +#ifndef SQLITE_OMIT_ATTACH
 1.83975 +/*
 1.83976 +** Resolve an expression that was part of an ATTACH or DETACH statement. This
 1.83977 +** is slightly different from resolving a normal SQL expression, because simple
 1.83978 +** identifiers are treated as strings, not possible column names or aliases.
 1.83979 +**
 1.83980 +** i.e. if the parser sees:
 1.83981 +**
 1.83982 +**     ATTACH DATABASE abc AS def
 1.83983 +**
 1.83984 +** it treats the two expressions as literal strings 'abc' and 'def' instead of
 1.83985 +** looking for columns of the same name.
 1.83986 +**
 1.83987 +** This only applies to the root node of pExpr, so the statement:
 1.83988 +**
 1.83989 +**     ATTACH DATABASE abc||def AS 'db2'
 1.83990 +**
 1.83991 +** will fail because neither abc or def can be resolved.
 1.83992 +*/
 1.83993 +static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
 1.83994 +{
 1.83995 +  int rc = SQLITE_OK;
 1.83996 +  if( pExpr ){
 1.83997 +    if( pExpr->op!=TK_ID ){
 1.83998 +      rc = sqlite3ResolveExprNames(pName, pExpr);
 1.83999 +    }else{
 1.84000 +      pExpr->op = TK_STRING;
 1.84001 +    }
 1.84002 +  }
 1.84003 +  return rc;
 1.84004 +}
 1.84005 +
 1.84006 +/*
 1.84007 +** An SQL user-function registered to do the work of an ATTACH statement. The
 1.84008 +** three arguments to the function come directly from an attach statement:
 1.84009 +**
 1.84010 +**     ATTACH DATABASE x AS y KEY z
 1.84011 +**
 1.84012 +**     SELECT sqlite_attach(x, y, z)
 1.84013 +**
 1.84014 +** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
 1.84015 +** third argument.
 1.84016 +*/
 1.84017 +static void attachFunc(
 1.84018 +  sqlite3_context *context,
 1.84019 +  int NotUsed,
 1.84020 +  sqlite3_value **argv
 1.84021 +){
 1.84022 +  int i;
 1.84023 +  int rc = 0;
 1.84024 +  sqlite3 *db = sqlite3_context_db_handle(context);
 1.84025 +  const char *zName;
 1.84026 +  const char *zFile;
 1.84027 +  char *zPath = 0;
 1.84028 +  char *zErr = 0;
 1.84029 +  unsigned int flags;
 1.84030 +  Db *aNew;
 1.84031 +  char *zErrDyn = 0;
 1.84032 +  sqlite3_vfs *pVfs;
 1.84033 +
 1.84034 +  UNUSED_PARAMETER(NotUsed);
 1.84035 +
 1.84036 +  zFile = (const char *)sqlite3_value_text(argv[0]);
 1.84037 +  zName = (const char *)sqlite3_value_text(argv[1]);
 1.84038 +  if( zFile==0 ) zFile = "";
 1.84039 +  if( zName==0 ) zName = "";
 1.84040 +
 1.84041 +  /* Check for the following errors:
 1.84042 +  **
 1.84043 +  **     * Too many attached databases,
 1.84044 +  **     * Transaction currently open
 1.84045 +  **     * Specified database name already being used.
 1.84046 +  */
 1.84047 +  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
 1.84048 +    zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
 1.84049 +      db->aLimit[SQLITE_LIMIT_ATTACHED]
 1.84050 +    );
 1.84051 +    goto attach_error;
 1.84052 +  }
 1.84053 +  if( !db->autoCommit ){
 1.84054 +    zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
 1.84055 +    goto attach_error;
 1.84056 +  }
 1.84057 +  for(i=0; i<db->nDb; i++){
 1.84058 +    char *z = db->aDb[i].zName;
 1.84059 +    assert( z && zName );
 1.84060 +    if( sqlite3StrICmp(z, zName)==0 ){
 1.84061 +      zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
 1.84062 +      goto attach_error;
 1.84063 +    }
 1.84064 +  }
 1.84065 +
 1.84066 +  /* Allocate the new entry in the db->aDb[] array and initialize the schema
 1.84067 +  ** hash tables.
 1.84068 +  */
 1.84069 +  if( db->aDb==db->aDbStatic ){
 1.84070 +    aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
 1.84071 +    if( aNew==0 ) return;
 1.84072 +    memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
 1.84073 +  }else{
 1.84074 +    aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
 1.84075 +    if( aNew==0 ) return;
 1.84076 +  }
 1.84077 +  db->aDb = aNew;
 1.84078 +  aNew = &db->aDb[db->nDb];
 1.84079 +  memset(aNew, 0, sizeof(*aNew));
 1.84080 +
 1.84081 +  /* Open the database file. If the btree is successfully opened, use
 1.84082 +  ** it to obtain the database schema. At this point the schema may
 1.84083 +  ** or may not be initialized.
 1.84084 +  */
 1.84085 +  flags = db->openFlags;
 1.84086 +  rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
 1.84087 +  if( rc!=SQLITE_OK ){
 1.84088 +    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
 1.84089 +    sqlite3_result_error(context, zErr, -1);
 1.84090 +    sqlite3_free(zErr);
 1.84091 +    return;
 1.84092 +  }
 1.84093 +  assert( pVfs );
 1.84094 +  flags |= SQLITE_OPEN_MAIN_DB;
 1.84095 +  rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
 1.84096 +  sqlite3_free( zPath );
 1.84097 +  db->nDb++;
 1.84098 +  if( rc==SQLITE_CONSTRAINT ){
 1.84099 +    rc = SQLITE_ERROR;
 1.84100 +    zErrDyn = sqlite3MPrintf(db, "database is already attached");
 1.84101 +  }else if( rc==SQLITE_OK ){
 1.84102 +    Pager *pPager;
 1.84103 +    aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
 1.84104 +    if( !aNew->pSchema ){
 1.84105 +      rc = SQLITE_NOMEM;
 1.84106 +    }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
 1.84107 +      zErrDyn = sqlite3MPrintf(db, 
 1.84108 +        "attached databases must use the same text encoding as main database");
 1.84109 +      rc = SQLITE_ERROR;
 1.84110 +    }
 1.84111 +    pPager = sqlite3BtreePager(aNew->pBt);
 1.84112 +    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
 1.84113 +    sqlite3BtreeSecureDelete(aNew->pBt,
 1.84114 +                             sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
 1.84115 +#ifndef SQLITE_OMIT_PAGER_PRAGMAS
 1.84116 +    sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
 1.84117 +#endif
 1.84118 +  }
 1.84119 +  aNew->safety_level = 3;
 1.84120 +  aNew->zName = sqlite3DbStrDup(db, zName);
 1.84121 +  if( rc==SQLITE_OK && aNew->zName==0 ){
 1.84122 +    rc = SQLITE_NOMEM;
 1.84123 +  }
 1.84124 +
 1.84125 +
 1.84126 +#ifdef SQLITE_HAS_CODEC
 1.84127 +  if( rc==SQLITE_OK ){
 1.84128 +    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
 1.84129 +    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
 1.84130 +    int nKey;
 1.84131 +    char *zKey;
 1.84132 +    int t = sqlite3_value_type(argv[2]);
 1.84133 +    switch( t ){
 1.84134 +      case SQLITE_INTEGER:
 1.84135 +      case SQLITE_FLOAT:
 1.84136 +        zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
 1.84137 +        rc = SQLITE_ERROR;
 1.84138 +        break;
 1.84139 +        
 1.84140 +      case SQLITE_TEXT:
 1.84141 +      case SQLITE_BLOB:
 1.84142 +        nKey = sqlite3_value_bytes(argv[2]);
 1.84143 +        zKey = (char *)sqlite3_value_blob(argv[2]);
 1.84144 +        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
 1.84145 +        break;
 1.84146 +
 1.84147 +      case SQLITE_NULL:
 1.84148 +        /* No key specified.  Use the key from the main database */
 1.84149 +        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
 1.84150 +        if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
 1.84151 +          rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
 1.84152 +        }
 1.84153 +        break;
 1.84154 +    }
 1.84155 +  }
 1.84156 +#endif
 1.84157 +
 1.84158 +  /* If the file was opened successfully, read the schema for the new database.
 1.84159 +  ** If this fails, or if opening the file failed, then close the file and 
 1.84160 +  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
 1.84161 +  ** we found it.
 1.84162 +  */
 1.84163 +  if( rc==SQLITE_OK ){
 1.84164 +    sqlite3BtreeEnterAll(db);
 1.84165 +    rc = sqlite3Init(db, &zErrDyn);
 1.84166 +    sqlite3BtreeLeaveAll(db);
 1.84167 +  }
 1.84168 +  if( rc ){
 1.84169 +    int iDb = db->nDb - 1;
 1.84170 +    assert( iDb>=2 );
 1.84171 +    if( db->aDb[iDb].pBt ){
 1.84172 +      sqlite3BtreeClose(db->aDb[iDb].pBt);
 1.84173 +      db->aDb[iDb].pBt = 0;
 1.84174 +      db->aDb[iDb].pSchema = 0;
 1.84175 +    }
 1.84176 +    sqlite3ResetAllSchemasOfConnection(db);
 1.84177 +    db->nDb = iDb;
 1.84178 +    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
 1.84179 +      db->mallocFailed = 1;
 1.84180 +      sqlite3DbFree(db, zErrDyn);
 1.84181 +      zErrDyn = sqlite3MPrintf(db, "out of memory");
 1.84182 +    }else if( zErrDyn==0 ){
 1.84183 +      zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
 1.84184 +    }
 1.84185 +    goto attach_error;
 1.84186 +  }
 1.84187 +  
 1.84188 +  return;
 1.84189 +
 1.84190 +attach_error:
 1.84191 +  /* Return an error if we get here */
 1.84192 +  if( zErrDyn ){
 1.84193 +    sqlite3_result_error(context, zErrDyn, -1);
 1.84194 +    sqlite3DbFree(db, zErrDyn);
 1.84195 +  }
 1.84196 +  if( rc ) sqlite3_result_error_code(context, rc);
 1.84197 +}
 1.84198 +
 1.84199 +/*
 1.84200 +** An SQL user-function registered to do the work of an DETACH statement. The
 1.84201 +** three arguments to the function come directly from a detach statement:
 1.84202 +**
 1.84203 +**     DETACH DATABASE x
 1.84204 +**
 1.84205 +**     SELECT sqlite_detach(x)
 1.84206 +*/
 1.84207 +static void detachFunc(
 1.84208 +  sqlite3_context *context,
 1.84209 +  int NotUsed,
 1.84210 +  sqlite3_value **argv
 1.84211 +){
 1.84212 +  const char *zName = (const char *)sqlite3_value_text(argv[0]);
 1.84213 +  sqlite3 *db = sqlite3_context_db_handle(context);
 1.84214 +  int i;
 1.84215 +  Db *pDb = 0;
 1.84216 +  char zErr[128];
 1.84217 +
 1.84218 +  UNUSED_PARAMETER(NotUsed);
 1.84219 +
 1.84220 +  if( zName==0 ) zName = "";
 1.84221 +  for(i=0; i<db->nDb; i++){
 1.84222 +    pDb = &db->aDb[i];
 1.84223 +    if( pDb->pBt==0 ) continue;
 1.84224 +    if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
 1.84225 +  }
 1.84226 +
 1.84227 +  if( i>=db->nDb ){
 1.84228 +    sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
 1.84229 +    goto detach_error;
 1.84230 +  }
 1.84231 +  if( i<2 ){
 1.84232 +    sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
 1.84233 +    goto detach_error;
 1.84234 +  }
 1.84235 +  if( !db->autoCommit ){
 1.84236 +    sqlite3_snprintf(sizeof(zErr), zErr,
 1.84237 +                     "cannot DETACH database within transaction");
 1.84238 +    goto detach_error;
 1.84239 +  }
 1.84240 +  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
 1.84241 +    sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
 1.84242 +    goto detach_error;
 1.84243 +  }
 1.84244 +
 1.84245 +  sqlite3BtreeClose(pDb->pBt);
 1.84246 +  pDb->pBt = 0;
 1.84247 +  pDb->pSchema = 0;
 1.84248 +  sqlite3ResetAllSchemasOfConnection(db);
 1.84249 +  return;
 1.84250 +
 1.84251 +detach_error:
 1.84252 +  sqlite3_result_error(context, zErr, -1);
 1.84253 +}
 1.84254 +
 1.84255 +/*
 1.84256 +** This procedure generates VDBE code for a single invocation of either the
 1.84257 +** sqlite_detach() or sqlite_attach() SQL user functions.
 1.84258 +*/
 1.84259 +static void codeAttach(
 1.84260 +  Parse *pParse,       /* The parser context */
 1.84261 +  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
 1.84262 +  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
 1.84263 +  Expr *pAuthArg,      /* Expression to pass to authorization callback */
 1.84264 +  Expr *pFilename,     /* Name of database file */
 1.84265 +  Expr *pDbname,       /* Name of the database to use internally */
 1.84266 +  Expr *pKey           /* Database key for encryption extension */
 1.84267 +){
 1.84268 +  int rc;
 1.84269 +  NameContext sName;
 1.84270 +  Vdbe *v;
 1.84271 +  sqlite3* db = pParse->db;
 1.84272 +  int regArgs;
 1.84273 +
 1.84274 +  memset(&sName, 0, sizeof(NameContext));
 1.84275 +  sName.pParse = pParse;
 1.84276 +
 1.84277 +  if( 
 1.84278 +      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
 1.84279 +      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
 1.84280 +      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
 1.84281 +  ){
 1.84282 +    pParse->nErr++;
 1.84283 +    goto attach_end;
 1.84284 +  }
 1.84285 +
 1.84286 +#ifndef SQLITE_OMIT_AUTHORIZATION
 1.84287 +  if( pAuthArg ){
 1.84288 +    char *zAuthArg;
 1.84289 +    if( pAuthArg->op==TK_STRING ){
 1.84290 +      zAuthArg = pAuthArg->u.zToken;
 1.84291 +    }else{
 1.84292 +      zAuthArg = 0;
 1.84293 +    }
 1.84294 +    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
 1.84295 +    if(rc!=SQLITE_OK ){
 1.84296 +      goto attach_end;
 1.84297 +    }
 1.84298 +  }
 1.84299 +#endif /* SQLITE_OMIT_AUTHORIZATION */
 1.84300 +
 1.84301 +
 1.84302 +  v = sqlite3GetVdbe(pParse);
 1.84303 +  regArgs = sqlite3GetTempRange(pParse, 4);
 1.84304 +  sqlite3ExprCode(pParse, pFilename, regArgs);
 1.84305 +  sqlite3ExprCode(pParse, pDbname, regArgs+1);
 1.84306 +  sqlite3ExprCode(pParse, pKey, regArgs+2);
 1.84307 +
 1.84308 +  assert( v || db->mallocFailed );
 1.84309 +  if( v ){
 1.84310 +    sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
 1.84311 +    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
 1.84312 +    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
 1.84313 +    sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
 1.84314 +
 1.84315 +    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
 1.84316 +    ** statement only). For DETACH, set it to false (expire all existing
 1.84317 +    ** statements).
 1.84318 +    */
 1.84319 +    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
 1.84320 +  }
 1.84321 +  
 1.84322 +attach_end:
 1.84323 +  sqlite3ExprDelete(db, pFilename);
 1.84324 +  sqlite3ExprDelete(db, pDbname);
 1.84325 +  sqlite3ExprDelete(db, pKey);
 1.84326 +}
 1.84327 +
 1.84328 +/*
 1.84329 +** Called by the parser to compile a DETACH statement.
 1.84330 +**
 1.84331 +**     DETACH pDbname
 1.84332 +*/
 1.84333 +SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
 1.84334 +  static const FuncDef detach_func = {
 1.84335 +    1,                /* nArg */
 1.84336 +    SQLITE_UTF8,      /* funcFlags */
 1.84337 +    0,                /* pUserData */
 1.84338 +    0,                /* pNext */
 1.84339 +    detachFunc,       /* xFunc */
 1.84340 +    0,                /* xStep */
 1.84341 +    0,                /* xFinalize */
 1.84342 +    "sqlite_detach",  /* zName */
 1.84343 +    0,                /* pHash */
 1.84344 +    0                 /* pDestructor */
 1.84345 +  };
 1.84346 +  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
 1.84347 +}
 1.84348 +
 1.84349 +/*
 1.84350 +** Called by the parser to compile an ATTACH statement.
 1.84351 +**
 1.84352 +**     ATTACH p AS pDbname KEY pKey
 1.84353 +*/
 1.84354 +SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
 1.84355 +  static const FuncDef attach_func = {
 1.84356 +    3,                /* nArg */
 1.84357 +    SQLITE_UTF8,      /* funcFlags */
 1.84358 +    0,                /* pUserData */
 1.84359 +    0,                /* pNext */
 1.84360 +    attachFunc,       /* xFunc */
 1.84361 +    0,                /* xStep */
 1.84362 +    0,                /* xFinalize */
 1.84363 +    "sqlite_attach",  /* zName */
 1.84364 +    0,                /* pHash */
 1.84365 +    0                 /* pDestructor */
 1.84366 +  };
 1.84367 +  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
 1.84368 +}
 1.84369 +#endif /* SQLITE_OMIT_ATTACH */
 1.84370 +
 1.84371 +/*
 1.84372 +** Initialize a DbFixer structure.  This routine must be called prior
 1.84373 +** to passing the structure to one of the sqliteFixAAAA() routines below.
 1.84374 +*/
 1.84375 +SQLITE_PRIVATE void sqlite3FixInit(
 1.84376 +  DbFixer *pFix,      /* The fixer to be initialized */
 1.84377 +  Parse *pParse,      /* Error messages will be written here */
 1.84378 +  int iDb,            /* This is the database that must be used */
 1.84379 +  const char *zType,  /* "view", "trigger", or "index" */
 1.84380 +  const Token *pName  /* Name of the view, trigger, or index */
 1.84381 +){
 1.84382 +  sqlite3 *db;
 1.84383 +
 1.84384 +  db = pParse->db;
 1.84385 +  assert( db->nDb>iDb );
 1.84386 +  pFix->pParse = pParse;
 1.84387 +  pFix->zDb = db->aDb[iDb].zName;
 1.84388 +  pFix->pSchema = db->aDb[iDb].pSchema;
 1.84389 +  pFix->zType = zType;
 1.84390 +  pFix->pName = pName;
 1.84391 +  pFix->bVarOnly = (iDb==1);
 1.84392 +}
 1.84393 +
 1.84394 +/*
 1.84395 +** The following set of routines walk through the parse tree and assign
 1.84396 +** a specific database to all table references where the database name
 1.84397 +** was left unspecified in the original SQL statement.  The pFix structure
 1.84398 +** must have been initialized by a prior call to sqlite3FixInit().
 1.84399 +**
 1.84400 +** These routines are used to make sure that an index, trigger, or
 1.84401 +** view in one database does not refer to objects in a different database.
 1.84402 +** (Exception: indices, triggers, and views in the TEMP database are
 1.84403 +** allowed to refer to anything.)  If a reference is explicitly made
 1.84404 +** to an object in a different database, an error message is added to
 1.84405 +** pParse->zErrMsg and these routines return non-zero.  If everything
 1.84406 +** checks out, these routines return 0.
 1.84407 +*/
 1.84408 +SQLITE_PRIVATE int sqlite3FixSrcList(
 1.84409 +  DbFixer *pFix,       /* Context of the fixation */
 1.84410 +  SrcList *pList       /* The Source list to check and modify */
 1.84411 +){
 1.84412 +  int i;
 1.84413 +  const char *zDb;
 1.84414 +  struct SrcList_item *pItem;
 1.84415 +
 1.84416 +  if( NEVER(pList==0) ) return 0;
 1.84417 +  zDb = pFix->zDb;
 1.84418 +  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
 1.84419 +    if( pFix->bVarOnly==0 ){
 1.84420 +      if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
 1.84421 +        sqlite3ErrorMsg(pFix->pParse,
 1.84422 +            "%s %T cannot reference objects in database %s",
 1.84423 +            pFix->zType, pFix->pName, pItem->zDatabase);
 1.84424 +        return 1;
 1.84425 +      }
 1.84426 +      sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
 1.84427 +      pItem->zDatabase = 0;
 1.84428 +      pItem->pSchema = pFix->pSchema;
 1.84429 +    }
 1.84430 +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
 1.84431 +    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
 1.84432 +    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
 1.84433 +#endif
 1.84434 +  }
 1.84435 +  return 0;
 1.84436 +}
 1.84437 +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
 1.84438 +SQLITE_PRIVATE int sqlite3FixSelect(
 1.84439 +  DbFixer *pFix,       /* Context of the fixation */
 1.84440 +  Select *pSelect      /* The SELECT statement to be fixed to one database */
 1.84441 +){
 1.84442 +  while( pSelect ){
 1.84443 +    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
 1.84444 +      return 1;
 1.84445 +    }
 1.84446 +    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
 1.84447 +      return 1;
 1.84448 +    }
 1.84449 +    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
 1.84450 +      return 1;
 1.84451 +    }
 1.84452 +    if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
 1.84453 +      return 1;
 1.84454 +    }
 1.84455 +    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
 1.84456 +      return 1;
 1.84457 +    }
 1.84458 +    if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
 1.84459 +      return 1;
 1.84460 +    }
 1.84461 +    if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
 1.84462 +      return 1;
 1.84463 +    }
 1.84464 +    if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
 1.84465 +      return 1;
 1.84466 +    }
 1.84467 +    pSelect = pSelect->pPrior;
 1.84468 +  }
 1.84469 +  return 0;
 1.84470 +}
 1.84471 +SQLITE_PRIVATE int sqlite3FixExpr(
 1.84472 +  DbFixer *pFix,     /* Context of the fixation */
 1.84473 +  Expr *pExpr        /* The expression to be fixed to one database */
 1.84474 +){
 1.84475 +  while( pExpr ){
 1.84476 +    if( pExpr->op==TK_VARIABLE ){
 1.84477 +      if( pFix->pParse->db->init.busy ){
 1.84478 +        pExpr->op = TK_NULL;
 1.84479 +      }else{
 1.84480 +        sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
 1.84481 +        return 1;
 1.84482 +      }
 1.84483 +    }
 1.84484 +    if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
 1.84485 +    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
 1.84486 +      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
 1.84487 +    }else{
 1.84488 +      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
 1.84489 +    }
 1.84490 +    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
 1.84491 +      return 1;
 1.84492 +    }
 1.84493 +    pExpr = pExpr->pLeft;
 1.84494 +  }
 1.84495 +  return 0;
 1.84496 +}
 1.84497 +SQLITE_PRIVATE int sqlite3FixExprList(
 1.84498 +  DbFixer *pFix,     /* Context of the fixation */
 1.84499 +  ExprList *pList    /* The expression to be fixed to one database */
 1.84500 +){
 1.84501 +  int i;
 1.84502 +  struct ExprList_item *pItem;
 1.84503 +  if( pList==0 ) return 0;
 1.84504 +  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
 1.84505 +    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
 1.84506 +      return 1;
 1.84507 +    }
 1.84508 +  }
 1.84509 +  return 0;
 1.84510 +}
 1.84511 +#endif
 1.84512 +
 1.84513 +#ifndef SQLITE_OMIT_TRIGGER
 1.84514 +SQLITE_PRIVATE int sqlite3FixTriggerStep(
 1.84515 +  DbFixer *pFix,     /* Context of the fixation */
 1.84516 +  TriggerStep *pStep /* The trigger step be fixed to one database */
 1.84517 +){
 1.84518 +  while( pStep ){
 1.84519 +    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
 1.84520 +      return 1;
 1.84521 +    }
 1.84522 +    if( sqlite3FixExpr(pFix, pStep->pWhere) ){
 1.84523 +      return 1;
 1.84524 +    }
 1.84525 +    if( sqlite3FixExprList(pFix, pStep->pExprList) ){
 1.84526 +      return 1;
 1.84527 +    }
 1.84528 +    pStep = pStep->pNext;
 1.84529 +  }
 1.84530 +  return 0;
 1.84531 +}
 1.84532 +#endif
 1.84533 +
 1.84534 +/************** End of attach.c **********************************************/
 1.84535 +/************** Begin file auth.c ********************************************/
 1.84536 +/*
 1.84537 +** 2003 January 11
 1.84538 +**
 1.84539 +** The author disclaims copyright to this source code.  In place of
 1.84540 +** a legal notice, here is a blessing:
 1.84541 +**
 1.84542 +**    May you do good and not evil.
 1.84543 +**    May you find forgiveness for yourself and forgive others.
 1.84544 +**    May you share freely, never taking more than you give.
 1.84545 +**
 1.84546 +*************************************************************************
 1.84547 +** This file contains code used to implement the sqlite3_set_authorizer()
 1.84548 +** API.  This facility is an optional feature of the library.  Embedded
 1.84549 +** systems that do not need this facility may omit it by recompiling
 1.84550 +** the library with -DSQLITE_OMIT_AUTHORIZATION=1
 1.84551 +*/
 1.84552 +
 1.84553 +/*
 1.84554 +** All of the code in this file may be omitted by defining a single
 1.84555 +** macro.
 1.84556 +*/
 1.84557 +#ifndef SQLITE_OMIT_AUTHORIZATION
 1.84558 +
 1.84559 +/*
 1.84560 +** Set or clear the access authorization function.
 1.84561 +**
 1.84562 +** The access authorization function is be called during the compilation
 1.84563 +** phase to verify that the user has read and/or write access permission on
 1.84564 +** various fields of the database.  The first argument to the auth function
 1.84565 +** is a copy of the 3rd argument to this routine.  The second argument
 1.84566 +** to the auth function is one of these constants:
 1.84567 +**
 1.84568 +**       SQLITE_CREATE_INDEX
 1.84569 +**       SQLITE_CREATE_TABLE
 1.84570 +**       SQLITE_CREATE_TEMP_INDEX
 1.84571 +**       SQLITE_CREATE_TEMP_TABLE
 1.84572 +**       SQLITE_CREATE_TEMP_TRIGGER
 1.84573 +**       SQLITE_CREATE_TEMP_VIEW
 1.84574 +**       SQLITE_CREATE_TRIGGER
 1.84575 +**       SQLITE_CREATE_VIEW
 1.84576 +**       SQLITE_DELETE
 1.84577 +**       SQLITE_DROP_INDEX
 1.84578 +**       SQLITE_DROP_TABLE
 1.84579 +**       SQLITE_DROP_TEMP_INDEX
 1.84580 +**       SQLITE_DROP_TEMP_TABLE
 1.84581 +**       SQLITE_DROP_TEMP_TRIGGER
 1.84582 +**       SQLITE_DROP_TEMP_VIEW
 1.84583 +**       SQLITE_DROP_TRIGGER
 1.84584 +**       SQLITE_DROP_VIEW
 1.84585 +**       SQLITE_INSERT
 1.84586 +**       SQLITE_PRAGMA
 1.84587 +**       SQLITE_READ
 1.84588 +**       SQLITE_SELECT
 1.84589 +**       SQLITE_TRANSACTION
 1.84590 +**       SQLITE_UPDATE
 1.84591 +**
 1.84592 +** The third and fourth arguments to the auth function are the name of
 1.84593 +** the table and the column that are being accessed.  The auth function
 1.84594 +** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
 1.84595 +** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
 1.84596 +** means that the SQL statement will never-run - the sqlite3_exec() call
 1.84597 +** will return with an error.  SQLITE_IGNORE means that the SQL statement
 1.84598 +** should run but attempts to read the specified column will return NULL
 1.84599 +** and attempts to write the column will be ignored.
 1.84600 +**
 1.84601 +** Setting the auth function to NULL disables this hook.  The default
 1.84602 +** setting of the auth function is NULL.
 1.84603 +*/
 1.84604 +SQLITE_API int sqlite3_set_authorizer(
 1.84605 +  sqlite3 *db,
 1.84606 +  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
 1.84607 +  void *pArg
 1.84608 +){
 1.84609 +  sqlite3_mutex_enter(db->mutex);
 1.84610 +  db->xAuth = xAuth;
 1.84611 +  db->pAuthArg = pArg;
 1.84612 +  sqlite3ExpirePreparedStatements(db);
 1.84613 +  sqlite3_mutex_leave(db->mutex);
 1.84614 +  return SQLITE_OK;
 1.84615 +}
 1.84616 +
 1.84617 +/*
 1.84618 +** Write an error message into pParse->zErrMsg that explains that the
 1.84619 +** user-supplied authorization function returned an illegal value.
 1.84620 +*/
 1.84621 +static void sqliteAuthBadReturnCode(Parse *pParse){
 1.84622 +  sqlite3ErrorMsg(pParse, "authorizer malfunction");
 1.84623 +  pParse->rc = SQLITE_ERROR;
 1.84624 +}
 1.84625 +
 1.84626 +/*
 1.84627 +** Invoke the authorization callback for permission to read column zCol from
 1.84628 +** table zTab in database zDb. This function assumes that an authorization
 1.84629 +** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
 1.84630 +**
 1.84631 +** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
 1.84632 +** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
 1.84633 +** is treated as SQLITE_DENY. In this case an error is left in pParse.
 1.84634 +*/
 1.84635 +SQLITE_PRIVATE int sqlite3AuthReadCol(
 1.84636 +  Parse *pParse,                  /* The parser context */
 1.84637 +  const char *zTab,               /* Table name */
 1.84638 +  const char *zCol,               /* Column name */
 1.84639 +  int iDb                         /* Index of containing database. */
 1.84640 +){
 1.84641 +  sqlite3 *db = pParse->db;       /* Database handle */
 1.84642 +  char *zDb = db->aDb[iDb].zName; /* Name of attached database */
 1.84643 +  int rc;                         /* Auth callback return code */
 1.84644 +
 1.84645 +  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
 1.84646 +  if( rc==SQLITE_DENY ){
 1.84647 +    if( db->nDb>2 || iDb!=0 ){
 1.84648 +      sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
 1.84649 +    }else{
 1.84650 +      sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
 1.84651 +    }
 1.84652 +    pParse->rc = SQLITE_AUTH;
 1.84653 +  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
 1.84654 +    sqliteAuthBadReturnCode(pParse);
 1.84655 +  }
 1.84656 +  return rc;
 1.84657 +}
 1.84658 +
 1.84659 +/*
 1.84660 +** The pExpr should be a TK_COLUMN expression.  The table referred to
 1.84661 +** is in pTabList or else it is the NEW or OLD table of a trigger.  
 1.84662 +** Check to see if it is OK to read this particular column.
 1.84663 +**
 1.84664 +** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
 1.84665 +** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
 1.84666 +** then generate an error.
 1.84667 +*/
 1.84668 +SQLITE_PRIVATE void sqlite3AuthRead(
 1.84669 +  Parse *pParse,        /* The parser context */
 1.84670 +  Expr *pExpr,          /* The expression to check authorization on */
 1.84671 +  Schema *pSchema,      /* The schema of the expression */
 1.84672 +  SrcList *pTabList     /* All table that pExpr might refer to */
 1.84673 +){
 1.84674 +  sqlite3 *db = pParse->db;
 1.84675 +  Table *pTab = 0;      /* The table being read */
 1.84676 +  const char *zCol;     /* Name of the column of the table */
 1.84677 +  int iSrc;             /* Index in pTabList->a[] of table being read */
 1.84678 +  int iDb;              /* The index of the database the expression refers to */
 1.84679 +  int iCol;             /* Index of column in table */
 1.84680 +
 1.84681 +  if( db->xAuth==0 ) return;
 1.84682 +  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
 1.84683 +  if( iDb<0 ){
 1.84684 +    /* An attempt to read a column out of a subquery or other
 1.84685 +    ** temporary table. */
 1.84686 +    return;
 1.84687 +  }
 1.84688 +
 1.84689 +  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
 1.84690 +  if( pExpr->op==TK_TRIGGER ){
 1.84691 +    pTab = pParse->pTriggerTab;
 1.84692 +  }else{
 1.84693 +    assert( pTabList );
 1.84694 +    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
 1.84695 +      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
 1.84696 +        pTab = pTabList->a[iSrc].pTab;
 1.84697 +        break;
 1.84698 +      }
 1.84699 +    }
 1.84700 +  }
 1.84701 +  iCol = pExpr->iColumn;
 1.84702 +  if( NEVER(pTab==0) ) return;
 1.84703 +
 1.84704 +  if( iCol>=0 ){
 1.84705 +    assert( iCol<pTab->nCol );
 1.84706 +    zCol = pTab->aCol[iCol].zName;
 1.84707 +  }else if( pTab->iPKey>=0 ){
 1.84708 +    assert( pTab->iPKey<pTab->nCol );
 1.84709 +    zCol = pTab->aCol[pTab->iPKey].zName;
 1.84710 +  }else{
 1.84711 +    zCol = "ROWID";
 1.84712 +  }
 1.84713 +  assert( iDb>=0 && iDb<db->nDb );
 1.84714 +  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
 1.84715 +    pExpr->op = TK_NULL;
 1.84716 +  }
 1.84717 +}
 1.84718 +
 1.84719 +/*
 1.84720 +** Do an authorization check using the code and arguments given.  Return
 1.84721 +** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
 1.84722 +** is returned, then the error count and error message in pParse are
 1.84723 +** modified appropriately.
 1.84724 +*/
 1.84725 +SQLITE_PRIVATE int sqlite3AuthCheck(
 1.84726 +  Parse *pParse,
 1.84727 +  int code,
 1.84728 +  const char *zArg1,
 1.84729 +  const char *zArg2,
 1.84730 +  const char *zArg3
 1.84731 +){
 1.84732 +  sqlite3 *db = pParse->db;
 1.84733 +  int rc;
 1.84734 +
 1.84735 +  /* Don't do any authorization checks if the database is initialising
 1.84736 +  ** or if the parser is being invoked from within sqlite3_declare_vtab.
 1.84737 +  */
 1.84738 +  if( db->init.busy || IN_DECLARE_VTAB ){
 1.84739 +    return SQLITE_OK;
 1.84740 +  }
 1.84741 +
 1.84742 +  if( db->xAuth==0 ){
 1.84743 +    return SQLITE_OK;
 1.84744 +  }
 1.84745 +  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
 1.84746 +  if( rc==SQLITE_DENY ){
 1.84747 +    sqlite3ErrorMsg(pParse, "not authorized");
 1.84748 +    pParse->rc = SQLITE_AUTH;
 1.84749 +  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
 1.84750 +    rc = SQLITE_DENY;
 1.84751 +    sqliteAuthBadReturnCode(pParse);
 1.84752 +  }
 1.84753 +  return rc;
 1.84754 +}
 1.84755 +
 1.84756 +/*
 1.84757 +** Push an authorization context.  After this routine is called, the
 1.84758 +** zArg3 argument to authorization callbacks will be zContext until
 1.84759 +** popped.  Or if pParse==0, this routine is a no-op.
 1.84760 +*/
 1.84761 +SQLITE_PRIVATE void sqlite3AuthContextPush(
 1.84762 +  Parse *pParse,
 1.84763 +  AuthContext *pContext, 
 1.84764 +  const char *zContext
 1.84765 +){
 1.84766 +  assert( pParse );
 1.84767 +  pContext->pParse = pParse;
 1.84768 +  pContext->zAuthContext = pParse->zAuthContext;
 1.84769 +  pParse->zAuthContext = zContext;
 1.84770 +}
 1.84771 +
 1.84772 +/*
 1.84773 +** Pop an authorization context that was previously pushed
 1.84774 +** by sqlite3AuthContextPush
 1.84775 +*/
 1.84776 +SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
 1.84777 +  if( pContext->pParse ){
 1.84778 +    pContext->pParse->zAuthContext = pContext->zAuthContext;
 1.84779 +    pContext->pParse = 0;
 1.84780 +  }
 1.84781 +}
 1.84782 +
 1.84783 +#endif /* SQLITE_OMIT_AUTHORIZATION */
 1.84784 +
 1.84785 +/************** End of auth.c ************************************************/
 1.84786 +/************** Begin file build.c *******************************************/
 1.84787 +/*
 1.84788 +** 2001 September 15
 1.84789 +**
 1.84790 +** The author disclaims copyright to this source code.  In place of
 1.84791 +** a legal notice, here is a blessing:
 1.84792 +**
 1.84793 +**    May you do good and not evil.
 1.84794 +**    May you find forgiveness for yourself and forgive others.
 1.84795 +**    May you share freely, never taking more than you give.
 1.84796 +**
 1.84797 +*************************************************************************
 1.84798 +** This file contains C code routines that are called by the SQLite parser
 1.84799 +** when syntax rules are reduced.  The routines in this file handle the
 1.84800 +** following kinds of SQL syntax:
 1.84801 +**
 1.84802 +**     CREATE TABLE
 1.84803 +**     DROP TABLE
 1.84804 +**     CREATE INDEX
 1.84805 +**     DROP INDEX
 1.84806 +**     creating ID lists
 1.84807 +**     BEGIN TRANSACTION
 1.84808 +**     COMMIT
 1.84809 +**     ROLLBACK
 1.84810 +*/
 1.84811 +
 1.84812 +/*
 1.84813 +** This routine is called when a new SQL statement is beginning to
 1.84814 +** be parsed.  Initialize the pParse structure as needed.
 1.84815 +*/
 1.84816 +SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
 1.84817 +  pParse->explain = (u8)explainFlag;
 1.84818 +  pParse->nVar = 0;
 1.84819 +}
 1.84820 +
 1.84821 +#ifndef SQLITE_OMIT_SHARED_CACHE
 1.84822 +/*
 1.84823 +** The TableLock structure is only used by the sqlite3TableLock() and
 1.84824 +** codeTableLocks() functions.
 1.84825 +*/
 1.84826 +struct TableLock {
 1.84827 +  int iDb;             /* The database containing the table to be locked */
 1.84828 +  int iTab;            /* The root page of the table to be locked */
 1.84829 +  u8 isWriteLock;      /* True for write lock.  False for a read lock */
 1.84830 +  const char *zName;   /* Name of the table */
 1.84831 +};
 1.84832 +
 1.84833 +/*
 1.84834 +** Record the fact that we want to lock a table at run-time.  
 1.84835 +**
 1.84836 +** The table to be locked has root page iTab and is found in database iDb.
 1.84837 +** A read or a write lock can be taken depending on isWritelock.
 1.84838 +**
 1.84839 +** This routine just records the fact that the lock is desired.  The
 1.84840 +** code to make the lock occur is generated by a later call to
 1.84841 +** codeTableLocks() which occurs during sqlite3FinishCoding().
 1.84842 +*/
 1.84843 +SQLITE_PRIVATE void sqlite3TableLock(
 1.84844 +  Parse *pParse,     /* Parsing context */
 1.84845 +  int iDb,           /* Index of the database containing the table to lock */
 1.84846 +  int iTab,          /* Root page number of the table to be locked */
 1.84847 +  u8 isWriteLock,    /* True for a write lock */
 1.84848 +  const char *zName  /* Name of the table to be locked */
 1.84849 +){
 1.84850 +  Parse *pToplevel = sqlite3ParseToplevel(pParse);
 1.84851 +  int i;
 1.84852 +  int nBytes;
 1.84853 +  TableLock *p;
 1.84854 +  assert( iDb>=0 );
 1.84855 +
 1.84856 +  for(i=0; i<pToplevel->nTableLock; i++){
 1.84857 +    p = &pToplevel->aTableLock[i];
 1.84858 +    if( p->iDb==iDb && p->iTab==iTab ){
 1.84859 +      p->isWriteLock = (p->isWriteLock || isWriteLock);
 1.84860 +      return;
 1.84861 +    }
 1.84862 +  }
 1.84863 +
 1.84864 +  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
 1.84865 +  pToplevel->aTableLock =
 1.84866 +      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
 1.84867 +  if( pToplevel->aTableLock ){
 1.84868 +    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
 1.84869 +    p->iDb = iDb;
 1.84870 +    p->iTab = iTab;
 1.84871 +    p->isWriteLock = isWriteLock;
 1.84872 +    p->zName = zName;
 1.84873 +  }else{
 1.84874 +    pToplevel->nTableLock = 0;
 1.84875 +    pToplevel->db->mallocFailed = 1;
 1.84876 +  }
 1.84877 +}
 1.84878 +
 1.84879 +/*
 1.84880 +** Code an OP_TableLock instruction for each table locked by the
 1.84881 +** statement (configured by calls to sqlite3TableLock()).
 1.84882 +*/
 1.84883 +static void codeTableLocks(Parse *pParse){
 1.84884 +  int i;
 1.84885 +  Vdbe *pVdbe; 
 1.84886 +
 1.84887 +  pVdbe = sqlite3GetVdbe(pParse);
 1.84888 +  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
 1.84889 +
 1.84890 +  for(i=0; i<pParse->nTableLock; i++){
 1.84891 +    TableLock *p = &pParse->aTableLock[i];
 1.84892 +    int p1 = p->iDb;
 1.84893 +    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
 1.84894 +                      p->zName, P4_STATIC);
 1.84895 +  }
 1.84896 +}
 1.84897 +#else
 1.84898 +  #define codeTableLocks(x)
 1.84899 +#endif
 1.84900 +
 1.84901 +/*
 1.84902 +** This routine is called after a single SQL statement has been
 1.84903 +** parsed and a VDBE program to execute that statement has been
 1.84904 +** prepared.  This routine puts the finishing touches on the
 1.84905 +** VDBE program and resets the pParse structure for the next
 1.84906 +** parse.
 1.84907 +**
 1.84908 +** Note that if an error occurred, it might be the case that
 1.84909 +** no VDBE code was generated.
 1.84910 +*/
 1.84911 +SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
 1.84912 +  sqlite3 *db;
 1.84913 +  Vdbe *v;
 1.84914 +
 1.84915 +  assert( pParse->pToplevel==0 );
 1.84916 +  db = pParse->db;
 1.84917 +  if( db->mallocFailed ) return;
 1.84918 +  if( pParse->nested ) return;
 1.84919 +  if( pParse->nErr ) return;
 1.84920 +
 1.84921 +  /* Begin by generating some termination code at the end of the
 1.84922 +  ** vdbe program
 1.84923 +  */
 1.84924 +  v = sqlite3GetVdbe(pParse);
 1.84925 +  assert( !pParse->isMultiWrite 
 1.84926 +       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
 1.84927 +  if( v ){
 1.84928 +    while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
 1.84929 +    sqlite3VdbeAddOp0(v, OP_Halt);
 1.84930 +
 1.84931 +    /* The cookie mask contains one bit for each database file open.
 1.84932 +    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
 1.84933 +    ** set for each database that is used.  Generate code to start a
 1.84934 +    ** transaction on each used database and to verify the schema cookie
 1.84935 +    ** on each used database.
 1.84936 +    */
 1.84937 +    if( db->mallocFailed==0 && (pParse->cookieMask || pParse->pConstExpr) ){
 1.84938 +      yDbMask mask;
 1.84939 +      int iDb, i;
 1.84940 +      assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
 1.84941 +      sqlite3VdbeJumpHere(v, 0);
 1.84942 +      for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
 1.84943 +        if( (mask & pParse->cookieMask)==0 ) continue;
 1.84944 +        sqlite3VdbeUsesBtree(v, iDb);
 1.84945 +        sqlite3VdbeAddOp4Int(v,
 1.84946 +          OP_Transaction,                    /* Opcode */
 1.84947 +          iDb,                               /* P1 */
 1.84948 +          (mask & pParse->writeMask)!=0,     /* P2 */
 1.84949 +          pParse->cookieValue[iDb],          /* P3 */
 1.84950 +          db->aDb[iDb].pSchema->iGeneration  /* P4 */
 1.84951 +        );
 1.84952 +        if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
 1.84953 +      }
 1.84954 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.84955 +      for(i=0; i<pParse->nVtabLock; i++){
 1.84956 +        char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
 1.84957 +        sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
 1.84958 +      }
 1.84959 +      pParse->nVtabLock = 0;
 1.84960 +#endif
 1.84961 +
 1.84962 +      /* Once all the cookies have been verified and transactions opened, 
 1.84963 +      ** obtain the required table-locks. This is a no-op unless the 
 1.84964 +      ** shared-cache feature is enabled.
 1.84965 +      */
 1.84966 +      codeTableLocks(pParse);
 1.84967 +
 1.84968 +      /* Initialize any AUTOINCREMENT data structures required.
 1.84969 +      */
 1.84970 +      sqlite3AutoincrementBegin(pParse);
 1.84971 +
 1.84972 +      /* Code constant expressions that where factored out of inner loops */
 1.84973 +      if( pParse->pConstExpr ){
 1.84974 +        ExprList *pEL = pParse->pConstExpr;
 1.84975 +        pParse->okConstFactor = 0;
 1.84976 +        for(i=0; i<pEL->nExpr; i++){
 1.84977 +          sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
 1.84978 +        }
 1.84979 +      }
 1.84980 +
 1.84981 +      /* Finally, jump back to the beginning of the executable code. */
 1.84982 +      sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
 1.84983 +    }
 1.84984 +  }
 1.84985 +
 1.84986 +
 1.84987 +  /* Get the VDBE program ready for execution
 1.84988 +  */
 1.84989 +  if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
 1.84990 +    assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
 1.84991 +    /* A minimum of one cursor is required if autoincrement is used
 1.84992 +    *  See ticket [a696379c1f08866] */
 1.84993 +    if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
 1.84994 +    sqlite3VdbeMakeReady(v, pParse);
 1.84995 +    pParse->rc = SQLITE_DONE;
 1.84996 +    pParse->colNamesSet = 0;
 1.84997 +  }else{
 1.84998 +    pParse->rc = SQLITE_ERROR;
 1.84999 +  }
 1.85000 +  pParse->nTab = 0;
 1.85001 +  pParse->nMem = 0;
 1.85002 +  pParse->nSet = 0;
 1.85003 +  pParse->nVar = 0;
 1.85004 +  pParse->cookieMask = 0;
 1.85005 +}
 1.85006 +
 1.85007 +/*
 1.85008 +** Run the parser and code generator recursively in order to generate
 1.85009 +** code for the SQL statement given onto the end of the pParse context
 1.85010 +** currently under construction.  When the parser is run recursively
 1.85011 +** this way, the final OP_Halt is not appended and other initialization
 1.85012 +** and finalization steps are omitted because those are handling by the
 1.85013 +** outermost parser.
 1.85014 +**
 1.85015 +** Not everything is nestable.  This facility is designed to permit
 1.85016 +** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
 1.85017 +** care if you decide to try to use this routine for some other purposes.
 1.85018 +*/
 1.85019 +SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
 1.85020 +  va_list ap;
 1.85021 +  char *zSql;
 1.85022 +  char *zErrMsg = 0;
 1.85023 +  sqlite3 *db = pParse->db;
 1.85024 +# define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
 1.85025 +  char saveBuf[SAVE_SZ];
 1.85026 +
 1.85027 +  if( pParse->nErr ) return;
 1.85028 +  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
 1.85029 +  va_start(ap, zFormat);
 1.85030 +  zSql = sqlite3VMPrintf(db, zFormat, ap);
 1.85031 +  va_end(ap);
 1.85032 +  if( zSql==0 ){
 1.85033 +    return;   /* A malloc must have failed */
 1.85034 +  }
 1.85035 +  pParse->nested++;
 1.85036 +  memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
 1.85037 +  memset(&pParse->nVar, 0, SAVE_SZ);
 1.85038 +  sqlite3RunParser(pParse, zSql, &zErrMsg);
 1.85039 +  sqlite3DbFree(db, zErrMsg);
 1.85040 +  sqlite3DbFree(db, zSql);
 1.85041 +  memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
 1.85042 +  pParse->nested--;
 1.85043 +}
 1.85044 +
 1.85045 +/*
 1.85046 +** Locate the in-memory structure that describes a particular database
 1.85047 +** table given the name of that table and (optionally) the name of the
 1.85048 +** database containing the table.  Return NULL if not found.
 1.85049 +**
 1.85050 +** If zDatabase is 0, all databases are searched for the table and the
 1.85051 +** first matching table is returned.  (No checking for duplicate table
 1.85052 +** names is done.)  The search order is TEMP first, then MAIN, then any
 1.85053 +** auxiliary databases added using the ATTACH command.
 1.85054 +**
 1.85055 +** See also sqlite3LocateTable().
 1.85056 +*/
 1.85057 +SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
 1.85058 +  Table *p = 0;
 1.85059 +  int i;
 1.85060 +  int nName;
 1.85061 +  assert( zName!=0 );
 1.85062 +  nName = sqlite3Strlen30(zName);
 1.85063 +  /* All mutexes are required for schema access.  Make sure we hold them. */
 1.85064 +  assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
 1.85065 +  for(i=OMIT_TEMPDB; i<db->nDb; i++){
 1.85066 +    int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
 1.85067 +    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
 1.85068 +    assert( sqlite3SchemaMutexHeld(db, j, 0) );
 1.85069 +    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
 1.85070 +    if( p ) break;
 1.85071 +  }
 1.85072 +  return p;
 1.85073 +}
 1.85074 +
 1.85075 +/*
 1.85076 +** Locate the in-memory structure that describes a particular database
 1.85077 +** table given the name of that table and (optionally) the name of the
 1.85078 +** database containing the table.  Return NULL if not found.  Also leave an
 1.85079 +** error message in pParse->zErrMsg.
 1.85080 +**
 1.85081 +** The difference between this routine and sqlite3FindTable() is that this
 1.85082 +** routine leaves an error message in pParse->zErrMsg where
 1.85083 +** sqlite3FindTable() does not.
 1.85084 +*/
 1.85085 +SQLITE_PRIVATE Table *sqlite3LocateTable(
 1.85086 +  Parse *pParse,         /* context in which to report errors */
 1.85087 +  int isView,            /* True if looking for a VIEW rather than a TABLE */
 1.85088 +  const char *zName,     /* Name of the table we are looking for */
 1.85089 +  const char *zDbase     /* Name of the database.  Might be NULL */
 1.85090 +){
 1.85091 +  Table *p;
 1.85092 +
 1.85093 +  /* Read the database schema. If an error occurs, leave an error message
 1.85094 +  ** and code in pParse and return NULL. */
 1.85095 +  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
 1.85096 +    return 0;
 1.85097 +  }
 1.85098 +
 1.85099 +  p = sqlite3FindTable(pParse->db, zName, zDbase);
 1.85100 +  if( p==0 ){
 1.85101 +    const char *zMsg = isView ? "no such view" : "no such table";
 1.85102 +    if( zDbase ){
 1.85103 +      sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
 1.85104 +    }else{
 1.85105 +      sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
 1.85106 +    }
 1.85107 +    pParse->checkSchema = 1;
 1.85108 +  }
 1.85109 +  return p;
 1.85110 +}
 1.85111 +
 1.85112 +/*
 1.85113 +** Locate the table identified by *p.
 1.85114 +**
 1.85115 +** This is a wrapper around sqlite3LocateTable(). The difference between
 1.85116 +** sqlite3LocateTable() and this function is that this function restricts
 1.85117 +** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
 1.85118 +** non-NULL if it is part of a view or trigger program definition. See
 1.85119 +** sqlite3FixSrcList() for details.
 1.85120 +*/
 1.85121 +SQLITE_PRIVATE Table *sqlite3LocateTableItem(
 1.85122 +  Parse *pParse, 
 1.85123 +  int isView, 
 1.85124 +  struct SrcList_item *p
 1.85125 +){
 1.85126 +  const char *zDb;
 1.85127 +  assert( p->pSchema==0 || p->zDatabase==0 );
 1.85128 +  if( p->pSchema ){
 1.85129 +    int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
 1.85130 +    zDb = pParse->db->aDb[iDb].zName;
 1.85131 +  }else{
 1.85132 +    zDb = p->zDatabase;
 1.85133 +  }
 1.85134 +  return sqlite3LocateTable(pParse, isView, p->zName, zDb);
 1.85135 +}
 1.85136 +
 1.85137 +/*
 1.85138 +** Locate the in-memory structure that describes 
 1.85139 +** a particular index given the name of that index
 1.85140 +** and the name of the database that contains the index.
 1.85141 +** Return NULL if not found.
 1.85142 +**
 1.85143 +** If zDatabase is 0, all databases are searched for the
 1.85144 +** table and the first matching index is returned.  (No checking
 1.85145 +** for duplicate index names is done.)  The search order is
 1.85146 +** TEMP first, then MAIN, then any auxiliary databases added
 1.85147 +** using the ATTACH command.
 1.85148 +*/
 1.85149 +SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
 1.85150 +  Index *p = 0;
 1.85151 +  int i;
 1.85152 +  int nName = sqlite3Strlen30(zName);
 1.85153 +  /* All mutexes are required for schema access.  Make sure we hold them. */
 1.85154 +  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
 1.85155 +  for(i=OMIT_TEMPDB; i<db->nDb; i++){
 1.85156 +    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
 1.85157 +    Schema *pSchema = db->aDb[j].pSchema;
 1.85158 +    assert( pSchema );
 1.85159 +    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
 1.85160 +    assert( sqlite3SchemaMutexHeld(db, j, 0) );
 1.85161 +    p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
 1.85162 +    if( p ) break;
 1.85163 +  }
 1.85164 +  return p;
 1.85165 +}
 1.85166 +
 1.85167 +/*
 1.85168 +** Reclaim the memory used by an index
 1.85169 +*/
 1.85170 +static void freeIndex(sqlite3 *db, Index *p){
 1.85171 +#ifndef SQLITE_OMIT_ANALYZE
 1.85172 +  sqlite3DeleteIndexSamples(db, p);
 1.85173 +#endif
 1.85174 +  if( db==0 || db->pnBytesFreed==0 ) sqlite3KeyInfoUnref(p->pKeyInfo);
 1.85175 +  sqlite3ExprDelete(db, p->pPartIdxWhere);
 1.85176 +  sqlite3DbFree(db, p->zColAff);
 1.85177 +  if( p->isResized ) sqlite3DbFree(db, p->azColl);
 1.85178 +  sqlite3DbFree(db, p);
 1.85179 +}
 1.85180 +
 1.85181 +/*
 1.85182 +** For the index called zIdxName which is found in the database iDb,
 1.85183 +** unlike that index from its Table then remove the index from
 1.85184 +** the index hash table and free all memory structures associated
 1.85185 +** with the index.
 1.85186 +*/
 1.85187 +SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
 1.85188 +  Index *pIndex;
 1.85189 +  int len;
 1.85190 +  Hash *pHash;
 1.85191 +
 1.85192 +  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 1.85193 +  pHash = &db->aDb[iDb].pSchema->idxHash;
 1.85194 +  len = sqlite3Strlen30(zIdxName);
 1.85195 +  pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
 1.85196 +  if( ALWAYS(pIndex) ){
 1.85197 +    if( pIndex->pTable->pIndex==pIndex ){
 1.85198 +      pIndex->pTable->pIndex = pIndex->pNext;
 1.85199 +    }else{
 1.85200 +      Index *p;
 1.85201 +      /* Justification of ALWAYS();  The index must be on the list of
 1.85202 +      ** indices. */
 1.85203 +      p = pIndex->pTable->pIndex;
 1.85204 +      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
 1.85205 +      if( ALWAYS(p && p->pNext==pIndex) ){
 1.85206 +        p->pNext = pIndex->pNext;
 1.85207 +      }
 1.85208 +    }
 1.85209 +    freeIndex(db, pIndex);
 1.85210 +  }
 1.85211 +  db->flags |= SQLITE_InternChanges;
 1.85212 +}
 1.85213 +
 1.85214 +/*
 1.85215 +** Look through the list of open database files in db->aDb[] and if
 1.85216 +** any have been closed, remove them from the list.  Reallocate the
 1.85217 +** db->aDb[] structure to a smaller size, if possible.
 1.85218 +**
 1.85219 +** Entry 0 (the "main" database) and entry 1 (the "temp" database)
 1.85220 +** are never candidates for being collapsed.
 1.85221 +*/
 1.85222 +SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
 1.85223 +  int i, j;
 1.85224 +  for(i=j=2; i<db->nDb; i++){
 1.85225 +    struct Db *pDb = &db->aDb[i];
 1.85226 +    if( pDb->pBt==0 ){
 1.85227 +      sqlite3DbFree(db, pDb->zName);
 1.85228 +      pDb->zName = 0;
 1.85229 +      continue;
 1.85230 +    }
 1.85231 +    if( j<i ){
 1.85232 +      db->aDb[j] = db->aDb[i];
 1.85233 +    }
 1.85234 +    j++;
 1.85235 +  }
 1.85236 +  memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
 1.85237 +  db->nDb = j;
 1.85238 +  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
 1.85239 +    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
 1.85240 +    sqlite3DbFree(db, db->aDb);
 1.85241 +    db->aDb = db->aDbStatic;
 1.85242 +  }
 1.85243 +}
 1.85244 +
 1.85245 +/*
 1.85246 +** Reset the schema for the database at index iDb.  Also reset the
 1.85247 +** TEMP schema.
 1.85248 +*/
 1.85249 +SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
 1.85250 +  Db *pDb;
 1.85251 +  assert( iDb<db->nDb );
 1.85252 +
 1.85253 +  /* Case 1:  Reset the single schema identified by iDb */
 1.85254 +  pDb = &db->aDb[iDb];
 1.85255 +  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 1.85256 +  assert( pDb->pSchema!=0 );
 1.85257 +  sqlite3SchemaClear(pDb->pSchema);
 1.85258 +
 1.85259 +  /* If any database other than TEMP is reset, then also reset TEMP
 1.85260 +  ** since TEMP might be holding triggers that reference tables in the
 1.85261 +  ** other database.
 1.85262 +  */
 1.85263 +  if( iDb!=1 ){
 1.85264 +    pDb = &db->aDb[1];
 1.85265 +    assert( pDb->pSchema!=0 );
 1.85266 +    sqlite3SchemaClear(pDb->pSchema);
 1.85267 +  }
 1.85268 +  return;
 1.85269 +}
 1.85270 +
 1.85271 +/*
 1.85272 +** Erase all schema information from all attached databases (including
 1.85273 +** "main" and "temp") for a single database connection.
 1.85274 +*/
 1.85275 +SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
 1.85276 +  int i;
 1.85277 +  sqlite3BtreeEnterAll(db);
 1.85278 +  for(i=0; i<db->nDb; i++){
 1.85279 +    Db *pDb = &db->aDb[i];
 1.85280 +    if( pDb->pSchema ){
 1.85281 +      sqlite3SchemaClear(pDb->pSchema);
 1.85282 +    }
 1.85283 +  }
 1.85284 +  db->flags &= ~SQLITE_InternChanges;
 1.85285 +  sqlite3VtabUnlockList(db);
 1.85286 +  sqlite3BtreeLeaveAll(db);
 1.85287 +  sqlite3CollapseDatabaseArray(db);
 1.85288 +}
 1.85289 +
 1.85290 +/*
 1.85291 +** This routine is called when a commit occurs.
 1.85292 +*/
 1.85293 +SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
 1.85294 +  db->flags &= ~SQLITE_InternChanges;
 1.85295 +}
 1.85296 +
 1.85297 +/*
 1.85298 +** Delete memory allocated for the column names of a table or view (the
 1.85299 +** Table.aCol[] array).
 1.85300 +*/
 1.85301 +static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
 1.85302 +  int i;
 1.85303 +  Column *pCol;
 1.85304 +  assert( pTable!=0 );
 1.85305 +  if( (pCol = pTable->aCol)!=0 ){
 1.85306 +    for(i=0; i<pTable->nCol; i++, pCol++){
 1.85307 +      sqlite3DbFree(db, pCol->zName);
 1.85308 +      sqlite3ExprDelete(db, pCol->pDflt);
 1.85309 +      sqlite3DbFree(db, pCol->zDflt);
 1.85310 +      sqlite3DbFree(db, pCol->zType);
 1.85311 +      sqlite3DbFree(db, pCol->zColl);
 1.85312 +    }
 1.85313 +    sqlite3DbFree(db, pTable->aCol);
 1.85314 +  }
 1.85315 +}
 1.85316 +
 1.85317 +/*
 1.85318 +** Remove the memory data structures associated with the given
 1.85319 +** Table.  No changes are made to disk by this routine.
 1.85320 +**
 1.85321 +** This routine just deletes the data structure.  It does not unlink
 1.85322 +** the table data structure from the hash table.  But it does destroy
 1.85323 +** memory structures of the indices and foreign keys associated with 
 1.85324 +** the table.
 1.85325 +**
 1.85326 +** The db parameter is optional.  It is needed if the Table object 
 1.85327 +** contains lookaside memory.  (Table objects in the schema do not use
 1.85328 +** lookaside memory, but some ephemeral Table objects do.)  Or the
 1.85329 +** db parameter can be used with db->pnBytesFreed to measure the memory
 1.85330 +** used by the Table object.
 1.85331 +*/
 1.85332 +SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
 1.85333 +  Index *pIndex, *pNext;
 1.85334 +  TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
 1.85335 +
 1.85336 +  assert( !pTable || pTable->nRef>0 );
 1.85337 +
 1.85338 +  /* Do not delete the table until the reference count reaches zero. */
 1.85339 +  if( !pTable ) return;
 1.85340 +  if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
 1.85341 +
 1.85342 +  /* Record the number of outstanding lookaside allocations in schema Tables
 1.85343 +  ** prior to doing any free() operations.  Since schema Tables do not use
 1.85344 +  ** lookaside, this number should not change. */
 1.85345 +  TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
 1.85346 +                         db->lookaside.nOut : 0 );
 1.85347 +
 1.85348 +  /* Delete all indices associated with this table. */
 1.85349 +  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
 1.85350 +    pNext = pIndex->pNext;
 1.85351 +    assert( pIndex->pSchema==pTable->pSchema );
 1.85352 +    if( !db || db->pnBytesFreed==0 ){
 1.85353 +      char *zName = pIndex->zName; 
 1.85354 +      TESTONLY ( Index *pOld = ) sqlite3HashInsert(
 1.85355 +         &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
 1.85356 +      );
 1.85357 +      assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
 1.85358 +      assert( pOld==pIndex || pOld==0 );
 1.85359 +    }
 1.85360 +    freeIndex(db, pIndex);
 1.85361 +  }
 1.85362 +
 1.85363 +  /* Delete any foreign keys attached to this table. */
 1.85364 +  sqlite3FkDelete(db, pTable);
 1.85365 +
 1.85366 +  /* Delete the Table structure itself.
 1.85367 +  */
 1.85368 +  sqliteDeleteColumnNames(db, pTable);
 1.85369 +  sqlite3DbFree(db, pTable->zName);
 1.85370 +  sqlite3DbFree(db, pTable->zColAff);
 1.85371 +  sqlite3SelectDelete(db, pTable->pSelect);
 1.85372 +#ifndef SQLITE_OMIT_CHECK
 1.85373 +  sqlite3ExprListDelete(db, pTable->pCheck);
 1.85374 +#endif
 1.85375 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.85376 +  sqlite3VtabClear(db, pTable);
 1.85377 +#endif
 1.85378 +  sqlite3DbFree(db, pTable);
 1.85379 +
 1.85380 +  /* Verify that no lookaside memory was used by schema tables */
 1.85381 +  assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
 1.85382 +}
 1.85383 +
 1.85384 +/*
 1.85385 +** Unlink the given table from the hash tables and the delete the
 1.85386 +** table structure with all its indices and foreign keys.
 1.85387 +*/
 1.85388 +SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
 1.85389 +  Table *p;
 1.85390 +  Db *pDb;
 1.85391 +
 1.85392 +  assert( db!=0 );
 1.85393 +  assert( iDb>=0 && iDb<db->nDb );
 1.85394 +  assert( zTabName );
 1.85395 +  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 1.85396 +  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
 1.85397 +  pDb = &db->aDb[iDb];
 1.85398 +  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
 1.85399 +                        sqlite3Strlen30(zTabName),0);
 1.85400 +  sqlite3DeleteTable(db, p);
 1.85401 +  db->flags |= SQLITE_InternChanges;
 1.85402 +}
 1.85403 +
 1.85404 +/*
 1.85405 +** Given a token, return a string that consists of the text of that
 1.85406 +** token.  Space to hold the returned string
 1.85407 +** is obtained from sqliteMalloc() and must be freed by the calling
 1.85408 +** function.
 1.85409 +**
 1.85410 +** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
 1.85411 +** surround the body of the token are removed.
 1.85412 +**
 1.85413 +** Tokens are often just pointers into the original SQL text and so
 1.85414 +** are not \000 terminated and are not persistent.  The returned string
 1.85415 +** is \000 terminated and is persistent.
 1.85416 +*/
 1.85417 +SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
 1.85418 +  char *zName;
 1.85419 +  if( pName ){
 1.85420 +    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
 1.85421 +    sqlite3Dequote(zName);
 1.85422 +  }else{
 1.85423 +    zName = 0;
 1.85424 +  }
 1.85425 +  return zName;
 1.85426 +}
 1.85427 +
 1.85428 +/*
 1.85429 +** Open the sqlite_master table stored in database number iDb for
 1.85430 +** writing. The table is opened using cursor 0.
 1.85431 +*/
 1.85432 +SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
 1.85433 +  Vdbe *v = sqlite3GetVdbe(p);
 1.85434 +  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
 1.85435 +  sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
 1.85436 +  if( p->nTab==0 ){
 1.85437 +    p->nTab = 1;
 1.85438 +  }
 1.85439 +}
 1.85440 +
 1.85441 +/*
 1.85442 +** Parameter zName points to a nul-terminated buffer containing the name
 1.85443 +** of a database ("main", "temp" or the name of an attached db). This
 1.85444 +** function returns the index of the named database in db->aDb[], or
 1.85445 +** -1 if the named db cannot be found.
 1.85446 +*/
 1.85447 +SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
 1.85448 +  int i = -1;         /* Database number */
 1.85449 +  if( zName ){
 1.85450 +    Db *pDb;
 1.85451 +    int n = sqlite3Strlen30(zName);
 1.85452 +    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
 1.85453 +      if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
 1.85454 +          0==sqlite3StrICmp(pDb->zName, zName) ){
 1.85455 +        break;
 1.85456 +      }
 1.85457 +    }
 1.85458 +  }
 1.85459 +  return i;
 1.85460 +}
 1.85461 +
 1.85462 +/*
 1.85463 +** The token *pName contains the name of a database (either "main" or
 1.85464 +** "temp" or the name of an attached db). This routine returns the
 1.85465 +** index of the named database in db->aDb[], or -1 if the named db 
 1.85466 +** does not exist.
 1.85467 +*/
 1.85468 +SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
 1.85469 +  int i;                               /* Database number */
 1.85470 +  char *zName;                         /* Name we are searching for */
 1.85471 +  zName = sqlite3NameFromToken(db, pName);
 1.85472 +  i = sqlite3FindDbName(db, zName);
 1.85473 +  sqlite3DbFree(db, zName);
 1.85474 +  return i;
 1.85475 +}
 1.85476 +
 1.85477 +/* The table or view or trigger name is passed to this routine via tokens
 1.85478 +** pName1 and pName2. If the table name was fully qualified, for example:
 1.85479 +**
 1.85480 +** CREATE TABLE xxx.yyy (...);
 1.85481 +** 
 1.85482 +** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
 1.85483 +** the table name is not fully qualified, i.e.:
 1.85484 +**
 1.85485 +** CREATE TABLE yyy(...);
 1.85486 +**
 1.85487 +** Then pName1 is set to "yyy" and pName2 is "".
 1.85488 +**
 1.85489 +** This routine sets the *ppUnqual pointer to point at the token (pName1 or
 1.85490 +** pName2) that stores the unqualified table name.  The index of the
 1.85491 +** database "xxx" is returned.
 1.85492 +*/
 1.85493 +SQLITE_PRIVATE int sqlite3TwoPartName(
 1.85494 +  Parse *pParse,      /* Parsing and code generating context */
 1.85495 +  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
 1.85496 +  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
 1.85497 +  Token **pUnqual     /* Write the unqualified object name here */
 1.85498 +){
 1.85499 +  int iDb;                    /* Database holding the object */
 1.85500 +  sqlite3 *db = pParse->db;
 1.85501 +
 1.85502 +  if( ALWAYS(pName2!=0) && pName2->n>0 ){
 1.85503 +    if( db->init.busy ) {
 1.85504 +      sqlite3ErrorMsg(pParse, "corrupt database");
 1.85505 +      pParse->nErr++;
 1.85506 +      return -1;
 1.85507 +    }
 1.85508 +    *pUnqual = pName2;
 1.85509 +    iDb = sqlite3FindDb(db, pName1);
 1.85510 +    if( iDb<0 ){
 1.85511 +      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
 1.85512 +      pParse->nErr++;
 1.85513 +      return -1;
 1.85514 +    }
 1.85515 +  }else{
 1.85516 +    assert( db->init.iDb==0 || db->init.busy );
 1.85517 +    iDb = db->init.iDb;
 1.85518 +    *pUnqual = pName1;
 1.85519 +  }
 1.85520 +  return iDb;
 1.85521 +}
 1.85522 +
 1.85523 +/*
 1.85524 +** This routine is used to check if the UTF-8 string zName is a legal
 1.85525 +** unqualified name for a new schema object (table, index, view or
 1.85526 +** trigger). All names are legal except those that begin with the string
 1.85527 +** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
 1.85528 +** is reserved for internal use.
 1.85529 +*/
 1.85530 +SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
 1.85531 +  if( !pParse->db->init.busy && pParse->nested==0 
 1.85532 +          && (pParse->db->flags & SQLITE_WriteSchema)==0
 1.85533 +          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
 1.85534 +    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
 1.85535 +    return SQLITE_ERROR;
 1.85536 +  }
 1.85537 +  return SQLITE_OK;
 1.85538 +}
 1.85539 +
 1.85540 +/*
 1.85541 +** Return the PRIMARY KEY index of a table
 1.85542 +*/
 1.85543 +SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
 1.85544 +  Index *p;
 1.85545 +  for(p=pTab->pIndex; p && p->autoIndex!=2; p=p->pNext){}
 1.85546 +  return p;
 1.85547 +}
 1.85548 +
 1.85549 +/*
 1.85550 +** Return the column of index pIdx that corresponds to table
 1.85551 +** column iCol.  Return -1 if not found.
 1.85552 +*/
 1.85553 +SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
 1.85554 +  int i;
 1.85555 +  for(i=0; i<pIdx->nColumn; i++){
 1.85556 +    if( iCol==pIdx->aiColumn[i] ) return i;
 1.85557 +  }
 1.85558 +  return -1;
 1.85559 +}
 1.85560 +
 1.85561 +/*
 1.85562 +** Begin constructing a new table representation in memory.  This is
 1.85563 +** the first of several action routines that get called in response
 1.85564 +** to a CREATE TABLE statement.  In particular, this routine is called
 1.85565 +** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
 1.85566 +** flag is true if the table should be stored in the auxiliary database
 1.85567 +** file instead of in the main database file.  This is normally the case
 1.85568 +** when the "TEMP" or "TEMPORARY" keyword occurs in between
 1.85569 +** CREATE and TABLE.
 1.85570 +**
 1.85571 +** The new table record is initialized and put in pParse->pNewTable.
 1.85572 +** As more of the CREATE TABLE statement is parsed, additional action
 1.85573 +** routines will be called to add more information to this record.
 1.85574 +** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
 1.85575 +** is called to complete the construction of the new table record.
 1.85576 +*/
 1.85577 +SQLITE_PRIVATE void sqlite3StartTable(
 1.85578 +  Parse *pParse,   /* Parser context */
 1.85579 +  Token *pName1,   /* First part of the name of the table or view */
 1.85580 +  Token *pName2,   /* Second part of the name of the table or view */
 1.85581 +  int isTemp,      /* True if this is a TEMP table */
 1.85582 +  int isView,      /* True if this is a VIEW */
 1.85583 +  int isVirtual,   /* True if this is a VIRTUAL table */
 1.85584 +  int noErr        /* Do nothing if table already exists */
 1.85585 +){
 1.85586 +  Table *pTable;
 1.85587 +  char *zName = 0; /* The name of the new table */
 1.85588 +  sqlite3 *db = pParse->db;
 1.85589 +  Vdbe *v;
 1.85590 +  int iDb;         /* Database number to create the table in */
 1.85591 +  Token *pName;    /* Unqualified name of the table to create */
 1.85592 +
 1.85593 +  /* The table or view name to create is passed to this routine via tokens
 1.85594 +  ** pName1 and pName2. If the table name was fully qualified, for example:
 1.85595 +  **
 1.85596 +  ** CREATE TABLE xxx.yyy (...);
 1.85597 +  ** 
 1.85598 +  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
 1.85599 +  ** the table name is not fully qualified, i.e.:
 1.85600 +  **
 1.85601 +  ** CREATE TABLE yyy(...);
 1.85602 +  **
 1.85603 +  ** Then pName1 is set to "yyy" and pName2 is "".
 1.85604 +  **
 1.85605 +  ** The call below sets the pName pointer to point at the token (pName1 or
 1.85606 +  ** pName2) that stores the unqualified table name. The variable iDb is
 1.85607 +  ** set to the index of the database that the table or view is to be
 1.85608 +  ** created in.
 1.85609 +  */
 1.85610 +  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
 1.85611 +  if( iDb<0 ) return;
 1.85612 +  if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
 1.85613 +    /* If creating a temp table, the name may not be qualified. Unless 
 1.85614 +    ** the database name is "temp" anyway.  */
 1.85615 +    sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
 1.85616 +    return;
 1.85617 +  }
 1.85618 +  if( !OMIT_TEMPDB && isTemp ) iDb = 1;
 1.85619 +
 1.85620 +  pParse->sNameToken = *pName;
 1.85621 +  zName = sqlite3NameFromToken(db, pName);
 1.85622 +  if( zName==0 ) return;
 1.85623 +  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
 1.85624 +    goto begin_table_error;
 1.85625 +  }
 1.85626 +  if( db->init.iDb==1 ) isTemp = 1;
 1.85627 +#ifndef SQLITE_OMIT_AUTHORIZATION
 1.85628 +  assert( (isTemp & 1)==isTemp );
 1.85629 +  {
 1.85630 +    int code;
 1.85631 +    char *zDb = db->aDb[iDb].zName;
 1.85632 +    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
 1.85633 +      goto begin_table_error;
 1.85634 +    }
 1.85635 +    if( isView ){
 1.85636 +      if( !OMIT_TEMPDB && isTemp ){
 1.85637 +        code = SQLITE_CREATE_TEMP_VIEW;
 1.85638 +      }else{
 1.85639 +        code = SQLITE_CREATE_VIEW;
 1.85640 +      }
 1.85641 +    }else{
 1.85642 +      if( !OMIT_TEMPDB && isTemp ){
 1.85643 +        code = SQLITE_CREATE_TEMP_TABLE;
 1.85644 +      }else{
 1.85645 +        code = SQLITE_CREATE_TABLE;
 1.85646 +      }
 1.85647 +    }
 1.85648 +    if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
 1.85649 +      goto begin_table_error;
 1.85650 +    }
 1.85651 +  }
 1.85652 +#endif
 1.85653 +
 1.85654 +  /* Make sure the new table name does not collide with an existing
 1.85655 +  ** index or table name in the same database.  Issue an error message if
 1.85656 +  ** it does. The exception is if the statement being parsed was passed
 1.85657 +  ** to an sqlite3_declare_vtab() call. In that case only the column names
 1.85658 +  ** and types will be used, so there is no need to test for namespace
 1.85659 +  ** collisions.
 1.85660 +  */
 1.85661 +  if( !IN_DECLARE_VTAB ){
 1.85662 +    char *zDb = db->aDb[iDb].zName;
 1.85663 +    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
 1.85664 +      goto begin_table_error;
 1.85665 +    }
 1.85666 +    pTable = sqlite3FindTable(db, zName, zDb);
 1.85667 +    if( pTable ){
 1.85668 +      if( !noErr ){
 1.85669 +        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
 1.85670 +      }else{
 1.85671 +        assert( !db->init.busy );
 1.85672 +        sqlite3CodeVerifySchema(pParse, iDb);
 1.85673 +      }
 1.85674 +      goto begin_table_error;
 1.85675 +    }
 1.85676 +    if( sqlite3FindIndex(db, zName, zDb)!=0 ){
 1.85677 +      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
 1.85678 +      goto begin_table_error;
 1.85679 +    }
 1.85680 +  }
 1.85681 +
 1.85682 +  pTable = sqlite3DbMallocZero(db, sizeof(Table));
 1.85683 +  if( pTable==0 ){
 1.85684 +    db->mallocFailed = 1;
 1.85685 +    pParse->rc = SQLITE_NOMEM;
 1.85686 +    pParse->nErr++;
 1.85687 +    goto begin_table_error;
 1.85688 +  }
 1.85689 +  pTable->zName = zName;
 1.85690 +  pTable->iPKey = -1;
 1.85691 +  pTable->pSchema = db->aDb[iDb].pSchema;
 1.85692 +  pTable->nRef = 1;
 1.85693 +  pTable->nRowEst = 1048576;
 1.85694 +  assert( pParse->pNewTable==0 );
 1.85695 +  pParse->pNewTable = pTable;
 1.85696 +
 1.85697 +  /* If this is the magic sqlite_sequence table used by autoincrement,
 1.85698 +  ** then record a pointer to this table in the main database structure
 1.85699 +  ** so that INSERT can find the table easily.
 1.85700 +  */
 1.85701 +#ifndef SQLITE_OMIT_AUTOINCREMENT
 1.85702 +  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
 1.85703 +    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 1.85704 +    pTable->pSchema->pSeqTab = pTable;
 1.85705 +  }
 1.85706 +#endif
 1.85707 +
 1.85708 +  /* Begin generating the code that will insert the table record into
 1.85709 +  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
 1.85710 +  ** and allocate the record number for the table entry now.  Before any
 1.85711 +  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
 1.85712 +  ** indices to be created and the table record must come before the 
 1.85713 +  ** indices.  Hence, the record number for the table must be allocated
 1.85714 +  ** now.
 1.85715 +  */
 1.85716 +  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
 1.85717 +    int j1;
 1.85718 +    int fileFormat;
 1.85719 +    int reg1, reg2, reg3;
 1.85720 +    sqlite3BeginWriteOperation(pParse, 0, iDb);
 1.85721 +
 1.85722 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.85723 +    if( isVirtual ){
 1.85724 +      sqlite3VdbeAddOp0(v, OP_VBegin);
 1.85725 +    }
 1.85726 +#endif
 1.85727 +
 1.85728 +    /* If the file format and encoding in the database have not been set, 
 1.85729 +    ** set them now.
 1.85730 +    */
 1.85731 +    reg1 = pParse->regRowid = ++pParse->nMem;
 1.85732 +    reg2 = pParse->regRoot = ++pParse->nMem;
 1.85733 +    reg3 = ++pParse->nMem;
 1.85734 +    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
 1.85735 +    sqlite3VdbeUsesBtree(v, iDb);
 1.85736 +    j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
 1.85737 +    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
 1.85738 +                  1 : SQLITE_MAX_FILE_FORMAT;
 1.85739 +    sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
 1.85740 +    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
 1.85741 +    sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
 1.85742 +    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
 1.85743 +    sqlite3VdbeJumpHere(v, j1);
 1.85744 +
 1.85745 +    /* This just creates a place-holder record in the sqlite_master table.
 1.85746 +    ** The record created does not contain anything yet.  It will be replaced
 1.85747 +    ** by the real entry in code generated at sqlite3EndTable().
 1.85748 +    **
 1.85749 +    ** The rowid for the new entry is left in register pParse->regRowid.
 1.85750 +    ** The root page number of the new table is left in reg pParse->regRoot.
 1.85751 +    ** The rowid and root page number values are needed by the code that
 1.85752 +    ** sqlite3EndTable will generate.
 1.85753 +    */
 1.85754 +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
 1.85755 +    if( isView || isVirtual ){
 1.85756 +      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
 1.85757 +    }else
 1.85758 +#endif
 1.85759 +    {
 1.85760 +      pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
 1.85761 +    }
 1.85762 +    sqlite3OpenMasterTable(pParse, iDb);
 1.85763 +    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
 1.85764 +    sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
 1.85765 +    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
 1.85766 +    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
 1.85767 +    sqlite3VdbeAddOp0(v, OP_Close);
 1.85768 +  }
 1.85769 +
 1.85770 +  /* Normal (non-error) return. */
 1.85771 +  return;
 1.85772 +
 1.85773 +  /* If an error occurs, we jump here */
 1.85774 +begin_table_error:
 1.85775 +  sqlite3DbFree(db, zName);
 1.85776 +  return;
 1.85777 +}
 1.85778 +
 1.85779 +/*
 1.85780 +** This macro is used to compare two strings in a case-insensitive manner.
 1.85781 +** It is slightly faster than calling sqlite3StrICmp() directly, but
 1.85782 +** produces larger code.
 1.85783 +**
 1.85784 +** WARNING: This macro is not compatible with the strcmp() family. It
 1.85785 +** returns true if the two strings are equal, otherwise false.
 1.85786 +*/
 1.85787 +#define STRICMP(x, y) (\
 1.85788 +sqlite3UpperToLower[*(unsigned char *)(x)]==   \
 1.85789 +sqlite3UpperToLower[*(unsigned char *)(y)]     \
 1.85790 +&& sqlite3StrICmp((x)+1,(y)+1)==0 )
 1.85791 +
 1.85792 +/*
 1.85793 +** Add a new column to the table currently being constructed.
 1.85794 +**
 1.85795 +** The parser calls this routine once for each column declaration
 1.85796 +** in a CREATE TABLE statement.  sqlite3StartTable() gets called
 1.85797 +** first to get things going.  Then this routine is called for each
 1.85798 +** column.
 1.85799 +*/
 1.85800 +SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
 1.85801 +  Table *p;
 1.85802 +  int i;
 1.85803 +  char *z;
 1.85804 +  Column *pCol;
 1.85805 +  sqlite3 *db = pParse->db;
 1.85806 +  if( (p = pParse->pNewTable)==0 ) return;
 1.85807 +#if SQLITE_MAX_COLUMN
 1.85808 +  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
 1.85809 +    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
 1.85810 +    return;
 1.85811 +  }
 1.85812 +#endif
 1.85813 +  z = sqlite3NameFromToken(db, pName);
 1.85814 +  if( z==0 ) return;
 1.85815 +  for(i=0; i<p->nCol; i++){
 1.85816 +    if( STRICMP(z, p->aCol[i].zName) ){
 1.85817 +      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
 1.85818 +      sqlite3DbFree(db, z);
 1.85819 +      return;
 1.85820 +    }
 1.85821 +  }
 1.85822 +  if( (p->nCol & 0x7)==0 ){
 1.85823 +    Column *aNew;
 1.85824 +    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
 1.85825 +    if( aNew==0 ){
 1.85826 +      sqlite3DbFree(db, z);
 1.85827 +      return;
 1.85828 +    }
 1.85829 +    p->aCol = aNew;
 1.85830 +  }
 1.85831 +  pCol = &p->aCol[p->nCol];
 1.85832 +  memset(pCol, 0, sizeof(p->aCol[0]));
 1.85833 +  pCol->zName = z;
 1.85834 + 
 1.85835 +  /* If there is no type specified, columns have the default affinity
 1.85836 +  ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
 1.85837 +  ** be called next to set pCol->affinity correctly.
 1.85838 +  */
 1.85839 +  pCol->affinity = SQLITE_AFF_NONE;
 1.85840 +  pCol->szEst = 1;
 1.85841 +  p->nCol++;
 1.85842 +}
 1.85843 +
 1.85844 +/*
 1.85845 +** This routine is called by the parser while in the middle of
 1.85846 +** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
 1.85847 +** been seen on a column.  This routine sets the notNull flag on
 1.85848 +** the column currently under construction.
 1.85849 +*/
 1.85850 +SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
 1.85851 +  Table *p;
 1.85852 +  p = pParse->pNewTable;
 1.85853 +  if( p==0 || NEVER(p->nCol<1) ) return;
 1.85854 +  p->aCol[p->nCol-1].notNull = (u8)onError;
 1.85855 +}
 1.85856 +
 1.85857 +/*
 1.85858 +** Scan the column type name zType (length nType) and return the
 1.85859 +** associated affinity type.
 1.85860 +**
 1.85861 +** This routine does a case-independent search of zType for the 
 1.85862 +** substrings in the following table. If one of the substrings is
 1.85863 +** found, the corresponding affinity is returned. If zType contains
 1.85864 +** more than one of the substrings, entries toward the top of 
 1.85865 +** the table take priority. For example, if zType is 'BLOBINT', 
 1.85866 +** SQLITE_AFF_INTEGER is returned.
 1.85867 +**
 1.85868 +** Substring     | Affinity
 1.85869 +** --------------------------------
 1.85870 +** 'INT'         | SQLITE_AFF_INTEGER
 1.85871 +** 'CHAR'        | SQLITE_AFF_TEXT
 1.85872 +** 'CLOB'        | SQLITE_AFF_TEXT
 1.85873 +** 'TEXT'        | SQLITE_AFF_TEXT
 1.85874 +** 'BLOB'        | SQLITE_AFF_NONE
 1.85875 +** 'REAL'        | SQLITE_AFF_REAL
 1.85876 +** 'FLOA'        | SQLITE_AFF_REAL
 1.85877 +** 'DOUB'        | SQLITE_AFF_REAL
 1.85878 +**
 1.85879 +** If none of the substrings in the above table are found,
 1.85880 +** SQLITE_AFF_NUMERIC is returned.
 1.85881 +*/
 1.85882 +SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
 1.85883 +  u32 h = 0;
 1.85884 +  char aff = SQLITE_AFF_NUMERIC;
 1.85885 +  const char *zChar = 0;
 1.85886 +
 1.85887 +  if( zIn==0 ) return aff;
 1.85888 +  while( zIn[0] ){
 1.85889 +    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
 1.85890 +    zIn++;
 1.85891 +    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
 1.85892 +      aff = SQLITE_AFF_TEXT;
 1.85893 +      zChar = zIn;
 1.85894 +    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
 1.85895 +      aff = SQLITE_AFF_TEXT;
 1.85896 +    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
 1.85897 +      aff = SQLITE_AFF_TEXT;
 1.85898 +    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
 1.85899 +        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
 1.85900 +      aff = SQLITE_AFF_NONE;
 1.85901 +      if( zIn[0]=='(' ) zChar = zIn;
 1.85902 +#ifndef SQLITE_OMIT_FLOATING_POINT
 1.85903 +    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
 1.85904 +        && aff==SQLITE_AFF_NUMERIC ){
 1.85905 +      aff = SQLITE_AFF_REAL;
 1.85906 +    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
 1.85907 +        && aff==SQLITE_AFF_NUMERIC ){
 1.85908 +      aff = SQLITE_AFF_REAL;
 1.85909 +    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
 1.85910 +        && aff==SQLITE_AFF_NUMERIC ){
 1.85911 +      aff = SQLITE_AFF_REAL;
 1.85912 +#endif
 1.85913 +    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
 1.85914 +      aff = SQLITE_AFF_INTEGER;
 1.85915 +      break;
 1.85916 +    }
 1.85917 +  }
 1.85918 +
 1.85919 +  /* If pszEst is not NULL, store an estimate of the field size.  The
 1.85920 +  ** estimate is scaled so that the size of an integer is 1.  */
 1.85921 +  if( pszEst ){
 1.85922 +    *pszEst = 1;   /* default size is approx 4 bytes */
 1.85923 +    if( aff<=SQLITE_AFF_NONE ){
 1.85924 +      if( zChar ){
 1.85925 +        while( zChar[0] ){
 1.85926 +          if( sqlite3Isdigit(zChar[0]) ){
 1.85927 +            int v = 0;
 1.85928 +            sqlite3GetInt32(zChar, &v);
 1.85929 +            v = v/4 + 1;
 1.85930 +            if( v>255 ) v = 255;
 1.85931 +            *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
 1.85932 +            break;
 1.85933 +          }
 1.85934 +          zChar++;
 1.85935 +        }
 1.85936 +      }else{
 1.85937 +        *pszEst = 5;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
 1.85938 +      }
 1.85939 +    }
 1.85940 +  }
 1.85941 +  return aff;
 1.85942 +}
 1.85943 +
 1.85944 +/*
 1.85945 +** This routine is called by the parser while in the middle of
 1.85946 +** parsing a CREATE TABLE statement.  The pFirst token is the first
 1.85947 +** token in the sequence of tokens that describe the type of the
 1.85948 +** column currently under construction.   pLast is the last token
 1.85949 +** in the sequence.  Use this information to construct a string
 1.85950 +** that contains the typename of the column and store that string
 1.85951 +** in zType.
 1.85952 +*/ 
 1.85953 +SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
 1.85954 +  Table *p;
 1.85955 +  Column *pCol;
 1.85956 +
 1.85957 +  p = pParse->pNewTable;
 1.85958 +  if( p==0 || NEVER(p->nCol<1) ) return;
 1.85959 +  pCol = &p->aCol[p->nCol-1];
 1.85960 +  assert( pCol->zType==0 );
 1.85961 +  pCol->zType = sqlite3NameFromToken(pParse->db, pType);
 1.85962 +  pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
 1.85963 +}
 1.85964 +
 1.85965 +/*
 1.85966 +** The expression is the default value for the most recently added column
 1.85967 +** of the table currently under construction.
 1.85968 +**
 1.85969 +** Default value expressions must be constant.  Raise an exception if this
 1.85970 +** is not the case.
 1.85971 +**
 1.85972 +** This routine is called by the parser while in the middle of
 1.85973 +** parsing a CREATE TABLE statement.
 1.85974 +*/
 1.85975 +SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
 1.85976 +  Table *p;
 1.85977 +  Column *pCol;
 1.85978 +  sqlite3 *db = pParse->db;
 1.85979 +  p = pParse->pNewTable;
 1.85980 +  if( p!=0 ){
 1.85981 +    pCol = &(p->aCol[p->nCol-1]);
 1.85982 +    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
 1.85983 +      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
 1.85984 +          pCol->zName);
 1.85985 +    }else{
 1.85986 +      /* A copy of pExpr is used instead of the original, as pExpr contains
 1.85987 +      ** tokens that point to volatile memory. The 'span' of the expression
 1.85988 +      ** is required by pragma table_info.
 1.85989 +      */
 1.85990 +      sqlite3ExprDelete(db, pCol->pDflt);
 1.85991 +      pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
 1.85992 +      sqlite3DbFree(db, pCol->zDflt);
 1.85993 +      pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
 1.85994 +                                     (int)(pSpan->zEnd - pSpan->zStart));
 1.85995 +    }
 1.85996 +  }
 1.85997 +  sqlite3ExprDelete(db, pSpan->pExpr);
 1.85998 +}
 1.85999 +
 1.86000 +/*
 1.86001 +** Designate the PRIMARY KEY for the table.  pList is a list of names 
 1.86002 +** of columns that form the primary key.  If pList is NULL, then the
 1.86003 +** most recently added column of the table is the primary key.
 1.86004 +**
 1.86005 +** A table can have at most one primary key.  If the table already has
 1.86006 +** a primary key (and this is the second primary key) then create an
 1.86007 +** error.
 1.86008 +**
 1.86009 +** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
 1.86010 +** then we will try to use that column as the rowid.  Set the Table.iPKey
 1.86011 +** field of the table under construction to be the index of the
 1.86012 +** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
 1.86013 +** no INTEGER PRIMARY KEY.
 1.86014 +**
 1.86015 +** If the key is not an INTEGER PRIMARY KEY, then create a unique
 1.86016 +** index for the key.  No index is created for INTEGER PRIMARY KEYs.
 1.86017 +*/
 1.86018 +SQLITE_PRIVATE void sqlite3AddPrimaryKey(
 1.86019 +  Parse *pParse,    /* Parsing context */
 1.86020 +  ExprList *pList,  /* List of field names to be indexed */
 1.86021 +  int onError,      /* What to do with a uniqueness conflict */
 1.86022 +  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
 1.86023 +  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
 1.86024 +){
 1.86025 +  Table *pTab = pParse->pNewTable;
 1.86026 +  char *zType = 0;
 1.86027 +  int iCol = -1, i;
 1.86028 +  int nTerm;
 1.86029 +  if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
 1.86030 +  if( pTab->tabFlags & TF_HasPrimaryKey ){
 1.86031 +    sqlite3ErrorMsg(pParse, 
 1.86032 +      "table \"%s\" has more than one primary key", pTab->zName);
 1.86033 +    goto primary_key_exit;
 1.86034 +  }
 1.86035 +  pTab->tabFlags |= TF_HasPrimaryKey;
 1.86036 +  if( pList==0 ){
 1.86037 +    iCol = pTab->nCol - 1;
 1.86038 +    pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
 1.86039 +    zType = pTab->aCol[iCol].zType;
 1.86040 +    nTerm = 1;
 1.86041 +  }else{
 1.86042 +    nTerm = pList->nExpr;
 1.86043 +    for(i=0; i<nTerm; i++){
 1.86044 +      for(iCol=0; iCol<pTab->nCol; iCol++){
 1.86045 +        if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
 1.86046 +          pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
 1.86047 +          zType = pTab->aCol[iCol].zType;
 1.86048 +          break;
 1.86049 +        }
 1.86050 +      }
 1.86051 +    }
 1.86052 +  }
 1.86053 +  if( nTerm==1
 1.86054 +   && zType && sqlite3StrICmp(zType, "INTEGER")==0
 1.86055 +   && sortOrder==SQLITE_SO_ASC
 1.86056 +  ){
 1.86057 +    pTab->iPKey = iCol;
 1.86058 +    pTab->keyConf = (u8)onError;
 1.86059 +    assert( autoInc==0 || autoInc==1 );
 1.86060 +    pTab->tabFlags |= autoInc*TF_Autoincrement;
 1.86061 +    if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
 1.86062 +  }else if( autoInc ){
 1.86063 +#ifndef SQLITE_OMIT_AUTOINCREMENT
 1.86064 +    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
 1.86065 +       "INTEGER PRIMARY KEY");
 1.86066 +#endif
 1.86067 +  }else{
 1.86068 +    Vdbe *v = pParse->pVdbe;
 1.86069 +    Index *p;
 1.86070 +    if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
 1.86071 +    p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
 1.86072 +                           0, sortOrder, 0);
 1.86073 +    if( p ){
 1.86074 +      p->autoIndex = 2;
 1.86075 +      if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
 1.86076 +    }
 1.86077 +    pList = 0;
 1.86078 +  }
 1.86079 +
 1.86080 +primary_key_exit:
 1.86081 +  sqlite3ExprListDelete(pParse->db, pList);
 1.86082 +  return;
 1.86083 +}
 1.86084 +
 1.86085 +/*
 1.86086 +** Add a new CHECK constraint to the table currently under construction.
 1.86087 +*/
 1.86088 +SQLITE_PRIVATE void sqlite3AddCheckConstraint(
 1.86089 +  Parse *pParse,    /* Parsing context */
 1.86090 +  Expr *pCheckExpr  /* The check expression */
 1.86091 +){
 1.86092 +#ifndef SQLITE_OMIT_CHECK
 1.86093 +  Table *pTab = pParse->pNewTable;
 1.86094 +  if( pTab && !IN_DECLARE_VTAB ){
 1.86095 +    pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
 1.86096 +    if( pParse->constraintName.n ){
 1.86097 +      sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
 1.86098 +    }
 1.86099 +  }else
 1.86100 +#endif
 1.86101 +  {
 1.86102 +    sqlite3ExprDelete(pParse->db, pCheckExpr);
 1.86103 +  }
 1.86104 +}
 1.86105 +
 1.86106 +/*
 1.86107 +** Set the collation function of the most recently parsed table column
 1.86108 +** to the CollSeq given.
 1.86109 +*/
 1.86110 +SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
 1.86111 +  Table *p;
 1.86112 +  int i;
 1.86113 +  char *zColl;              /* Dequoted name of collation sequence */
 1.86114 +  sqlite3 *db;
 1.86115 +
 1.86116 +  if( (p = pParse->pNewTable)==0 ) return;
 1.86117 +  i = p->nCol-1;
 1.86118 +  db = pParse->db;
 1.86119 +  zColl = sqlite3NameFromToken(db, pToken);
 1.86120 +  if( !zColl ) return;
 1.86121 +
 1.86122 +  if( sqlite3LocateCollSeq(pParse, zColl) ){
 1.86123 +    Index *pIdx;
 1.86124 +    sqlite3DbFree(db, p->aCol[i].zColl);
 1.86125 +    p->aCol[i].zColl = zColl;
 1.86126 +  
 1.86127 +    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
 1.86128 +    ** then an index may have been created on this column before the
 1.86129 +    ** collation type was added. Correct this if it is the case.
 1.86130 +    */
 1.86131 +    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
 1.86132 +      assert( pIdx->nKeyCol==1 );
 1.86133 +      if( pIdx->aiColumn[0]==i ){
 1.86134 +        pIdx->azColl[0] = p->aCol[i].zColl;
 1.86135 +      }
 1.86136 +    }
 1.86137 +  }else{
 1.86138 +    sqlite3DbFree(db, zColl);
 1.86139 +  }
 1.86140 +}
 1.86141 +
 1.86142 +/*
 1.86143 +** This function returns the collation sequence for database native text
 1.86144 +** encoding identified by the string zName, length nName.
 1.86145 +**
 1.86146 +** If the requested collation sequence is not available, or not available
 1.86147 +** in the database native encoding, the collation factory is invoked to
 1.86148 +** request it. If the collation factory does not supply such a sequence,
 1.86149 +** and the sequence is available in another text encoding, then that is
 1.86150 +** returned instead.
 1.86151 +**
 1.86152 +** If no versions of the requested collations sequence are available, or
 1.86153 +** another error occurs, NULL is returned and an error message written into
 1.86154 +** pParse.
 1.86155 +**
 1.86156 +** This routine is a wrapper around sqlite3FindCollSeq().  This routine
 1.86157 +** invokes the collation factory if the named collation cannot be found
 1.86158 +** and generates an error message.
 1.86159 +**
 1.86160 +** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
 1.86161 +*/
 1.86162 +SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
 1.86163 +  sqlite3 *db = pParse->db;
 1.86164 +  u8 enc = ENC(db);
 1.86165 +  u8 initbusy = db->init.busy;
 1.86166 +  CollSeq *pColl;
 1.86167 +
 1.86168 +  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
 1.86169 +  if( !initbusy && (!pColl || !pColl->xCmp) ){
 1.86170 +    pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
 1.86171 +  }
 1.86172 +
 1.86173 +  return pColl;
 1.86174 +}
 1.86175 +
 1.86176 +
 1.86177 +/*
 1.86178 +** Generate code that will increment the schema cookie.
 1.86179 +**
 1.86180 +** The schema cookie is used to determine when the schema for the
 1.86181 +** database changes.  After each schema change, the cookie value
 1.86182 +** changes.  When a process first reads the schema it records the
 1.86183 +** cookie.  Thereafter, whenever it goes to access the database,
 1.86184 +** it checks the cookie to make sure the schema has not changed
 1.86185 +** since it was last read.
 1.86186 +**
 1.86187 +** This plan is not completely bullet-proof.  It is possible for
 1.86188 +** the schema to change multiple times and for the cookie to be
 1.86189 +** set back to prior value.  But schema changes are infrequent
 1.86190 +** and the probability of hitting the same cookie value is only
 1.86191 +** 1 chance in 2^32.  So we're safe enough.
 1.86192 +*/
 1.86193 +SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
 1.86194 +  int r1 = sqlite3GetTempReg(pParse);
 1.86195 +  sqlite3 *db = pParse->db;
 1.86196 +  Vdbe *v = pParse->pVdbe;
 1.86197 +  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 1.86198 +  sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
 1.86199 +  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
 1.86200 +  sqlite3ReleaseTempReg(pParse, r1);
 1.86201 +}
 1.86202 +
 1.86203 +/*
 1.86204 +** Measure the number of characters needed to output the given
 1.86205 +** identifier.  The number returned includes any quotes used
 1.86206 +** but does not include the null terminator.
 1.86207 +**
 1.86208 +** The estimate is conservative.  It might be larger that what is
 1.86209 +** really needed.
 1.86210 +*/
 1.86211 +static int identLength(const char *z){
 1.86212 +  int n;
 1.86213 +  for(n=0; *z; n++, z++){
 1.86214 +    if( *z=='"' ){ n++; }
 1.86215 +  }
 1.86216 +  return n + 2;
 1.86217 +}
 1.86218 +
 1.86219 +/*
 1.86220 +** The first parameter is a pointer to an output buffer. The second 
 1.86221 +** parameter is a pointer to an integer that contains the offset at
 1.86222 +** which to write into the output buffer. This function copies the
 1.86223 +** nul-terminated string pointed to by the third parameter, zSignedIdent,
 1.86224 +** to the specified offset in the buffer and updates *pIdx to refer
 1.86225 +** to the first byte after the last byte written before returning.
 1.86226 +** 
 1.86227 +** If the string zSignedIdent consists entirely of alpha-numeric
 1.86228 +** characters, does not begin with a digit and is not an SQL keyword,
 1.86229 +** then it is copied to the output buffer exactly as it is. Otherwise,
 1.86230 +** it is quoted using double-quotes.
 1.86231 +*/
 1.86232 +static void identPut(char *z, int *pIdx, char *zSignedIdent){
 1.86233 +  unsigned char *zIdent = (unsigned char*)zSignedIdent;
 1.86234 +  int i, j, needQuote;
 1.86235 +  i = *pIdx;
 1.86236 +
 1.86237 +  for(j=0; zIdent[j]; j++){
 1.86238 +    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
 1.86239 +  }
 1.86240 +  needQuote = sqlite3Isdigit(zIdent[0])
 1.86241 +            || sqlite3KeywordCode(zIdent, j)!=TK_ID
 1.86242 +            || zIdent[j]!=0
 1.86243 +            || j==0;
 1.86244 +
 1.86245 +  if( needQuote ) z[i++] = '"';
 1.86246 +  for(j=0; zIdent[j]; j++){
 1.86247 +    z[i++] = zIdent[j];
 1.86248 +    if( zIdent[j]=='"' ) z[i++] = '"';
 1.86249 +  }
 1.86250 +  if( needQuote ) z[i++] = '"';
 1.86251 +  z[i] = 0;
 1.86252 +  *pIdx = i;
 1.86253 +}
 1.86254 +
 1.86255 +/*
 1.86256 +** Generate a CREATE TABLE statement appropriate for the given
 1.86257 +** table.  Memory to hold the text of the statement is obtained
 1.86258 +** from sqliteMalloc() and must be freed by the calling function.
 1.86259 +*/
 1.86260 +static char *createTableStmt(sqlite3 *db, Table *p){
 1.86261 +  int i, k, n;
 1.86262 +  char *zStmt;
 1.86263 +  char *zSep, *zSep2, *zEnd;
 1.86264 +  Column *pCol;
 1.86265 +  n = 0;
 1.86266 +  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
 1.86267 +    n += identLength(pCol->zName) + 5;
 1.86268 +  }
 1.86269 +  n += identLength(p->zName);
 1.86270 +  if( n<50 ){ 
 1.86271 +    zSep = "";
 1.86272 +    zSep2 = ",";
 1.86273 +    zEnd = ")";
 1.86274 +  }else{
 1.86275 +    zSep = "\n  ";
 1.86276 +    zSep2 = ",\n  ";
 1.86277 +    zEnd = "\n)";
 1.86278 +  }
 1.86279 +  n += 35 + 6*p->nCol;
 1.86280 +  zStmt = sqlite3DbMallocRaw(0, n);
 1.86281 +  if( zStmt==0 ){
 1.86282 +    db->mallocFailed = 1;
 1.86283 +    return 0;
 1.86284 +  }
 1.86285 +  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
 1.86286 +  k = sqlite3Strlen30(zStmt);
 1.86287 +  identPut(zStmt, &k, p->zName);
 1.86288 +  zStmt[k++] = '(';
 1.86289 +  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
 1.86290 +    static const char * const azType[] = {
 1.86291 +        /* SQLITE_AFF_TEXT    */ " TEXT",
 1.86292 +        /* SQLITE_AFF_NONE    */ "",
 1.86293 +        /* SQLITE_AFF_NUMERIC */ " NUM",
 1.86294 +        /* SQLITE_AFF_INTEGER */ " INT",
 1.86295 +        /* SQLITE_AFF_REAL    */ " REAL"
 1.86296 +    };
 1.86297 +    int len;
 1.86298 +    const char *zType;
 1.86299 +
 1.86300 +    sqlite3_snprintf(n-k, &zStmt[k], zSep);
 1.86301 +    k += sqlite3Strlen30(&zStmt[k]);
 1.86302 +    zSep = zSep2;
 1.86303 +    identPut(zStmt, &k, pCol->zName);
 1.86304 +    assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
 1.86305 +    assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
 1.86306 +    testcase( pCol->affinity==SQLITE_AFF_TEXT );
 1.86307 +    testcase( pCol->affinity==SQLITE_AFF_NONE );
 1.86308 +    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
 1.86309 +    testcase( pCol->affinity==SQLITE_AFF_INTEGER );
 1.86310 +    testcase( pCol->affinity==SQLITE_AFF_REAL );
 1.86311 +    
 1.86312 +    zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
 1.86313 +    len = sqlite3Strlen30(zType);
 1.86314 +    assert( pCol->affinity==SQLITE_AFF_NONE 
 1.86315 +            || pCol->affinity==sqlite3AffinityType(zType, 0) );
 1.86316 +    memcpy(&zStmt[k], zType, len);
 1.86317 +    k += len;
 1.86318 +    assert( k<=n );
 1.86319 +  }
 1.86320 +  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
 1.86321 +  return zStmt;
 1.86322 +}
 1.86323 +
 1.86324 +/*
 1.86325 +** Resize an Index object to hold N columns total.  Return SQLITE_OK
 1.86326 +** on success and SQLITE_NOMEM on an OOM error.
 1.86327 +*/
 1.86328 +static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
 1.86329 +  char *zExtra;
 1.86330 +  int nByte;
 1.86331 +  if( pIdx->nColumn>=N ) return SQLITE_OK;
 1.86332 +  assert( pIdx->isResized==0 );
 1.86333 +  nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
 1.86334 +  zExtra = sqlite3DbMallocZero(db, nByte);
 1.86335 +  if( zExtra==0 ) return SQLITE_NOMEM;
 1.86336 +  memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
 1.86337 +  pIdx->azColl = (char**)zExtra;
 1.86338 +  zExtra += sizeof(char*)*N;
 1.86339 +  memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
 1.86340 +  pIdx->aiColumn = (i16*)zExtra;
 1.86341 +  zExtra += sizeof(i16)*N;
 1.86342 +  memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
 1.86343 +  pIdx->aSortOrder = (u8*)zExtra;
 1.86344 +  pIdx->nColumn = N;
 1.86345 +  pIdx->isResized = 1;
 1.86346 +  return SQLITE_OK;
 1.86347 +}
 1.86348 +
 1.86349 +/*
 1.86350 +** Estimate the total row width for a table.
 1.86351 +*/
 1.86352 +static void estimateTableWidth(Table *pTab){
 1.86353 +  unsigned wTable = 0;
 1.86354 +  const Column *pTabCol;
 1.86355 +  int i;
 1.86356 +  for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
 1.86357 +    wTable += pTabCol->szEst;
 1.86358 +  }
 1.86359 +  if( pTab->iPKey<0 ) wTable++;
 1.86360 +  pTab->szTabRow = sqlite3LogEst(wTable*4);
 1.86361 +}
 1.86362 +
 1.86363 +/*
 1.86364 +** Estimate the average size of a row for an index.
 1.86365 +*/
 1.86366 +static void estimateIndexWidth(Index *pIdx){
 1.86367 +  unsigned wIndex = 0;
 1.86368 +  int i;
 1.86369 +  const Column *aCol = pIdx->pTable->aCol;
 1.86370 +  for(i=0; i<pIdx->nColumn; i++){
 1.86371 +    i16 x = pIdx->aiColumn[i];
 1.86372 +    assert( x<pIdx->pTable->nCol );
 1.86373 +    wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
 1.86374 +  }
 1.86375 +  pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
 1.86376 +}
 1.86377 +
 1.86378 +/* Return true if value x is found any of the first nCol entries of aiCol[]
 1.86379 +*/
 1.86380 +static int hasColumn(const i16 *aiCol, int nCol, int x){
 1.86381 +  while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
 1.86382 +  return 0;
 1.86383 +}
 1.86384 +
 1.86385 +/*
 1.86386 +** This routine runs at the end of parsing a CREATE TABLE statement that
 1.86387 +** has a WITHOUT ROWID clause.  The job of this routine is to convert both
 1.86388 +** internal schema data structures and the generated VDBE code so that they
 1.86389 +** are appropriate for a WITHOUT ROWID table instead of a rowid table.
 1.86390 +** Changes include:
 1.86391 +**
 1.86392 +**     (1)  Convert the OP_CreateTable into an OP_CreateIndex.  There is
 1.86393 +**          no rowid btree for a WITHOUT ROWID.  Instead, the canonical
 1.86394 +**          data storage is a covering index btree.
 1.86395 +**     (2)  Bypass the creation of the sqlite_master table entry
 1.86396 +**          for the PRIMARY KEY as the the primary key index is now
 1.86397 +**          identified by the sqlite_master table entry of the table itself.
 1.86398 +**     (3)  Set the Index.tnum of the PRIMARY KEY Index object in the
 1.86399 +**          schema to the rootpage from the main table.
 1.86400 +**     (4)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
 1.86401 +**     (5)  Add all table columns to the PRIMARY KEY Index object
 1.86402 +**          so that the PRIMARY KEY is a covering index.  The surplus
 1.86403 +**          columns are part of KeyInfo.nXField and are not used for
 1.86404 +**          sorting or lookup or uniqueness checks.
 1.86405 +**     (6)  Replace the rowid tail on all automatically generated UNIQUE
 1.86406 +**          indices with the PRIMARY KEY columns.
 1.86407 +*/
 1.86408 +static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
 1.86409 +  Index *pIdx;
 1.86410 +  Index *pPk;
 1.86411 +  int nPk;
 1.86412 +  int i, j;
 1.86413 +  sqlite3 *db = pParse->db;
 1.86414 +  Vdbe *v = pParse->pVdbe;
 1.86415 +
 1.86416 +  /* Convert the OP_CreateTable opcode that would normally create the
 1.86417 +  ** root-page for the table into a OP_CreateIndex opcode.  The index
 1.86418 +  ** created will become the PRIMARY KEY index.
 1.86419 +  */
 1.86420 +  if( pParse->addrCrTab ){
 1.86421 +    assert( v );
 1.86422 +    sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
 1.86423 +  }
 1.86424 +
 1.86425 +  /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
 1.86426 +  ** table entry.
 1.86427 +  */
 1.86428 +  if( pParse->addrSkipPK ){
 1.86429 +    assert( v );
 1.86430 +    sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
 1.86431 +  }
 1.86432 +
 1.86433 +  /* Locate the PRIMARY KEY index.  Or, if this table was originally
 1.86434 +  ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index. 
 1.86435 +  */
 1.86436 +  if( pTab->iPKey>=0 ){
 1.86437 +    ExprList *pList;
 1.86438 +    pList = sqlite3ExprListAppend(pParse, 0, 0);
 1.86439 +    if( pList==0 ) return;
 1.86440 +    pList->a[0].zName = sqlite3DbStrDup(pParse->db,
 1.86441 +                                        pTab->aCol[pTab->iPKey].zName);
 1.86442 +    pList->a[0].sortOrder = pParse->iPkSortOrder;
 1.86443 +    assert( pParse->pNewTable==pTab );
 1.86444 +    pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
 1.86445 +    if( pPk==0 ) return;
 1.86446 +    pPk->autoIndex = 2;
 1.86447 +    pTab->iPKey = -1;
 1.86448 +  }else{
 1.86449 +    pPk = sqlite3PrimaryKeyIndex(pTab);
 1.86450 +  }
 1.86451 +  pPk->isCovering = 1;
 1.86452 +  assert( pPk!=0 );
 1.86453 +  nPk = pPk->nKeyCol;
 1.86454 +
 1.86455 +  /* Make sure every column of the PRIMARY KEY is NOT NULL */
 1.86456 +  for(i=0; i<nPk; i++){
 1.86457 +    pTab->aCol[pPk->aiColumn[i]].notNull = 1;
 1.86458 +  }
 1.86459 +  pPk->uniqNotNull = 1;
 1.86460 +
 1.86461 +  /* The root page of the PRIMARY KEY is the table root page */
 1.86462 +  pPk->tnum = pTab->tnum;
 1.86463 +
 1.86464 +  /* Update the in-memory representation of all UNIQUE indices by converting
 1.86465 +  ** the final rowid column into one or more columns of the PRIMARY KEY.
 1.86466 +  */
 1.86467 +  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
 1.86468 +    int n;
 1.86469 +    if( pIdx->autoIndex==2 ) continue;
 1.86470 +    for(i=n=0; i<nPk; i++){
 1.86471 +      if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
 1.86472 +    }
 1.86473 +    if( n==0 ){
 1.86474 +      /* This index is a superset of the primary key */
 1.86475 +      pIdx->nColumn = pIdx->nKeyCol;
 1.86476 +      continue;
 1.86477 +    }
 1.86478 +    if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
 1.86479 +    for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
 1.86480 +      if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
 1.86481 +        pIdx->aiColumn[j] = pPk->aiColumn[i];
 1.86482 +        pIdx->azColl[j] = pPk->azColl[i];
 1.86483 +        j++;
 1.86484 +      }
 1.86485 +    }
 1.86486 +    assert( pIdx->nColumn>=pIdx->nKeyCol+n );
 1.86487 +    assert( pIdx->nColumn>=j );
 1.86488 +  }
 1.86489 +
 1.86490 +  /* Add all table columns to the PRIMARY KEY index
 1.86491 +  */
 1.86492 +  if( nPk<pTab->nCol ){
 1.86493 +    if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
 1.86494 +    for(i=0, j=nPk; i<pTab->nCol; i++){
 1.86495 +      if( !hasColumn(pPk->aiColumn, j, i) ){
 1.86496 +        assert( j<pPk->nColumn );
 1.86497 +        pPk->aiColumn[j] = i;
 1.86498 +        pPk->azColl[j] = "BINARY";
 1.86499 +        j++;
 1.86500 +      }
 1.86501 +    }
 1.86502 +    assert( pPk->nColumn==j );
 1.86503 +    assert( pTab->nCol==j );
 1.86504 +  }else{
 1.86505 +    pPk->nColumn = pTab->nCol;
 1.86506 +  }
 1.86507 +}
 1.86508 +
 1.86509 +/*
 1.86510 +** This routine is called to report the final ")" that terminates
 1.86511 +** a CREATE TABLE statement.
 1.86512 +**
 1.86513 +** The table structure that other action routines have been building
 1.86514 +** is added to the internal hash tables, assuming no errors have
 1.86515 +** occurred.
 1.86516 +**
 1.86517 +** An entry for the table is made in the master table on disk, unless
 1.86518 +** this is a temporary table or db->init.busy==1.  When db->init.busy==1
 1.86519 +** it means we are reading the sqlite_master table because we just
 1.86520 +** connected to the database or because the sqlite_master table has
 1.86521 +** recently changed, so the entry for this table already exists in
 1.86522 +** the sqlite_master table.  We do not want to create it again.
 1.86523 +**
 1.86524 +** If the pSelect argument is not NULL, it means that this routine
 1.86525 +** was called to create a table generated from a 
 1.86526 +** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
 1.86527 +** the new table will match the result set of the SELECT.
 1.86528 +*/
 1.86529 +SQLITE_PRIVATE void sqlite3EndTable(
 1.86530 +  Parse *pParse,          /* Parse context */
 1.86531 +  Token *pCons,           /* The ',' token after the last column defn. */
 1.86532 +  Token *pEnd,            /* The ')' before options in the CREATE TABLE */
 1.86533 +  u8 tabOpts,             /* Extra table options. Usually 0. */
 1.86534 +  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
 1.86535 +){
 1.86536 +  Table *p;                 /* The new table */
 1.86537 +  sqlite3 *db = pParse->db; /* The database connection */
 1.86538 +  int iDb;                  /* Database in which the table lives */
 1.86539 +  Index *pIdx;              /* An implied index of the table */
 1.86540 +
 1.86541 +  if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
 1.86542 +    return;
 1.86543 +  }
 1.86544 +  p = pParse->pNewTable;
 1.86545 +  if( p==0 ) return;
 1.86546 +
 1.86547 +  assert( !db->init.busy || !pSelect );
 1.86548 +
 1.86549 +  /* If the db->init.busy is 1 it means we are reading the SQL off the
 1.86550 +  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
 1.86551 +  ** So do not write to the disk again.  Extract the root page number
 1.86552 +  ** for the table from the db->init.newTnum field.  (The page number
 1.86553 +  ** should have been put there by the sqliteOpenCb routine.)
 1.86554 +  */
 1.86555 +  if( db->init.busy ){
 1.86556 +    p->tnum = db->init.newTnum;
 1.86557 +  }
 1.86558 +
 1.86559 +  /* Special processing for WITHOUT ROWID Tables */
 1.86560 +  if( tabOpts & TF_WithoutRowid ){
 1.86561 +    if( (p->tabFlags & TF_Autoincrement) ){
 1.86562 +      sqlite3ErrorMsg(pParse,
 1.86563 +          "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
 1.86564 +      return;
 1.86565 +    }
 1.86566 +    if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
 1.86567 +      sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
 1.86568 +    }else{
 1.86569 +      p->tabFlags |= TF_WithoutRowid;
 1.86570 +      convertToWithoutRowidTable(pParse, p);
 1.86571 +    }
 1.86572 +  }
 1.86573 +
 1.86574 +  iDb = sqlite3SchemaToIndex(db, p->pSchema);
 1.86575 +
 1.86576 +#ifndef SQLITE_OMIT_CHECK
 1.86577 +  /* Resolve names in all CHECK constraint expressions.
 1.86578 +  */
 1.86579 +  if( p->pCheck ){
 1.86580 +    sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
 1.86581 +  }
 1.86582 +#endif /* !defined(SQLITE_OMIT_CHECK) */
 1.86583 +
 1.86584 +  /* Estimate the average row size for the table and for all implied indices */
 1.86585 +  estimateTableWidth(p);
 1.86586 +  for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
 1.86587 +    estimateIndexWidth(pIdx);
 1.86588 +  }
 1.86589 +
 1.86590 +  /* If not initializing, then create a record for the new table
 1.86591 +  ** in the SQLITE_MASTER table of the database.
 1.86592 +  **
 1.86593 +  ** If this is a TEMPORARY table, write the entry into the auxiliary
 1.86594 +  ** file instead of into the main database file.
 1.86595 +  */
 1.86596 +  if( !db->init.busy ){
 1.86597 +    int n;
 1.86598 +    Vdbe *v;
 1.86599 +    char *zType;    /* "view" or "table" */
 1.86600 +    char *zType2;   /* "VIEW" or "TABLE" */
 1.86601 +    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
 1.86602 +
 1.86603 +    v = sqlite3GetVdbe(pParse);
 1.86604 +    if( NEVER(v==0) ) return;
 1.86605 +
 1.86606 +    sqlite3VdbeAddOp1(v, OP_Close, 0);
 1.86607 +
 1.86608 +    /* 
 1.86609 +    ** Initialize zType for the new view or table.
 1.86610 +    */
 1.86611 +    if( p->pSelect==0 ){
 1.86612 +      /* A regular table */
 1.86613 +      zType = "table";
 1.86614 +      zType2 = "TABLE";
 1.86615 +#ifndef SQLITE_OMIT_VIEW
 1.86616 +    }else{
 1.86617 +      /* A view */
 1.86618 +      zType = "view";
 1.86619 +      zType2 = "VIEW";
 1.86620 +#endif
 1.86621 +    }
 1.86622 +
 1.86623 +    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
 1.86624 +    ** statement to populate the new table. The root-page number for the
 1.86625 +    ** new table is in register pParse->regRoot.
 1.86626 +    **
 1.86627 +    ** Once the SELECT has been coded by sqlite3Select(), it is in a
 1.86628 +    ** suitable state to query for the column names and types to be used
 1.86629 +    ** by the new table.
 1.86630 +    **
 1.86631 +    ** A shared-cache write-lock is not required to write to the new table,
 1.86632 +    ** as a schema-lock must have already been obtained to create it. Since
 1.86633 +    ** a schema-lock excludes all other database users, the write-lock would
 1.86634 +    ** be redundant.
 1.86635 +    */
 1.86636 +    if( pSelect ){
 1.86637 +      SelectDest dest;
 1.86638 +      Table *pSelTab;
 1.86639 +
 1.86640 +      assert(pParse->nTab==1);
 1.86641 +      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
 1.86642 +      sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
 1.86643 +      pParse->nTab = 2;
 1.86644 +      sqlite3SelectDestInit(&dest, SRT_Table, 1);
 1.86645 +      sqlite3Select(pParse, pSelect, &dest);
 1.86646 +      sqlite3VdbeAddOp1(v, OP_Close, 1);
 1.86647 +      if( pParse->nErr==0 ){
 1.86648 +        pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
 1.86649 +        if( pSelTab==0 ) return;
 1.86650 +        assert( p->aCol==0 );
 1.86651 +        p->nCol = pSelTab->nCol;
 1.86652 +        p->aCol = pSelTab->aCol;
 1.86653 +        pSelTab->nCol = 0;
 1.86654 +        pSelTab->aCol = 0;
 1.86655 +        sqlite3DeleteTable(db, pSelTab);
 1.86656 +      }
 1.86657 +    }
 1.86658 +
 1.86659 +    /* Compute the complete text of the CREATE statement */
 1.86660 +    if( pSelect ){
 1.86661 +      zStmt = createTableStmt(db, p);
 1.86662 +    }else{
 1.86663 +      Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
 1.86664 +      n = (int)(pEnd2->z - pParse->sNameToken.z);
 1.86665 +      if( pEnd2->z[0]!=';' ) n += pEnd2->n;
 1.86666 +      zStmt = sqlite3MPrintf(db, 
 1.86667 +          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
 1.86668 +      );
 1.86669 +    }
 1.86670 +
 1.86671 +    /* A slot for the record has already been allocated in the 
 1.86672 +    ** SQLITE_MASTER table.  We just need to update that slot with all
 1.86673 +    ** the information we've collected.
 1.86674 +    */
 1.86675 +    sqlite3NestedParse(pParse,
 1.86676 +      "UPDATE %Q.%s "
 1.86677 +         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
 1.86678 +       "WHERE rowid=#%d",
 1.86679 +      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
 1.86680 +      zType,
 1.86681 +      p->zName,
 1.86682 +      p->zName,
 1.86683 +      pParse->regRoot,
 1.86684 +      zStmt,
 1.86685 +      pParse->regRowid
 1.86686 +    );
 1.86687 +    sqlite3DbFree(db, zStmt);
 1.86688 +    sqlite3ChangeCookie(pParse, iDb);
 1.86689 +
 1.86690 +#ifndef SQLITE_OMIT_AUTOINCREMENT
 1.86691 +    /* Check to see if we need to create an sqlite_sequence table for
 1.86692 +    ** keeping track of autoincrement keys.
 1.86693 +    */
 1.86694 +    if( p->tabFlags & TF_Autoincrement ){
 1.86695 +      Db *pDb = &db->aDb[iDb];
 1.86696 +      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 1.86697 +      if( pDb->pSchema->pSeqTab==0 ){
 1.86698 +        sqlite3NestedParse(pParse,
 1.86699 +          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
 1.86700 +          pDb->zName
 1.86701 +        );
 1.86702 +      }
 1.86703 +    }
 1.86704 +#endif
 1.86705 +
 1.86706 +    /* Reparse everything to update our internal data structures */
 1.86707 +    sqlite3VdbeAddParseSchemaOp(v, iDb,
 1.86708 +           sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
 1.86709 +  }
 1.86710 +
 1.86711 +
 1.86712 +  /* Add the table to the in-memory representation of the database.
 1.86713 +  */
 1.86714 +  if( db->init.busy ){
 1.86715 +    Table *pOld;
 1.86716 +    Schema *pSchema = p->pSchema;
 1.86717 +    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 1.86718 +    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
 1.86719 +                             sqlite3Strlen30(p->zName),p);
 1.86720 +    if( pOld ){
 1.86721 +      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
 1.86722 +      db->mallocFailed = 1;
 1.86723 +      return;
 1.86724 +    }
 1.86725 +    pParse->pNewTable = 0;
 1.86726 +    db->flags |= SQLITE_InternChanges;
 1.86727 +
 1.86728 +#ifndef SQLITE_OMIT_ALTERTABLE
 1.86729 +    if( !p->pSelect ){
 1.86730 +      const char *zName = (const char *)pParse->sNameToken.z;
 1.86731 +      int nName;
 1.86732 +      assert( !pSelect && pCons && pEnd );
 1.86733 +      if( pCons->z==0 ){
 1.86734 +        pCons = pEnd;
 1.86735 +      }
 1.86736 +      nName = (int)((const char *)pCons->z - zName);
 1.86737 +      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
 1.86738 +    }
 1.86739 +#endif
 1.86740 +  }
 1.86741 +}
 1.86742 +
 1.86743 +#ifndef SQLITE_OMIT_VIEW
 1.86744 +/*
 1.86745 +** The parser calls this routine in order to create a new VIEW
 1.86746 +*/
 1.86747 +SQLITE_PRIVATE void sqlite3CreateView(
 1.86748 +  Parse *pParse,     /* The parsing context */
 1.86749 +  Token *pBegin,     /* The CREATE token that begins the statement */
 1.86750 +  Token *pName1,     /* The token that holds the name of the view */
 1.86751 +  Token *pName2,     /* The token that holds the name of the view */
 1.86752 +  Select *pSelect,   /* A SELECT statement that will become the new view */
 1.86753 +  int isTemp,        /* TRUE for a TEMPORARY view */
 1.86754 +  int noErr          /* Suppress error messages if VIEW already exists */
 1.86755 +){
 1.86756 +  Table *p;
 1.86757 +  int n;
 1.86758 +  const char *z;
 1.86759 +  Token sEnd;
 1.86760 +  DbFixer sFix;
 1.86761 +  Token *pName = 0;
 1.86762 +  int iDb;
 1.86763 +  sqlite3 *db = pParse->db;
 1.86764 +
 1.86765 +  if( pParse->nVar>0 ){
 1.86766 +    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
 1.86767 +    sqlite3SelectDelete(db, pSelect);
 1.86768 +    return;
 1.86769 +  }
 1.86770 +  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
 1.86771 +  p = pParse->pNewTable;
 1.86772 +  if( p==0 || pParse->nErr ){
 1.86773 +    sqlite3SelectDelete(db, pSelect);
 1.86774 +    return;
 1.86775 +  }
 1.86776 +  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
 1.86777 +  iDb = sqlite3SchemaToIndex(db, p->pSchema);
 1.86778 +  sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
 1.86779 +  if( sqlite3FixSelect(&sFix, pSelect) ){
 1.86780 +    sqlite3SelectDelete(db, pSelect);
 1.86781 +    return;
 1.86782 +  }
 1.86783 +
 1.86784 +  /* Make a copy of the entire SELECT statement that defines the view.
 1.86785 +  ** This will force all the Expr.token.z values to be dynamically
 1.86786 +  ** allocated rather than point to the input string - which means that
 1.86787 +  ** they will persist after the current sqlite3_exec() call returns.
 1.86788 +  */
 1.86789 +  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
 1.86790 +  sqlite3SelectDelete(db, pSelect);
 1.86791 +  if( db->mallocFailed ){
 1.86792 +    return;
 1.86793 +  }
 1.86794 +  if( !db->init.busy ){
 1.86795 +    sqlite3ViewGetColumnNames(pParse, p);
 1.86796 +  }
 1.86797 +
 1.86798 +  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
 1.86799 +  ** the end.
 1.86800 +  */
 1.86801 +  sEnd = pParse->sLastToken;
 1.86802 +  if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
 1.86803 +    sEnd.z += sEnd.n;
 1.86804 +  }
 1.86805 +  sEnd.n = 0;
 1.86806 +  n = (int)(sEnd.z - pBegin->z);
 1.86807 +  z = pBegin->z;
 1.86808 +  while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
 1.86809 +  sEnd.z = &z[n-1];
 1.86810 +  sEnd.n = 1;
 1.86811 +
 1.86812 +  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
 1.86813 +  sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
 1.86814 +  return;
 1.86815 +}
 1.86816 +#endif /* SQLITE_OMIT_VIEW */
 1.86817 +
 1.86818 +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
 1.86819 +/*
 1.86820 +** The Table structure pTable is really a VIEW.  Fill in the names of
 1.86821 +** the columns of the view in the pTable structure.  Return the number
 1.86822 +** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
 1.86823 +*/
 1.86824 +SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
 1.86825 +  Table *pSelTab;   /* A fake table from which we get the result set */
 1.86826 +  Select *pSel;     /* Copy of the SELECT that implements the view */
 1.86827 +  int nErr = 0;     /* Number of errors encountered */
 1.86828 +  int n;            /* Temporarily holds the number of cursors assigned */
 1.86829 +  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
 1.86830 +  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
 1.86831 +
 1.86832 +  assert( pTable );
 1.86833 +
 1.86834 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.86835 +  if( sqlite3VtabCallConnect(pParse, pTable) ){
 1.86836 +    return SQLITE_ERROR;
 1.86837 +  }
 1.86838 +  if( IsVirtual(pTable) ) return 0;
 1.86839 +#endif
 1.86840 +
 1.86841 +#ifndef SQLITE_OMIT_VIEW
 1.86842 +  /* A positive nCol means the columns names for this view are
 1.86843 +  ** already known.
 1.86844 +  */
 1.86845 +  if( pTable->nCol>0 ) return 0;
 1.86846 +
 1.86847 +  /* A negative nCol is a special marker meaning that we are currently
 1.86848 +  ** trying to compute the column names.  If we enter this routine with
 1.86849 +  ** a negative nCol, it means two or more views form a loop, like this:
 1.86850 +  **
 1.86851 +  **     CREATE VIEW one AS SELECT * FROM two;
 1.86852 +  **     CREATE VIEW two AS SELECT * FROM one;
 1.86853 +  **
 1.86854 +  ** Actually, the error above is now caught prior to reaching this point.
 1.86855 +  ** But the following test is still important as it does come up
 1.86856 +  ** in the following:
 1.86857 +  ** 
 1.86858 +  **     CREATE TABLE main.ex1(a);
 1.86859 +  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
 1.86860 +  **     SELECT * FROM temp.ex1;
 1.86861 +  */
 1.86862 +  if( pTable->nCol<0 ){
 1.86863 +    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
 1.86864 +    return 1;
 1.86865 +  }
 1.86866 +  assert( pTable->nCol>=0 );
 1.86867 +
 1.86868 +  /* If we get this far, it means we need to compute the table names.
 1.86869 +  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
 1.86870 +  ** "*" elements in the results set of the view and will assign cursors
 1.86871 +  ** to the elements of the FROM clause.  But we do not want these changes
 1.86872 +  ** to be permanent.  So the computation is done on a copy of the SELECT
 1.86873 +  ** statement that defines the view.
 1.86874 +  */
 1.86875 +  assert( pTable->pSelect );
 1.86876 +  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
 1.86877 +  if( pSel ){
 1.86878 +    u8 enableLookaside = db->lookaside.bEnabled;
 1.86879 +    n = pParse->nTab;
 1.86880 +    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
 1.86881 +    pTable->nCol = -1;
 1.86882 +    db->lookaside.bEnabled = 0;
 1.86883 +#ifndef SQLITE_OMIT_AUTHORIZATION
 1.86884 +    xAuth = db->xAuth;
 1.86885 +    db->xAuth = 0;
 1.86886 +    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
 1.86887 +    db->xAuth = xAuth;
 1.86888 +#else
 1.86889 +    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
 1.86890 +#endif
 1.86891 +    db->lookaside.bEnabled = enableLookaside;
 1.86892 +    pParse->nTab = n;
 1.86893 +    if( pSelTab ){
 1.86894 +      assert( pTable->aCol==0 );
 1.86895 +      pTable->nCol = pSelTab->nCol;
 1.86896 +      pTable->aCol = pSelTab->aCol;
 1.86897 +      pSelTab->nCol = 0;
 1.86898 +      pSelTab->aCol = 0;
 1.86899 +      sqlite3DeleteTable(db, pSelTab);
 1.86900 +      assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
 1.86901 +      pTable->pSchema->flags |= DB_UnresetViews;
 1.86902 +    }else{
 1.86903 +      pTable->nCol = 0;
 1.86904 +      nErr++;
 1.86905 +    }
 1.86906 +    sqlite3SelectDelete(db, pSel);
 1.86907 +  } else {
 1.86908 +    nErr++;
 1.86909 +  }
 1.86910 +#endif /* SQLITE_OMIT_VIEW */
 1.86911 +  return nErr;  
 1.86912 +}
 1.86913 +#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
 1.86914 +
 1.86915 +#ifndef SQLITE_OMIT_VIEW
 1.86916 +/*
 1.86917 +** Clear the column names from every VIEW in database idx.
 1.86918 +*/
 1.86919 +static void sqliteViewResetAll(sqlite3 *db, int idx){
 1.86920 +  HashElem *i;
 1.86921 +  assert( sqlite3SchemaMutexHeld(db, idx, 0) );
 1.86922 +  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
 1.86923 +  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
 1.86924 +    Table *pTab = sqliteHashData(i);
 1.86925 +    if( pTab->pSelect ){
 1.86926 +      sqliteDeleteColumnNames(db, pTab);
 1.86927 +      pTab->aCol = 0;
 1.86928 +      pTab->nCol = 0;
 1.86929 +    }
 1.86930 +  }
 1.86931 +  DbClearProperty(db, idx, DB_UnresetViews);
 1.86932 +}
 1.86933 +#else
 1.86934 +# define sqliteViewResetAll(A,B)
 1.86935 +#endif /* SQLITE_OMIT_VIEW */
 1.86936 +
 1.86937 +/*
 1.86938 +** This function is called by the VDBE to adjust the internal schema
 1.86939 +** used by SQLite when the btree layer moves a table root page. The
 1.86940 +** root-page of a table or index in database iDb has changed from iFrom
 1.86941 +** to iTo.
 1.86942 +**
 1.86943 +** Ticket #1728:  The symbol table might still contain information
 1.86944 +** on tables and/or indices that are the process of being deleted.
 1.86945 +** If you are unlucky, one of those deleted indices or tables might
 1.86946 +** have the same rootpage number as the real table or index that is
 1.86947 +** being moved.  So we cannot stop searching after the first match 
 1.86948 +** because the first match might be for one of the deleted indices
 1.86949 +** or tables and not the table/index that is actually being moved.
 1.86950 +** We must continue looping until all tables and indices with
 1.86951 +** rootpage==iFrom have been converted to have a rootpage of iTo
 1.86952 +** in order to be certain that we got the right one.
 1.86953 +*/
 1.86954 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.86955 +SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
 1.86956 +  HashElem *pElem;
 1.86957 +  Hash *pHash;
 1.86958 +  Db *pDb;
 1.86959 +
 1.86960 +  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 1.86961 +  pDb = &db->aDb[iDb];
 1.86962 +  pHash = &pDb->pSchema->tblHash;
 1.86963 +  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
 1.86964 +    Table *pTab = sqliteHashData(pElem);
 1.86965 +    if( pTab->tnum==iFrom ){
 1.86966 +      pTab->tnum = iTo;
 1.86967 +    }
 1.86968 +  }
 1.86969 +  pHash = &pDb->pSchema->idxHash;
 1.86970 +  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
 1.86971 +    Index *pIdx = sqliteHashData(pElem);
 1.86972 +    if( pIdx->tnum==iFrom ){
 1.86973 +      pIdx->tnum = iTo;
 1.86974 +    }
 1.86975 +  }
 1.86976 +}
 1.86977 +#endif
 1.86978 +
 1.86979 +/*
 1.86980 +** Write code to erase the table with root-page iTable from database iDb.
 1.86981 +** Also write code to modify the sqlite_master table and internal schema
 1.86982 +** if a root-page of another table is moved by the btree-layer whilst
 1.86983 +** erasing iTable (this can happen with an auto-vacuum database).
 1.86984 +*/ 
 1.86985 +static void destroyRootPage(Parse *pParse, int iTable, int iDb){
 1.86986 +  Vdbe *v = sqlite3GetVdbe(pParse);
 1.86987 +  int r1 = sqlite3GetTempReg(pParse);
 1.86988 +  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
 1.86989 +  sqlite3MayAbort(pParse);
 1.86990 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.86991 +  /* OP_Destroy stores an in integer r1. If this integer
 1.86992 +  ** is non-zero, then it is the root page number of a table moved to
 1.86993 +  ** location iTable. The following code modifies the sqlite_master table to
 1.86994 +  ** reflect this.
 1.86995 +  **
 1.86996 +  ** The "#NNN" in the SQL is a special constant that means whatever value
 1.86997 +  ** is in register NNN.  See grammar rules associated with the TK_REGISTER
 1.86998 +  ** token for additional information.
 1.86999 +  */
 1.87000 +  sqlite3NestedParse(pParse, 
 1.87001 +     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
 1.87002 +     pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
 1.87003 +#endif
 1.87004 +  sqlite3ReleaseTempReg(pParse, r1);
 1.87005 +}
 1.87006 +
 1.87007 +/*
 1.87008 +** Write VDBE code to erase table pTab and all associated indices on disk.
 1.87009 +** Code to update the sqlite_master tables and internal schema definitions
 1.87010 +** in case a root-page belonging to another table is moved by the btree layer
 1.87011 +** is also added (this can happen with an auto-vacuum database).
 1.87012 +*/
 1.87013 +static void destroyTable(Parse *pParse, Table *pTab){
 1.87014 +#ifdef SQLITE_OMIT_AUTOVACUUM
 1.87015 +  Index *pIdx;
 1.87016 +  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
 1.87017 +  destroyRootPage(pParse, pTab->tnum, iDb);
 1.87018 +  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
 1.87019 +    destroyRootPage(pParse, pIdx->tnum, iDb);
 1.87020 +  }
 1.87021 +#else
 1.87022 +  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
 1.87023 +  ** is not defined), then it is important to call OP_Destroy on the
 1.87024 +  ** table and index root-pages in order, starting with the numerically 
 1.87025 +  ** largest root-page number. This guarantees that none of the root-pages
 1.87026 +  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
 1.87027 +  ** following were coded:
 1.87028 +  **
 1.87029 +  ** OP_Destroy 4 0
 1.87030 +  ** ...
 1.87031 +  ** OP_Destroy 5 0
 1.87032 +  **
 1.87033 +  ** and root page 5 happened to be the largest root-page number in the
 1.87034 +  ** database, then root page 5 would be moved to page 4 by the 
 1.87035 +  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
 1.87036 +  ** a free-list page.
 1.87037 +  */
 1.87038 +  int iTab = pTab->tnum;
 1.87039 +  int iDestroyed = 0;
 1.87040 +
 1.87041 +  while( 1 ){
 1.87042 +    Index *pIdx;
 1.87043 +    int iLargest = 0;
 1.87044 +
 1.87045 +    if( iDestroyed==0 || iTab<iDestroyed ){
 1.87046 +      iLargest = iTab;
 1.87047 +    }
 1.87048 +    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
 1.87049 +      int iIdx = pIdx->tnum;
 1.87050 +      assert( pIdx->pSchema==pTab->pSchema );
 1.87051 +      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
 1.87052 +        iLargest = iIdx;
 1.87053 +      }
 1.87054 +    }
 1.87055 +    if( iLargest==0 ){
 1.87056 +      return;
 1.87057 +    }else{
 1.87058 +      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
 1.87059 +      assert( iDb>=0 && iDb<pParse->db->nDb );
 1.87060 +      destroyRootPage(pParse, iLargest, iDb);
 1.87061 +      iDestroyed = iLargest;
 1.87062 +    }
 1.87063 +  }
 1.87064 +#endif
 1.87065 +}
 1.87066 +
 1.87067 +/*
 1.87068 +** Remove entries from the sqlite_statN tables (for N in (1,2,3))
 1.87069 +** after a DROP INDEX or DROP TABLE command.
 1.87070 +*/
 1.87071 +static void sqlite3ClearStatTables(
 1.87072 +  Parse *pParse,         /* The parsing context */
 1.87073 +  int iDb,               /* The database number */
 1.87074 +  const char *zType,     /* "idx" or "tbl" */
 1.87075 +  const char *zName      /* Name of index or table */
 1.87076 +){
 1.87077 +  int i;
 1.87078 +  const char *zDbName = pParse->db->aDb[iDb].zName;
 1.87079 +  for(i=1; i<=4; i++){
 1.87080 +    char zTab[24];
 1.87081 +    sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
 1.87082 +    if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
 1.87083 +      sqlite3NestedParse(pParse,
 1.87084 +        "DELETE FROM %Q.%s WHERE %s=%Q",
 1.87085 +        zDbName, zTab, zType, zName
 1.87086 +      );
 1.87087 +    }
 1.87088 +  }
 1.87089 +}
 1.87090 +
 1.87091 +/*
 1.87092 +** Generate code to drop a table.
 1.87093 +*/
 1.87094 +SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
 1.87095 +  Vdbe *v;
 1.87096 +  sqlite3 *db = pParse->db;
 1.87097 +  Trigger *pTrigger;
 1.87098 +  Db *pDb = &db->aDb[iDb];
 1.87099 +
 1.87100 +  v = sqlite3GetVdbe(pParse);
 1.87101 +  assert( v!=0 );
 1.87102 +  sqlite3BeginWriteOperation(pParse, 1, iDb);
 1.87103 +
 1.87104 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.87105 +  if( IsVirtual(pTab) ){
 1.87106 +    sqlite3VdbeAddOp0(v, OP_VBegin);
 1.87107 +  }
 1.87108 +#endif
 1.87109 +
 1.87110 +  /* Drop all triggers associated with the table being dropped. Code
 1.87111 +  ** is generated to remove entries from sqlite_master and/or
 1.87112 +  ** sqlite_temp_master if required.
 1.87113 +  */
 1.87114 +  pTrigger = sqlite3TriggerList(pParse, pTab);
 1.87115 +  while( pTrigger ){
 1.87116 +    assert( pTrigger->pSchema==pTab->pSchema || 
 1.87117 +        pTrigger->pSchema==db->aDb[1].pSchema );
 1.87118 +    sqlite3DropTriggerPtr(pParse, pTrigger);
 1.87119 +    pTrigger = pTrigger->pNext;
 1.87120 +  }
 1.87121 +
 1.87122 +#ifndef SQLITE_OMIT_AUTOINCREMENT
 1.87123 +  /* Remove any entries of the sqlite_sequence table associated with
 1.87124 +  ** the table being dropped. This is done before the table is dropped
 1.87125 +  ** at the btree level, in case the sqlite_sequence table needs to
 1.87126 +  ** move as a result of the drop (can happen in auto-vacuum mode).
 1.87127 +  */
 1.87128 +  if( pTab->tabFlags & TF_Autoincrement ){
 1.87129 +    sqlite3NestedParse(pParse,
 1.87130 +      "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
 1.87131 +      pDb->zName, pTab->zName
 1.87132 +    );
 1.87133 +  }
 1.87134 +#endif
 1.87135 +
 1.87136 +  /* Drop all SQLITE_MASTER table and index entries that refer to the
 1.87137 +  ** table. The program name loops through the master table and deletes
 1.87138 +  ** every row that refers to a table of the same name as the one being
 1.87139 +  ** dropped. Triggers are handled separately because a trigger can be
 1.87140 +  ** created in the temp database that refers to a table in another
 1.87141 +  ** database.
 1.87142 +  */
 1.87143 +  sqlite3NestedParse(pParse, 
 1.87144 +      "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
 1.87145 +      pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
 1.87146 +  if( !isView && !IsVirtual(pTab) ){
 1.87147 +    destroyTable(pParse, pTab);
 1.87148 +  }
 1.87149 +
 1.87150 +  /* Remove the table entry from SQLite's internal schema and modify
 1.87151 +  ** the schema cookie.
 1.87152 +  */
 1.87153 +  if( IsVirtual(pTab) ){
 1.87154 +    sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
 1.87155 +  }
 1.87156 +  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
 1.87157 +  sqlite3ChangeCookie(pParse, iDb);
 1.87158 +  sqliteViewResetAll(db, iDb);
 1.87159 +}
 1.87160 +
 1.87161 +/*
 1.87162 +** This routine is called to do the work of a DROP TABLE statement.
 1.87163 +** pName is the name of the table to be dropped.
 1.87164 +*/
 1.87165 +SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
 1.87166 +  Table *pTab;
 1.87167 +  Vdbe *v;
 1.87168 +  sqlite3 *db = pParse->db;
 1.87169 +  int iDb;
 1.87170 +
 1.87171 +  if( db->mallocFailed ){
 1.87172 +    goto exit_drop_table;
 1.87173 +  }
 1.87174 +  assert( pParse->nErr==0 );
 1.87175 +  assert( pName->nSrc==1 );
 1.87176 +  if( noErr ) db->suppressErr++;
 1.87177 +  pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
 1.87178 +  if( noErr ) db->suppressErr--;
 1.87179 +
 1.87180 +  if( pTab==0 ){
 1.87181 +    if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
 1.87182 +    goto exit_drop_table;
 1.87183 +  }
 1.87184 +  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
 1.87185 +  assert( iDb>=0 && iDb<db->nDb );
 1.87186 +
 1.87187 +  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
 1.87188 +  ** it is initialized.
 1.87189 +  */
 1.87190 +  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
 1.87191 +    goto exit_drop_table;
 1.87192 +  }
 1.87193 +#ifndef SQLITE_OMIT_AUTHORIZATION
 1.87194 +  {
 1.87195 +    int code;
 1.87196 +    const char *zTab = SCHEMA_TABLE(iDb);
 1.87197 +    const char *zDb = db->aDb[iDb].zName;
 1.87198 +    const char *zArg2 = 0;
 1.87199 +    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
 1.87200 +      goto exit_drop_table;
 1.87201 +    }
 1.87202 +    if( isView ){
 1.87203 +      if( !OMIT_TEMPDB && iDb==1 ){
 1.87204 +        code = SQLITE_DROP_TEMP_VIEW;
 1.87205 +      }else{
 1.87206 +        code = SQLITE_DROP_VIEW;
 1.87207 +      }
 1.87208 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.87209 +    }else if( IsVirtual(pTab) ){
 1.87210 +      code = SQLITE_DROP_VTABLE;
 1.87211 +      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
 1.87212 +#endif
 1.87213 +    }else{
 1.87214 +      if( !OMIT_TEMPDB && iDb==1 ){
 1.87215 +        code = SQLITE_DROP_TEMP_TABLE;
 1.87216 +      }else{
 1.87217 +        code = SQLITE_DROP_TABLE;
 1.87218 +      }
 1.87219 +    }
 1.87220 +    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
 1.87221 +      goto exit_drop_table;
 1.87222 +    }
 1.87223 +    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
 1.87224 +      goto exit_drop_table;
 1.87225 +    }
 1.87226 +  }
 1.87227 +#endif
 1.87228 +  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
 1.87229 +    && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
 1.87230 +    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
 1.87231 +    goto exit_drop_table;
 1.87232 +  }
 1.87233 +
 1.87234 +#ifndef SQLITE_OMIT_VIEW
 1.87235 +  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
 1.87236 +  ** on a table.
 1.87237 +  */
 1.87238 +  if( isView && pTab->pSelect==0 ){
 1.87239 +    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
 1.87240 +    goto exit_drop_table;
 1.87241 +  }
 1.87242 +  if( !isView && pTab->pSelect ){
 1.87243 +    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
 1.87244 +    goto exit_drop_table;
 1.87245 +  }
 1.87246 +#endif
 1.87247 +
 1.87248 +  /* Generate code to remove the table from the master table
 1.87249 +  ** on disk.
 1.87250 +  */
 1.87251 +  v = sqlite3GetVdbe(pParse);
 1.87252 +  if( v ){
 1.87253 +    sqlite3BeginWriteOperation(pParse, 1, iDb);
 1.87254 +    sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
 1.87255 +    sqlite3FkDropTable(pParse, pName, pTab);
 1.87256 +    sqlite3CodeDropTable(pParse, pTab, iDb, isView);
 1.87257 +  }
 1.87258 +
 1.87259 +exit_drop_table:
 1.87260 +  sqlite3SrcListDelete(db, pName);
 1.87261 +}
 1.87262 +
 1.87263 +/*
 1.87264 +** This routine is called to create a new foreign key on the table
 1.87265 +** currently under construction.  pFromCol determines which columns
 1.87266 +** in the current table point to the foreign key.  If pFromCol==0 then
 1.87267 +** connect the key to the last column inserted.  pTo is the name of
 1.87268 +** the table referred to (a.k.a the "parent" table).  pToCol is a list
 1.87269 +** of tables in the parent pTo table.  flags contains all
 1.87270 +** information about the conflict resolution algorithms specified
 1.87271 +** in the ON DELETE, ON UPDATE and ON INSERT clauses.
 1.87272 +**
 1.87273 +** An FKey structure is created and added to the table currently
 1.87274 +** under construction in the pParse->pNewTable field.
 1.87275 +**
 1.87276 +** The foreign key is set for IMMEDIATE processing.  A subsequent call
 1.87277 +** to sqlite3DeferForeignKey() might change this to DEFERRED.
 1.87278 +*/
 1.87279 +SQLITE_PRIVATE void sqlite3CreateForeignKey(
 1.87280 +  Parse *pParse,       /* Parsing context */
 1.87281 +  ExprList *pFromCol,  /* Columns in this table that point to other table */
 1.87282 +  Token *pTo,          /* Name of the other table */
 1.87283 +  ExprList *pToCol,    /* Columns in the other table */
 1.87284 +  int flags            /* Conflict resolution algorithms. */
 1.87285 +){
 1.87286 +  sqlite3 *db = pParse->db;
 1.87287 +#ifndef SQLITE_OMIT_FOREIGN_KEY
 1.87288 +  FKey *pFKey = 0;
 1.87289 +  FKey *pNextTo;
 1.87290 +  Table *p = pParse->pNewTable;
 1.87291 +  int nByte;
 1.87292 +  int i;
 1.87293 +  int nCol;
 1.87294 +  char *z;
 1.87295 +
 1.87296 +  assert( pTo!=0 );
 1.87297 +  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
 1.87298 +  if( pFromCol==0 ){
 1.87299 +    int iCol = p->nCol-1;
 1.87300 +    if( NEVER(iCol<0) ) goto fk_end;
 1.87301 +    if( pToCol && pToCol->nExpr!=1 ){
 1.87302 +      sqlite3ErrorMsg(pParse, "foreign key on %s"
 1.87303 +         " should reference only one column of table %T",
 1.87304 +         p->aCol[iCol].zName, pTo);
 1.87305 +      goto fk_end;
 1.87306 +    }
 1.87307 +    nCol = 1;
 1.87308 +  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
 1.87309 +    sqlite3ErrorMsg(pParse,
 1.87310 +        "number of columns in foreign key does not match the number of "
 1.87311 +        "columns in the referenced table");
 1.87312 +    goto fk_end;
 1.87313 +  }else{
 1.87314 +    nCol = pFromCol->nExpr;
 1.87315 +  }
 1.87316 +  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
 1.87317 +  if( pToCol ){
 1.87318 +    for(i=0; i<pToCol->nExpr; i++){
 1.87319 +      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
 1.87320 +    }
 1.87321 +  }
 1.87322 +  pFKey = sqlite3DbMallocZero(db, nByte );
 1.87323 +  if( pFKey==0 ){
 1.87324 +    goto fk_end;
 1.87325 +  }
 1.87326 +  pFKey->pFrom = p;
 1.87327 +  pFKey->pNextFrom = p->pFKey;
 1.87328 +  z = (char*)&pFKey->aCol[nCol];
 1.87329 +  pFKey->zTo = z;
 1.87330 +  memcpy(z, pTo->z, pTo->n);
 1.87331 +  z[pTo->n] = 0;
 1.87332 +  sqlite3Dequote(z);
 1.87333 +  z += pTo->n+1;
 1.87334 +  pFKey->nCol = nCol;
 1.87335 +  if( pFromCol==0 ){
 1.87336 +    pFKey->aCol[0].iFrom = p->nCol-1;
 1.87337 +  }else{
 1.87338 +    for(i=0; i<nCol; i++){
 1.87339 +      int j;
 1.87340 +      for(j=0; j<p->nCol; j++){
 1.87341 +        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
 1.87342 +          pFKey->aCol[i].iFrom = j;
 1.87343 +          break;
 1.87344 +        }
 1.87345 +      }
 1.87346 +      if( j>=p->nCol ){
 1.87347 +        sqlite3ErrorMsg(pParse, 
 1.87348 +          "unknown column \"%s\" in foreign key definition", 
 1.87349 +          pFromCol->a[i].zName);
 1.87350 +        goto fk_end;
 1.87351 +      }
 1.87352 +    }
 1.87353 +  }
 1.87354 +  if( pToCol ){
 1.87355 +    for(i=0; i<nCol; i++){
 1.87356 +      int n = sqlite3Strlen30(pToCol->a[i].zName);
 1.87357 +      pFKey->aCol[i].zCol = z;
 1.87358 +      memcpy(z, pToCol->a[i].zName, n);
 1.87359 +      z[n] = 0;
 1.87360 +      z += n+1;
 1.87361 +    }
 1.87362 +  }
 1.87363 +  pFKey->isDeferred = 0;
 1.87364 +  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
 1.87365 +  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
 1.87366 +
 1.87367 +  assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
 1.87368 +  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
 1.87369 +      pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
 1.87370 +  );
 1.87371 +  if( pNextTo==pFKey ){
 1.87372 +    db->mallocFailed = 1;
 1.87373 +    goto fk_end;
 1.87374 +  }
 1.87375 +  if( pNextTo ){
 1.87376 +    assert( pNextTo->pPrevTo==0 );
 1.87377 +    pFKey->pNextTo = pNextTo;
 1.87378 +    pNextTo->pPrevTo = pFKey;
 1.87379 +  }
 1.87380 +
 1.87381 +  /* Link the foreign key to the table as the last step.
 1.87382 +  */
 1.87383 +  p->pFKey = pFKey;
 1.87384 +  pFKey = 0;
 1.87385 +
 1.87386 +fk_end:
 1.87387 +  sqlite3DbFree(db, pFKey);
 1.87388 +#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
 1.87389 +  sqlite3ExprListDelete(db, pFromCol);
 1.87390 +  sqlite3ExprListDelete(db, pToCol);
 1.87391 +}
 1.87392 +
 1.87393 +/*
 1.87394 +** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
 1.87395 +** clause is seen as part of a foreign key definition.  The isDeferred
 1.87396 +** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
 1.87397 +** The behavior of the most recently created foreign key is adjusted
 1.87398 +** accordingly.
 1.87399 +*/
 1.87400 +SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
 1.87401 +#ifndef SQLITE_OMIT_FOREIGN_KEY
 1.87402 +  Table *pTab;
 1.87403 +  FKey *pFKey;
 1.87404 +  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
 1.87405 +  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
 1.87406 +  pFKey->isDeferred = (u8)isDeferred;
 1.87407 +#endif
 1.87408 +}
 1.87409 +
 1.87410 +/*
 1.87411 +** Generate code that will erase and refill index *pIdx.  This is
 1.87412 +** used to initialize a newly created index or to recompute the
 1.87413 +** content of an index in response to a REINDEX command.
 1.87414 +**
 1.87415 +** if memRootPage is not negative, it means that the index is newly
 1.87416 +** created.  The register specified by memRootPage contains the
 1.87417 +** root page number of the index.  If memRootPage is negative, then
 1.87418 +** the index already exists and must be cleared before being refilled and
 1.87419 +** the root page number of the index is taken from pIndex->tnum.
 1.87420 +*/
 1.87421 +static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
 1.87422 +  Table *pTab = pIndex->pTable;  /* The table that is indexed */
 1.87423 +  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
 1.87424 +  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
 1.87425 +  int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
 1.87426 +  int addr1;                     /* Address of top of loop */
 1.87427 +  int addr2;                     /* Address to jump to for next iteration */
 1.87428 +  int tnum;                      /* Root page of index */
 1.87429 +  int iPartIdxLabel;             /* Jump to this label to skip a row */
 1.87430 +  Vdbe *v;                       /* Generate code into this virtual machine */
 1.87431 +  KeyInfo *pKey;                 /* KeyInfo for index */
 1.87432 +  int regRecord;                 /* Register holding assemblied index record */
 1.87433 +  sqlite3 *db = pParse->db;      /* The database connection */
 1.87434 +  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
 1.87435 +
 1.87436 +#ifndef SQLITE_OMIT_AUTHORIZATION
 1.87437 +  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
 1.87438 +      db->aDb[iDb].zName ) ){
 1.87439 +    return;
 1.87440 +  }
 1.87441 +#endif
 1.87442 +
 1.87443 +  /* Require a write-lock on the table to perform this operation */
 1.87444 +  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
 1.87445 +
 1.87446 +  v = sqlite3GetVdbe(pParse);
 1.87447 +  if( v==0 ) return;
 1.87448 +  if( memRootPage>=0 ){
 1.87449 +    tnum = memRootPage;
 1.87450 +  }else{
 1.87451 +    tnum = pIndex->tnum;
 1.87452 +  }
 1.87453 +  pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
 1.87454 +
 1.87455 +  /* Open the sorter cursor if we are to use one. */
 1.87456 +  iSorter = pParse->nTab++;
 1.87457 +  sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)
 1.87458 +                    sqlite3KeyInfoRef(pKey), P4_KEYINFO);
 1.87459 +
 1.87460 +  /* Open the table. Loop through all rows of the table, inserting index
 1.87461 +  ** records into the sorter. */
 1.87462 +  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
 1.87463 +  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
 1.87464 +  regRecord = sqlite3GetTempReg(pParse);
 1.87465 +
 1.87466 +  sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
 1.87467 +  sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
 1.87468 +  sqlite3VdbeResolveLabel(v, iPartIdxLabel);
 1.87469 +  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
 1.87470 +  sqlite3VdbeJumpHere(v, addr1);
 1.87471 +  if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
 1.87472 +  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
 1.87473 +                    (char *)pKey, P4_KEYINFO);
 1.87474 +  sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
 1.87475 +
 1.87476 +  addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
 1.87477 +  assert( pKey!=0 || db->mallocFailed || pParse->nErr );
 1.87478 +  if( pIndex->onError!=OE_None && pKey!=0 ){
 1.87479 +    int j2 = sqlite3VdbeCurrentAddr(v) + 3;
 1.87480 +    sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
 1.87481 +    addr2 = sqlite3VdbeCurrentAddr(v);
 1.87482 +    sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
 1.87483 +                         pKey->nField - pIndex->nKeyCol); VdbeCoverage(v);
 1.87484 +    sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
 1.87485 +  }else{
 1.87486 +    addr2 = sqlite3VdbeCurrentAddr(v);
 1.87487 +  }
 1.87488 +  sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
 1.87489 +  sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
 1.87490 +  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
 1.87491 +  sqlite3ReleaseTempReg(pParse, regRecord);
 1.87492 +  sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
 1.87493 +  sqlite3VdbeJumpHere(v, addr1);
 1.87494 +
 1.87495 +  sqlite3VdbeAddOp1(v, OP_Close, iTab);
 1.87496 +  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
 1.87497 +  sqlite3VdbeAddOp1(v, OP_Close, iSorter);
 1.87498 +}
 1.87499 +
 1.87500 +/*
 1.87501 +** Allocate heap space to hold an Index object with nCol columns.
 1.87502 +**
 1.87503 +** Increase the allocation size to provide an extra nExtra bytes
 1.87504 +** of 8-byte aligned space after the Index object and return a
 1.87505 +** pointer to this extra space in *ppExtra.
 1.87506 +*/
 1.87507 +SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
 1.87508 +  sqlite3 *db,         /* Database connection */
 1.87509 +  i16 nCol,            /* Total number of columns in the index */
 1.87510 +  int nExtra,          /* Number of bytes of extra space to alloc */
 1.87511 +  char **ppExtra       /* Pointer to the "extra" space */
 1.87512 +){
 1.87513 +  Index *p;            /* Allocated index object */
 1.87514 +  int nByte;           /* Bytes of space for Index object + arrays */
 1.87515 +
 1.87516 +  nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
 1.87517 +          ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
 1.87518 +          ROUND8(sizeof(tRowcnt)*(nCol+1) +    /* Index.aiRowEst   */
 1.87519 +                 sizeof(i16)*nCol +            /* Index.aiColumn   */
 1.87520 +                 sizeof(u8)*nCol);             /* Index.aSortOrder */
 1.87521 +  p = sqlite3DbMallocZero(db, nByte + nExtra);
 1.87522 +  if( p ){
 1.87523 +    char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
 1.87524 +    p->azColl = (char**)pExtra;      pExtra += ROUND8(sizeof(char*)*nCol);
 1.87525 +    p->aiRowEst = (tRowcnt*)pExtra;  pExtra += sizeof(tRowcnt)*(nCol+1);
 1.87526 +    p->aiColumn = (i16*)pExtra;      pExtra += sizeof(i16)*nCol;
 1.87527 +    p->aSortOrder = (u8*)pExtra;
 1.87528 +    p->nColumn = nCol;
 1.87529 +    p->nKeyCol = nCol - 1;
 1.87530 +    *ppExtra = ((char*)p) + nByte;
 1.87531 +  }
 1.87532 +  return p;
 1.87533 +}
 1.87534 +
 1.87535 +/*
 1.87536 +** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
 1.87537 +** and pTblList is the name of the table that is to be indexed.  Both will 
 1.87538 +** be NULL for a primary key or an index that is created to satisfy a
 1.87539 +** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
 1.87540 +** as the table to be indexed.  pParse->pNewTable is a table that is
 1.87541 +** currently being constructed by a CREATE TABLE statement.
 1.87542 +**
 1.87543 +** pList is a list of columns to be indexed.  pList will be NULL if this
 1.87544 +** is a primary key or unique-constraint on the most recent column added
 1.87545 +** to the table currently under construction.  
 1.87546 +**
 1.87547 +** If the index is created successfully, return a pointer to the new Index
 1.87548 +** structure. This is used by sqlite3AddPrimaryKey() to mark the index
 1.87549 +** as the tables primary key (Index.autoIndex==2).
 1.87550 +*/
 1.87551 +SQLITE_PRIVATE Index *sqlite3CreateIndex(
 1.87552 +  Parse *pParse,     /* All information about this parse */
 1.87553 +  Token *pName1,     /* First part of index name. May be NULL */
 1.87554 +  Token *pName2,     /* Second part of index name. May be NULL */
 1.87555 +  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
 1.87556 +  ExprList *pList,   /* A list of columns to be indexed */
 1.87557 +  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
 1.87558 +  Token *pStart,     /* The CREATE token that begins this statement */
 1.87559 +  Expr *pPIWhere,    /* WHERE clause for partial indices */
 1.87560 +  int sortOrder,     /* Sort order of primary key when pList==NULL */
 1.87561 +  int ifNotExist     /* Omit error if index already exists */
 1.87562 +){
 1.87563 +  Index *pRet = 0;     /* Pointer to return */
 1.87564 +  Table *pTab = 0;     /* Table to be indexed */
 1.87565 +  Index *pIndex = 0;   /* The index to be created */
 1.87566 +  char *zName = 0;     /* Name of the index */
 1.87567 +  int nName;           /* Number of characters in zName */
 1.87568 +  int i, j;
 1.87569 +  DbFixer sFix;        /* For assigning database names to pTable */
 1.87570 +  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
 1.87571 +  sqlite3 *db = pParse->db;
 1.87572 +  Db *pDb;             /* The specific table containing the indexed database */
 1.87573 +  int iDb;             /* Index of the database that is being written */
 1.87574 +  Token *pName = 0;    /* Unqualified name of the index to create */
 1.87575 +  struct ExprList_item *pListItem; /* For looping over pList */
 1.87576 +  const Column *pTabCol;           /* A column in the table */
 1.87577 +  int nExtra = 0;                  /* Space allocated for zExtra[] */
 1.87578 +  int nExtraCol;                   /* Number of extra columns needed */
 1.87579 +  char *zExtra = 0;                /* Extra space after the Index object */
 1.87580 +  Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
 1.87581 +
 1.87582 +  assert( pParse->nErr==0 );      /* Never called with prior errors */
 1.87583 +  if( db->mallocFailed || IN_DECLARE_VTAB ){
 1.87584 +    goto exit_create_index;
 1.87585 +  }
 1.87586 +  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
 1.87587 +    goto exit_create_index;
 1.87588 +  }
 1.87589 +
 1.87590 +  /*
 1.87591 +  ** Find the table that is to be indexed.  Return early if not found.
 1.87592 +  */
 1.87593 +  if( pTblName!=0 ){
 1.87594 +
 1.87595 +    /* Use the two-part index name to determine the database 
 1.87596 +    ** to search for the table. 'Fix' the table name to this db
 1.87597 +    ** before looking up the table.
 1.87598 +    */
 1.87599 +    assert( pName1 && pName2 );
 1.87600 +    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
 1.87601 +    if( iDb<0 ) goto exit_create_index;
 1.87602 +    assert( pName && pName->z );
 1.87603 +
 1.87604 +#ifndef SQLITE_OMIT_TEMPDB
 1.87605 +    /* If the index name was unqualified, check if the table
 1.87606 +    ** is a temp table. If so, set the database to 1. Do not do this
 1.87607 +    ** if initialising a database schema.
 1.87608 +    */
 1.87609 +    if( !db->init.busy ){
 1.87610 +      pTab = sqlite3SrcListLookup(pParse, pTblName);
 1.87611 +      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
 1.87612 +        iDb = 1;
 1.87613 +      }
 1.87614 +    }
 1.87615 +#endif
 1.87616 +
 1.87617 +    sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
 1.87618 +    if( sqlite3FixSrcList(&sFix, pTblName) ){
 1.87619 +      /* Because the parser constructs pTblName from a single identifier,
 1.87620 +      ** sqlite3FixSrcList can never fail. */
 1.87621 +      assert(0);
 1.87622 +    }
 1.87623 +    pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
 1.87624 +    assert( db->mallocFailed==0 || pTab==0 );
 1.87625 +    if( pTab==0 ) goto exit_create_index;
 1.87626 +    if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
 1.87627 +      sqlite3ErrorMsg(pParse, 
 1.87628 +           "cannot create a TEMP index on non-TEMP table \"%s\"",
 1.87629 +           pTab->zName);
 1.87630 +      goto exit_create_index;
 1.87631 +    }
 1.87632 +    if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
 1.87633 +  }else{
 1.87634 +    assert( pName==0 );
 1.87635 +    assert( pStart==0 );
 1.87636 +    pTab = pParse->pNewTable;
 1.87637 +    if( !pTab ) goto exit_create_index;
 1.87638 +    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
 1.87639 +  }
 1.87640 +  pDb = &db->aDb[iDb];
 1.87641 +
 1.87642 +  assert( pTab!=0 );
 1.87643 +  assert( pParse->nErr==0 );
 1.87644 +  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
 1.87645 +       && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
 1.87646 +    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
 1.87647 +    goto exit_create_index;
 1.87648 +  }
 1.87649 +#ifndef SQLITE_OMIT_VIEW
 1.87650 +  if( pTab->pSelect ){
 1.87651 +    sqlite3ErrorMsg(pParse, "views may not be indexed");
 1.87652 +    goto exit_create_index;
 1.87653 +  }
 1.87654 +#endif
 1.87655 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.87656 +  if( IsVirtual(pTab) ){
 1.87657 +    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
 1.87658 +    goto exit_create_index;
 1.87659 +  }
 1.87660 +#endif
 1.87661 +
 1.87662 +  /*
 1.87663 +  ** Find the name of the index.  Make sure there is not already another
 1.87664 +  ** index or table with the same name.  
 1.87665 +  **
 1.87666 +  ** Exception:  If we are reading the names of permanent indices from the
 1.87667 +  ** sqlite_master table (because some other process changed the schema) and
 1.87668 +  ** one of the index names collides with the name of a temporary table or
 1.87669 +  ** index, then we will continue to process this index.
 1.87670 +  **
 1.87671 +  ** If pName==0 it means that we are
 1.87672 +  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
 1.87673 +  ** own name.
 1.87674 +  */
 1.87675 +  if( pName ){
 1.87676 +    zName = sqlite3NameFromToken(db, pName);
 1.87677 +    if( zName==0 ) goto exit_create_index;
 1.87678 +    assert( pName->z!=0 );
 1.87679 +    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
 1.87680 +      goto exit_create_index;
 1.87681 +    }
 1.87682 +    if( !db->init.busy ){
 1.87683 +      if( sqlite3FindTable(db, zName, 0)!=0 ){
 1.87684 +        sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
 1.87685 +        goto exit_create_index;
 1.87686 +      }
 1.87687 +    }
 1.87688 +    if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
 1.87689 +      if( !ifNotExist ){
 1.87690 +        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
 1.87691 +      }else{
 1.87692 +        assert( !db->init.busy );
 1.87693 +        sqlite3CodeVerifySchema(pParse, iDb);
 1.87694 +      }
 1.87695 +      goto exit_create_index;
 1.87696 +    }
 1.87697 +  }else{
 1.87698 +    int n;
 1.87699 +    Index *pLoop;
 1.87700 +    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
 1.87701 +    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
 1.87702 +    if( zName==0 ){
 1.87703 +      goto exit_create_index;
 1.87704 +    }
 1.87705 +  }
 1.87706 +
 1.87707 +  /* Check for authorization to create an index.
 1.87708 +  */
 1.87709 +#ifndef SQLITE_OMIT_AUTHORIZATION
 1.87710 +  {
 1.87711 +    const char *zDb = pDb->zName;
 1.87712 +    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
 1.87713 +      goto exit_create_index;
 1.87714 +    }
 1.87715 +    i = SQLITE_CREATE_INDEX;
 1.87716 +    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
 1.87717 +    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
 1.87718 +      goto exit_create_index;
 1.87719 +    }
 1.87720 +  }
 1.87721 +#endif
 1.87722 +
 1.87723 +  /* If pList==0, it means this routine was called to make a primary
 1.87724 +  ** key out of the last column added to the table under construction.
 1.87725 +  ** So create a fake list to simulate this.
 1.87726 +  */
 1.87727 +  if( pList==0 ){
 1.87728 +    pList = sqlite3ExprListAppend(pParse, 0, 0);
 1.87729 +    if( pList==0 ) goto exit_create_index;
 1.87730 +    pList->a[0].zName = sqlite3DbStrDup(pParse->db,
 1.87731 +                                        pTab->aCol[pTab->nCol-1].zName);
 1.87732 +    pList->a[0].sortOrder = (u8)sortOrder;
 1.87733 +  }
 1.87734 +
 1.87735 +  /* Figure out how many bytes of space are required to store explicitly
 1.87736 +  ** specified collation sequence names.
 1.87737 +  */
 1.87738 +  for(i=0; i<pList->nExpr; i++){
 1.87739 +    Expr *pExpr = pList->a[i].pExpr;
 1.87740 +    if( pExpr ){
 1.87741 +      assert( pExpr->op==TK_COLLATE );
 1.87742 +      nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
 1.87743 +    }
 1.87744 +  }
 1.87745 +
 1.87746 +  /* 
 1.87747 +  ** Allocate the index structure. 
 1.87748 +  */
 1.87749 +  nName = sqlite3Strlen30(zName);
 1.87750 +  nExtraCol = pPk ? pPk->nKeyCol : 1;
 1.87751 +  pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
 1.87752 +                                      nName + nExtra + 1, &zExtra);
 1.87753 +  if( db->mallocFailed ){
 1.87754 +    goto exit_create_index;
 1.87755 +  }
 1.87756 +  assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
 1.87757 +  assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
 1.87758 +  pIndex->zName = zExtra;
 1.87759 +  zExtra += nName + 1;
 1.87760 +  memcpy(pIndex->zName, zName, nName+1);
 1.87761 +  pIndex->pTable = pTab;
 1.87762 +  pIndex->onError = (u8)onError;
 1.87763 +  pIndex->uniqNotNull = onError!=OE_None;
 1.87764 +  pIndex->autoIndex = (u8)(pName==0);
 1.87765 +  pIndex->pSchema = db->aDb[iDb].pSchema;
 1.87766 +  pIndex->nKeyCol = pList->nExpr;
 1.87767 +  if( pPIWhere ){
 1.87768 +    sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
 1.87769 +    pIndex->pPartIdxWhere = pPIWhere;
 1.87770 +    pPIWhere = 0;
 1.87771 +  }
 1.87772 +  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 1.87773 +
 1.87774 +  /* Check to see if we should honor DESC requests on index columns
 1.87775 +  */
 1.87776 +  if( pDb->pSchema->file_format>=4 ){
 1.87777 +    sortOrderMask = -1;   /* Honor DESC */
 1.87778 +  }else{
 1.87779 +    sortOrderMask = 0;    /* Ignore DESC */
 1.87780 +  }
 1.87781 +
 1.87782 +  /* Scan the names of the columns of the table to be indexed and
 1.87783 +  ** load the column indices into the Index structure.  Report an error
 1.87784 +  ** if any column is not found.
 1.87785 +  **
 1.87786 +  ** TODO:  Add a test to make sure that the same column is not named
 1.87787 +  ** more than once within the same index.  Only the first instance of
 1.87788 +  ** the column will ever be used by the optimizer.  Note that using the
 1.87789 +  ** same column more than once cannot be an error because that would 
 1.87790 +  ** break backwards compatibility - it needs to be a warning.
 1.87791 +  */
 1.87792 +  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
 1.87793 +    const char *zColName = pListItem->zName;
 1.87794 +    int requestedSortOrder;
 1.87795 +    char *zColl;                   /* Collation sequence name */
 1.87796 +
 1.87797 +    for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
 1.87798 +      if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
 1.87799 +    }
 1.87800 +    if( j>=pTab->nCol ){
 1.87801 +      sqlite3ErrorMsg(pParse, "table %s has no column named %s",
 1.87802 +        pTab->zName, zColName);
 1.87803 +      pParse->checkSchema = 1;
 1.87804 +      goto exit_create_index;
 1.87805 +    }
 1.87806 +    assert( pTab->nCol<=0x7fff && j<=0x7fff );
 1.87807 +    pIndex->aiColumn[i] = (i16)j;
 1.87808 +    if( pListItem->pExpr ){
 1.87809 +      int nColl;
 1.87810 +      assert( pListItem->pExpr->op==TK_COLLATE );
 1.87811 +      zColl = pListItem->pExpr->u.zToken;
 1.87812 +      nColl = sqlite3Strlen30(zColl) + 1;
 1.87813 +      assert( nExtra>=nColl );
 1.87814 +      memcpy(zExtra, zColl, nColl);
 1.87815 +      zColl = zExtra;
 1.87816 +      zExtra += nColl;
 1.87817 +      nExtra -= nColl;
 1.87818 +    }else{
 1.87819 +      zColl = pTab->aCol[j].zColl;
 1.87820 +      if( !zColl ) zColl = "BINARY";
 1.87821 +    }
 1.87822 +    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
 1.87823 +      goto exit_create_index;
 1.87824 +    }
 1.87825 +    pIndex->azColl[i] = zColl;
 1.87826 +    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
 1.87827 +    pIndex->aSortOrder[i] = (u8)requestedSortOrder;
 1.87828 +    if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
 1.87829 +  }
 1.87830 +  if( pPk ){
 1.87831 +    for(j=0; j<pPk->nKeyCol; j++){
 1.87832 +      int x = pPk->aiColumn[j];
 1.87833 +      if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
 1.87834 +        pIndex->nColumn--; 
 1.87835 +      }else{
 1.87836 +        pIndex->aiColumn[i] = x;
 1.87837 +        pIndex->azColl[i] = pPk->azColl[j];
 1.87838 +        pIndex->aSortOrder[i] = pPk->aSortOrder[j];
 1.87839 +        i++;
 1.87840 +      }
 1.87841 +    }
 1.87842 +    assert( i==pIndex->nColumn );
 1.87843 +  }else{
 1.87844 +    pIndex->aiColumn[i] = -1;
 1.87845 +    pIndex->azColl[i] = "BINARY";
 1.87846 +  }
 1.87847 +  sqlite3DefaultRowEst(pIndex);
 1.87848 +  if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
 1.87849 +
 1.87850 +  if( pTab==pParse->pNewTable ){
 1.87851 +    /* This routine has been called to create an automatic index as a
 1.87852 +    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
 1.87853 +    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
 1.87854 +    ** i.e. one of:
 1.87855 +    **
 1.87856 +    ** CREATE TABLE t(x PRIMARY KEY, y);
 1.87857 +    ** CREATE TABLE t(x, y, UNIQUE(x, y));
 1.87858 +    **
 1.87859 +    ** Either way, check to see if the table already has such an index. If
 1.87860 +    ** so, don't bother creating this one. This only applies to
 1.87861 +    ** automatically created indices. Users can do as they wish with
 1.87862 +    ** explicit indices.
 1.87863 +    **
 1.87864 +    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
 1.87865 +    ** (and thus suppressing the second one) even if they have different
 1.87866 +    ** sort orders.
 1.87867 +    **
 1.87868 +    ** If there are different collating sequences or if the columns of
 1.87869 +    ** the constraint occur in different orders, then the constraints are
 1.87870 +    ** considered distinct and both result in separate indices.
 1.87871 +    */
 1.87872 +    Index *pIdx;
 1.87873 +    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
 1.87874 +      int k;
 1.87875 +      assert( pIdx->onError!=OE_None );
 1.87876 +      assert( pIdx->autoIndex );
 1.87877 +      assert( pIndex->onError!=OE_None );
 1.87878 +
 1.87879 +      if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
 1.87880 +      for(k=0; k<pIdx->nKeyCol; k++){
 1.87881 +        const char *z1;
 1.87882 +        const char *z2;
 1.87883 +        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
 1.87884 +        z1 = pIdx->azColl[k];
 1.87885 +        z2 = pIndex->azColl[k];
 1.87886 +        if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
 1.87887 +      }
 1.87888 +      if( k==pIdx->nKeyCol ){
 1.87889 +        if( pIdx->onError!=pIndex->onError ){
 1.87890 +          /* This constraint creates the same index as a previous
 1.87891 +          ** constraint specified somewhere in the CREATE TABLE statement.
 1.87892 +          ** However the ON CONFLICT clauses are different. If both this 
 1.87893 +          ** constraint and the previous equivalent constraint have explicit
 1.87894 +          ** ON CONFLICT clauses this is an error. Otherwise, use the
 1.87895 +          ** explicitly specified behavior for the index.
 1.87896 +          */
 1.87897 +          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
 1.87898 +            sqlite3ErrorMsg(pParse, 
 1.87899 +                "conflicting ON CONFLICT clauses specified", 0);
 1.87900 +          }
 1.87901 +          if( pIdx->onError==OE_Default ){
 1.87902 +            pIdx->onError = pIndex->onError;
 1.87903 +          }
 1.87904 +        }
 1.87905 +        goto exit_create_index;
 1.87906 +      }
 1.87907 +    }
 1.87908 +  }
 1.87909 +
 1.87910 +  /* Link the new Index structure to its table and to the other
 1.87911 +  ** in-memory database structures. 
 1.87912 +  */
 1.87913 +  if( db->init.busy ){
 1.87914 +    Index *p;
 1.87915 +    assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
 1.87916 +    p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
 1.87917 +                          pIndex->zName, sqlite3Strlen30(pIndex->zName),
 1.87918 +                          pIndex);
 1.87919 +    if( p ){
 1.87920 +      assert( p==pIndex );  /* Malloc must have failed */
 1.87921 +      db->mallocFailed = 1;
 1.87922 +      goto exit_create_index;
 1.87923 +    }
 1.87924 +    db->flags |= SQLITE_InternChanges;
 1.87925 +    if( pTblName!=0 ){
 1.87926 +      pIndex->tnum = db->init.newTnum;
 1.87927 +    }
 1.87928 +  }
 1.87929 +
 1.87930 +  /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
 1.87931 +  ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
 1.87932 +  ** emit code to allocate the index rootpage on disk and make an entry for
 1.87933 +  ** the index in the sqlite_master table and populate the index with
 1.87934 +  ** content.  But, do not do this if we are simply reading the sqlite_master
 1.87935 +  ** table to parse the schema, or if this index is the PRIMARY KEY index
 1.87936 +  ** of a WITHOUT ROWID table.
 1.87937 +  **
 1.87938 +  ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
 1.87939 +  ** or UNIQUE index in a CREATE TABLE statement.  Since the table
 1.87940 +  ** has just been created, it contains no data and the index initialization
 1.87941 +  ** step can be skipped.
 1.87942 +  */
 1.87943 +  else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
 1.87944 +    Vdbe *v;
 1.87945 +    char *zStmt;
 1.87946 +    int iMem = ++pParse->nMem;
 1.87947 +
 1.87948 +    v = sqlite3GetVdbe(pParse);
 1.87949 +    if( v==0 ) goto exit_create_index;
 1.87950 +
 1.87951 +
 1.87952 +    /* Create the rootpage for the index
 1.87953 +    */
 1.87954 +    sqlite3BeginWriteOperation(pParse, 1, iDb);
 1.87955 +    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
 1.87956 +
 1.87957 +    /* Gather the complete text of the CREATE INDEX statement into
 1.87958 +    ** the zStmt variable
 1.87959 +    */
 1.87960 +    if( pStart ){
 1.87961 +      int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
 1.87962 +      if( pName->z[n-1]==';' ) n--;
 1.87963 +      /* A named index with an explicit CREATE INDEX statement */
 1.87964 +      zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
 1.87965 +        onError==OE_None ? "" : " UNIQUE", n, pName->z);
 1.87966 +    }else{
 1.87967 +      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
 1.87968 +      /* zStmt = sqlite3MPrintf(""); */
 1.87969 +      zStmt = 0;
 1.87970 +    }
 1.87971 +
 1.87972 +    /* Add an entry in sqlite_master for this index
 1.87973 +    */
 1.87974 +    sqlite3NestedParse(pParse, 
 1.87975 +        "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
 1.87976 +        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
 1.87977 +        pIndex->zName,
 1.87978 +        pTab->zName,
 1.87979 +        iMem,
 1.87980 +        zStmt
 1.87981 +    );
 1.87982 +    sqlite3DbFree(db, zStmt);
 1.87983 +
 1.87984 +    /* Fill the index with data and reparse the schema. Code an OP_Expire
 1.87985 +    ** to invalidate all pre-compiled statements.
 1.87986 +    */
 1.87987 +    if( pTblName ){
 1.87988 +      sqlite3RefillIndex(pParse, pIndex, iMem);
 1.87989 +      sqlite3ChangeCookie(pParse, iDb);
 1.87990 +      sqlite3VdbeAddParseSchemaOp(v, iDb,
 1.87991 +         sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
 1.87992 +      sqlite3VdbeAddOp1(v, OP_Expire, 0);
 1.87993 +    }
 1.87994 +  }
 1.87995 +
 1.87996 +  /* When adding an index to the list of indices for a table, make
 1.87997 +  ** sure all indices labeled OE_Replace come after all those labeled
 1.87998 +  ** OE_Ignore.  This is necessary for the correct constraint check
 1.87999 +  ** processing (in sqlite3GenerateConstraintChecks()) as part of
 1.88000 +  ** UPDATE and INSERT statements.  
 1.88001 +  */
 1.88002 +  if( db->init.busy || pTblName==0 ){
 1.88003 +    if( onError!=OE_Replace || pTab->pIndex==0
 1.88004 +         || pTab->pIndex->onError==OE_Replace){
 1.88005 +      pIndex->pNext = pTab->pIndex;
 1.88006 +      pTab->pIndex = pIndex;
 1.88007 +    }else{
 1.88008 +      Index *pOther = pTab->pIndex;
 1.88009 +      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
 1.88010 +        pOther = pOther->pNext;
 1.88011 +      }
 1.88012 +      pIndex->pNext = pOther->pNext;
 1.88013 +      pOther->pNext = pIndex;
 1.88014 +    }
 1.88015 +    pRet = pIndex;
 1.88016 +    pIndex = 0;
 1.88017 +  }
 1.88018 +
 1.88019 +  /* Clean up before exiting */
 1.88020 +exit_create_index:
 1.88021 +  if( pIndex ) freeIndex(db, pIndex);
 1.88022 +  sqlite3ExprDelete(db, pPIWhere);
 1.88023 +  sqlite3ExprListDelete(db, pList);
 1.88024 +  sqlite3SrcListDelete(db, pTblName);
 1.88025 +  sqlite3DbFree(db, zName);
 1.88026 +  return pRet;
 1.88027 +}
 1.88028 +
 1.88029 +/*
 1.88030 +** Fill the Index.aiRowEst[] array with default information - information
 1.88031 +** to be used when we have not run the ANALYZE command.
 1.88032 +**
 1.88033 +** aiRowEst[0] is suppose to contain the number of elements in the index.
 1.88034 +** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
 1.88035 +** number of rows in the table that match any particular value of the
 1.88036 +** first column of the index.  aiRowEst[2] is an estimate of the number
 1.88037 +** of rows that match any particular combiniation of the first 2 columns
 1.88038 +** of the index.  And so forth.  It must always be the case that
 1.88039 +*
 1.88040 +**           aiRowEst[N]<=aiRowEst[N-1]
 1.88041 +**           aiRowEst[N]>=1
 1.88042 +**
 1.88043 +** Apart from that, we have little to go on besides intuition as to
 1.88044 +** how aiRowEst[] should be initialized.  The numbers generated here
 1.88045 +** are based on typical values found in actual indices.
 1.88046 +*/
 1.88047 +SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
 1.88048 +  tRowcnt *a = pIdx->aiRowEst;
 1.88049 +  int i;
 1.88050 +  tRowcnt n;
 1.88051 +  assert( a!=0 );
 1.88052 +  a[0] = pIdx->pTable->nRowEst;
 1.88053 +  if( a[0]<10 ) a[0] = 10;
 1.88054 +  n = 10;
 1.88055 +  for(i=1; i<=pIdx->nKeyCol; i++){
 1.88056 +    a[i] = n;
 1.88057 +    if( n>5 ) n--;
 1.88058 +  }
 1.88059 +  if( pIdx->onError!=OE_None ){
 1.88060 +    a[pIdx->nKeyCol] = 1;
 1.88061 +  }
 1.88062 +}
 1.88063 +
 1.88064 +/*
 1.88065 +** This routine will drop an existing named index.  This routine
 1.88066 +** implements the DROP INDEX statement.
 1.88067 +*/
 1.88068 +SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
 1.88069 +  Index *pIndex;
 1.88070 +  Vdbe *v;
 1.88071 +  sqlite3 *db = pParse->db;
 1.88072 +  int iDb;
 1.88073 +
 1.88074 +  assert( pParse->nErr==0 );   /* Never called with prior errors */
 1.88075 +  if( db->mallocFailed ){
 1.88076 +    goto exit_drop_index;
 1.88077 +  }
 1.88078 +  assert( pName->nSrc==1 );
 1.88079 +  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
 1.88080 +    goto exit_drop_index;
 1.88081 +  }
 1.88082 +  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
 1.88083 +  if( pIndex==0 ){
 1.88084 +    if( !ifExists ){
 1.88085 +      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
 1.88086 +    }else{
 1.88087 +      sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
 1.88088 +    }
 1.88089 +    pParse->checkSchema = 1;
 1.88090 +    goto exit_drop_index;
 1.88091 +  }
 1.88092 +  if( pIndex->autoIndex ){
 1.88093 +    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
 1.88094 +      "or PRIMARY KEY constraint cannot be dropped", 0);
 1.88095 +    goto exit_drop_index;
 1.88096 +  }
 1.88097 +  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
 1.88098 +#ifndef SQLITE_OMIT_AUTHORIZATION
 1.88099 +  {
 1.88100 +    int code = SQLITE_DROP_INDEX;
 1.88101 +    Table *pTab = pIndex->pTable;
 1.88102 +    const char *zDb = db->aDb[iDb].zName;
 1.88103 +    const char *zTab = SCHEMA_TABLE(iDb);
 1.88104 +    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
 1.88105 +      goto exit_drop_index;
 1.88106 +    }
 1.88107 +    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
 1.88108 +    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
 1.88109 +      goto exit_drop_index;
 1.88110 +    }
 1.88111 +  }
 1.88112 +#endif
 1.88113 +
 1.88114 +  /* Generate code to remove the index and from the master table */
 1.88115 +  v = sqlite3GetVdbe(pParse);
 1.88116 +  if( v ){
 1.88117 +    sqlite3BeginWriteOperation(pParse, 1, iDb);
 1.88118 +    sqlite3NestedParse(pParse,
 1.88119 +       "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
 1.88120 +       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
 1.88121 +    );
 1.88122 +    sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
 1.88123 +    sqlite3ChangeCookie(pParse, iDb);
 1.88124 +    destroyRootPage(pParse, pIndex->tnum, iDb);
 1.88125 +    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
 1.88126 +  }
 1.88127 +
 1.88128 +exit_drop_index:
 1.88129 +  sqlite3SrcListDelete(db, pName);
 1.88130 +}
 1.88131 +
 1.88132 +/*
 1.88133 +** pArray is a pointer to an array of objects. Each object in the
 1.88134 +** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
 1.88135 +** to extend the array so that there is space for a new object at the end.
 1.88136 +**
 1.88137 +** When this function is called, *pnEntry contains the current size of
 1.88138 +** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
 1.88139 +** in total).
 1.88140 +**
 1.88141 +** If the realloc() is successful (i.e. if no OOM condition occurs), the
 1.88142 +** space allocated for the new object is zeroed, *pnEntry updated to
 1.88143 +** reflect the new size of the array and a pointer to the new allocation
 1.88144 +** returned. *pIdx is set to the index of the new array entry in this case.
 1.88145 +**
 1.88146 +** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
 1.88147 +** unchanged and a copy of pArray returned.
 1.88148 +*/
 1.88149 +SQLITE_PRIVATE void *sqlite3ArrayAllocate(
 1.88150 +  sqlite3 *db,      /* Connection to notify of malloc failures */
 1.88151 +  void *pArray,     /* Array of objects.  Might be reallocated */
 1.88152 +  int szEntry,      /* Size of each object in the array */
 1.88153 +  int *pnEntry,     /* Number of objects currently in use */
 1.88154 +  int *pIdx         /* Write the index of a new slot here */
 1.88155 +){
 1.88156 +  char *z;
 1.88157 +  int n = *pnEntry;
 1.88158 +  if( (n & (n-1))==0 ){
 1.88159 +    int sz = (n==0) ? 1 : 2*n;
 1.88160 +    void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
 1.88161 +    if( pNew==0 ){
 1.88162 +      *pIdx = -1;
 1.88163 +      return pArray;
 1.88164 +    }
 1.88165 +    pArray = pNew;
 1.88166 +  }
 1.88167 +  z = (char*)pArray;
 1.88168 +  memset(&z[n * szEntry], 0, szEntry);
 1.88169 +  *pIdx = n;
 1.88170 +  ++*pnEntry;
 1.88171 +  return pArray;
 1.88172 +}
 1.88173 +
 1.88174 +/*
 1.88175 +** Append a new element to the given IdList.  Create a new IdList if
 1.88176 +** need be.
 1.88177 +**
 1.88178 +** A new IdList is returned, or NULL if malloc() fails.
 1.88179 +*/
 1.88180 +SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
 1.88181 +  int i;
 1.88182 +  if( pList==0 ){
 1.88183 +    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
 1.88184 +    if( pList==0 ) return 0;
 1.88185 +  }
 1.88186 +  pList->a = sqlite3ArrayAllocate(
 1.88187 +      db,
 1.88188 +      pList->a,
 1.88189 +      sizeof(pList->a[0]),
 1.88190 +      &pList->nId,
 1.88191 +      &i
 1.88192 +  );
 1.88193 +  if( i<0 ){
 1.88194 +    sqlite3IdListDelete(db, pList);
 1.88195 +    return 0;
 1.88196 +  }
 1.88197 +  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
 1.88198 +  return pList;
 1.88199 +}
 1.88200 +
 1.88201 +/*
 1.88202 +** Delete an IdList.
 1.88203 +*/
 1.88204 +SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
 1.88205 +  int i;
 1.88206 +  if( pList==0 ) return;
 1.88207 +  for(i=0; i<pList->nId; i++){
 1.88208 +    sqlite3DbFree(db, pList->a[i].zName);
 1.88209 +  }
 1.88210 +  sqlite3DbFree(db, pList->a);
 1.88211 +  sqlite3DbFree(db, pList);
 1.88212 +}
 1.88213 +
 1.88214 +/*
 1.88215 +** Return the index in pList of the identifier named zId.  Return -1
 1.88216 +** if not found.
 1.88217 +*/
 1.88218 +SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
 1.88219 +  int i;
 1.88220 +  if( pList==0 ) return -1;
 1.88221 +  for(i=0; i<pList->nId; i++){
 1.88222 +    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
 1.88223 +  }
 1.88224 +  return -1;
 1.88225 +}
 1.88226 +
 1.88227 +/*
 1.88228 +** Expand the space allocated for the given SrcList object by
 1.88229 +** creating nExtra new slots beginning at iStart.  iStart is zero based.
 1.88230 +** New slots are zeroed.
 1.88231 +**
 1.88232 +** For example, suppose a SrcList initially contains two entries: A,B.
 1.88233 +** To append 3 new entries onto the end, do this:
 1.88234 +**
 1.88235 +**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
 1.88236 +**
 1.88237 +** After the call above it would contain:  A, B, nil, nil, nil.
 1.88238 +** If the iStart argument had been 1 instead of 2, then the result
 1.88239 +** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
 1.88240 +** the iStart value would be 0.  The result then would
 1.88241 +** be: nil, nil, nil, A, B.
 1.88242 +**
 1.88243 +** If a memory allocation fails the SrcList is unchanged.  The
 1.88244 +** db->mallocFailed flag will be set to true.
 1.88245 +*/
 1.88246 +SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
 1.88247 +  sqlite3 *db,       /* Database connection to notify of OOM errors */
 1.88248 +  SrcList *pSrc,     /* The SrcList to be enlarged */
 1.88249 +  int nExtra,        /* Number of new slots to add to pSrc->a[] */
 1.88250 +  int iStart         /* Index in pSrc->a[] of first new slot */
 1.88251 +){
 1.88252 +  int i;
 1.88253 +
 1.88254 +  /* Sanity checking on calling parameters */
 1.88255 +  assert( iStart>=0 );
 1.88256 +  assert( nExtra>=1 );
 1.88257 +  assert( pSrc!=0 );
 1.88258 +  assert( iStart<=pSrc->nSrc );
 1.88259 +
 1.88260 +  /* Allocate additional space if needed */
 1.88261 +  if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
 1.88262 +    SrcList *pNew;
 1.88263 +    int nAlloc = pSrc->nSrc+nExtra;
 1.88264 +    int nGot;
 1.88265 +    pNew = sqlite3DbRealloc(db, pSrc,
 1.88266 +               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
 1.88267 +    if( pNew==0 ){
 1.88268 +      assert( db->mallocFailed );
 1.88269 +      return pSrc;
 1.88270 +    }
 1.88271 +    pSrc = pNew;
 1.88272 +    nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
 1.88273 +    pSrc->nAlloc = nGot;
 1.88274 +  }
 1.88275 +
 1.88276 +  /* Move existing slots that come after the newly inserted slots
 1.88277 +  ** out of the way */
 1.88278 +  for(i=pSrc->nSrc-1; i>=iStart; i--){
 1.88279 +    pSrc->a[i+nExtra] = pSrc->a[i];
 1.88280 +  }
 1.88281 +  pSrc->nSrc += nExtra;
 1.88282 +
 1.88283 +  /* Zero the newly allocated slots */
 1.88284 +  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
 1.88285 +  for(i=iStart; i<iStart+nExtra; i++){
 1.88286 +    pSrc->a[i].iCursor = -1;
 1.88287 +  }
 1.88288 +
 1.88289 +  /* Return a pointer to the enlarged SrcList */
 1.88290 +  return pSrc;
 1.88291 +}
 1.88292 +
 1.88293 +
 1.88294 +/*
 1.88295 +** Append a new table name to the given SrcList.  Create a new SrcList if
 1.88296 +** need be.  A new entry is created in the SrcList even if pTable is NULL.
 1.88297 +**
 1.88298 +** A SrcList is returned, or NULL if there is an OOM error.  The returned
 1.88299 +** SrcList might be the same as the SrcList that was input or it might be
 1.88300 +** a new one.  If an OOM error does occurs, then the prior value of pList
 1.88301 +** that is input to this routine is automatically freed.
 1.88302 +**
 1.88303 +** If pDatabase is not null, it means that the table has an optional
 1.88304 +** database name prefix.  Like this:  "database.table".  The pDatabase
 1.88305 +** points to the table name and the pTable points to the database name.
 1.88306 +** The SrcList.a[].zName field is filled with the table name which might
 1.88307 +** come from pTable (if pDatabase is NULL) or from pDatabase.  
 1.88308 +** SrcList.a[].zDatabase is filled with the database name from pTable,
 1.88309 +** or with NULL if no database is specified.
 1.88310 +**
 1.88311 +** In other words, if call like this:
 1.88312 +**
 1.88313 +**         sqlite3SrcListAppend(D,A,B,0);
 1.88314 +**
 1.88315 +** Then B is a table name and the database name is unspecified.  If called
 1.88316 +** like this:
 1.88317 +**
 1.88318 +**         sqlite3SrcListAppend(D,A,B,C);
 1.88319 +**
 1.88320 +** Then C is the table name and B is the database name.  If C is defined
 1.88321 +** then so is B.  In other words, we never have a case where:
 1.88322 +**
 1.88323 +**         sqlite3SrcListAppend(D,A,0,C);
 1.88324 +**
 1.88325 +** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
 1.88326 +** before being added to the SrcList.
 1.88327 +*/
 1.88328 +SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
 1.88329 +  sqlite3 *db,        /* Connection to notify of malloc failures */
 1.88330 +  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
 1.88331 +  Token *pTable,      /* Table to append */
 1.88332 +  Token *pDatabase    /* Database of the table */
 1.88333 +){
 1.88334 +  struct SrcList_item *pItem;
 1.88335 +  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
 1.88336 +  if( pList==0 ){
 1.88337 +    pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
 1.88338 +    if( pList==0 ) return 0;
 1.88339 +    pList->nAlloc = 1;
 1.88340 +  }
 1.88341 +  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
 1.88342 +  if( db->mallocFailed ){
 1.88343 +    sqlite3SrcListDelete(db, pList);
 1.88344 +    return 0;
 1.88345 +  }
 1.88346 +  pItem = &pList->a[pList->nSrc-1];
 1.88347 +  if( pDatabase && pDatabase->z==0 ){
 1.88348 +    pDatabase = 0;
 1.88349 +  }
 1.88350 +  if( pDatabase ){
 1.88351 +    Token *pTemp = pDatabase;
 1.88352 +    pDatabase = pTable;
 1.88353 +    pTable = pTemp;
 1.88354 +  }
 1.88355 +  pItem->zName = sqlite3NameFromToken(db, pTable);
 1.88356 +  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
 1.88357 +  return pList;
 1.88358 +}
 1.88359 +
 1.88360 +/*
 1.88361 +** Assign VdbeCursor index numbers to all tables in a SrcList
 1.88362 +*/
 1.88363 +SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
 1.88364 +  int i;
 1.88365 +  struct SrcList_item *pItem;
 1.88366 +  assert(pList || pParse->db->mallocFailed );
 1.88367 +  if( pList ){
 1.88368 +    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
 1.88369 +      if( pItem->iCursor>=0 ) break;
 1.88370 +      pItem->iCursor = pParse->nTab++;
 1.88371 +      if( pItem->pSelect ){
 1.88372 +        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
 1.88373 +      }
 1.88374 +    }
 1.88375 +  }
 1.88376 +}
 1.88377 +
 1.88378 +/*
 1.88379 +** Delete an entire SrcList including all its substructure.
 1.88380 +*/
 1.88381 +SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
 1.88382 +  int i;
 1.88383 +  struct SrcList_item *pItem;
 1.88384 +  if( pList==0 ) return;
 1.88385 +  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
 1.88386 +    sqlite3DbFree(db, pItem->zDatabase);
 1.88387 +    sqlite3DbFree(db, pItem->zName);
 1.88388 +    sqlite3DbFree(db, pItem->zAlias);
 1.88389 +    sqlite3DbFree(db, pItem->zIndex);
 1.88390 +    sqlite3DeleteTable(db, pItem->pTab);
 1.88391 +    sqlite3SelectDelete(db, pItem->pSelect);
 1.88392 +    sqlite3ExprDelete(db, pItem->pOn);
 1.88393 +    sqlite3IdListDelete(db, pItem->pUsing);
 1.88394 +  }
 1.88395 +  sqlite3DbFree(db, pList);
 1.88396 +}
 1.88397 +
 1.88398 +/*
 1.88399 +** This routine is called by the parser to add a new term to the
 1.88400 +** end of a growing FROM clause.  The "p" parameter is the part of
 1.88401 +** the FROM clause that has already been constructed.  "p" is NULL
 1.88402 +** if this is the first term of the FROM clause.  pTable and pDatabase
 1.88403 +** are the name of the table and database named in the FROM clause term.
 1.88404 +** pDatabase is NULL if the database name qualifier is missing - the
 1.88405 +** usual case.  If the term has a alias, then pAlias points to the
 1.88406 +** alias token.  If the term is a subquery, then pSubquery is the
 1.88407 +** SELECT statement that the subquery encodes.  The pTable and
 1.88408 +** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
 1.88409 +** parameters are the content of the ON and USING clauses.
 1.88410 +**
 1.88411 +** Return a new SrcList which encodes is the FROM with the new
 1.88412 +** term added.
 1.88413 +*/
 1.88414 +SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
 1.88415 +  Parse *pParse,          /* Parsing context */
 1.88416 +  SrcList *p,             /* The left part of the FROM clause already seen */
 1.88417 +  Token *pTable,          /* Name of the table to add to the FROM clause */
 1.88418 +  Token *pDatabase,       /* Name of the database containing pTable */
 1.88419 +  Token *pAlias,          /* The right-hand side of the AS subexpression */
 1.88420 +  Select *pSubquery,      /* A subquery used in place of a table name */
 1.88421 +  Expr *pOn,              /* The ON clause of a join */
 1.88422 +  IdList *pUsing          /* The USING clause of a join */
 1.88423 +){
 1.88424 +  struct SrcList_item *pItem;
 1.88425 +  sqlite3 *db = pParse->db;
 1.88426 +  if( !p && (pOn || pUsing) ){
 1.88427 +    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
 1.88428 +      (pOn ? "ON" : "USING")
 1.88429 +    );
 1.88430 +    goto append_from_error;
 1.88431 +  }
 1.88432 +  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
 1.88433 +  if( p==0 || NEVER(p->nSrc==0) ){
 1.88434 +    goto append_from_error;
 1.88435 +  }
 1.88436 +  pItem = &p->a[p->nSrc-1];
 1.88437 +  assert( pAlias!=0 );
 1.88438 +  if( pAlias->n ){
 1.88439 +    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
 1.88440 +  }
 1.88441 +  pItem->pSelect = pSubquery;
 1.88442 +  pItem->pOn = pOn;
 1.88443 +  pItem->pUsing = pUsing;
 1.88444 +  return p;
 1.88445 +
 1.88446 + append_from_error:
 1.88447 +  assert( p==0 );
 1.88448 +  sqlite3ExprDelete(db, pOn);
 1.88449 +  sqlite3IdListDelete(db, pUsing);
 1.88450 +  sqlite3SelectDelete(db, pSubquery);
 1.88451 +  return 0;
 1.88452 +}
 1.88453 +
 1.88454 +/*
 1.88455 +** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
 1.88456 +** element of the source-list passed as the second argument.
 1.88457 +*/
 1.88458 +SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
 1.88459 +  assert( pIndexedBy!=0 );
 1.88460 +  if( p && ALWAYS(p->nSrc>0) ){
 1.88461 +    struct SrcList_item *pItem = &p->a[p->nSrc-1];
 1.88462 +    assert( pItem->notIndexed==0 && pItem->zIndex==0 );
 1.88463 +    if( pIndexedBy->n==1 && !pIndexedBy->z ){
 1.88464 +      /* A "NOT INDEXED" clause was supplied. See parse.y 
 1.88465 +      ** construct "indexed_opt" for details. */
 1.88466 +      pItem->notIndexed = 1;
 1.88467 +    }else{
 1.88468 +      pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
 1.88469 +    }
 1.88470 +  }
 1.88471 +}
 1.88472 +
 1.88473 +/*
 1.88474 +** When building up a FROM clause in the parser, the join operator
 1.88475 +** is initially attached to the left operand.  But the code generator
 1.88476 +** expects the join operator to be on the right operand.  This routine
 1.88477 +** Shifts all join operators from left to right for an entire FROM
 1.88478 +** clause.
 1.88479 +**
 1.88480 +** Example: Suppose the join is like this:
 1.88481 +**
 1.88482 +**           A natural cross join B
 1.88483 +**
 1.88484 +** The operator is "natural cross join".  The A and B operands are stored
 1.88485 +** in p->a[0] and p->a[1], respectively.  The parser initially stores the
 1.88486 +** operator with A.  This routine shifts that operator over to B.
 1.88487 +*/
 1.88488 +SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
 1.88489 +  if( p ){
 1.88490 +    int i;
 1.88491 +    assert( p->a || p->nSrc==0 );
 1.88492 +    for(i=p->nSrc-1; i>0; i--){
 1.88493 +      p->a[i].jointype = p->a[i-1].jointype;
 1.88494 +    }
 1.88495 +    p->a[0].jointype = 0;
 1.88496 +  }
 1.88497 +}
 1.88498 +
 1.88499 +/*
 1.88500 +** Begin a transaction
 1.88501 +*/
 1.88502 +SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
 1.88503 +  sqlite3 *db;
 1.88504 +  Vdbe *v;
 1.88505 +  int i;
 1.88506 +
 1.88507 +  assert( pParse!=0 );
 1.88508 +  db = pParse->db;
 1.88509 +  assert( db!=0 );
 1.88510 +/*  if( db->aDb[0].pBt==0 ) return; */
 1.88511 +  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
 1.88512 +    return;
 1.88513 +  }
 1.88514 +  v = sqlite3GetVdbe(pParse);
 1.88515 +  if( !v ) return;
 1.88516 +  if( type!=TK_DEFERRED ){
 1.88517 +    for(i=0; i<db->nDb; i++){
 1.88518 +      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
 1.88519 +      sqlite3VdbeUsesBtree(v, i);
 1.88520 +    }
 1.88521 +  }
 1.88522 +  sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
 1.88523 +}
 1.88524 +
 1.88525 +/*
 1.88526 +** Commit a transaction
 1.88527 +*/
 1.88528 +SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
 1.88529 +  Vdbe *v;
 1.88530 +
 1.88531 +  assert( pParse!=0 );
 1.88532 +  assert( pParse->db!=0 );
 1.88533 +  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
 1.88534 +    return;
 1.88535 +  }
 1.88536 +  v = sqlite3GetVdbe(pParse);
 1.88537 +  if( v ){
 1.88538 +    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
 1.88539 +  }
 1.88540 +}
 1.88541 +
 1.88542 +/*
 1.88543 +** Rollback a transaction
 1.88544 +*/
 1.88545 +SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
 1.88546 +  Vdbe *v;
 1.88547 +
 1.88548 +  assert( pParse!=0 );
 1.88549 +  assert( pParse->db!=0 );
 1.88550 +  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
 1.88551 +    return;
 1.88552 +  }
 1.88553 +  v = sqlite3GetVdbe(pParse);
 1.88554 +  if( v ){
 1.88555 +    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
 1.88556 +  }
 1.88557 +}
 1.88558 +
 1.88559 +/*
 1.88560 +** This function is called by the parser when it parses a command to create,
 1.88561 +** release or rollback an SQL savepoint. 
 1.88562 +*/
 1.88563 +SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
 1.88564 +  char *zName = sqlite3NameFromToken(pParse->db, pName);
 1.88565 +  if( zName ){
 1.88566 +    Vdbe *v = sqlite3GetVdbe(pParse);
 1.88567 +#ifndef SQLITE_OMIT_AUTHORIZATION
 1.88568 +    static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
 1.88569 +    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
 1.88570 +#endif
 1.88571 +    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
 1.88572 +      sqlite3DbFree(pParse->db, zName);
 1.88573 +      return;
 1.88574 +    }
 1.88575 +    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
 1.88576 +  }
 1.88577 +}
 1.88578 +
 1.88579 +/*
 1.88580 +** Make sure the TEMP database is open and available for use.  Return
 1.88581 +** the number of errors.  Leave any error messages in the pParse structure.
 1.88582 +*/
 1.88583 +SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
 1.88584 +  sqlite3 *db = pParse->db;
 1.88585 +  if( db->aDb[1].pBt==0 && !pParse->explain ){
 1.88586 +    int rc;
 1.88587 +    Btree *pBt;
 1.88588 +    static const int flags = 
 1.88589 +          SQLITE_OPEN_READWRITE |
 1.88590 +          SQLITE_OPEN_CREATE |
 1.88591 +          SQLITE_OPEN_EXCLUSIVE |
 1.88592 +          SQLITE_OPEN_DELETEONCLOSE |
 1.88593 +          SQLITE_OPEN_TEMP_DB;
 1.88594 +
 1.88595 +    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
 1.88596 +    if( rc!=SQLITE_OK ){
 1.88597 +      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
 1.88598 +        "file for storing temporary tables");
 1.88599 +      pParse->rc = rc;
 1.88600 +      return 1;
 1.88601 +    }
 1.88602 +    db->aDb[1].pBt = pBt;
 1.88603 +    assert( db->aDb[1].pSchema );
 1.88604 +    if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
 1.88605 +      db->mallocFailed = 1;
 1.88606 +      return 1;
 1.88607 +    }
 1.88608 +  }
 1.88609 +  return 0;
 1.88610 +}
 1.88611 +
 1.88612 +/*
 1.88613 +** Record the fact that the schema cookie will need to be verified
 1.88614 +** for database iDb.  The code to actually verify the schema cookie
 1.88615 +** will occur at the end of the top-level VDBE and will be generated
 1.88616 +** later, by sqlite3FinishCoding().
 1.88617 +*/
 1.88618 +SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
 1.88619 +  Parse *pToplevel = sqlite3ParseToplevel(pParse);
 1.88620 +  sqlite3 *db = pToplevel->db;
 1.88621 +  yDbMask mask;
 1.88622 +
 1.88623 +  assert( iDb>=0 && iDb<db->nDb );
 1.88624 +  assert( db->aDb[iDb].pBt!=0 || iDb==1 );
 1.88625 +  assert( iDb<SQLITE_MAX_ATTACHED+2 );
 1.88626 +  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 1.88627 +  mask = ((yDbMask)1)<<iDb;
 1.88628 +  if( (pToplevel->cookieMask & mask)==0 ){
 1.88629 +    pToplevel->cookieMask |= mask;
 1.88630 +    pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
 1.88631 +    if( !OMIT_TEMPDB && iDb==1 ){
 1.88632 +      sqlite3OpenTempDatabase(pToplevel);
 1.88633 +    }
 1.88634 +  }
 1.88635 +}
 1.88636 +
 1.88637 +/*
 1.88638 +** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 
 1.88639 +** attached database. Otherwise, invoke it for the database named zDb only.
 1.88640 +*/
 1.88641 +SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
 1.88642 +  sqlite3 *db = pParse->db;
 1.88643 +  int i;
 1.88644 +  for(i=0; i<db->nDb; i++){
 1.88645 +    Db *pDb = &db->aDb[i];
 1.88646 +    if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
 1.88647 +      sqlite3CodeVerifySchema(pParse, i);
 1.88648 +    }
 1.88649 +  }
 1.88650 +}
 1.88651 +
 1.88652 +/*
 1.88653 +** Generate VDBE code that prepares for doing an operation that
 1.88654 +** might change the database.
 1.88655 +**
 1.88656 +** This routine starts a new transaction if we are not already within
 1.88657 +** a transaction.  If we are already within a transaction, then a checkpoint
 1.88658 +** is set if the setStatement parameter is true.  A checkpoint should
 1.88659 +** be set for operations that might fail (due to a constraint) part of
 1.88660 +** the way through and which will need to undo some writes without having to
 1.88661 +** rollback the whole transaction.  For operations where all constraints
 1.88662 +** can be checked before any changes are made to the database, it is never
 1.88663 +** necessary to undo a write and the checkpoint should not be set.
 1.88664 +*/
 1.88665 +SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
 1.88666 +  Parse *pToplevel = sqlite3ParseToplevel(pParse);
 1.88667 +  sqlite3CodeVerifySchema(pParse, iDb);
 1.88668 +  pToplevel->writeMask |= ((yDbMask)1)<<iDb;
 1.88669 +  pToplevel->isMultiWrite |= setStatement;
 1.88670 +}
 1.88671 +
 1.88672 +/*
 1.88673 +** Indicate that the statement currently under construction might write
 1.88674 +** more than one entry (example: deleting one row then inserting another,
 1.88675 +** inserting multiple rows in a table, or inserting a row and index entries.)
 1.88676 +** If an abort occurs after some of these writes have completed, then it will
 1.88677 +** be necessary to undo the completed writes.
 1.88678 +*/
 1.88679 +SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
 1.88680 +  Parse *pToplevel = sqlite3ParseToplevel(pParse);
 1.88681 +  pToplevel->isMultiWrite = 1;
 1.88682 +}
 1.88683 +
 1.88684 +/* 
 1.88685 +** The code generator calls this routine if is discovers that it is
 1.88686 +** possible to abort a statement prior to completion.  In order to 
 1.88687 +** perform this abort without corrupting the database, we need to make
 1.88688 +** sure that the statement is protected by a statement transaction.
 1.88689 +**
 1.88690 +** Technically, we only need to set the mayAbort flag if the
 1.88691 +** isMultiWrite flag was previously set.  There is a time dependency
 1.88692 +** such that the abort must occur after the multiwrite.  This makes
 1.88693 +** some statements involving the REPLACE conflict resolution algorithm
 1.88694 +** go a little faster.  But taking advantage of this time dependency
 1.88695 +** makes it more difficult to prove that the code is correct (in 
 1.88696 +** particular, it prevents us from writing an effective
 1.88697 +** implementation of sqlite3AssertMayAbort()) and so we have chosen
 1.88698 +** to take the safe route and skip the optimization.
 1.88699 +*/
 1.88700 +SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
 1.88701 +  Parse *pToplevel = sqlite3ParseToplevel(pParse);
 1.88702 +  pToplevel->mayAbort = 1;
 1.88703 +}
 1.88704 +
 1.88705 +/*
 1.88706 +** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
 1.88707 +** error. The onError parameter determines which (if any) of the statement
 1.88708 +** and/or current transaction is rolled back.
 1.88709 +*/
 1.88710 +SQLITE_PRIVATE void sqlite3HaltConstraint(
 1.88711 +  Parse *pParse,    /* Parsing context */
 1.88712 +  int errCode,      /* extended error code */
 1.88713 +  int onError,      /* Constraint type */
 1.88714 +  char *p4,         /* Error message */
 1.88715 +  i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
 1.88716 +  u8 p5Errmsg       /* P5_ErrMsg type */
 1.88717 +){
 1.88718 +  Vdbe *v = sqlite3GetVdbe(pParse);
 1.88719 +  assert( (errCode&0xff)==SQLITE_CONSTRAINT );
 1.88720 +  if( onError==OE_Abort ){
 1.88721 +    sqlite3MayAbort(pParse);
 1.88722 +  }
 1.88723 +  sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
 1.88724 +  if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
 1.88725 +}
 1.88726 +
 1.88727 +/*
 1.88728 +** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
 1.88729 +*/
 1.88730 +SQLITE_PRIVATE void sqlite3UniqueConstraint(
 1.88731 +  Parse *pParse,    /* Parsing context */
 1.88732 +  int onError,      /* Constraint type */
 1.88733 +  Index *pIdx       /* The index that triggers the constraint */
 1.88734 +){
 1.88735 +  char *zErr;
 1.88736 +  int j;
 1.88737 +  StrAccum errMsg;
 1.88738 +  Table *pTab = pIdx->pTable;
 1.88739 +
 1.88740 +  sqlite3StrAccumInit(&errMsg, 0, 0, 200);
 1.88741 +  errMsg.db = pParse->db;
 1.88742 +  for(j=0; j<pIdx->nKeyCol; j++){
 1.88743 +    char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
 1.88744 +    if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
 1.88745 +    sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
 1.88746 +    sqlite3StrAccumAppend(&errMsg, ".", 1);
 1.88747 +    sqlite3StrAccumAppendAll(&errMsg, zCol);
 1.88748 +  }
 1.88749 +  zErr = sqlite3StrAccumFinish(&errMsg);
 1.88750 +  sqlite3HaltConstraint(pParse, 
 1.88751 +    (pIdx->autoIndex==2)?SQLITE_CONSTRAINT_PRIMARYKEY:SQLITE_CONSTRAINT_UNIQUE,
 1.88752 +    onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
 1.88753 +}
 1.88754 +
 1.88755 +
 1.88756 +/*
 1.88757 +** Code an OP_Halt due to non-unique rowid.
 1.88758 +*/
 1.88759 +SQLITE_PRIVATE void sqlite3RowidConstraint(
 1.88760 +  Parse *pParse,    /* Parsing context */
 1.88761 +  int onError,      /* Conflict resolution algorithm */
 1.88762 +  Table *pTab       /* The table with the non-unique rowid */ 
 1.88763 +){
 1.88764 +  char *zMsg;
 1.88765 +  int rc;
 1.88766 +  if( pTab->iPKey>=0 ){
 1.88767 +    zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
 1.88768 +                          pTab->aCol[pTab->iPKey].zName);
 1.88769 +    rc = SQLITE_CONSTRAINT_PRIMARYKEY;
 1.88770 +  }else{
 1.88771 +    zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
 1.88772 +    rc = SQLITE_CONSTRAINT_ROWID;
 1.88773 +  }
 1.88774 +  sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
 1.88775 +                        P5_ConstraintUnique);
 1.88776 +}
 1.88777 +
 1.88778 +/*
 1.88779 +** Check to see if pIndex uses the collating sequence pColl.  Return
 1.88780 +** true if it does and false if it does not.
 1.88781 +*/
 1.88782 +#ifndef SQLITE_OMIT_REINDEX
 1.88783 +static int collationMatch(const char *zColl, Index *pIndex){
 1.88784 +  int i;
 1.88785 +  assert( zColl!=0 );
 1.88786 +  for(i=0; i<pIndex->nColumn; i++){
 1.88787 +    const char *z = pIndex->azColl[i];
 1.88788 +    assert( z!=0 || pIndex->aiColumn[i]<0 );
 1.88789 +    if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
 1.88790 +      return 1;
 1.88791 +    }
 1.88792 +  }
 1.88793 +  return 0;
 1.88794 +}
 1.88795 +#endif
 1.88796 +
 1.88797 +/*
 1.88798 +** Recompute all indices of pTab that use the collating sequence pColl.
 1.88799 +** If pColl==0 then recompute all indices of pTab.
 1.88800 +*/
 1.88801 +#ifndef SQLITE_OMIT_REINDEX
 1.88802 +static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
 1.88803 +  Index *pIndex;              /* An index associated with pTab */
 1.88804 +
 1.88805 +  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
 1.88806 +    if( zColl==0 || collationMatch(zColl, pIndex) ){
 1.88807 +      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
 1.88808 +      sqlite3BeginWriteOperation(pParse, 0, iDb);
 1.88809 +      sqlite3RefillIndex(pParse, pIndex, -1);
 1.88810 +    }
 1.88811 +  }
 1.88812 +}
 1.88813 +#endif
 1.88814 +
 1.88815 +/*
 1.88816 +** Recompute all indices of all tables in all databases where the
 1.88817 +** indices use the collating sequence pColl.  If pColl==0 then recompute
 1.88818 +** all indices everywhere.
 1.88819 +*/
 1.88820 +#ifndef SQLITE_OMIT_REINDEX
 1.88821 +static void reindexDatabases(Parse *pParse, char const *zColl){
 1.88822 +  Db *pDb;                    /* A single database */
 1.88823 +  int iDb;                    /* The database index number */
 1.88824 +  sqlite3 *db = pParse->db;   /* The database connection */
 1.88825 +  HashElem *k;                /* For looping over tables in pDb */
 1.88826 +  Table *pTab;                /* A table in the database */
 1.88827 +
 1.88828 +  assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
 1.88829 +  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
 1.88830 +    assert( pDb!=0 );
 1.88831 +    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
 1.88832 +      pTab = (Table*)sqliteHashData(k);
 1.88833 +      reindexTable(pParse, pTab, zColl);
 1.88834 +    }
 1.88835 +  }
 1.88836 +}
 1.88837 +#endif
 1.88838 +
 1.88839 +/*
 1.88840 +** Generate code for the REINDEX command.
 1.88841 +**
 1.88842 +**        REINDEX                            -- 1
 1.88843 +**        REINDEX  <collation>               -- 2
 1.88844 +**        REINDEX  ?<database>.?<tablename>  -- 3
 1.88845 +**        REINDEX  ?<database>.?<indexname>  -- 4
 1.88846 +**
 1.88847 +** Form 1 causes all indices in all attached databases to be rebuilt.
 1.88848 +** Form 2 rebuilds all indices in all databases that use the named
 1.88849 +** collating function.  Forms 3 and 4 rebuild the named index or all
 1.88850 +** indices associated with the named table.
 1.88851 +*/
 1.88852 +#ifndef SQLITE_OMIT_REINDEX
 1.88853 +SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
 1.88854 +  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
 1.88855 +  char *z;                    /* Name of a table or index */
 1.88856 +  const char *zDb;            /* Name of the database */
 1.88857 +  Table *pTab;                /* A table in the database */
 1.88858 +  Index *pIndex;              /* An index associated with pTab */
 1.88859 +  int iDb;                    /* The database index number */
 1.88860 +  sqlite3 *db = pParse->db;   /* The database connection */
 1.88861 +  Token *pObjName;            /* Name of the table or index to be reindexed */
 1.88862 +
 1.88863 +  /* Read the database schema. If an error occurs, leave an error message
 1.88864 +  ** and code in pParse and return NULL. */
 1.88865 +  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
 1.88866 +    return;
 1.88867 +  }
 1.88868 +
 1.88869 +  if( pName1==0 ){
 1.88870 +    reindexDatabases(pParse, 0);
 1.88871 +    return;
 1.88872 +  }else if( NEVER(pName2==0) || pName2->z==0 ){
 1.88873 +    char *zColl;
 1.88874 +    assert( pName1->z );
 1.88875 +    zColl = sqlite3NameFromToken(pParse->db, pName1);
 1.88876 +    if( !zColl ) return;
 1.88877 +    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
 1.88878 +    if( pColl ){
 1.88879 +      reindexDatabases(pParse, zColl);
 1.88880 +      sqlite3DbFree(db, zColl);
 1.88881 +      return;
 1.88882 +    }
 1.88883 +    sqlite3DbFree(db, zColl);
 1.88884 +  }
 1.88885 +  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
 1.88886 +  if( iDb<0 ) return;
 1.88887 +  z = sqlite3NameFromToken(db, pObjName);
 1.88888 +  if( z==0 ) return;
 1.88889 +  zDb = db->aDb[iDb].zName;
 1.88890 +  pTab = sqlite3FindTable(db, z, zDb);
 1.88891 +  if( pTab ){
 1.88892 +    reindexTable(pParse, pTab, 0);
 1.88893 +    sqlite3DbFree(db, z);
 1.88894 +    return;
 1.88895 +  }
 1.88896 +  pIndex = sqlite3FindIndex(db, z, zDb);
 1.88897 +  sqlite3DbFree(db, z);
 1.88898 +  if( pIndex ){
 1.88899 +    sqlite3BeginWriteOperation(pParse, 0, iDb);
 1.88900 +    sqlite3RefillIndex(pParse, pIndex, -1);
 1.88901 +    return;
 1.88902 +  }
 1.88903 +  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
 1.88904 +}
 1.88905 +#endif
 1.88906 +
 1.88907 +/*
 1.88908 +** Return a KeyInfo structure that is appropriate for the given Index.
 1.88909 +**
 1.88910 +** The KeyInfo structure for an index is cached in the Index object.
 1.88911 +** So there might be multiple references to the returned pointer.  The
 1.88912 +** caller should not try to modify the KeyInfo object.
 1.88913 +**
 1.88914 +** The caller should invoke sqlite3KeyInfoUnref() on the returned object
 1.88915 +** when it has finished using it.
 1.88916 +*/
 1.88917 +SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
 1.88918 +  if( pParse->nErr ) return 0;
 1.88919 +#ifndef SQLITE_OMIT_SHARED_CACHE
 1.88920 +  if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){
 1.88921 +    sqlite3KeyInfoUnref(pIdx->pKeyInfo);
 1.88922 +    pIdx->pKeyInfo = 0;
 1.88923 +  }
 1.88924 +#endif
 1.88925 +  if( pIdx->pKeyInfo==0 ){
 1.88926 +    int i;
 1.88927 +    int nCol = pIdx->nColumn;
 1.88928 +    int nKey = pIdx->nKeyCol;
 1.88929 +    KeyInfo *pKey;
 1.88930 +    if( pIdx->uniqNotNull ){
 1.88931 +      pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
 1.88932 +    }else{
 1.88933 +      pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
 1.88934 +    }
 1.88935 +    if( pKey ){
 1.88936 +      assert( sqlite3KeyInfoIsWriteable(pKey) );
 1.88937 +      for(i=0; i<nCol; i++){
 1.88938 +        char *zColl = pIdx->azColl[i];
 1.88939 +        assert( zColl!=0 );
 1.88940 +        pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
 1.88941 +                          sqlite3LocateCollSeq(pParse, zColl);
 1.88942 +        pKey->aSortOrder[i] = pIdx->aSortOrder[i];
 1.88943 +      }
 1.88944 +      if( pParse->nErr ){
 1.88945 +        sqlite3KeyInfoUnref(pKey);
 1.88946 +      }else{
 1.88947 +        pIdx->pKeyInfo = pKey;
 1.88948 +      }
 1.88949 +    }
 1.88950 +  }
 1.88951 +  return sqlite3KeyInfoRef(pIdx->pKeyInfo);
 1.88952 +}
 1.88953 +
 1.88954 +#ifndef SQLITE_OMIT_CTE
 1.88955 +/* 
 1.88956 +** This routine is invoked once per CTE by the parser while parsing a 
 1.88957 +** WITH clause. 
 1.88958 +*/
 1.88959 +SQLITE_PRIVATE With *sqlite3WithAdd(
 1.88960 +  Parse *pParse,          /* Parsing context */
 1.88961 +  With *pWith,            /* Existing WITH clause, or NULL */
 1.88962 +  Token *pName,           /* Name of the common-table */
 1.88963 +  ExprList *pArglist,     /* Optional column name list for the table */
 1.88964 +  Select *pQuery          /* Query used to initialize the table */
 1.88965 +){
 1.88966 +  sqlite3 *db = pParse->db;
 1.88967 +  With *pNew;
 1.88968 +  char *zName;
 1.88969 +
 1.88970 +  /* Check that the CTE name is unique within this WITH clause. If
 1.88971 +  ** not, store an error in the Parse structure. */
 1.88972 +  zName = sqlite3NameFromToken(pParse->db, pName);
 1.88973 +  if( zName && pWith ){
 1.88974 +    int i;
 1.88975 +    for(i=0; i<pWith->nCte; i++){
 1.88976 +      if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
 1.88977 +        sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
 1.88978 +      }
 1.88979 +    }
 1.88980 +  }
 1.88981 +
 1.88982 +  if( pWith ){
 1.88983 +    int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
 1.88984 +    pNew = sqlite3DbRealloc(db, pWith, nByte);
 1.88985 +  }else{
 1.88986 +    pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
 1.88987 +  }
 1.88988 +  assert( zName!=0 || pNew==0 );
 1.88989 +  assert( db->mallocFailed==0 || pNew==0 );
 1.88990 +
 1.88991 +  if( pNew==0 ){
 1.88992 +    sqlite3ExprListDelete(db, pArglist);
 1.88993 +    sqlite3SelectDelete(db, pQuery);
 1.88994 +    sqlite3DbFree(db, zName);
 1.88995 +    pNew = pWith;
 1.88996 +  }else{
 1.88997 +    pNew->a[pNew->nCte].pSelect = pQuery;
 1.88998 +    pNew->a[pNew->nCte].pCols = pArglist;
 1.88999 +    pNew->a[pNew->nCte].zName = zName;
 1.89000 +    pNew->a[pNew->nCte].zErr = 0;
 1.89001 +    pNew->nCte++;
 1.89002 +  }
 1.89003 +
 1.89004 +  return pNew;
 1.89005 +}
 1.89006 +
 1.89007 +/*
 1.89008 +** Free the contents of the With object passed as the second argument.
 1.89009 +*/
 1.89010 +SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
 1.89011 +  if( pWith ){
 1.89012 +    int i;
 1.89013 +    for(i=0; i<pWith->nCte; i++){
 1.89014 +      struct Cte *pCte = &pWith->a[i];
 1.89015 +      sqlite3ExprListDelete(db, pCte->pCols);
 1.89016 +      sqlite3SelectDelete(db, pCte->pSelect);
 1.89017 +      sqlite3DbFree(db, pCte->zName);
 1.89018 +    }
 1.89019 +    sqlite3DbFree(db, pWith);
 1.89020 +  }
 1.89021 +}
 1.89022 +#endif /* !defined(SQLITE_OMIT_CTE) */
 1.89023 +
 1.89024 +/************** End of build.c ***********************************************/
 1.89025 +/************** Begin file callback.c ****************************************/
 1.89026 +/*
 1.89027 +** 2005 May 23 
 1.89028 +**
 1.89029 +** The author disclaims copyright to this source code.  In place of
 1.89030 +** a legal notice, here is a blessing:
 1.89031 +**
 1.89032 +**    May you do good and not evil.
 1.89033 +**    May you find forgiveness for yourself and forgive others.
 1.89034 +**    May you share freely, never taking more than you give.
 1.89035 +**
 1.89036 +*************************************************************************
 1.89037 +**
 1.89038 +** This file contains functions used to access the internal hash tables
 1.89039 +** of user defined functions and collation sequences.
 1.89040 +*/
 1.89041 +
 1.89042 +
 1.89043 +/*
 1.89044 +** Invoke the 'collation needed' callback to request a collation sequence
 1.89045 +** in the encoding enc of name zName, length nName.
 1.89046 +*/
 1.89047 +static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
 1.89048 +  assert( !db->xCollNeeded || !db->xCollNeeded16 );
 1.89049 +  if( db->xCollNeeded ){
 1.89050 +    char *zExternal = sqlite3DbStrDup(db, zName);
 1.89051 +    if( !zExternal ) return;
 1.89052 +    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
 1.89053 +    sqlite3DbFree(db, zExternal);
 1.89054 +  }
 1.89055 +#ifndef SQLITE_OMIT_UTF16
 1.89056 +  if( db->xCollNeeded16 ){
 1.89057 +    char const *zExternal;
 1.89058 +    sqlite3_value *pTmp = sqlite3ValueNew(db);
 1.89059 +    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
 1.89060 +    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
 1.89061 +    if( zExternal ){
 1.89062 +      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
 1.89063 +    }
 1.89064 +    sqlite3ValueFree(pTmp);
 1.89065 +  }
 1.89066 +#endif
 1.89067 +}
 1.89068 +
 1.89069 +/*
 1.89070 +** This routine is called if the collation factory fails to deliver a
 1.89071 +** collation function in the best encoding but there may be other versions
 1.89072 +** of this collation function (for other text encodings) available. Use one
 1.89073 +** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
 1.89074 +** possible.
 1.89075 +*/
 1.89076 +static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
 1.89077 +  CollSeq *pColl2;
 1.89078 +  char *z = pColl->zName;
 1.89079 +  int i;
 1.89080 +  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
 1.89081 +  for(i=0; i<3; i++){
 1.89082 +    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
 1.89083 +    if( pColl2->xCmp!=0 ){
 1.89084 +      memcpy(pColl, pColl2, sizeof(CollSeq));
 1.89085 +      pColl->xDel = 0;         /* Do not copy the destructor */
 1.89086 +      return SQLITE_OK;
 1.89087 +    }
 1.89088 +  }
 1.89089 +  return SQLITE_ERROR;
 1.89090 +}
 1.89091 +
 1.89092 +/*
 1.89093 +** This function is responsible for invoking the collation factory callback
 1.89094 +** or substituting a collation sequence of a different encoding when the
 1.89095 +** requested collation sequence is not available in the desired encoding.
 1.89096 +** 
 1.89097 +** If it is not NULL, then pColl must point to the database native encoding 
 1.89098 +** collation sequence with name zName, length nName.
 1.89099 +**
 1.89100 +** The return value is either the collation sequence to be used in database
 1.89101 +** db for collation type name zName, length nName, or NULL, if no collation
 1.89102 +** sequence can be found.  If no collation is found, leave an error message.
 1.89103 +**
 1.89104 +** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
 1.89105 +*/
 1.89106 +SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
 1.89107 +  Parse *pParse,        /* Parsing context */
 1.89108 +  u8 enc,               /* The desired encoding for the collating sequence */
 1.89109 +  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
 1.89110 +  const char *zName     /* Collating sequence name */
 1.89111 +){
 1.89112 +  CollSeq *p;
 1.89113 +  sqlite3 *db = pParse->db;
 1.89114 +
 1.89115 +  p = pColl;
 1.89116 +  if( !p ){
 1.89117 +    p = sqlite3FindCollSeq(db, enc, zName, 0);
 1.89118 +  }
 1.89119 +  if( !p || !p->xCmp ){
 1.89120 +    /* No collation sequence of this type for this encoding is registered.
 1.89121 +    ** Call the collation factory to see if it can supply us with one.
 1.89122 +    */
 1.89123 +    callCollNeeded(db, enc, zName);
 1.89124 +    p = sqlite3FindCollSeq(db, enc, zName, 0);
 1.89125 +  }
 1.89126 +  if( p && !p->xCmp && synthCollSeq(db, p) ){
 1.89127 +    p = 0;
 1.89128 +  }
 1.89129 +  assert( !p || p->xCmp );
 1.89130 +  if( p==0 ){
 1.89131 +    sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
 1.89132 +  }
 1.89133 +  return p;
 1.89134 +}
 1.89135 +
 1.89136 +/*
 1.89137 +** This routine is called on a collation sequence before it is used to
 1.89138 +** check that it is defined. An undefined collation sequence exists when
 1.89139 +** a database is loaded that contains references to collation sequences
 1.89140 +** that have not been defined by sqlite3_create_collation() etc.
 1.89141 +**
 1.89142 +** If required, this routine calls the 'collation needed' callback to
 1.89143 +** request a definition of the collating sequence. If this doesn't work, 
 1.89144 +** an equivalent collating sequence that uses a text encoding different
 1.89145 +** from the main database is substituted, if one is available.
 1.89146 +*/
 1.89147 +SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
 1.89148 +  if( pColl ){
 1.89149 +    const char *zName = pColl->zName;
 1.89150 +    sqlite3 *db = pParse->db;
 1.89151 +    CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
 1.89152 +    if( !p ){
 1.89153 +      return SQLITE_ERROR;
 1.89154 +    }
 1.89155 +    assert( p==pColl );
 1.89156 +  }
 1.89157 +  return SQLITE_OK;
 1.89158 +}
 1.89159 +
 1.89160 +
 1.89161 +
 1.89162 +/*
 1.89163 +** Locate and return an entry from the db.aCollSeq hash table. If the entry
 1.89164 +** specified by zName and nName is not found and parameter 'create' is
 1.89165 +** true, then create a new entry. Otherwise return NULL.
 1.89166 +**
 1.89167 +** Each pointer stored in the sqlite3.aCollSeq hash table contains an
 1.89168 +** array of three CollSeq structures. The first is the collation sequence
 1.89169 +** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
 1.89170 +**
 1.89171 +** Stored immediately after the three collation sequences is a copy of
 1.89172 +** the collation sequence name. A pointer to this string is stored in
 1.89173 +** each collation sequence structure.
 1.89174 +*/
 1.89175 +static CollSeq *findCollSeqEntry(
 1.89176 +  sqlite3 *db,          /* Database connection */
 1.89177 +  const char *zName,    /* Name of the collating sequence */
 1.89178 +  int create            /* Create a new entry if true */
 1.89179 +){
 1.89180 +  CollSeq *pColl;
 1.89181 +  int nName = sqlite3Strlen30(zName);
 1.89182 +  pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
 1.89183 +
 1.89184 +  if( 0==pColl && create ){
 1.89185 +    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
 1.89186 +    if( pColl ){
 1.89187 +      CollSeq *pDel = 0;
 1.89188 +      pColl[0].zName = (char*)&pColl[3];
 1.89189 +      pColl[0].enc = SQLITE_UTF8;
 1.89190 +      pColl[1].zName = (char*)&pColl[3];
 1.89191 +      pColl[1].enc = SQLITE_UTF16LE;
 1.89192 +      pColl[2].zName = (char*)&pColl[3];
 1.89193 +      pColl[2].enc = SQLITE_UTF16BE;
 1.89194 +      memcpy(pColl[0].zName, zName, nName);
 1.89195 +      pColl[0].zName[nName] = 0;
 1.89196 +      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
 1.89197 +
 1.89198 +      /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
 1.89199 +      ** return the pColl pointer to be deleted (because it wasn't added
 1.89200 +      ** to the hash table).
 1.89201 +      */
 1.89202 +      assert( pDel==0 || pDel==pColl );
 1.89203 +      if( pDel!=0 ){
 1.89204 +        db->mallocFailed = 1;
 1.89205 +        sqlite3DbFree(db, pDel);
 1.89206 +        pColl = 0;
 1.89207 +      }
 1.89208 +    }
 1.89209 +  }
 1.89210 +  return pColl;
 1.89211 +}
 1.89212 +
 1.89213 +/*
 1.89214 +** Parameter zName points to a UTF-8 encoded string nName bytes long.
 1.89215 +** Return the CollSeq* pointer for the collation sequence named zName
 1.89216 +** for the encoding 'enc' from the database 'db'.
 1.89217 +**
 1.89218 +** If the entry specified is not found and 'create' is true, then create a
 1.89219 +** new entry.  Otherwise return NULL.
 1.89220 +**
 1.89221 +** A separate function sqlite3LocateCollSeq() is a wrapper around
 1.89222 +** this routine.  sqlite3LocateCollSeq() invokes the collation factory
 1.89223 +** if necessary and generates an error message if the collating sequence
 1.89224 +** cannot be found.
 1.89225 +**
 1.89226 +** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
 1.89227 +*/
 1.89228 +SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
 1.89229 +  sqlite3 *db,
 1.89230 +  u8 enc,
 1.89231 +  const char *zName,
 1.89232 +  int create
 1.89233 +){
 1.89234 +  CollSeq *pColl;
 1.89235 +  if( zName ){
 1.89236 +    pColl = findCollSeqEntry(db, zName, create);
 1.89237 +  }else{
 1.89238 +    pColl = db->pDfltColl;
 1.89239 +  }
 1.89240 +  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
 1.89241 +  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
 1.89242 +  if( pColl ) pColl += enc-1;
 1.89243 +  return pColl;
 1.89244 +}
 1.89245 +
 1.89246 +/* During the search for the best function definition, this procedure
 1.89247 +** is called to test how well the function passed as the first argument
 1.89248 +** matches the request for a function with nArg arguments in a system
 1.89249 +** that uses encoding enc. The value returned indicates how well the
 1.89250 +** request is matched. A higher value indicates a better match.
 1.89251 +**
 1.89252 +** If nArg is -1 that means to only return a match (non-zero) if p->nArg
 1.89253 +** is also -1.  In other words, we are searching for a function that
 1.89254 +** takes a variable number of arguments.
 1.89255 +**
 1.89256 +** If nArg is -2 that means that we are searching for any function 
 1.89257 +** regardless of the number of arguments it uses, so return a positive
 1.89258 +** match score for any
 1.89259 +**
 1.89260 +** The returned value is always between 0 and 6, as follows:
 1.89261 +**
 1.89262 +** 0: Not a match.
 1.89263 +** 1: UTF8/16 conversion required and function takes any number of arguments.
 1.89264 +** 2: UTF16 byte order change required and function takes any number of args.
 1.89265 +** 3: encoding matches and function takes any number of arguments
 1.89266 +** 4: UTF8/16 conversion required - argument count matches exactly
 1.89267 +** 5: UTF16 byte order conversion required - argument count matches exactly
 1.89268 +** 6: Perfect match:  encoding and argument count match exactly.
 1.89269 +**
 1.89270 +** If nArg==(-2) then any function with a non-null xStep or xFunc is
 1.89271 +** a perfect match and any function with both xStep and xFunc NULL is
 1.89272 +** a non-match.
 1.89273 +*/
 1.89274 +#define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
 1.89275 +static int matchQuality(
 1.89276 +  FuncDef *p,     /* The function we are evaluating for match quality */
 1.89277 +  int nArg,       /* Desired number of arguments.  (-1)==any */
 1.89278 +  u8 enc          /* Desired text encoding */
 1.89279 +){
 1.89280 +  int match;
 1.89281 +
 1.89282 +  /* nArg of -2 is a special case */
 1.89283 +  if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
 1.89284 +
 1.89285 +  /* Wrong number of arguments means "no match" */
 1.89286 +  if( p->nArg!=nArg && p->nArg>=0 ) return 0;
 1.89287 +
 1.89288 +  /* Give a better score to a function with a specific number of arguments
 1.89289 +  ** than to function that accepts any number of arguments. */
 1.89290 +  if( p->nArg==nArg ){
 1.89291 +    match = 4;
 1.89292 +  }else{
 1.89293 +    match = 1;
 1.89294 +  }
 1.89295 +
 1.89296 +  /* Bonus points if the text encoding matches */
 1.89297 +  if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
 1.89298 +    match += 2;  /* Exact encoding match */
 1.89299 +  }else if( (enc & p->funcFlags & 2)!=0 ){
 1.89300 +    match += 1;  /* Both are UTF16, but with different byte orders */
 1.89301 +  }
 1.89302 +
 1.89303 +  return match;
 1.89304 +}
 1.89305 +
 1.89306 +/*
 1.89307 +** Search a FuncDefHash for a function with the given name.  Return
 1.89308 +** a pointer to the matching FuncDef if found, or 0 if there is no match.
 1.89309 +*/
 1.89310 +static FuncDef *functionSearch(
 1.89311 +  FuncDefHash *pHash,  /* Hash table to search */
 1.89312 +  int h,               /* Hash of the name */
 1.89313 +  const char *zFunc,   /* Name of function */
 1.89314 +  int nFunc            /* Number of bytes in zFunc */
 1.89315 +){
 1.89316 +  FuncDef *p;
 1.89317 +  for(p=pHash->a[h]; p; p=p->pHash){
 1.89318 +    if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
 1.89319 +      return p;
 1.89320 +    }
 1.89321 +  }
 1.89322 +  return 0;
 1.89323 +}
 1.89324 +
 1.89325 +/*
 1.89326 +** Insert a new FuncDef into a FuncDefHash hash table.
 1.89327 +*/
 1.89328 +SQLITE_PRIVATE void sqlite3FuncDefInsert(
 1.89329 +  FuncDefHash *pHash,  /* The hash table into which to insert */
 1.89330 +  FuncDef *pDef        /* The function definition to insert */
 1.89331 +){
 1.89332 +  FuncDef *pOther;
 1.89333 +  int nName = sqlite3Strlen30(pDef->zName);
 1.89334 +  u8 c1 = (u8)pDef->zName[0];
 1.89335 +  int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
 1.89336 +  pOther = functionSearch(pHash, h, pDef->zName, nName);
 1.89337 +  if( pOther ){
 1.89338 +    assert( pOther!=pDef && pOther->pNext!=pDef );
 1.89339 +    pDef->pNext = pOther->pNext;
 1.89340 +    pOther->pNext = pDef;
 1.89341 +  }else{
 1.89342 +    pDef->pNext = 0;
 1.89343 +    pDef->pHash = pHash->a[h];
 1.89344 +    pHash->a[h] = pDef;
 1.89345 +  }
 1.89346 +}
 1.89347 +  
 1.89348 +  
 1.89349 +
 1.89350 +/*
 1.89351 +** Locate a user function given a name, a number of arguments and a flag
 1.89352 +** indicating whether the function prefers UTF-16 over UTF-8.  Return a
 1.89353 +** pointer to the FuncDef structure that defines that function, or return
 1.89354 +** NULL if the function does not exist.
 1.89355 +**
 1.89356 +** If the createFlag argument is true, then a new (blank) FuncDef
 1.89357 +** structure is created and liked into the "db" structure if a
 1.89358 +** no matching function previously existed.
 1.89359 +**
 1.89360 +** If nArg is -2, then the first valid function found is returned.  A
 1.89361 +** function is valid if either xFunc or xStep is non-zero.  The nArg==(-2)
 1.89362 +** case is used to see if zName is a valid function name for some number
 1.89363 +** of arguments.  If nArg is -2, then createFlag must be 0.
 1.89364 +**
 1.89365 +** If createFlag is false, then a function with the required name and
 1.89366 +** number of arguments may be returned even if the eTextRep flag does not
 1.89367 +** match that requested.
 1.89368 +*/
 1.89369 +SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
 1.89370 +  sqlite3 *db,       /* An open database */
 1.89371 +  const char *zName, /* Name of the function.  Not null-terminated */
 1.89372 +  int nName,         /* Number of characters in the name */
 1.89373 +  int nArg,          /* Number of arguments.  -1 means any number */
 1.89374 +  u8 enc,            /* Preferred text encoding */
 1.89375 +  u8 createFlag      /* Create new entry if true and does not otherwise exist */
 1.89376 +){
 1.89377 +  FuncDef *p;         /* Iterator variable */
 1.89378 +  FuncDef *pBest = 0; /* Best match found so far */
 1.89379 +  int bestScore = 0;  /* Score of best match */
 1.89380 +  int h;              /* Hash value */
 1.89381 +
 1.89382 +  assert( nArg>=(-2) );
 1.89383 +  assert( nArg>=(-1) || createFlag==0 );
 1.89384 +  h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
 1.89385 +
 1.89386 +  /* First search for a match amongst the application-defined functions.
 1.89387 +  */
 1.89388 +  p = functionSearch(&db->aFunc, h, zName, nName);
 1.89389 +  while( p ){
 1.89390 +    int score = matchQuality(p, nArg, enc);
 1.89391 +    if( score>bestScore ){
 1.89392 +      pBest = p;
 1.89393 +      bestScore = score;
 1.89394 +    }
 1.89395 +    p = p->pNext;
 1.89396 +  }
 1.89397 +
 1.89398 +  /* If no match is found, search the built-in functions.
 1.89399 +  **
 1.89400 +  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
 1.89401 +  ** functions even if a prior app-defined function was found.  And give
 1.89402 +  ** priority to built-in functions.
 1.89403 +  **
 1.89404 +  ** Except, if createFlag is true, that means that we are trying to
 1.89405 +  ** install a new function.  Whatever FuncDef structure is returned it will
 1.89406 +  ** have fields overwritten with new information appropriate for the
 1.89407 +  ** new function.  But the FuncDefs for built-in functions are read-only.
 1.89408 +  ** So we must not search for built-ins when creating a new function.
 1.89409 +  */ 
 1.89410 +  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
 1.89411 +    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
 1.89412 +    bestScore = 0;
 1.89413 +    p = functionSearch(pHash, h, zName, nName);
 1.89414 +    while( p ){
 1.89415 +      int score = matchQuality(p, nArg, enc);
 1.89416 +      if( score>bestScore ){
 1.89417 +        pBest = p;
 1.89418 +        bestScore = score;
 1.89419 +      }
 1.89420 +      p = p->pNext;
 1.89421 +    }
 1.89422 +  }
 1.89423 +
 1.89424 +  /* If the createFlag parameter is true and the search did not reveal an
 1.89425 +  ** exact match for the name, number of arguments and encoding, then add a
 1.89426 +  ** new entry to the hash table and return it.
 1.89427 +  */
 1.89428 +  if( createFlag && bestScore<FUNC_PERFECT_MATCH && 
 1.89429 +      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
 1.89430 +    pBest->zName = (char *)&pBest[1];
 1.89431 +    pBest->nArg = (u16)nArg;
 1.89432 +    pBest->funcFlags = enc;
 1.89433 +    memcpy(pBest->zName, zName, nName);
 1.89434 +    pBest->zName[nName] = 0;
 1.89435 +    sqlite3FuncDefInsert(&db->aFunc, pBest);
 1.89436 +  }
 1.89437 +
 1.89438 +  if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
 1.89439 +    return pBest;
 1.89440 +  }
 1.89441 +  return 0;
 1.89442 +}
 1.89443 +
 1.89444 +/*
 1.89445 +** Free all resources held by the schema structure. The void* argument points
 1.89446 +** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
 1.89447 +** pointer itself, it just cleans up subsidiary resources (i.e. the contents
 1.89448 +** of the schema hash tables).
 1.89449 +**
 1.89450 +** The Schema.cache_size variable is not cleared.
 1.89451 +*/
 1.89452 +SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
 1.89453 +  Hash temp1;
 1.89454 +  Hash temp2;
 1.89455 +  HashElem *pElem;
 1.89456 +  Schema *pSchema = (Schema *)p;
 1.89457 +
 1.89458 +  temp1 = pSchema->tblHash;
 1.89459 +  temp2 = pSchema->trigHash;
 1.89460 +  sqlite3HashInit(&pSchema->trigHash);
 1.89461 +  sqlite3HashClear(&pSchema->idxHash);
 1.89462 +  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
 1.89463 +    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
 1.89464 +  }
 1.89465 +  sqlite3HashClear(&temp2);
 1.89466 +  sqlite3HashInit(&pSchema->tblHash);
 1.89467 +  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
 1.89468 +    Table *pTab = sqliteHashData(pElem);
 1.89469 +    sqlite3DeleteTable(0, pTab);
 1.89470 +  }
 1.89471 +  sqlite3HashClear(&temp1);
 1.89472 +  sqlite3HashClear(&pSchema->fkeyHash);
 1.89473 +  pSchema->pSeqTab = 0;
 1.89474 +  if( pSchema->flags & DB_SchemaLoaded ){
 1.89475 +    pSchema->iGeneration++;
 1.89476 +    pSchema->flags &= ~DB_SchemaLoaded;
 1.89477 +  }
 1.89478 +}
 1.89479 +
 1.89480 +/*
 1.89481 +** Find and return the schema associated with a BTree.  Create
 1.89482 +** a new one if necessary.
 1.89483 +*/
 1.89484 +SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
 1.89485 +  Schema * p;
 1.89486 +  if( pBt ){
 1.89487 +    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
 1.89488 +  }else{
 1.89489 +    p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
 1.89490 +  }
 1.89491 +  if( !p ){
 1.89492 +    db->mallocFailed = 1;
 1.89493 +  }else if ( 0==p->file_format ){
 1.89494 +    sqlite3HashInit(&p->tblHash);
 1.89495 +    sqlite3HashInit(&p->idxHash);
 1.89496 +    sqlite3HashInit(&p->trigHash);
 1.89497 +    sqlite3HashInit(&p->fkeyHash);
 1.89498 +    p->enc = SQLITE_UTF8;
 1.89499 +  }
 1.89500 +  return p;
 1.89501 +}
 1.89502 +
 1.89503 +/************** End of callback.c ********************************************/
 1.89504 +/************** Begin file delete.c ******************************************/
 1.89505 +/*
 1.89506 +** 2001 September 15
 1.89507 +**
 1.89508 +** The author disclaims copyright to this source code.  In place of
 1.89509 +** a legal notice, here is a blessing:
 1.89510 +**
 1.89511 +**    May you do good and not evil.
 1.89512 +**    May you find forgiveness for yourself and forgive others.
 1.89513 +**    May you share freely, never taking more than you give.
 1.89514 +**
 1.89515 +*************************************************************************
 1.89516 +** This file contains C code routines that are called by the parser
 1.89517 +** in order to generate code for DELETE FROM statements.
 1.89518 +*/
 1.89519 +
 1.89520 +/*
 1.89521 +** While a SrcList can in general represent multiple tables and subqueries
 1.89522 +** (as in the FROM clause of a SELECT statement) in this case it contains
 1.89523 +** the name of a single table, as one might find in an INSERT, DELETE,
 1.89524 +** or UPDATE statement.  Look up that table in the symbol table and
 1.89525 +** return a pointer.  Set an error message and return NULL if the table 
 1.89526 +** name is not found or if any other error occurs.
 1.89527 +**
 1.89528 +** The following fields are initialized appropriate in pSrc:
 1.89529 +**
 1.89530 +**    pSrc->a[0].pTab       Pointer to the Table object
 1.89531 +**    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
 1.89532 +**
 1.89533 +*/
 1.89534 +SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
 1.89535 +  struct SrcList_item *pItem = pSrc->a;
 1.89536 +  Table *pTab;
 1.89537 +  assert( pItem && pSrc->nSrc==1 );
 1.89538 +  pTab = sqlite3LocateTableItem(pParse, 0, pItem);
 1.89539 +  sqlite3DeleteTable(pParse->db, pItem->pTab);
 1.89540 +  pItem->pTab = pTab;
 1.89541 +  if( pTab ){
 1.89542 +    pTab->nRef++;
 1.89543 +  }
 1.89544 +  if( sqlite3IndexedByLookup(pParse, pItem) ){
 1.89545 +    pTab = 0;
 1.89546 +  }
 1.89547 +  return pTab;
 1.89548 +}
 1.89549 +
 1.89550 +/*
 1.89551 +** Check to make sure the given table is writable.  If it is not
 1.89552 +** writable, generate an error message and return 1.  If it is
 1.89553 +** writable return 0;
 1.89554 +*/
 1.89555 +SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
 1.89556 +  /* A table is not writable under the following circumstances:
 1.89557 +  **
 1.89558 +  **   1) It is a virtual table and no implementation of the xUpdate method
 1.89559 +  **      has been provided, or
 1.89560 +  **   2) It is a system table (i.e. sqlite_master), this call is not
 1.89561 +  **      part of a nested parse and writable_schema pragma has not 
 1.89562 +  **      been specified.
 1.89563 +  **
 1.89564 +  ** In either case leave an error message in pParse and return non-zero.
 1.89565 +  */
 1.89566 +  if( ( IsVirtual(pTab) 
 1.89567 +     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
 1.89568 +   || ( (pTab->tabFlags & TF_Readonly)!=0
 1.89569 +     && (pParse->db->flags & SQLITE_WriteSchema)==0
 1.89570 +     && pParse->nested==0 )
 1.89571 +  ){
 1.89572 +    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
 1.89573 +    return 1;
 1.89574 +  }
 1.89575 +
 1.89576 +#ifndef SQLITE_OMIT_VIEW
 1.89577 +  if( !viewOk && pTab->pSelect ){
 1.89578 +    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
 1.89579 +    return 1;
 1.89580 +  }
 1.89581 +#endif
 1.89582 +  return 0;
 1.89583 +}
 1.89584 +
 1.89585 +
 1.89586 +#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
 1.89587 +/*
 1.89588 +** Evaluate a view and store its result in an ephemeral table.  The
 1.89589 +** pWhere argument is an optional WHERE clause that restricts the
 1.89590 +** set of rows in the view that are to be added to the ephemeral table.
 1.89591 +*/
 1.89592 +SQLITE_PRIVATE void sqlite3MaterializeView(
 1.89593 +  Parse *pParse,       /* Parsing context */
 1.89594 +  Table *pView,        /* View definition */
 1.89595 +  Expr *pWhere,        /* Optional WHERE clause to be added */
 1.89596 +  int iCur             /* Cursor number for ephemerial table */
 1.89597 +){
 1.89598 +  SelectDest dest;
 1.89599 +  Select *pSel;
 1.89600 +  SrcList *pFrom;
 1.89601 +  sqlite3 *db = pParse->db;
 1.89602 +  int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
 1.89603 +  pWhere = sqlite3ExprDup(db, pWhere, 0);
 1.89604 +  pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
 1.89605 +  if( pFrom ){
 1.89606 +    assert( pFrom->nSrc==1 );
 1.89607 +    pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
 1.89608 +    pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
 1.89609 +    assert( pFrom->a[0].pOn==0 );
 1.89610 +    assert( pFrom->a[0].pUsing==0 );
 1.89611 +  }
 1.89612 +  pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
 1.89613 +  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
 1.89614 +  sqlite3Select(pParse, pSel, &dest);
 1.89615 +  sqlite3SelectDelete(db, pSel);
 1.89616 +}
 1.89617 +#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
 1.89618 +
 1.89619 +#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
 1.89620 +/*
 1.89621 +** Generate an expression tree to implement the WHERE, ORDER BY,
 1.89622 +** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
 1.89623 +**
 1.89624 +**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
 1.89625 +**                            \__________________________/
 1.89626 +**                               pLimitWhere (pInClause)
 1.89627 +*/
 1.89628 +SQLITE_PRIVATE Expr *sqlite3LimitWhere(
 1.89629 +  Parse *pParse,               /* The parser context */
 1.89630 +  SrcList *pSrc,               /* the FROM clause -- which tables to scan */
 1.89631 +  Expr *pWhere,                /* The WHERE clause.  May be null */
 1.89632 +  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
 1.89633 +  Expr *pLimit,                /* The LIMIT clause.  May be null */
 1.89634 +  Expr *pOffset,               /* The OFFSET clause.  May be null */
 1.89635 +  char *zStmtType              /* Either DELETE or UPDATE.  For err msgs. */
 1.89636 +){
 1.89637 +  Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
 1.89638 +  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
 1.89639 +  Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
 1.89640 +  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
 1.89641 +  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
 1.89642 +  Select *pSelect = NULL;      /* Complete SELECT tree */
 1.89643 +
 1.89644 +  /* Check that there isn't an ORDER BY without a LIMIT clause.
 1.89645 +  */
 1.89646 +  if( pOrderBy && (pLimit == 0) ) {
 1.89647 +    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
 1.89648 +    goto limit_where_cleanup_2;
 1.89649 +  }
 1.89650 +
 1.89651 +  /* We only need to generate a select expression if there
 1.89652 +  ** is a limit/offset term to enforce.
 1.89653 +  */
 1.89654 +  if( pLimit == 0 ) {
 1.89655 +    /* if pLimit is null, pOffset will always be null as well. */
 1.89656 +    assert( pOffset == 0 );
 1.89657 +    return pWhere;
 1.89658 +  }
 1.89659 +
 1.89660 +  /* Generate a select expression tree to enforce the limit/offset 
 1.89661 +  ** term for the DELETE or UPDATE statement.  For example:
 1.89662 +  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
 1.89663 +  ** becomes:
 1.89664 +  **   DELETE FROM table_a WHERE rowid IN ( 
 1.89665 +  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
 1.89666 +  **   );
 1.89667 +  */
 1.89668 +
 1.89669 +  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
 1.89670 +  if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
 1.89671 +  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
 1.89672 +  if( pEList == 0 ) goto limit_where_cleanup_2;
 1.89673 +
 1.89674 +  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
 1.89675 +  ** and the SELECT subtree. */
 1.89676 +  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
 1.89677 +  if( pSelectSrc == 0 ) {
 1.89678 +    sqlite3ExprListDelete(pParse->db, pEList);
 1.89679 +    goto limit_where_cleanup_2;
 1.89680 +  }
 1.89681 +
 1.89682 +  /* generate the SELECT expression tree. */
 1.89683 +  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
 1.89684 +                             pOrderBy,0,pLimit,pOffset);
 1.89685 +  if( pSelect == 0 ) return 0;
 1.89686 +
 1.89687 +  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
 1.89688 +  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
 1.89689 +  if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
 1.89690 +  pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
 1.89691 +  if( pInClause == 0 ) goto limit_where_cleanup_1;
 1.89692 +
 1.89693 +  pInClause->x.pSelect = pSelect;
 1.89694 +  pInClause->flags |= EP_xIsSelect;
 1.89695 +  sqlite3ExprSetHeight(pParse, pInClause);
 1.89696 +  return pInClause;
 1.89697 +
 1.89698 +  /* something went wrong. clean up anything allocated. */
 1.89699 +limit_where_cleanup_1:
 1.89700 +  sqlite3SelectDelete(pParse->db, pSelect);
 1.89701 +  return 0;
 1.89702 +
 1.89703 +limit_where_cleanup_2:
 1.89704 +  sqlite3ExprDelete(pParse->db, pWhere);
 1.89705 +  sqlite3ExprListDelete(pParse->db, pOrderBy);
 1.89706 +  sqlite3ExprDelete(pParse->db, pLimit);
 1.89707 +  sqlite3ExprDelete(pParse->db, pOffset);
 1.89708 +  return 0;
 1.89709 +}
 1.89710 +#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
 1.89711 +       /*      && !defined(SQLITE_OMIT_SUBQUERY) */
 1.89712 +
 1.89713 +/*
 1.89714 +** Generate code for a DELETE FROM statement.
 1.89715 +**
 1.89716 +**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
 1.89717 +**                 \________/       \________________/
 1.89718 +**                  pTabList              pWhere
 1.89719 +*/
 1.89720 +SQLITE_PRIVATE void sqlite3DeleteFrom(
 1.89721 +  Parse *pParse,         /* The parser context */
 1.89722 +  SrcList *pTabList,     /* The table from which we should delete things */
 1.89723 +  Expr *pWhere           /* The WHERE clause.  May be null */
 1.89724 +){
 1.89725 +  Vdbe *v;               /* The virtual database engine */
 1.89726 +  Table *pTab;           /* The table from which records will be deleted */
 1.89727 +  const char *zDb;       /* Name of database holding pTab */
 1.89728 +  int i;                 /* Loop counter */
 1.89729 +  WhereInfo *pWInfo;     /* Information about the WHERE clause */
 1.89730 +  Index *pIdx;           /* For looping over indices of the table */
 1.89731 +  int iTabCur;           /* Cursor number for the table */
 1.89732 +  int iDataCur;          /* VDBE cursor for the canonical data source */
 1.89733 +  int iIdxCur;           /* Cursor number of the first index */
 1.89734 +  int nIdx;              /* Number of indices */
 1.89735 +  sqlite3 *db;           /* Main database structure */
 1.89736 +  AuthContext sContext;  /* Authorization context */
 1.89737 +  NameContext sNC;       /* Name context to resolve expressions in */
 1.89738 +  int iDb;               /* Database number */
 1.89739 +  int memCnt = -1;       /* Memory cell used for change counting */
 1.89740 +  int rcauth;            /* Value returned by authorization callback */
 1.89741 +  int okOnePass;         /* True for one-pass algorithm without the FIFO */
 1.89742 +  int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
 1.89743 +  u8 *aToOpen = 0;       /* Open cursor iTabCur+j if aToOpen[j] is true */
 1.89744 +  Index *pPk;            /* The PRIMARY KEY index on the table */
 1.89745 +  int iPk = 0;           /* First of nPk registers holding PRIMARY KEY value */
 1.89746 +  i16 nPk = 1;           /* Number of columns in the PRIMARY KEY */
 1.89747 +  int iKey;              /* Memory cell holding key of row to be deleted */
 1.89748 +  i16 nKey;              /* Number of memory cells in the row key */
 1.89749 +  int iEphCur = 0;       /* Ephemeral table holding all primary key values */
 1.89750 +  int iRowSet = 0;       /* Register for rowset of rows to delete */
 1.89751 +  int addrBypass = 0;    /* Address of jump over the delete logic */
 1.89752 +  int addrLoop = 0;      /* Top of the delete loop */
 1.89753 +  int addrDelete = 0;    /* Jump directly to the delete logic */
 1.89754 +  int addrEphOpen = 0;   /* Instruction to open the Ephermeral table */
 1.89755 + 
 1.89756 +#ifndef SQLITE_OMIT_TRIGGER
 1.89757 +  int isView;                  /* True if attempting to delete from a view */
 1.89758 +  Trigger *pTrigger;           /* List of table triggers, if required */
 1.89759 +#endif
 1.89760 +
 1.89761 +  memset(&sContext, 0, sizeof(sContext));
 1.89762 +  db = pParse->db;
 1.89763 +  if( pParse->nErr || db->mallocFailed ){
 1.89764 +    goto delete_from_cleanup;
 1.89765 +  }
 1.89766 +  assert( pTabList->nSrc==1 );
 1.89767 +
 1.89768 +  /* Locate the table which we want to delete.  This table has to be
 1.89769 +  ** put in an SrcList structure because some of the subroutines we
 1.89770 +  ** will be calling are designed to work with multiple tables and expect
 1.89771 +  ** an SrcList* parameter instead of just a Table* parameter.
 1.89772 +  */
 1.89773 +  pTab = sqlite3SrcListLookup(pParse, pTabList);
 1.89774 +  if( pTab==0 )  goto delete_from_cleanup;
 1.89775 +
 1.89776 +  /* Figure out if we have any triggers and if the table being
 1.89777 +  ** deleted from is a view
 1.89778 +  */
 1.89779 +#ifndef SQLITE_OMIT_TRIGGER
 1.89780 +  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
 1.89781 +  isView = pTab->pSelect!=0;
 1.89782 +#else
 1.89783 +# define pTrigger 0
 1.89784 +# define isView 0
 1.89785 +#endif
 1.89786 +#ifdef SQLITE_OMIT_VIEW
 1.89787 +# undef isView
 1.89788 +# define isView 0
 1.89789 +#endif
 1.89790 +
 1.89791 +  /* If pTab is really a view, make sure it has been initialized.
 1.89792 +  */
 1.89793 +  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
 1.89794 +    goto delete_from_cleanup;
 1.89795 +  }
 1.89796 +
 1.89797 +  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
 1.89798 +    goto delete_from_cleanup;
 1.89799 +  }
 1.89800 +  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
 1.89801 +  assert( iDb<db->nDb );
 1.89802 +  zDb = db->aDb[iDb].zName;
 1.89803 +  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
 1.89804 +  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
 1.89805 +  if( rcauth==SQLITE_DENY ){
 1.89806 +    goto delete_from_cleanup;
 1.89807 +  }
 1.89808 +  assert(!isView || pTrigger);
 1.89809 +
 1.89810 +  /* Assign cursor numbers to the table and all its indices.
 1.89811 +  */
 1.89812 +  assert( pTabList->nSrc==1 );
 1.89813 +  iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
 1.89814 +  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
 1.89815 +    pParse->nTab++;
 1.89816 +  }
 1.89817 +
 1.89818 +  /* Start the view context
 1.89819 +  */
 1.89820 +  if( isView ){
 1.89821 +    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
 1.89822 +  }
 1.89823 +
 1.89824 +  /* Begin generating code.
 1.89825 +  */
 1.89826 +  v = sqlite3GetVdbe(pParse);
 1.89827 +  if( v==0 ){
 1.89828 +    goto delete_from_cleanup;
 1.89829 +  }
 1.89830 +  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
 1.89831 +  sqlite3BeginWriteOperation(pParse, 1, iDb);
 1.89832 +
 1.89833 +  /* If we are trying to delete from a view, realize that view into
 1.89834 +  ** a ephemeral table.
 1.89835 +  */
 1.89836 +#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
 1.89837 +  if( isView ){
 1.89838 +    sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
 1.89839 +    iDataCur = iIdxCur = iTabCur;
 1.89840 +  }
 1.89841 +#endif
 1.89842 +
 1.89843 +  /* Resolve the column names in the WHERE clause.
 1.89844 +  */
 1.89845 +  memset(&sNC, 0, sizeof(sNC));
 1.89846 +  sNC.pParse = pParse;
 1.89847 +  sNC.pSrcList = pTabList;
 1.89848 +  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
 1.89849 +    goto delete_from_cleanup;
 1.89850 +  }
 1.89851 +
 1.89852 +  /* Initialize the counter of the number of rows deleted, if
 1.89853 +  ** we are counting rows.
 1.89854 +  */
 1.89855 +  if( db->flags & SQLITE_CountRows ){
 1.89856 +    memCnt = ++pParse->nMem;
 1.89857 +    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
 1.89858 +  }
 1.89859 +
 1.89860 +#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
 1.89861 +  /* Special case: A DELETE without a WHERE clause deletes everything.
 1.89862 +  ** It is easier just to erase the whole table. Prior to version 3.6.5,
 1.89863 +  ** this optimization caused the row change count (the value returned by 
 1.89864 +  ** API function sqlite3_count_changes) to be set incorrectly.  */
 1.89865 +  if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
 1.89866 +   && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
 1.89867 +  ){
 1.89868 +    assert( !isView );
 1.89869 +    sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
 1.89870 +    if( HasRowid(pTab) ){
 1.89871 +      sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
 1.89872 +                        pTab->zName, P4_STATIC);
 1.89873 +    }
 1.89874 +    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
 1.89875 +      assert( pIdx->pSchema==pTab->pSchema );
 1.89876 +      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
 1.89877 +    }
 1.89878 +  }else
 1.89879 +#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
 1.89880 +  {
 1.89881 +    if( HasRowid(pTab) ){
 1.89882 +      /* For a rowid table, initialize the RowSet to an empty set */
 1.89883 +      pPk = 0;
 1.89884 +      nPk = 1;
 1.89885 +      iRowSet = ++pParse->nMem;
 1.89886 +      sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
 1.89887 +    }else{
 1.89888 +      /* For a WITHOUT ROWID table, create an ephermeral table used to
 1.89889 +      ** hold all primary keys for rows to be deleted. */
 1.89890 +      pPk = sqlite3PrimaryKeyIndex(pTab);
 1.89891 +      assert( pPk!=0 );
 1.89892 +      nPk = pPk->nKeyCol;
 1.89893 +      iPk = pParse->nMem+1;
 1.89894 +      pParse->nMem += nPk;
 1.89895 +      iEphCur = pParse->nTab++;
 1.89896 +      addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
 1.89897 +      sqlite3VdbeSetP4KeyInfo(pParse, pPk);
 1.89898 +    }
 1.89899 +  
 1.89900 +    /* Construct a query to find the rowid or primary key for every row
 1.89901 +    ** to be deleted, based on the WHERE clause.
 1.89902 +    */
 1.89903 +    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, 
 1.89904 +                               WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK,
 1.89905 +                               iTabCur+1);
 1.89906 +    if( pWInfo==0 ) goto delete_from_cleanup;
 1.89907 +    okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
 1.89908 +  
 1.89909 +    /* Keep track of the number of rows to be deleted */
 1.89910 +    if( db->flags & SQLITE_CountRows ){
 1.89911 +      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
 1.89912 +    }
 1.89913 +  
 1.89914 +    /* Extract the rowid or primary key for the current row */
 1.89915 +    if( pPk ){
 1.89916 +      for(i=0; i<nPk; i++){
 1.89917 +        sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
 1.89918 +                                        pPk->aiColumn[i], iPk+i);
 1.89919 +      }
 1.89920 +      iKey = iPk;
 1.89921 +    }else{
 1.89922 +      iKey = pParse->nMem + 1;
 1.89923 +      iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
 1.89924 +      if( iKey>pParse->nMem ) pParse->nMem = iKey;
 1.89925 +    }
 1.89926 +  
 1.89927 +    if( okOnePass ){
 1.89928 +      /* For ONEPASS, no need to store the rowid/primary-key.  There is only
 1.89929 +      ** one, so just keep it in its register(s) and fall through to the
 1.89930 +      ** delete code.
 1.89931 +      */
 1.89932 +      nKey = nPk; /* OP_Found will use an unpacked key */
 1.89933 +      aToOpen = sqlite3DbMallocRaw(db, nIdx+2);
 1.89934 +      if( aToOpen==0 ){
 1.89935 +        sqlite3WhereEnd(pWInfo);
 1.89936 +        goto delete_from_cleanup;
 1.89937 +      }
 1.89938 +      memset(aToOpen, 1, nIdx+1);
 1.89939 +      aToOpen[nIdx+1] = 0;
 1.89940 +      if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
 1.89941 +      if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
 1.89942 +      if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
 1.89943 +      addrDelete = sqlite3VdbeAddOp0(v, OP_Goto); /* Jump to DELETE logic */
 1.89944 +    }else if( pPk ){
 1.89945 +      /* Construct a composite key for the row to be deleted and remember it */
 1.89946 +      iKey = ++pParse->nMem;
 1.89947 +      nKey = 0;   /* Zero tells OP_Found to use a composite key */
 1.89948 +      sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
 1.89949 +                        sqlite3IndexAffinityStr(v, pPk), nPk);
 1.89950 +      sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
 1.89951 +    }else{
 1.89952 +      /* Get the rowid of the row to be deleted and remember it in the RowSet */
 1.89953 +      nKey = 1;  /* OP_Seek always uses a single rowid */
 1.89954 +      sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
 1.89955 +    }
 1.89956 +  
 1.89957 +    /* End of the WHERE loop */
 1.89958 +    sqlite3WhereEnd(pWInfo);
 1.89959 +    if( okOnePass ){
 1.89960 +      /* Bypass the delete logic below if the WHERE loop found zero rows */
 1.89961 +      addrBypass = sqlite3VdbeMakeLabel(v);
 1.89962 +      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBypass);
 1.89963 +      sqlite3VdbeJumpHere(v, addrDelete);
 1.89964 +    }
 1.89965 +  
 1.89966 +    /* Unless this is a view, open cursors for the table we are 
 1.89967 +    ** deleting from and all its indices. If this is a view, then the
 1.89968 +    ** only effect this statement has is to fire the INSTEAD OF 
 1.89969 +    ** triggers.
 1.89970 +    */
 1.89971 +    if( !isView ){
 1.89972 +      sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iTabCur, aToOpen,
 1.89973 +                                 &iDataCur, &iIdxCur);
 1.89974 +      assert( pPk || iDataCur==iTabCur );
 1.89975 +      assert( pPk || iIdxCur==iDataCur+1 );
 1.89976 +    }
 1.89977 +  
 1.89978 +    /* Set up a loop over the rowids/primary-keys that were found in the
 1.89979 +    ** where-clause loop above.
 1.89980 +    */
 1.89981 +    if( okOnePass ){
 1.89982 +      /* Just one row.  Hence the top-of-loop is a no-op */
 1.89983 +      assert( nKey==nPk ); /* OP_Found will use an unpacked key */
 1.89984 +      if( aToOpen[iDataCur-iTabCur] ){
 1.89985 +        assert( pPk!=0 );
 1.89986 +        sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
 1.89987 +        VdbeCoverage(v);
 1.89988 +      }
 1.89989 +    }else if( pPk ){
 1.89990 +      addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
 1.89991 +      sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
 1.89992 +      assert( nKey==0 );  /* OP_Found will use a composite key */
 1.89993 +    }else{
 1.89994 +      addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
 1.89995 +      VdbeCoverage(v);
 1.89996 +      assert( nKey==1 );
 1.89997 +    }  
 1.89998 +  
 1.89999 +    /* Delete the row */
 1.90000 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.90001 +    if( IsVirtual(pTab) ){
 1.90002 +      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
 1.90003 +      sqlite3VtabMakeWritable(pParse, pTab);
 1.90004 +      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
 1.90005 +      sqlite3VdbeChangeP5(v, OE_Abort);
 1.90006 +      sqlite3MayAbort(pParse);
 1.90007 +    }else
 1.90008 +#endif
 1.90009 +    {
 1.90010 +      int count = (pParse->nested==0);    /* True to count changes */
 1.90011 +      sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
 1.90012 +                               iKey, nKey, count, OE_Default, okOnePass);
 1.90013 +    }
 1.90014 +  
 1.90015 +    /* End of the loop over all rowids/primary-keys. */
 1.90016 +    if( okOnePass ){
 1.90017 +      sqlite3VdbeResolveLabel(v, addrBypass);
 1.90018 +    }else if( pPk ){
 1.90019 +      sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
 1.90020 +      sqlite3VdbeJumpHere(v, addrLoop);
 1.90021 +    }else{
 1.90022 +      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrLoop);
 1.90023 +      sqlite3VdbeJumpHere(v, addrLoop);
 1.90024 +    }     
 1.90025 +  
 1.90026 +    /* Close the cursors open on the table and its indexes. */
 1.90027 +    if( !isView && !IsVirtual(pTab) ){
 1.90028 +      if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
 1.90029 +      for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
 1.90030 +        sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
 1.90031 +      }
 1.90032 +    }
 1.90033 +  } /* End non-truncate path */
 1.90034 +
 1.90035 +  /* Update the sqlite_sequence table by storing the content of the
 1.90036 +  ** maximum rowid counter values recorded while inserting into
 1.90037 +  ** autoincrement tables.
 1.90038 +  */
 1.90039 +  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
 1.90040 +    sqlite3AutoincrementEnd(pParse);
 1.90041 +  }
 1.90042 +
 1.90043 +  /* Return the number of rows that were deleted. If this routine is 
 1.90044 +  ** generating code because of a call to sqlite3NestedParse(), do not
 1.90045 +  ** invoke the callback function.
 1.90046 +  */
 1.90047 +  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
 1.90048 +    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
 1.90049 +    sqlite3VdbeSetNumCols(v, 1);
 1.90050 +    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
 1.90051 +  }
 1.90052 +
 1.90053 +delete_from_cleanup:
 1.90054 +  sqlite3AuthContextPop(&sContext);
 1.90055 +  sqlite3SrcListDelete(db, pTabList);
 1.90056 +  sqlite3ExprDelete(db, pWhere);
 1.90057 +  sqlite3DbFree(db, aToOpen);
 1.90058 +  return;
 1.90059 +}
 1.90060 +/* Make sure "isView" and other macros defined above are undefined. Otherwise
 1.90061 +** thely may interfere with compilation of other functions in this file
 1.90062 +** (or in another file, if this file becomes part of the amalgamation).  */
 1.90063 +#ifdef isView
 1.90064 + #undef isView
 1.90065 +#endif
 1.90066 +#ifdef pTrigger
 1.90067 + #undef pTrigger
 1.90068 +#endif
 1.90069 +
 1.90070 +/*
 1.90071 +** This routine generates VDBE code that causes a single row of a
 1.90072 +** single table to be deleted.  Both the original table entry and
 1.90073 +** all indices are removed.
 1.90074 +**
 1.90075 +** Preconditions:
 1.90076 +**
 1.90077 +**   1.  iDataCur is an open cursor on the btree that is the canonical data
 1.90078 +**       store for the table.  (This will be either the table itself,
 1.90079 +**       in the case of a rowid table, or the PRIMARY KEY index in the case
 1.90080 +**       of a WITHOUT ROWID table.)
 1.90081 +**
 1.90082 +**   2.  Read/write cursors for all indices of pTab must be open as
 1.90083 +**       cursor number iIdxCur+i for the i-th index.
 1.90084 +**
 1.90085 +**   3.  The primary key for the row to be deleted must be stored in a
 1.90086 +**       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
 1.90087 +**       that a search record formed from OP_MakeRecord is contained in the
 1.90088 +**       single memory location iPk.
 1.90089 +*/
 1.90090 +SQLITE_PRIVATE void sqlite3GenerateRowDelete(
 1.90091 +  Parse *pParse,     /* Parsing context */
 1.90092 +  Table *pTab,       /* Table containing the row to be deleted */
 1.90093 +  Trigger *pTrigger, /* List of triggers to (potentially) fire */
 1.90094 +  int iDataCur,      /* Cursor from which column data is extracted */
 1.90095 +  int iIdxCur,       /* First index cursor */
 1.90096 +  int iPk,           /* First memory cell containing the PRIMARY KEY */
 1.90097 +  i16 nPk,           /* Number of PRIMARY KEY memory cells */
 1.90098 +  u8 count,          /* If non-zero, increment the row change counter */
 1.90099 +  u8 onconf,         /* Default ON CONFLICT policy for triggers */
 1.90100 +  u8 bNoSeek         /* iDataCur is already pointing to the row to delete */
 1.90101 +){
 1.90102 +  Vdbe *v = pParse->pVdbe;        /* Vdbe */
 1.90103 +  int iOld = 0;                   /* First register in OLD.* array */
 1.90104 +  int iLabel;                     /* Label resolved to end of generated code */
 1.90105 +  u8 opSeek;                      /* Seek opcode */
 1.90106 +
 1.90107 +  /* Vdbe is guaranteed to have been allocated by this stage. */
 1.90108 +  assert( v );
 1.90109 +  VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
 1.90110 +                         iDataCur, iIdxCur, iPk, (int)nPk));
 1.90111 +
 1.90112 +  /* Seek cursor iCur to the row to delete. If this row no longer exists 
 1.90113 +  ** (this can happen if a trigger program has already deleted it), do
 1.90114 +  ** not attempt to delete it or fire any DELETE triggers.  */
 1.90115 +  iLabel = sqlite3VdbeMakeLabel(v);
 1.90116 +  opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
 1.90117 +  if( !bNoSeek ){
 1.90118 +    sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
 1.90119 +    VdbeCoverageIf(v, opSeek==OP_NotExists);
 1.90120 +    VdbeCoverageIf(v, opSeek==OP_NotFound);
 1.90121 +  }
 1.90122 + 
 1.90123 +  /* If there are any triggers to fire, allocate a range of registers to
 1.90124 +  ** use for the old.* references in the triggers.  */
 1.90125 +  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
 1.90126 +    u32 mask;                     /* Mask of OLD.* columns in use */
 1.90127 +    int iCol;                     /* Iterator used while populating OLD.* */
 1.90128 +    int addrStart;                /* Start of BEFORE trigger programs */
 1.90129 +
 1.90130 +    /* TODO: Could use temporary registers here. Also could attempt to
 1.90131 +    ** avoid copying the contents of the rowid register.  */
 1.90132 +    mask = sqlite3TriggerColmask(
 1.90133 +        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
 1.90134 +    );
 1.90135 +    mask |= sqlite3FkOldmask(pParse, pTab);
 1.90136 +    iOld = pParse->nMem+1;
 1.90137 +    pParse->nMem += (1 + pTab->nCol);
 1.90138 +
 1.90139 +    /* Populate the OLD.* pseudo-table register array. These values will be 
 1.90140 +    ** used by any BEFORE and AFTER triggers that exist.  */
 1.90141 +    sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
 1.90142 +    for(iCol=0; iCol<pTab->nCol; iCol++){
 1.90143 +      testcase( mask!=0xffffffff && iCol==31 );
 1.90144 +      testcase( mask!=0xffffffff && iCol==32 );
 1.90145 +      if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
 1.90146 +        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
 1.90147 +      }
 1.90148 +    }
 1.90149 +
 1.90150 +    /* Invoke BEFORE DELETE trigger programs. */
 1.90151 +    addrStart = sqlite3VdbeCurrentAddr(v);
 1.90152 +    sqlite3CodeRowTrigger(pParse, pTrigger, 
 1.90153 +        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
 1.90154 +    );
 1.90155 +
 1.90156 +    /* If any BEFORE triggers were coded, then seek the cursor to the 
 1.90157 +    ** row to be deleted again. It may be that the BEFORE triggers moved
 1.90158 +    ** the cursor or of already deleted the row that the cursor was
 1.90159 +    ** pointing to.
 1.90160 +    */
 1.90161 +    if( addrStart<sqlite3VdbeCurrentAddr(v) ){
 1.90162 +      sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
 1.90163 +      VdbeCoverageIf(v, opSeek==OP_NotExists);
 1.90164 +      VdbeCoverageIf(v, opSeek==OP_NotFound);
 1.90165 +    }
 1.90166 +
 1.90167 +    /* Do FK processing. This call checks that any FK constraints that
 1.90168 +    ** refer to this table (i.e. constraints attached to other tables) 
 1.90169 +    ** are not violated by deleting this row.  */
 1.90170 +    sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
 1.90171 +  }
 1.90172 +
 1.90173 +  /* Delete the index and table entries. Skip this step if pTab is really
 1.90174 +  ** a view (in which case the only effect of the DELETE statement is to
 1.90175 +  ** fire the INSTEAD OF triggers).  */ 
 1.90176 +  if( pTab->pSelect==0 ){
 1.90177 +    sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
 1.90178 +    sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
 1.90179 +    if( count ){
 1.90180 +      sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
 1.90181 +    }
 1.90182 +  }
 1.90183 +
 1.90184 +  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
 1.90185 +  ** handle rows (possibly in other tables) that refer via a foreign key
 1.90186 +  ** to the row just deleted. */ 
 1.90187 +  sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
 1.90188 +
 1.90189 +  /* Invoke AFTER DELETE trigger programs. */
 1.90190 +  sqlite3CodeRowTrigger(pParse, pTrigger, 
 1.90191 +      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
 1.90192 +  );
 1.90193 +
 1.90194 +  /* Jump here if the row had already been deleted before any BEFORE
 1.90195 +  ** trigger programs were invoked. Or if a trigger program throws a 
 1.90196 +  ** RAISE(IGNORE) exception.  */
 1.90197 +  sqlite3VdbeResolveLabel(v, iLabel);
 1.90198 +  VdbeModuleComment((v, "END: GenRowDel()"));
 1.90199 +}
 1.90200 +
 1.90201 +/*
 1.90202 +** This routine generates VDBE code that causes the deletion of all
 1.90203 +** index entries associated with a single row of a single table, pTab
 1.90204 +**
 1.90205 +** Preconditions:
 1.90206 +**
 1.90207 +**   1.  A read/write cursor "iDataCur" must be open on the canonical storage
 1.90208 +**       btree for the table pTab.  (This will be either the table itself
 1.90209 +**       for rowid tables or to the primary key index for WITHOUT ROWID
 1.90210 +**       tables.)
 1.90211 +**
 1.90212 +**   2.  Read/write cursors for all indices of pTab must be open as
 1.90213 +**       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
 1.90214 +**       index is the 0-th index.)
 1.90215 +**
 1.90216 +**   3.  The "iDataCur" cursor must be already be positioned on the row
 1.90217 +**       that is to be deleted.
 1.90218 +*/
 1.90219 +SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
 1.90220 +  Parse *pParse,     /* Parsing and code generating context */
 1.90221 +  Table *pTab,       /* Table containing the row to be deleted */
 1.90222 +  int iDataCur,      /* Cursor of table holding data. */
 1.90223 +  int iIdxCur,       /* First index cursor */
 1.90224 +  int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
 1.90225 +){
 1.90226 +  int i;             /* Index loop counter */
 1.90227 +  int r1 = -1;       /* Register holding an index key */
 1.90228 +  int iPartIdxLabel; /* Jump destination for skipping partial index entries */
 1.90229 +  Index *pIdx;       /* Current index */
 1.90230 +  Index *pPrior = 0; /* Prior index */
 1.90231 +  Vdbe *v;           /* The prepared statement under construction */
 1.90232 +  Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
 1.90233 +
 1.90234 +  v = pParse->pVdbe;
 1.90235 +  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
 1.90236 +  for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
 1.90237 +    assert( iIdxCur+i!=iDataCur || pPk==pIdx );
 1.90238 +    if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
 1.90239 +    if( pIdx==pPk ) continue;
 1.90240 +    VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
 1.90241 +    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
 1.90242 +                                 &iPartIdxLabel, pPrior, r1);
 1.90243 +    sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
 1.90244 +                      pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
 1.90245 +    sqlite3VdbeResolveLabel(v, iPartIdxLabel);
 1.90246 +    pPrior = pIdx;
 1.90247 +  }
 1.90248 +}
 1.90249 +
 1.90250 +/*
 1.90251 +** Generate code that will assemble an index key and stores it in register
 1.90252 +** regOut.  The key with be for index pIdx which is an index on pTab.
 1.90253 +** iCur is the index of a cursor open on the pTab table and pointing to
 1.90254 +** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
 1.90255 +** iCur must be the cursor of the PRIMARY KEY index.
 1.90256 +**
 1.90257 +** Return a register number which is the first in a block of
 1.90258 +** registers that holds the elements of the index key.  The
 1.90259 +** block of registers has already been deallocated by the time
 1.90260 +** this routine returns.
 1.90261 +**
 1.90262 +** If *piPartIdxLabel is not NULL, fill it in with a label and jump
 1.90263 +** to that label if pIdx is a partial index that should be skipped.
 1.90264 +** A partial index should be skipped if its WHERE clause evaluates
 1.90265 +** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
 1.90266 +** will be set to zero which is an empty label that is ignored by
 1.90267 +** sqlite3VdbeResolveLabel().
 1.90268 +**
 1.90269 +** The pPrior and regPrior parameters are used to implement a cache to
 1.90270 +** avoid unnecessary register loads.  If pPrior is not NULL, then it is
 1.90271 +** a pointer to a different index for which an index key has just been
 1.90272 +** computed into register regPrior.  If the current pIdx index is generating
 1.90273 +** its key into the same sequence of registers and if pPrior and pIdx share
 1.90274 +** a column in common, then the register corresponding to that column already
 1.90275 +** holds the correct value and the loading of that register is skipped.
 1.90276 +** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK 
 1.90277 +** on a table with multiple indices, and especially with the ROWID or
 1.90278 +** PRIMARY KEY columns of the index.
 1.90279 +*/
 1.90280 +SQLITE_PRIVATE int sqlite3GenerateIndexKey(
 1.90281 +  Parse *pParse,       /* Parsing context */
 1.90282 +  Index *pIdx,         /* The index for which to generate a key */
 1.90283 +  int iDataCur,        /* Cursor number from which to take column data */
 1.90284 +  int regOut,          /* Put the new key into this register if not 0 */
 1.90285 +  int prefixOnly,      /* Compute only a unique prefix of the key */
 1.90286 +  int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
 1.90287 +  Index *pPrior,       /* Previously generated index key */
 1.90288 +  int regPrior         /* Register holding previous generated key */
 1.90289 +){
 1.90290 +  Vdbe *v = pParse->pVdbe;
 1.90291 +  int j;
 1.90292 +  Table *pTab = pIdx->pTable;
 1.90293 +  int regBase;
 1.90294 +  int nCol;
 1.90295 +
 1.90296 +  if( piPartIdxLabel ){
 1.90297 +    if( pIdx->pPartIdxWhere ){
 1.90298 +      *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
 1.90299 +      pParse->iPartIdxTab = iDataCur;
 1.90300 +      sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel, 
 1.90301 +                         SQLITE_JUMPIFNULL);
 1.90302 +    }else{
 1.90303 +      *piPartIdxLabel = 0;
 1.90304 +    }
 1.90305 +  }
 1.90306 +  nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
 1.90307 +  regBase = sqlite3GetTempRange(pParse, nCol);
 1.90308 +  if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
 1.90309 +  for(j=0; j<nCol; j++){
 1.90310 +    if( pPrior && pPrior->aiColumn[j]==pIdx->aiColumn[j] ) continue;
 1.90311 +    sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pIdx->aiColumn[j],
 1.90312 +                                    regBase+j);
 1.90313 +    /* If the column affinity is REAL but the number is an integer, then it
 1.90314 +    ** might be stored in the table as an integer (using a compact
 1.90315 +    ** representation) then converted to REAL by an OP_RealAffinity opcode.
 1.90316 +    ** But we are getting ready to store this value back into an index, where
 1.90317 +    ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity
 1.90318 +    ** opcode if it is present */
 1.90319 +    sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
 1.90320 +  }
 1.90321 +  if( regOut ){
 1.90322 +    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
 1.90323 +  }
 1.90324 +  sqlite3ReleaseTempRange(pParse, regBase, nCol);
 1.90325 +  return regBase;
 1.90326 +}
 1.90327 +
 1.90328 +/************** End of delete.c **********************************************/
 1.90329 +/************** Begin file func.c ********************************************/
 1.90330 +/*
 1.90331 +** 2002 February 23
 1.90332 +**
 1.90333 +** The author disclaims copyright to this source code.  In place of
 1.90334 +** a legal notice, here is a blessing:
 1.90335 +**
 1.90336 +**    May you do good and not evil.
 1.90337 +**    May you find forgiveness for yourself and forgive others.
 1.90338 +**    May you share freely, never taking more than you give.
 1.90339 +**
 1.90340 +*************************************************************************
 1.90341 +** This file contains the C functions that implement various SQL
 1.90342 +** functions of SQLite.  
 1.90343 +**
 1.90344 +** There is only one exported symbol in this file - the function
 1.90345 +** sqliteRegisterBuildinFunctions() found at the bottom of the file.
 1.90346 +** All other code has file scope.
 1.90347 +*/
 1.90348 +/* #include <stdlib.h> */
 1.90349 +/* #include <assert.h> */
 1.90350 +
 1.90351 +/*
 1.90352 +** Return the collating function associated with a function.
 1.90353 +*/
 1.90354 +static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
 1.90355 +  return context->pColl;
 1.90356 +}
 1.90357 +
 1.90358 +/*
 1.90359 +** Indicate that the accumulator load should be skipped on this
 1.90360 +** iteration of the aggregate loop.
 1.90361 +*/
 1.90362 +static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
 1.90363 +  context->skipFlag = 1;
 1.90364 +}
 1.90365 +
 1.90366 +/*
 1.90367 +** Implementation of the non-aggregate min() and max() functions
 1.90368 +*/
 1.90369 +static void minmaxFunc(
 1.90370 +  sqlite3_context *context,
 1.90371 +  int argc,
 1.90372 +  sqlite3_value **argv
 1.90373 +){
 1.90374 +  int i;
 1.90375 +  int mask;    /* 0 for min() or 0xffffffff for max() */
 1.90376 +  int iBest;
 1.90377 +  CollSeq *pColl;
 1.90378 +
 1.90379 +  assert( argc>1 );
 1.90380 +  mask = sqlite3_user_data(context)==0 ? 0 : -1;
 1.90381 +  pColl = sqlite3GetFuncCollSeq(context);
 1.90382 +  assert( pColl );
 1.90383 +  assert( mask==-1 || mask==0 );
 1.90384 +  iBest = 0;
 1.90385 +  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
 1.90386 +  for(i=1; i<argc; i++){
 1.90387 +    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
 1.90388 +    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
 1.90389 +      testcase( mask==0 );
 1.90390 +      iBest = i;
 1.90391 +    }
 1.90392 +  }
 1.90393 +  sqlite3_result_value(context, argv[iBest]);
 1.90394 +}
 1.90395 +
 1.90396 +/*
 1.90397 +** Return the type of the argument.
 1.90398 +*/
 1.90399 +static void typeofFunc(
 1.90400 +  sqlite3_context *context,
 1.90401 +  int NotUsed,
 1.90402 +  sqlite3_value **argv
 1.90403 +){
 1.90404 +  const char *z = 0;
 1.90405 +  UNUSED_PARAMETER(NotUsed);
 1.90406 +  switch( sqlite3_value_type(argv[0]) ){
 1.90407 +    case SQLITE_INTEGER: z = "integer"; break;
 1.90408 +    case SQLITE_TEXT:    z = "text";    break;
 1.90409 +    case SQLITE_FLOAT:   z = "real";    break;
 1.90410 +    case SQLITE_BLOB:    z = "blob";    break;
 1.90411 +    default:             z = "null";    break;
 1.90412 +  }
 1.90413 +  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
 1.90414 +}
 1.90415 +
 1.90416 +
 1.90417 +/*
 1.90418 +** Implementation of the length() function
 1.90419 +*/
 1.90420 +static void lengthFunc(
 1.90421 +  sqlite3_context *context,
 1.90422 +  int argc,
 1.90423 +  sqlite3_value **argv
 1.90424 +){
 1.90425 +  int len;
 1.90426 +
 1.90427 +  assert( argc==1 );
 1.90428 +  UNUSED_PARAMETER(argc);
 1.90429 +  switch( sqlite3_value_type(argv[0]) ){
 1.90430 +    case SQLITE_BLOB:
 1.90431 +    case SQLITE_INTEGER:
 1.90432 +    case SQLITE_FLOAT: {
 1.90433 +      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
 1.90434 +      break;
 1.90435 +    }
 1.90436 +    case SQLITE_TEXT: {
 1.90437 +      const unsigned char *z = sqlite3_value_text(argv[0]);
 1.90438 +      if( z==0 ) return;
 1.90439 +      len = 0;
 1.90440 +      while( *z ){
 1.90441 +        len++;
 1.90442 +        SQLITE_SKIP_UTF8(z);
 1.90443 +      }
 1.90444 +      sqlite3_result_int(context, len);
 1.90445 +      break;
 1.90446 +    }
 1.90447 +    default: {
 1.90448 +      sqlite3_result_null(context);
 1.90449 +      break;
 1.90450 +    }
 1.90451 +  }
 1.90452 +}
 1.90453 +
 1.90454 +/*
 1.90455 +** Implementation of the abs() function.
 1.90456 +**
 1.90457 +** IMP: R-23979-26855 The abs(X) function returns the absolute value of
 1.90458 +** the numeric argument X. 
 1.90459 +*/
 1.90460 +static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
 1.90461 +  assert( argc==1 );
 1.90462 +  UNUSED_PARAMETER(argc);
 1.90463 +  switch( sqlite3_value_type(argv[0]) ){
 1.90464 +    case SQLITE_INTEGER: {
 1.90465 +      i64 iVal = sqlite3_value_int64(argv[0]);
 1.90466 +      if( iVal<0 ){
 1.90467 +        if( iVal==SMALLEST_INT64 ){
 1.90468 +          /* IMP: R-31676-45509 If X is the integer -9223372036854775808
 1.90469 +          ** then abs(X) throws an integer overflow error since there is no
 1.90470 +          ** equivalent positive 64-bit two complement value. */
 1.90471 +          sqlite3_result_error(context, "integer overflow", -1);
 1.90472 +          return;
 1.90473 +        }
 1.90474 +        iVal = -iVal;
 1.90475 +      } 
 1.90476 +      sqlite3_result_int64(context, iVal);
 1.90477 +      break;
 1.90478 +    }
 1.90479 +    case SQLITE_NULL: {
 1.90480 +      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
 1.90481 +      sqlite3_result_null(context);
 1.90482 +      break;
 1.90483 +    }
 1.90484 +    default: {
 1.90485 +      /* Because sqlite3_value_double() returns 0.0 if the argument is not
 1.90486 +      ** something that can be converted into a number, we have:
 1.90487 +      ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
 1.90488 +      ** cannot be converted to a numeric value. 
 1.90489 +      */
 1.90490 +      double rVal = sqlite3_value_double(argv[0]);
 1.90491 +      if( rVal<0 ) rVal = -rVal;
 1.90492 +      sqlite3_result_double(context, rVal);
 1.90493 +      break;
 1.90494 +    }
 1.90495 +  }
 1.90496 +}
 1.90497 +
 1.90498 +/*
 1.90499 +** Implementation of the instr() function.
 1.90500 +**
 1.90501 +** instr(haystack,needle) finds the first occurrence of needle
 1.90502 +** in haystack and returns the number of previous characters plus 1,
 1.90503 +** or 0 if needle does not occur within haystack.
 1.90504 +**
 1.90505 +** If both haystack and needle are BLOBs, then the result is one more than
 1.90506 +** the number of bytes in haystack prior to the first occurrence of needle,
 1.90507 +** or 0 if needle never occurs in haystack.
 1.90508 +*/
 1.90509 +static void instrFunc(
 1.90510 +  sqlite3_context *context,
 1.90511 +  int argc,
 1.90512 +  sqlite3_value **argv
 1.90513 +){
 1.90514 +  const unsigned char *zHaystack;
 1.90515 +  const unsigned char *zNeedle;
 1.90516 +  int nHaystack;
 1.90517 +  int nNeedle;
 1.90518 +  int typeHaystack, typeNeedle;
 1.90519 +  int N = 1;
 1.90520 +  int isText;
 1.90521 +
 1.90522 +  UNUSED_PARAMETER(argc);
 1.90523 +  typeHaystack = sqlite3_value_type(argv[0]);
 1.90524 +  typeNeedle = sqlite3_value_type(argv[1]);
 1.90525 +  if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
 1.90526 +  nHaystack = sqlite3_value_bytes(argv[0]);
 1.90527 +  nNeedle = sqlite3_value_bytes(argv[1]);
 1.90528 +  if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
 1.90529 +    zHaystack = sqlite3_value_blob(argv[0]);
 1.90530 +    zNeedle = sqlite3_value_blob(argv[1]);
 1.90531 +    isText = 0;
 1.90532 +  }else{
 1.90533 +    zHaystack = sqlite3_value_text(argv[0]);
 1.90534 +    zNeedle = sqlite3_value_text(argv[1]);
 1.90535 +    isText = 1;
 1.90536 +  }
 1.90537 +  while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
 1.90538 +    N++;
 1.90539 +    do{
 1.90540 +      nHaystack--;
 1.90541 +      zHaystack++;
 1.90542 +    }while( isText && (zHaystack[0]&0xc0)==0x80 );
 1.90543 +  }
 1.90544 +  if( nNeedle>nHaystack ) N = 0;
 1.90545 +  sqlite3_result_int(context, N);
 1.90546 +}
 1.90547 +
 1.90548 +/*
 1.90549 +** Implementation of the printf() function.
 1.90550 +*/
 1.90551 +static void printfFunc(
 1.90552 +  sqlite3_context *context,
 1.90553 +  int argc,
 1.90554 +  sqlite3_value **argv
 1.90555 +){
 1.90556 +  PrintfArguments x;
 1.90557 +  StrAccum str;
 1.90558 +  const char *zFormat;
 1.90559 +  int n;
 1.90560 +
 1.90561 +  if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
 1.90562 +    x.nArg = argc-1;
 1.90563 +    x.nUsed = 0;
 1.90564 +    x.apArg = argv+1;
 1.90565 +    sqlite3StrAccumInit(&str, 0, 0, SQLITE_MAX_LENGTH);
 1.90566 +    str.db = sqlite3_context_db_handle(context);
 1.90567 +    sqlite3XPrintf(&str, SQLITE_PRINTF_SQLFUNC, zFormat, &x);
 1.90568 +    n = str.nChar;
 1.90569 +    sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
 1.90570 +                        SQLITE_DYNAMIC);
 1.90571 +  }
 1.90572 +}
 1.90573 +
 1.90574 +/*
 1.90575 +** Implementation of the substr() function.
 1.90576 +**
 1.90577 +** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
 1.90578 +** p1 is 1-indexed.  So substr(x,1,1) returns the first character
 1.90579 +** of x.  If x is text, then we actually count UTF-8 characters.
 1.90580 +** If x is a blob, then we count bytes.
 1.90581 +**
 1.90582 +** If p1 is negative, then we begin abs(p1) from the end of x[].
 1.90583 +**
 1.90584 +** If p2 is negative, return the p2 characters preceding p1.
 1.90585 +*/
 1.90586 +static void substrFunc(
 1.90587 +  sqlite3_context *context,
 1.90588 +  int argc,
 1.90589 +  sqlite3_value **argv
 1.90590 +){
 1.90591 +  const unsigned char *z;
 1.90592 +  const unsigned char *z2;
 1.90593 +  int len;
 1.90594 +  int p0type;
 1.90595 +  i64 p1, p2;
 1.90596 +  int negP2 = 0;
 1.90597 +
 1.90598 +  assert( argc==3 || argc==2 );
 1.90599 +  if( sqlite3_value_type(argv[1])==SQLITE_NULL
 1.90600 +   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
 1.90601 +  ){
 1.90602 +    return;
 1.90603 +  }
 1.90604 +  p0type = sqlite3_value_type(argv[0]);
 1.90605 +  p1 = sqlite3_value_int(argv[1]);
 1.90606 +  if( p0type==SQLITE_BLOB ){
 1.90607 +    len = sqlite3_value_bytes(argv[0]);
 1.90608 +    z = sqlite3_value_blob(argv[0]);
 1.90609 +    if( z==0 ) return;
 1.90610 +    assert( len==sqlite3_value_bytes(argv[0]) );
 1.90611 +  }else{
 1.90612 +    z = sqlite3_value_text(argv[0]);
 1.90613 +    if( z==0 ) return;
 1.90614 +    len = 0;
 1.90615 +    if( p1<0 ){
 1.90616 +      for(z2=z; *z2; len++){
 1.90617 +        SQLITE_SKIP_UTF8(z2);
 1.90618 +      }
 1.90619 +    }
 1.90620 +  }
 1.90621 +  if( argc==3 ){
 1.90622 +    p2 = sqlite3_value_int(argv[2]);
 1.90623 +    if( p2<0 ){
 1.90624 +      p2 = -p2;
 1.90625 +      negP2 = 1;
 1.90626 +    }
 1.90627 +  }else{
 1.90628 +    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
 1.90629 +  }
 1.90630 +  if( p1<0 ){
 1.90631 +    p1 += len;
 1.90632 +    if( p1<0 ){
 1.90633 +      p2 += p1;
 1.90634 +      if( p2<0 ) p2 = 0;
 1.90635 +      p1 = 0;
 1.90636 +    }
 1.90637 +  }else if( p1>0 ){
 1.90638 +    p1--;
 1.90639 +  }else if( p2>0 ){
 1.90640 +    p2--;
 1.90641 +  }
 1.90642 +  if( negP2 ){
 1.90643 +    p1 -= p2;
 1.90644 +    if( p1<0 ){
 1.90645 +      p2 += p1;
 1.90646 +      p1 = 0;
 1.90647 +    }
 1.90648 +  }
 1.90649 +  assert( p1>=0 && p2>=0 );
 1.90650 +  if( p0type!=SQLITE_BLOB ){
 1.90651 +    while( *z && p1 ){
 1.90652 +      SQLITE_SKIP_UTF8(z);
 1.90653 +      p1--;
 1.90654 +    }
 1.90655 +    for(z2=z; *z2 && p2; p2--){
 1.90656 +      SQLITE_SKIP_UTF8(z2);
 1.90657 +    }
 1.90658 +    sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
 1.90659 +  }else{
 1.90660 +    if( p1+p2>len ){
 1.90661 +      p2 = len-p1;
 1.90662 +      if( p2<0 ) p2 = 0;
 1.90663 +    }
 1.90664 +    sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
 1.90665 +  }
 1.90666 +}
 1.90667 +
 1.90668 +/*
 1.90669 +** Implementation of the round() function
 1.90670 +*/
 1.90671 +#ifndef SQLITE_OMIT_FLOATING_POINT
 1.90672 +static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
 1.90673 +  int n = 0;
 1.90674 +  double r;
 1.90675 +  char *zBuf;
 1.90676 +  assert( argc==1 || argc==2 );
 1.90677 +  if( argc==2 ){
 1.90678 +    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
 1.90679 +    n = sqlite3_value_int(argv[1]);
 1.90680 +    if( n>30 ) n = 30;
 1.90681 +    if( n<0 ) n = 0;
 1.90682 +  }
 1.90683 +  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
 1.90684 +  r = sqlite3_value_double(argv[0]);
 1.90685 +  /* If Y==0 and X will fit in a 64-bit int,
 1.90686 +  ** handle the rounding directly,
 1.90687 +  ** otherwise use printf.
 1.90688 +  */
 1.90689 +  if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
 1.90690 +    r = (double)((sqlite_int64)(r+0.5));
 1.90691 +  }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
 1.90692 +    r = -(double)((sqlite_int64)((-r)+0.5));
 1.90693 +  }else{
 1.90694 +    zBuf = sqlite3_mprintf("%.*f",n,r);
 1.90695 +    if( zBuf==0 ){
 1.90696 +      sqlite3_result_error_nomem(context);
 1.90697 +      return;
 1.90698 +    }
 1.90699 +    sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
 1.90700 +    sqlite3_free(zBuf);
 1.90701 +  }
 1.90702 +  sqlite3_result_double(context, r);
 1.90703 +}
 1.90704 +#endif
 1.90705 +
 1.90706 +/*
 1.90707 +** Allocate nByte bytes of space using sqlite3_malloc(). If the
 1.90708 +** allocation fails, call sqlite3_result_error_nomem() to notify
 1.90709 +** the database handle that malloc() has failed and return NULL.
 1.90710 +** If nByte is larger than the maximum string or blob length, then
 1.90711 +** raise an SQLITE_TOOBIG exception and return NULL.
 1.90712 +*/
 1.90713 +static void *contextMalloc(sqlite3_context *context, i64 nByte){
 1.90714 +  char *z;
 1.90715 +  sqlite3 *db = sqlite3_context_db_handle(context);
 1.90716 +  assert( nByte>0 );
 1.90717 +  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
 1.90718 +  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
 1.90719 +  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
 1.90720 +    sqlite3_result_error_toobig(context);
 1.90721 +    z = 0;
 1.90722 +  }else{
 1.90723 +    z = sqlite3Malloc((int)nByte);
 1.90724 +    if( !z ){
 1.90725 +      sqlite3_result_error_nomem(context);
 1.90726 +    }
 1.90727 +  }
 1.90728 +  return z;
 1.90729 +}
 1.90730 +
 1.90731 +/*
 1.90732 +** Implementation of the upper() and lower() SQL functions.
 1.90733 +*/
 1.90734 +static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
 1.90735 +  char *z1;
 1.90736 +  const char *z2;
 1.90737 +  int i, n;
 1.90738 +  UNUSED_PARAMETER(argc);
 1.90739 +  z2 = (char*)sqlite3_value_text(argv[0]);
 1.90740 +  n = sqlite3_value_bytes(argv[0]);
 1.90741 +  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
 1.90742 +  assert( z2==(char*)sqlite3_value_text(argv[0]) );
 1.90743 +  if( z2 ){
 1.90744 +    z1 = contextMalloc(context, ((i64)n)+1);
 1.90745 +    if( z1 ){
 1.90746 +      for(i=0; i<n; i++){
 1.90747 +        z1[i] = (char)sqlite3Toupper(z2[i]);
 1.90748 +      }
 1.90749 +      sqlite3_result_text(context, z1, n, sqlite3_free);
 1.90750 +    }
 1.90751 +  }
 1.90752 +}
 1.90753 +static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
 1.90754 +  char *z1;
 1.90755 +  const char *z2;
 1.90756 +  int i, n;
 1.90757 +  UNUSED_PARAMETER(argc);
 1.90758 +  z2 = (char*)sqlite3_value_text(argv[0]);
 1.90759 +  n = sqlite3_value_bytes(argv[0]);
 1.90760 +  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
 1.90761 +  assert( z2==(char*)sqlite3_value_text(argv[0]) );
 1.90762 +  if( z2 ){
 1.90763 +    z1 = contextMalloc(context, ((i64)n)+1);
 1.90764 +    if( z1 ){
 1.90765 +      for(i=0; i<n; i++){
 1.90766 +        z1[i] = sqlite3Tolower(z2[i]);
 1.90767 +      }
 1.90768 +      sqlite3_result_text(context, z1, n, sqlite3_free);
 1.90769 +    }
 1.90770 +  }
 1.90771 +}
 1.90772 +
 1.90773 +/*
 1.90774 +** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
 1.90775 +** as VDBE code so that unused argument values do not have to be computed.
 1.90776 +** However, we still need some kind of function implementation for this
 1.90777 +** routines in the function table.  The noopFunc macro provides this.
 1.90778 +** noopFunc will never be called so it doesn't matter what the implementation
 1.90779 +** is.  We might as well use the "version()" function as a substitute.
 1.90780 +*/
 1.90781 +#define noopFunc versionFunc   /* Substitute function - never called */
 1.90782 +
 1.90783 +/*
 1.90784 +** Implementation of random().  Return a random integer.  
 1.90785 +*/
 1.90786 +static void randomFunc(
 1.90787 +  sqlite3_context *context,
 1.90788 +  int NotUsed,
 1.90789 +  sqlite3_value **NotUsed2
 1.90790 +){
 1.90791 +  sqlite_int64 r;
 1.90792 +  UNUSED_PARAMETER2(NotUsed, NotUsed2);
 1.90793 +  sqlite3_randomness(sizeof(r), &r);
 1.90794 +  if( r<0 ){
 1.90795 +    /* We need to prevent a random number of 0x8000000000000000 
 1.90796 +    ** (or -9223372036854775808) since when you do abs() of that
 1.90797 +    ** number of you get the same value back again.  To do this
 1.90798 +    ** in a way that is testable, mask the sign bit off of negative
 1.90799 +    ** values, resulting in a positive value.  Then take the 
 1.90800 +    ** 2s complement of that positive value.  The end result can
 1.90801 +    ** therefore be no less than -9223372036854775807.
 1.90802 +    */
 1.90803 +    r = -(r & LARGEST_INT64);
 1.90804 +  }
 1.90805 +  sqlite3_result_int64(context, r);
 1.90806 +}
 1.90807 +
 1.90808 +/*
 1.90809 +** Implementation of randomblob(N).  Return a random blob
 1.90810 +** that is N bytes long.
 1.90811 +*/
 1.90812 +static void randomBlob(
 1.90813 +  sqlite3_context *context,
 1.90814 +  int argc,
 1.90815 +  sqlite3_value **argv
 1.90816 +){
 1.90817 +  int n;
 1.90818 +  unsigned char *p;
 1.90819 +  assert( argc==1 );
 1.90820 +  UNUSED_PARAMETER(argc);
 1.90821 +  n = sqlite3_value_int(argv[0]);
 1.90822 +  if( n<1 ){
 1.90823 +    n = 1;
 1.90824 +  }
 1.90825 +  p = contextMalloc(context, n);
 1.90826 +  if( p ){
 1.90827 +    sqlite3_randomness(n, p);
 1.90828 +    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
 1.90829 +  }
 1.90830 +}
 1.90831 +
 1.90832 +/*
 1.90833 +** Implementation of the last_insert_rowid() SQL function.  The return
 1.90834 +** value is the same as the sqlite3_last_insert_rowid() API function.
 1.90835 +*/
 1.90836 +static void last_insert_rowid(
 1.90837 +  sqlite3_context *context, 
 1.90838 +  int NotUsed, 
 1.90839 +  sqlite3_value **NotUsed2
 1.90840 +){
 1.90841 +  sqlite3 *db = sqlite3_context_db_handle(context);
 1.90842 +  UNUSED_PARAMETER2(NotUsed, NotUsed2);
 1.90843 +  /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
 1.90844 +  ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
 1.90845 +  ** function. */
 1.90846 +  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
 1.90847 +}
 1.90848 +
 1.90849 +/*
 1.90850 +** Implementation of the changes() SQL function.
 1.90851 +**
 1.90852 +** IMP: R-62073-11209 The changes() SQL function is a wrapper
 1.90853 +** around the sqlite3_changes() C/C++ function and hence follows the same
 1.90854 +** rules for counting changes.
 1.90855 +*/
 1.90856 +static void changes(
 1.90857 +  sqlite3_context *context,
 1.90858 +  int NotUsed,
 1.90859 +  sqlite3_value **NotUsed2
 1.90860 +){
 1.90861 +  sqlite3 *db = sqlite3_context_db_handle(context);
 1.90862 +  UNUSED_PARAMETER2(NotUsed, NotUsed2);
 1.90863 +  sqlite3_result_int(context, sqlite3_changes(db));
 1.90864 +}
 1.90865 +
 1.90866 +/*
 1.90867 +** Implementation of the total_changes() SQL function.  The return value is
 1.90868 +** the same as the sqlite3_total_changes() API function.
 1.90869 +*/
 1.90870 +static void total_changes(
 1.90871 +  sqlite3_context *context,
 1.90872 +  int NotUsed,
 1.90873 +  sqlite3_value **NotUsed2
 1.90874 +){
 1.90875 +  sqlite3 *db = sqlite3_context_db_handle(context);
 1.90876 +  UNUSED_PARAMETER2(NotUsed, NotUsed2);
 1.90877 +  /* IMP: R-52756-41993 This function is a wrapper around the
 1.90878 +  ** sqlite3_total_changes() C/C++ interface. */
 1.90879 +  sqlite3_result_int(context, sqlite3_total_changes(db));
 1.90880 +}
 1.90881 +
 1.90882 +/*
 1.90883 +** A structure defining how to do GLOB-style comparisons.
 1.90884 +*/
 1.90885 +struct compareInfo {
 1.90886 +  u8 matchAll;
 1.90887 +  u8 matchOne;
 1.90888 +  u8 matchSet;
 1.90889 +  u8 noCase;
 1.90890 +};
 1.90891 +
 1.90892 +/*
 1.90893 +** For LIKE and GLOB matching on EBCDIC machines, assume that every
 1.90894 +** character is exactly one byte in size.  Also, all characters are
 1.90895 +** able to participate in upper-case-to-lower-case mappings in EBCDIC
 1.90896 +** whereas only characters less than 0x80 do in ASCII.
 1.90897 +*/
 1.90898 +#if defined(SQLITE_EBCDIC)
 1.90899 +# define sqlite3Utf8Read(A)    (*((*A)++))
 1.90900 +# define GlobUpperToLower(A)   A = sqlite3UpperToLower[A]
 1.90901 +#else
 1.90902 +# define GlobUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
 1.90903 +#endif
 1.90904 +
 1.90905 +static const struct compareInfo globInfo = { '*', '?', '[', 0 };
 1.90906 +/* The correct SQL-92 behavior is for the LIKE operator to ignore
 1.90907 +** case.  Thus  'a' LIKE 'A' would be true. */
 1.90908 +static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
 1.90909 +/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
 1.90910 +** is case sensitive causing 'a' LIKE 'A' to be false */
 1.90911 +static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
 1.90912 +
 1.90913 +/*
 1.90914 +** Compare two UTF-8 strings for equality where the first string can
 1.90915 +** potentially be a "glob" expression.  Return true (1) if they
 1.90916 +** are the same and false (0) if they are different.
 1.90917 +**
 1.90918 +** Globbing rules:
 1.90919 +**
 1.90920 +**      '*'       Matches any sequence of zero or more characters.
 1.90921 +**
 1.90922 +**      '?'       Matches exactly one character.
 1.90923 +**
 1.90924 +**     [...]      Matches one character from the enclosed list of
 1.90925 +**                characters.
 1.90926 +**
 1.90927 +**     [^...]     Matches one character not in the enclosed list.
 1.90928 +**
 1.90929 +** With the [...] and [^...] matching, a ']' character can be included
 1.90930 +** in the list by making it the first character after '[' or '^'.  A
 1.90931 +** range of characters can be specified using '-'.  Example:
 1.90932 +** "[a-z]" matches any single lower-case letter.  To match a '-', make
 1.90933 +** it the last character in the list.
 1.90934 +**
 1.90935 +** This routine is usually quick, but can be N**2 in the worst case.
 1.90936 +**
 1.90937 +** Hints: to match '*' or '?', put them in "[]".  Like this:
 1.90938 +**
 1.90939 +**         abc[*]xyz        Matches "abc*xyz" only
 1.90940 +*/
 1.90941 +static int patternCompare(
 1.90942 +  const u8 *zPattern,              /* The glob pattern */
 1.90943 +  const u8 *zString,               /* The string to compare against the glob */
 1.90944 +  const struct compareInfo *pInfo, /* Information about how to do the compare */
 1.90945 +  u32 esc                          /* The escape character */
 1.90946 +){
 1.90947 +  u32 c, c2;
 1.90948 +  int invert;
 1.90949 +  int seen;
 1.90950 +  u8 matchOne = pInfo->matchOne;
 1.90951 +  u8 matchAll = pInfo->matchAll;
 1.90952 +  u8 matchSet = pInfo->matchSet;
 1.90953 +  u8 noCase = pInfo->noCase; 
 1.90954 +  int prevEscape = 0;     /* True if the previous character was 'escape' */
 1.90955 +
 1.90956 +  while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
 1.90957 +    if( c==matchAll && !prevEscape ){
 1.90958 +      while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
 1.90959 +               || c == matchOne ){
 1.90960 +        if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
 1.90961 +          return 0;
 1.90962 +        }
 1.90963 +      }
 1.90964 +      if( c==0 ){
 1.90965 +        return 1;
 1.90966 +      }else if( c==esc ){
 1.90967 +        c = sqlite3Utf8Read(&zPattern);
 1.90968 +        if( c==0 ){
 1.90969 +          return 0;
 1.90970 +        }
 1.90971 +      }else if( c==matchSet ){
 1.90972 +        assert( esc==0 );         /* This is GLOB, not LIKE */
 1.90973 +        assert( matchSet<0x80 );  /* '[' is a single-byte character */
 1.90974 +        while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
 1.90975 +          SQLITE_SKIP_UTF8(zString);
 1.90976 +        }
 1.90977 +        return *zString!=0;
 1.90978 +      }
 1.90979 +      while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
 1.90980 +        if( noCase ){
 1.90981 +          GlobUpperToLower(c2);
 1.90982 +          GlobUpperToLower(c);
 1.90983 +          while( c2 != 0 && c2 != c ){
 1.90984 +            c2 = sqlite3Utf8Read(&zString);
 1.90985 +            GlobUpperToLower(c2);
 1.90986 +          }
 1.90987 +        }else{
 1.90988 +          while( c2 != 0 && c2 != c ){
 1.90989 +            c2 = sqlite3Utf8Read(&zString);
 1.90990 +          }
 1.90991 +        }
 1.90992 +        if( c2==0 ) return 0;
 1.90993 +        if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
 1.90994 +      }
 1.90995 +      return 0;
 1.90996 +    }else if( c==matchOne && !prevEscape ){
 1.90997 +      if( sqlite3Utf8Read(&zString)==0 ){
 1.90998 +        return 0;
 1.90999 +      }
 1.91000 +    }else if( c==matchSet ){
 1.91001 +      u32 prior_c = 0;
 1.91002 +      assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
 1.91003 +      seen = 0;
 1.91004 +      invert = 0;
 1.91005 +      c = sqlite3Utf8Read(&zString);
 1.91006 +      if( c==0 ) return 0;
 1.91007 +      c2 = sqlite3Utf8Read(&zPattern);
 1.91008 +      if( c2=='^' ){
 1.91009 +        invert = 1;
 1.91010 +        c2 = sqlite3Utf8Read(&zPattern);
 1.91011 +      }
 1.91012 +      if( c2==']' ){
 1.91013 +        if( c==']' ) seen = 1;
 1.91014 +        c2 = sqlite3Utf8Read(&zPattern);
 1.91015 +      }
 1.91016 +      while( c2 && c2!=']' ){
 1.91017 +        if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
 1.91018 +          c2 = sqlite3Utf8Read(&zPattern);
 1.91019 +          if( c>=prior_c && c<=c2 ) seen = 1;
 1.91020 +          prior_c = 0;
 1.91021 +        }else{
 1.91022 +          if( c==c2 ){
 1.91023 +            seen = 1;
 1.91024 +          }
 1.91025 +          prior_c = c2;
 1.91026 +        }
 1.91027 +        c2 = sqlite3Utf8Read(&zPattern);
 1.91028 +      }
 1.91029 +      if( c2==0 || (seen ^ invert)==0 ){
 1.91030 +        return 0;
 1.91031 +      }
 1.91032 +    }else if( esc==c && !prevEscape ){
 1.91033 +      prevEscape = 1;
 1.91034 +    }else{
 1.91035 +      c2 = sqlite3Utf8Read(&zString);
 1.91036 +      if( noCase ){
 1.91037 +        GlobUpperToLower(c);
 1.91038 +        GlobUpperToLower(c2);
 1.91039 +      }
 1.91040 +      if( c!=c2 ){
 1.91041 +        return 0;
 1.91042 +      }
 1.91043 +      prevEscape = 0;
 1.91044 +    }
 1.91045 +  }
 1.91046 +  return *zString==0;
 1.91047 +}
 1.91048 +
 1.91049 +/*
 1.91050 +** The sqlite3_strglob() interface.
 1.91051 +*/
 1.91052 +SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
 1.91053 +  return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
 1.91054 +}
 1.91055 +
 1.91056 +/*
 1.91057 +** Count the number of times that the LIKE operator (or GLOB which is
 1.91058 +** just a variation of LIKE) gets called.  This is used for testing
 1.91059 +** only.
 1.91060 +*/
 1.91061 +#ifdef SQLITE_TEST
 1.91062 +SQLITE_API int sqlite3_like_count = 0;
 1.91063 +#endif
 1.91064 +
 1.91065 +
 1.91066 +/*
 1.91067 +** Implementation of the like() SQL function.  This function implements
 1.91068 +** the build-in LIKE operator.  The first argument to the function is the
 1.91069 +** pattern and the second argument is the string.  So, the SQL statements:
 1.91070 +**
 1.91071 +**       A LIKE B
 1.91072 +**
 1.91073 +** is implemented as like(B,A).
 1.91074 +**
 1.91075 +** This same function (with a different compareInfo structure) computes
 1.91076 +** the GLOB operator.
 1.91077 +*/
 1.91078 +static void likeFunc(
 1.91079 +  sqlite3_context *context, 
 1.91080 +  int argc, 
 1.91081 +  sqlite3_value **argv
 1.91082 +){
 1.91083 +  const unsigned char *zA, *zB;
 1.91084 +  u32 escape = 0;
 1.91085 +  int nPat;
 1.91086 +  sqlite3 *db = sqlite3_context_db_handle(context);
 1.91087 +
 1.91088 +  zB = sqlite3_value_text(argv[0]);
 1.91089 +  zA = sqlite3_value_text(argv[1]);
 1.91090 +
 1.91091 +  /* Limit the length of the LIKE or GLOB pattern to avoid problems
 1.91092 +  ** of deep recursion and N*N behavior in patternCompare().
 1.91093 +  */
 1.91094 +  nPat = sqlite3_value_bytes(argv[0]);
 1.91095 +  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
 1.91096 +  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
 1.91097 +  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
 1.91098 +    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
 1.91099 +    return;
 1.91100 +  }
 1.91101 +  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
 1.91102 +
 1.91103 +  if( argc==3 ){
 1.91104 +    /* The escape character string must consist of a single UTF-8 character.
 1.91105 +    ** Otherwise, return an error.
 1.91106 +    */
 1.91107 +    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
 1.91108 +    if( zEsc==0 ) return;
 1.91109 +    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
 1.91110 +      sqlite3_result_error(context, 
 1.91111 +          "ESCAPE expression must be a single character", -1);
 1.91112 +      return;
 1.91113 +    }
 1.91114 +    escape = sqlite3Utf8Read(&zEsc);
 1.91115 +  }
 1.91116 +  if( zA && zB ){
 1.91117 +    struct compareInfo *pInfo = sqlite3_user_data(context);
 1.91118 +#ifdef SQLITE_TEST
 1.91119 +    sqlite3_like_count++;
 1.91120 +#endif
 1.91121 +    
 1.91122 +    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
 1.91123 +  }
 1.91124 +}
 1.91125 +
 1.91126 +/*
 1.91127 +** Implementation of the NULLIF(x,y) function.  The result is the first
 1.91128 +** argument if the arguments are different.  The result is NULL if the
 1.91129 +** arguments are equal to each other.
 1.91130 +*/
 1.91131 +static void nullifFunc(
 1.91132 +  sqlite3_context *context,
 1.91133 +  int NotUsed,
 1.91134 +  sqlite3_value **argv
 1.91135 +){
 1.91136 +  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
 1.91137 +  UNUSED_PARAMETER(NotUsed);
 1.91138 +  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
 1.91139 +    sqlite3_result_value(context, argv[0]);
 1.91140 +  }
 1.91141 +}
 1.91142 +
 1.91143 +/*
 1.91144 +** Implementation of the sqlite_version() function.  The result is the version
 1.91145 +** of the SQLite library that is running.
 1.91146 +*/
 1.91147 +static void versionFunc(
 1.91148 +  sqlite3_context *context,
 1.91149 +  int NotUsed,
 1.91150 +  sqlite3_value **NotUsed2
 1.91151 +){
 1.91152 +  UNUSED_PARAMETER2(NotUsed, NotUsed2);
 1.91153 +  /* IMP: R-48699-48617 This function is an SQL wrapper around the
 1.91154 +  ** sqlite3_libversion() C-interface. */
 1.91155 +  sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
 1.91156 +}
 1.91157 +
 1.91158 +/*
 1.91159 +** Implementation of the sqlite_source_id() function. The result is a string
 1.91160 +** that identifies the particular version of the source code used to build
 1.91161 +** SQLite.
 1.91162 +*/
 1.91163 +static void sourceidFunc(
 1.91164 +  sqlite3_context *context,
 1.91165 +  int NotUsed,
 1.91166 +  sqlite3_value **NotUsed2
 1.91167 +){
 1.91168 +  UNUSED_PARAMETER2(NotUsed, NotUsed2);
 1.91169 +  /* IMP: R-24470-31136 This function is an SQL wrapper around the
 1.91170 +  ** sqlite3_sourceid() C interface. */
 1.91171 +  sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
 1.91172 +}
 1.91173 +
 1.91174 +/*
 1.91175 +** Implementation of the sqlite_log() function.  This is a wrapper around
 1.91176 +** sqlite3_log().  The return value is NULL.  The function exists purely for
 1.91177 +** its side-effects.
 1.91178 +*/
 1.91179 +static void errlogFunc(
 1.91180 +  sqlite3_context *context,
 1.91181 +  int argc,
 1.91182 +  sqlite3_value **argv
 1.91183 +){
 1.91184 +  UNUSED_PARAMETER(argc);
 1.91185 +  UNUSED_PARAMETER(context);
 1.91186 +  sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
 1.91187 +}
 1.91188 +
 1.91189 +/*
 1.91190 +** Implementation of the sqlite_compileoption_used() function.
 1.91191 +** The result is an integer that identifies if the compiler option
 1.91192 +** was used to build SQLite.
 1.91193 +*/
 1.91194 +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
 1.91195 +static void compileoptionusedFunc(
 1.91196 +  sqlite3_context *context,
 1.91197 +  int argc,
 1.91198 +  sqlite3_value **argv
 1.91199 +){
 1.91200 +  const char *zOptName;
 1.91201 +  assert( argc==1 );
 1.91202 +  UNUSED_PARAMETER(argc);
 1.91203 +  /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
 1.91204 +  ** function is a wrapper around the sqlite3_compileoption_used() C/C++
 1.91205 +  ** function.
 1.91206 +  */
 1.91207 +  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
 1.91208 +    sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
 1.91209 +  }
 1.91210 +}
 1.91211 +#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
 1.91212 +
 1.91213 +/*
 1.91214 +** Implementation of the sqlite_compileoption_get() function. 
 1.91215 +** The result is a string that identifies the compiler options 
 1.91216 +** used to build SQLite.
 1.91217 +*/
 1.91218 +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
 1.91219 +static void compileoptiongetFunc(
 1.91220 +  sqlite3_context *context,
 1.91221 +  int argc,
 1.91222 +  sqlite3_value **argv
 1.91223 +){
 1.91224 +  int n;
 1.91225 +  assert( argc==1 );
 1.91226 +  UNUSED_PARAMETER(argc);
 1.91227 +  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
 1.91228 +  ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
 1.91229 +  */
 1.91230 +  n = sqlite3_value_int(argv[0]);
 1.91231 +  sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
 1.91232 +}
 1.91233 +#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
 1.91234 +
 1.91235 +/* Array for converting from half-bytes (nybbles) into ASCII hex
 1.91236 +** digits. */
 1.91237 +static const char hexdigits[] = {
 1.91238 +  '0', '1', '2', '3', '4', '5', '6', '7',
 1.91239 +  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
 1.91240 +};
 1.91241 +
 1.91242 +/*
 1.91243 +** Implementation of the QUOTE() function.  This function takes a single
 1.91244 +** argument.  If the argument is numeric, the return value is the same as
 1.91245 +** the argument.  If the argument is NULL, the return value is the string
 1.91246 +** "NULL".  Otherwise, the argument is enclosed in single quotes with
 1.91247 +** single-quote escapes.
 1.91248 +*/
 1.91249 +static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
 1.91250 +  assert( argc==1 );
 1.91251 +  UNUSED_PARAMETER(argc);
 1.91252 +  switch( sqlite3_value_type(argv[0]) ){
 1.91253 +    case SQLITE_FLOAT: {
 1.91254 +      double r1, r2;
 1.91255 +      char zBuf[50];
 1.91256 +      r1 = sqlite3_value_double(argv[0]);
 1.91257 +      sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
 1.91258 +      sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
 1.91259 +      if( r1!=r2 ){
 1.91260 +        sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
 1.91261 +      }
 1.91262 +      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
 1.91263 +      break;
 1.91264 +    }
 1.91265 +    case SQLITE_INTEGER: {
 1.91266 +      sqlite3_result_value(context, argv[0]);
 1.91267 +      break;
 1.91268 +    }
 1.91269 +    case SQLITE_BLOB: {
 1.91270 +      char *zText = 0;
 1.91271 +      char const *zBlob = sqlite3_value_blob(argv[0]);
 1.91272 +      int nBlob = sqlite3_value_bytes(argv[0]);
 1.91273 +      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
 1.91274 +      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
 1.91275 +      if( zText ){
 1.91276 +        int i;
 1.91277 +        for(i=0; i<nBlob; i++){
 1.91278 +          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
 1.91279 +          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
 1.91280 +        }
 1.91281 +        zText[(nBlob*2)+2] = '\'';
 1.91282 +        zText[(nBlob*2)+3] = '\0';
 1.91283 +        zText[0] = 'X';
 1.91284 +        zText[1] = '\'';
 1.91285 +        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
 1.91286 +        sqlite3_free(zText);
 1.91287 +      }
 1.91288 +      break;
 1.91289 +    }
 1.91290 +    case SQLITE_TEXT: {
 1.91291 +      int i,j;
 1.91292 +      u64 n;
 1.91293 +      const unsigned char *zArg = sqlite3_value_text(argv[0]);
 1.91294 +      char *z;
 1.91295 +
 1.91296 +      if( zArg==0 ) return;
 1.91297 +      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
 1.91298 +      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
 1.91299 +      if( z ){
 1.91300 +        z[0] = '\'';
 1.91301 +        for(i=0, j=1; zArg[i]; i++){
 1.91302 +          z[j++] = zArg[i];
 1.91303 +          if( zArg[i]=='\'' ){
 1.91304 +            z[j++] = '\'';
 1.91305 +          }
 1.91306 +        }
 1.91307 +        z[j++] = '\'';
 1.91308 +        z[j] = 0;
 1.91309 +        sqlite3_result_text(context, z, j, sqlite3_free);
 1.91310 +      }
 1.91311 +      break;
 1.91312 +    }
 1.91313 +    default: {
 1.91314 +      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
 1.91315 +      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
 1.91316 +      break;
 1.91317 +    }
 1.91318 +  }
 1.91319 +}
 1.91320 +
 1.91321 +/*
 1.91322 +** The unicode() function.  Return the integer unicode code-point value
 1.91323 +** for the first character of the input string. 
 1.91324 +*/
 1.91325 +static void unicodeFunc(
 1.91326 +  sqlite3_context *context,
 1.91327 +  int argc,
 1.91328 +  sqlite3_value **argv
 1.91329 +){
 1.91330 +  const unsigned char *z = sqlite3_value_text(argv[0]);
 1.91331 +  (void)argc;
 1.91332 +  if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
 1.91333 +}
 1.91334 +
 1.91335 +/*
 1.91336 +** The char() function takes zero or more arguments, each of which is
 1.91337 +** an integer.  It constructs a string where each character of the string
 1.91338 +** is the unicode character for the corresponding integer argument.
 1.91339 +*/
 1.91340 +static void charFunc(
 1.91341 +  sqlite3_context *context,
 1.91342 +  int argc,
 1.91343 +  sqlite3_value **argv
 1.91344 +){
 1.91345 +  unsigned char *z, *zOut;
 1.91346 +  int i;
 1.91347 +  zOut = z = sqlite3_malloc( argc*4+1 );
 1.91348 +  if( z==0 ){
 1.91349 +    sqlite3_result_error_nomem(context);
 1.91350 +    return;
 1.91351 +  }
 1.91352 +  for(i=0; i<argc; i++){
 1.91353 +    sqlite3_int64 x;
 1.91354 +    unsigned c;
 1.91355 +    x = sqlite3_value_int64(argv[i]);
 1.91356 +    if( x<0 || x>0x10ffff ) x = 0xfffd;
 1.91357 +    c = (unsigned)(x & 0x1fffff);
 1.91358 +    if( c<0x00080 ){
 1.91359 +      *zOut++ = (u8)(c&0xFF);
 1.91360 +    }else if( c<0x00800 ){
 1.91361 +      *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
 1.91362 +      *zOut++ = 0x80 + (u8)(c & 0x3F);
 1.91363 +    }else if( c<0x10000 ){
 1.91364 +      *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
 1.91365 +      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
 1.91366 +      *zOut++ = 0x80 + (u8)(c & 0x3F);
 1.91367 +    }else{
 1.91368 +      *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
 1.91369 +      *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
 1.91370 +      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
 1.91371 +      *zOut++ = 0x80 + (u8)(c & 0x3F);
 1.91372 +    }                                                    \
 1.91373 +  }
 1.91374 +  sqlite3_result_text(context, (char*)z, (int)(zOut-z), sqlite3_free);
 1.91375 +}
 1.91376 +
 1.91377 +/*
 1.91378 +** The hex() function.  Interpret the argument as a blob.  Return
 1.91379 +** a hexadecimal rendering as text.
 1.91380 +*/
 1.91381 +static void hexFunc(
 1.91382 +  sqlite3_context *context,
 1.91383 +  int argc,
 1.91384 +  sqlite3_value **argv
 1.91385 +){
 1.91386 +  int i, n;
 1.91387 +  const unsigned char *pBlob;
 1.91388 +  char *zHex, *z;
 1.91389 +  assert( argc==1 );
 1.91390 +  UNUSED_PARAMETER(argc);
 1.91391 +  pBlob = sqlite3_value_blob(argv[0]);
 1.91392 +  n = sqlite3_value_bytes(argv[0]);
 1.91393 +  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
 1.91394 +  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
 1.91395 +  if( zHex ){
 1.91396 +    for(i=0; i<n; i++, pBlob++){
 1.91397 +      unsigned char c = *pBlob;
 1.91398 +      *(z++) = hexdigits[(c>>4)&0xf];
 1.91399 +      *(z++) = hexdigits[c&0xf];
 1.91400 +    }
 1.91401 +    *z = 0;
 1.91402 +    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
 1.91403 +  }
 1.91404 +}
 1.91405 +
 1.91406 +/*
 1.91407 +** The zeroblob(N) function returns a zero-filled blob of size N bytes.
 1.91408 +*/
 1.91409 +static void zeroblobFunc(
 1.91410 +  sqlite3_context *context,
 1.91411 +  int argc,
 1.91412 +  sqlite3_value **argv
 1.91413 +){
 1.91414 +  i64 n;
 1.91415 +  sqlite3 *db = sqlite3_context_db_handle(context);
 1.91416 +  assert( argc==1 );
 1.91417 +  UNUSED_PARAMETER(argc);
 1.91418 +  n = sqlite3_value_int64(argv[0]);
 1.91419 +  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
 1.91420 +  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
 1.91421 +  if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
 1.91422 +    sqlite3_result_error_toobig(context);
 1.91423 +  }else{
 1.91424 +    sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
 1.91425 +  }
 1.91426 +}
 1.91427 +
 1.91428 +/*
 1.91429 +** The replace() function.  Three arguments are all strings: call
 1.91430 +** them A, B, and C. The result is also a string which is derived
 1.91431 +** from A by replacing every occurrence of B with C.  The match
 1.91432 +** must be exact.  Collating sequences are not used.
 1.91433 +*/
 1.91434 +static void replaceFunc(
 1.91435 +  sqlite3_context *context,
 1.91436 +  int argc,
 1.91437 +  sqlite3_value **argv
 1.91438 +){
 1.91439 +  const unsigned char *zStr;        /* The input string A */
 1.91440 +  const unsigned char *zPattern;    /* The pattern string B */
 1.91441 +  const unsigned char *zRep;        /* The replacement string C */
 1.91442 +  unsigned char *zOut;              /* The output */
 1.91443 +  int nStr;                /* Size of zStr */
 1.91444 +  int nPattern;            /* Size of zPattern */
 1.91445 +  int nRep;                /* Size of zRep */
 1.91446 +  i64 nOut;                /* Maximum size of zOut */
 1.91447 +  int loopLimit;           /* Last zStr[] that might match zPattern[] */
 1.91448 +  int i, j;                /* Loop counters */
 1.91449 +
 1.91450 +  assert( argc==3 );
 1.91451 +  UNUSED_PARAMETER(argc);
 1.91452 +  zStr = sqlite3_value_text(argv[0]);
 1.91453 +  if( zStr==0 ) return;
 1.91454 +  nStr = sqlite3_value_bytes(argv[0]);
 1.91455 +  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
 1.91456 +  zPattern = sqlite3_value_text(argv[1]);
 1.91457 +  if( zPattern==0 ){
 1.91458 +    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
 1.91459 +            || sqlite3_context_db_handle(context)->mallocFailed );
 1.91460 +    return;
 1.91461 +  }
 1.91462 +  if( zPattern[0]==0 ){
 1.91463 +    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
 1.91464 +    sqlite3_result_value(context, argv[0]);
 1.91465 +    return;
 1.91466 +  }
 1.91467 +  nPattern = sqlite3_value_bytes(argv[1]);
 1.91468 +  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
 1.91469 +  zRep = sqlite3_value_text(argv[2]);
 1.91470 +  if( zRep==0 ) return;
 1.91471 +  nRep = sqlite3_value_bytes(argv[2]);
 1.91472 +  assert( zRep==sqlite3_value_text(argv[2]) );
 1.91473 +  nOut = nStr + 1;
 1.91474 +  assert( nOut<SQLITE_MAX_LENGTH );
 1.91475 +  zOut = contextMalloc(context, (i64)nOut);
 1.91476 +  if( zOut==0 ){
 1.91477 +    return;
 1.91478 +  }
 1.91479 +  loopLimit = nStr - nPattern;  
 1.91480 +  for(i=j=0; i<=loopLimit; i++){
 1.91481 +    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
 1.91482 +      zOut[j++] = zStr[i];
 1.91483 +    }else{
 1.91484 +      u8 *zOld;
 1.91485 +      sqlite3 *db = sqlite3_context_db_handle(context);
 1.91486 +      nOut += nRep - nPattern;
 1.91487 +      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
 1.91488 +      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
 1.91489 +      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
 1.91490 +        sqlite3_result_error_toobig(context);
 1.91491 +        sqlite3_free(zOut);
 1.91492 +        return;
 1.91493 +      }
 1.91494 +      zOld = zOut;
 1.91495 +      zOut = sqlite3_realloc(zOut, (int)nOut);
 1.91496 +      if( zOut==0 ){
 1.91497 +        sqlite3_result_error_nomem(context);
 1.91498 +        sqlite3_free(zOld);
 1.91499 +        return;
 1.91500 +      }
 1.91501 +      memcpy(&zOut[j], zRep, nRep);
 1.91502 +      j += nRep;
 1.91503 +      i += nPattern-1;
 1.91504 +    }
 1.91505 +  }
 1.91506 +  assert( j+nStr-i+1==nOut );
 1.91507 +  memcpy(&zOut[j], &zStr[i], nStr-i);
 1.91508 +  j += nStr - i;
 1.91509 +  assert( j<=nOut );
 1.91510 +  zOut[j] = 0;
 1.91511 +  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
 1.91512 +}
 1.91513 +
 1.91514 +/*
 1.91515 +** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
 1.91516 +** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
 1.91517 +*/
 1.91518 +static void trimFunc(
 1.91519 +  sqlite3_context *context,
 1.91520 +  int argc,
 1.91521 +  sqlite3_value **argv
 1.91522 +){
 1.91523 +  const unsigned char *zIn;         /* Input string */
 1.91524 +  const unsigned char *zCharSet;    /* Set of characters to trim */
 1.91525 +  int nIn;                          /* Number of bytes in input */
 1.91526 +  int flags;                        /* 1: trimleft  2: trimright  3: trim */
 1.91527 +  int i;                            /* Loop counter */
 1.91528 +  unsigned char *aLen = 0;          /* Length of each character in zCharSet */
 1.91529 +  unsigned char **azChar = 0;       /* Individual characters in zCharSet */
 1.91530 +  int nChar;                        /* Number of characters in zCharSet */
 1.91531 +
 1.91532 +  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
 1.91533 +    return;
 1.91534 +  }
 1.91535 +  zIn = sqlite3_value_text(argv[0]);
 1.91536 +  if( zIn==0 ) return;
 1.91537 +  nIn = sqlite3_value_bytes(argv[0]);
 1.91538 +  assert( zIn==sqlite3_value_text(argv[0]) );
 1.91539 +  if( argc==1 ){
 1.91540 +    static const unsigned char lenOne[] = { 1 };
 1.91541 +    static unsigned char * const azOne[] = { (u8*)" " };
 1.91542 +    nChar = 1;
 1.91543 +    aLen = (u8*)lenOne;
 1.91544 +    azChar = (unsigned char **)azOne;
 1.91545 +    zCharSet = 0;
 1.91546 +  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
 1.91547 +    return;
 1.91548 +  }else{
 1.91549 +    const unsigned char *z;
 1.91550 +    for(z=zCharSet, nChar=0; *z; nChar++){
 1.91551 +      SQLITE_SKIP_UTF8(z);
 1.91552 +    }
 1.91553 +    if( nChar>0 ){
 1.91554 +      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
 1.91555 +      if( azChar==0 ){
 1.91556 +        return;
 1.91557 +      }
 1.91558 +      aLen = (unsigned char*)&azChar[nChar];
 1.91559 +      for(z=zCharSet, nChar=0; *z; nChar++){
 1.91560 +        azChar[nChar] = (unsigned char *)z;
 1.91561 +        SQLITE_SKIP_UTF8(z);
 1.91562 +        aLen[nChar] = (u8)(z - azChar[nChar]);
 1.91563 +      }
 1.91564 +    }
 1.91565 +  }
 1.91566 +  if( nChar>0 ){
 1.91567 +    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
 1.91568 +    if( flags & 1 ){
 1.91569 +      while( nIn>0 ){
 1.91570 +        int len = 0;
 1.91571 +        for(i=0; i<nChar; i++){
 1.91572 +          len = aLen[i];
 1.91573 +          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
 1.91574 +        }
 1.91575 +        if( i>=nChar ) break;
 1.91576 +        zIn += len;
 1.91577 +        nIn -= len;
 1.91578 +      }
 1.91579 +    }
 1.91580 +    if( flags & 2 ){
 1.91581 +      while( nIn>0 ){
 1.91582 +        int len = 0;
 1.91583 +        for(i=0; i<nChar; i++){
 1.91584 +          len = aLen[i];
 1.91585 +          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
 1.91586 +        }
 1.91587 +        if( i>=nChar ) break;
 1.91588 +        nIn -= len;
 1.91589 +      }
 1.91590 +    }
 1.91591 +    if( zCharSet ){
 1.91592 +      sqlite3_free(azChar);
 1.91593 +    }
 1.91594 +  }
 1.91595 +  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
 1.91596 +}
 1.91597 +
 1.91598 +
 1.91599 +/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
 1.91600 +** is only available if the SQLITE_SOUNDEX compile-time option is used
 1.91601 +** when SQLite is built.
 1.91602 +*/
 1.91603 +#ifdef SQLITE_SOUNDEX
 1.91604 +/*
 1.91605 +** Compute the soundex encoding of a word.
 1.91606 +**
 1.91607 +** IMP: R-59782-00072 The soundex(X) function returns a string that is the
 1.91608 +** soundex encoding of the string X. 
 1.91609 +*/
 1.91610 +static void soundexFunc(
 1.91611 +  sqlite3_context *context,
 1.91612 +  int argc,
 1.91613 +  sqlite3_value **argv
 1.91614 +){
 1.91615 +  char zResult[8];
 1.91616 +  const u8 *zIn;
 1.91617 +  int i, j;
 1.91618 +  static const unsigned char iCode[] = {
 1.91619 +    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
 1.91620 +    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
 1.91621 +    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
 1.91622 +    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
 1.91623 +    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
 1.91624 +    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
 1.91625 +    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
 1.91626 +    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
 1.91627 +  };
 1.91628 +  assert( argc==1 );
 1.91629 +  zIn = (u8*)sqlite3_value_text(argv[0]);
 1.91630 +  if( zIn==0 ) zIn = (u8*)"";
 1.91631 +  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
 1.91632 +  if( zIn[i] ){
 1.91633 +    u8 prevcode = iCode[zIn[i]&0x7f];
 1.91634 +    zResult[0] = sqlite3Toupper(zIn[i]);
 1.91635 +    for(j=1; j<4 && zIn[i]; i++){
 1.91636 +      int code = iCode[zIn[i]&0x7f];
 1.91637 +      if( code>0 ){
 1.91638 +        if( code!=prevcode ){
 1.91639 +          prevcode = code;
 1.91640 +          zResult[j++] = code + '0';
 1.91641 +        }
 1.91642 +      }else{
 1.91643 +        prevcode = 0;
 1.91644 +      }
 1.91645 +    }
 1.91646 +    while( j<4 ){
 1.91647 +      zResult[j++] = '0';
 1.91648 +    }
 1.91649 +    zResult[j] = 0;
 1.91650 +    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
 1.91651 +  }else{
 1.91652 +    /* IMP: R-64894-50321 The string "?000" is returned if the argument
 1.91653 +    ** is NULL or contains no ASCII alphabetic characters. */
 1.91654 +    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
 1.91655 +  }
 1.91656 +}
 1.91657 +#endif /* SQLITE_SOUNDEX */
 1.91658 +
 1.91659 +#ifndef SQLITE_OMIT_LOAD_EXTENSION
 1.91660 +/*
 1.91661 +** A function that loads a shared-library extension then returns NULL.
 1.91662 +*/
 1.91663 +static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
 1.91664 +  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
 1.91665 +  const char *zProc;
 1.91666 +  sqlite3 *db = sqlite3_context_db_handle(context);
 1.91667 +  char *zErrMsg = 0;
 1.91668 +
 1.91669 +  if( argc==2 ){
 1.91670 +    zProc = (const char *)sqlite3_value_text(argv[1]);
 1.91671 +  }else{
 1.91672 +    zProc = 0;
 1.91673 +  }
 1.91674 +  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
 1.91675 +    sqlite3_result_error(context, zErrMsg, -1);
 1.91676 +    sqlite3_free(zErrMsg);
 1.91677 +  }
 1.91678 +}
 1.91679 +#endif
 1.91680 +
 1.91681 +
 1.91682 +/*
 1.91683 +** An instance of the following structure holds the context of a
 1.91684 +** sum() or avg() aggregate computation.
 1.91685 +*/
 1.91686 +typedef struct SumCtx SumCtx;
 1.91687 +struct SumCtx {
 1.91688 +  double rSum;      /* Floating point sum */
 1.91689 +  i64 iSum;         /* Integer sum */   
 1.91690 +  i64 cnt;          /* Number of elements summed */
 1.91691 +  u8 overflow;      /* True if integer overflow seen */
 1.91692 +  u8 approx;        /* True if non-integer value was input to the sum */
 1.91693 +};
 1.91694 +
 1.91695 +/*
 1.91696 +** Routines used to compute the sum, average, and total.
 1.91697 +**
 1.91698 +** The SUM() function follows the (broken) SQL standard which means
 1.91699 +** that it returns NULL if it sums over no inputs.  TOTAL returns
 1.91700 +** 0.0 in that case.  In addition, TOTAL always returns a float where
 1.91701 +** SUM might return an integer if it never encounters a floating point
 1.91702 +** value.  TOTAL never fails, but SUM might through an exception if
 1.91703 +** it overflows an integer.
 1.91704 +*/
 1.91705 +static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
 1.91706 +  SumCtx *p;
 1.91707 +  int type;
 1.91708 +  assert( argc==1 );
 1.91709 +  UNUSED_PARAMETER(argc);
 1.91710 +  p = sqlite3_aggregate_context(context, sizeof(*p));
 1.91711 +  type = sqlite3_value_numeric_type(argv[0]);
 1.91712 +  if( p && type!=SQLITE_NULL ){
 1.91713 +    p->cnt++;
 1.91714 +    if( type==SQLITE_INTEGER ){
 1.91715 +      i64 v = sqlite3_value_int64(argv[0]);
 1.91716 +      p->rSum += v;
 1.91717 +      if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
 1.91718 +        p->overflow = 1;
 1.91719 +      }
 1.91720 +    }else{
 1.91721 +      p->rSum += sqlite3_value_double(argv[0]);
 1.91722 +      p->approx = 1;
 1.91723 +    }
 1.91724 +  }
 1.91725 +}
 1.91726 +static void sumFinalize(sqlite3_context *context){
 1.91727 +  SumCtx *p;
 1.91728 +  p = sqlite3_aggregate_context(context, 0);
 1.91729 +  if( p && p->cnt>0 ){
 1.91730 +    if( p->overflow ){
 1.91731 +      sqlite3_result_error(context,"integer overflow",-1);
 1.91732 +    }else if( p->approx ){
 1.91733 +      sqlite3_result_double(context, p->rSum);
 1.91734 +    }else{
 1.91735 +      sqlite3_result_int64(context, p->iSum);
 1.91736 +    }
 1.91737 +  }
 1.91738 +}
 1.91739 +static void avgFinalize(sqlite3_context *context){
 1.91740 +  SumCtx *p;
 1.91741 +  p = sqlite3_aggregate_context(context, 0);
 1.91742 +  if( p && p->cnt>0 ){
 1.91743 +    sqlite3_result_double(context, p->rSum/(double)p->cnt);
 1.91744 +  }
 1.91745 +}
 1.91746 +static void totalFinalize(sqlite3_context *context){
 1.91747 +  SumCtx *p;
 1.91748 +  p = sqlite3_aggregate_context(context, 0);
 1.91749 +  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
 1.91750 +  sqlite3_result_double(context, p ? p->rSum : (double)0);
 1.91751 +}
 1.91752 +
 1.91753 +/*
 1.91754 +** The following structure keeps track of state information for the
 1.91755 +** count() aggregate function.
 1.91756 +*/
 1.91757 +typedef struct CountCtx CountCtx;
 1.91758 +struct CountCtx {
 1.91759 +  i64 n;
 1.91760 +};
 1.91761 +
 1.91762 +/*
 1.91763 +** Routines to implement the count() aggregate function.
 1.91764 +*/
 1.91765 +static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
 1.91766 +  CountCtx *p;
 1.91767 +  p = sqlite3_aggregate_context(context, sizeof(*p));
 1.91768 +  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
 1.91769 +    p->n++;
 1.91770 +  }
 1.91771 +
 1.91772 +#ifndef SQLITE_OMIT_DEPRECATED
 1.91773 +  /* The sqlite3_aggregate_count() function is deprecated.  But just to make
 1.91774 +  ** sure it still operates correctly, verify that its count agrees with our 
 1.91775 +  ** internal count when using count(*) and when the total count can be
 1.91776 +  ** expressed as a 32-bit integer. */
 1.91777 +  assert( argc==1 || p==0 || p->n>0x7fffffff
 1.91778 +          || p->n==sqlite3_aggregate_count(context) );
 1.91779 +#endif
 1.91780 +}   
 1.91781 +static void countFinalize(sqlite3_context *context){
 1.91782 +  CountCtx *p;
 1.91783 +  p = sqlite3_aggregate_context(context, 0);
 1.91784 +  sqlite3_result_int64(context, p ? p->n : 0);
 1.91785 +}
 1.91786 +
 1.91787 +/*
 1.91788 +** Routines to implement min() and max() aggregate functions.
 1.91789 +*/
 1.91790 +static void minmaxStep(
 1.91791 +  sqlite3_context *context, 
 1.91792 +  int NotUsed, 
 1.91793 +  sqlite3_value **argv
 1.91794 +){
 1.91795 +  Mem *pArg  = (Mem *)argv[0];
 1.91796 +  Mem *pBest;
 1.91797 +  UNUSED_PARAMETER(NotUsed);
 1.91798 +
 1.91799 +  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
 1.91800 +  if( !pBest ) return;
 1.91801 +
 1.91802 +  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
 1.91803 +    if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
 1.91804 +  }else if( pBest->flags ){
 1.91805 +    int max;
 1.91806 +    int cmp;
 1.91807 +    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
 1.91808 +    /* This step function is used for both the min() and max() aggregates,
 1.91809 +    ** the only difference between the two being that the sense of the
 1.91810 +    ** comparison is inverted. For the max() aggregate, the
 1.91811 +    ** sqlite3_user_data() function returns (void *)-1. For min() it
 1.91812 +    ** returns (void *)db, where db is the sqlite3* database pointer.
 1.91813 +    ** Therefore the next statement sets variable 'max' to 1 for the max()
 1.91814 +    ** aggregate, or 0 for min().
 1.91815 +    */
 1.91816 +    max = sqlite3_user_data(context)!=0;
 1.91817 +    cmp = sqlite3MemCompare(pBest, pArg, pColl);
 1.91818 +    if( (max && cmp<0) || (!max && cmp>0) ){
 1.91819 +      sqlite3VdbeMemCopy(pBest, pArg);
 1.91820 +    }else{
 1.91821 +      sqlite3SkipAccumulatorLoad(context);
 1.91822 +    }
 1.91823 +  }else{
 1.91824 +    sqlite3VdbeMemCopy(pBest, pArg);
 1.91825 +  }
 1.91826 +}
 1.91827 +static void minMaxFinalize(sqlite3_context *context){
 1.91828 +  sqlite3_value *pRes;
 1.91829 +  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
 1.91830 +  if( pRes ){
 1.91831 +    if( pRes->flags ){
 1.91832 +      sqlite3_result_value(context, pRes);
 1.91833 +    }
 1.91834 +    sqlite3VdbeMemRelease(pRes);
 1.91835 +  }
 1.91836 +}
 1.91837 +
 1.91838 +/*
 1.91839 +** group_concat(EXPR, ?SEPARATOR?)
 1.91840 +*/
 1.91841 +static void groupConcatStep(
 1.91842 +  sqlite3_context *context,
 1.91843 +  int argc,
 1.91844 +  sqlite3_value **argv
 1.91845 +){
 1.91846 +  const char *zVal;
 1.91847 +  StrAccum *pAccum;
 1.91848 +  const char *zSep;
 1.91849 +  int nVal, nSep;
 1.91850 +  assert( argc==1 || argc==2 );
 1.91851 +  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
 1.91852 +  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
 1.91853 +
 1.91854 +  if( pAccum ){
 1.91855 +    sqlite3 *db = sqlite3_context_db_handle(context);
 1.91856 +    int firstTerm = pAccum->useMalloc==0;
 1.91857 +    pAccum->useMalloc = 2;
 1.91858 +    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
 1.91859 +    if( !firstTerm ){
 1.91860 +      if( argc==2 ){
 1.91861 +        zSep = (char*)sqlite3_value_text(argv[1]);
 1.91862 +        nSep = sqlite3_value_bytes(argv[1]);
 1.91863 +      }else{
 1.91864 +        zSep = ",";
 1.91865 +        nSep = 1;
 1.91866 +      }
 1.91867 +      if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
 1.91868 +    }
 1.91869 +    zVal = (char*)sqlite3_value_text(argv[0]);
 1.91870 +    nVal = sqlite3_value_bytes(argv[0]);
 1.91871 +    if( nVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
 1.91872 +  }
 1.91873 +}
 1.91874 +static void groupConcatFinalize(sqlite3_context *context){
 1.91875 +  StrAccum *pAccum;
 1.91876 +  pAccum = sqlite3_aggregate_context(context, 0);
 1.91877 +  if( pAccum ){
 1.91878 +    if( pAccum->accError==STRACCUM_TOOBIG ){
 1.91879 +      sqlite3_result_error_toobig(context);
 1.91880 +    }else if( pAccum->accError==STRACCUM_NOMEM ){
 1.91881 +      sqlite3_result_error_nomem(context);
 1.91882 +    }else{    
 1.91883 +      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
 1.91884 +                          sqlite3_free);
 1.91885 +    }
 1.91886 +  }
 1.91887 +}
 1.91888 +
 1.91889 +/*
 1.91890 +** This routine does per-connection function registration.  Most
 1.91891 +** of the built-in functions above are part of the global function set.
 1.91892 +** This routine only deals with those that are not global.
 1.91893 +*/
 1.91894 +SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
 1.91895 +  int rc = sqlite3_overload_function(db, "MATCH", 2);
 1.91896 +  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
 1.91897 +  if( rc==SQLITE_NOMEM ){
 1.91898 +    db->mallocFailed = 1;
 1.91899 +  }
 1.91900 +}
 1.91901 +
 1.91902 +/*
 1.91903 +** Set the LIKEOPT flag on the 2-argument function with the given name.
 1.91904 +*/
 1.91905 +static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
 1.91906 +  FuncDef *pDef;
 1.91907 +  pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
 1.91908 +                             2, SQLITE_UTF8, 0);
 1.91909 +  if( ALWAYS(pDef) ){
 1.91910 +    pDef->funcFlags |= flagVal;
 1.91911 +  }
 1.91912 +}
 1.91913 +
 1.91914 +/*
 1.91915 +** Register the built-in LIKE and GLOB functions.  The caseSensitive
 1.91916 +** parameter determines whether or not the LIKE operator is case
 1.91917 +** sensitive.  GLOB is always case sensitive.
 1.91918 +*/
 1.91919 +SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
 1.91920 +  struct compareInfo *pInfo;
 1.91921 +  if( caseSensitive ){
 1.91922 +    pInfo = (struct compareInfo*)&likeInfoAlt;
 1.91923 +  }else{
 1.91924 +    pInfo = (struct compareInfo*)&likeInfoNorm;
 1.91925 +  }
 1.91926 +  sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
 1.91927 +  sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
 1.91928 +  sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
 1.91929 +      (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
 1.91930 +  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
 1.91931 +  setLikeOptFlag(db, "like", 
 1.91932 +      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
 1.91933 +}
 1.91934 +
 1.91935 +/*
 1.91936 +** pExpr points to an expression which implements a function.  If
 1.91937 +** it is appropriate to apply the LIKE optimization to that function
 1.91938 +** then set aWc[0] through aWc[2] to the wildcard characters and
 1.91939 +** return TRUE.  If the function is not a LIKE-style function then
 1.91940 +** return FALSE.
 1.91941 +*/
 1.91942 +SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
 1.91943 +  FuncDef *pDef;
 1.91944 +  if( pExpr->op!=TK_FUNCTION 
 1.91945 +   || !pExpr->x.pList 
 1.91946 +   || pExpr->x.pList->nExpr!=2
 1.91947 +  ){
 1.91948 +    return 0;
 1.91949 +  }
 1.91950 +  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
 1.91951 +  pDef = sqlite3FindFunction(db, pExpr->u.zToken, 
 1.91952 +                             sqlite3Strlen30(pExpr->u.zToken),
 1.91953 +                             2, SQLITE_UTF8, 0);
 1.91954 +  if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
 1.91955 +    return 0;
 1.91956 +  }
 1.91957 +
 1.91958 +  /* The memcpy() statement assumes that the wildcard characters are
 1.91959 +  ** the first three statements in the compareInfo structure.  The
 1.91960 +  ** asserts() that follow verify that assumption
 1.91961 +  */
 1.91962 +  memcpy(aWc, pDef->pUserData, 3);
 1.91963 +  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
 1.91964 +  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
 1.91965 +  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
 1.91966 +  *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
 1.91967 +  return 1;
 1.91968 +}
 1.91969 +
 1.91970 +/*
 1.91971 +** All all of the FuncDef structures in the aBuiltinFunc[] array above
 1.91972 +** to the global function hash table.  This occurs at start-time (as
 1.91973 +** a consequence of calling sqlite3_initialize()).
 1.91974 +**
 1.91975 +** After this routine runs
 1.91976 +*/
 1.91977 +SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
 1.91978 +  /*
 1.91979 +  ** The following array holds FuncDef structures for all of the functions
 1.91980 +  ** defined in this file.
 1.91981 +  **
 1.91982 +  ** The array cannot be constant since changes are made to the
 1.91983 +  ** FuncDef.pHash elements at start-time.  The elements of this array
 1.91984 +  ** are read-only after initialization is complete.
 1.91985 +  */
 1.91986 +  static SQLITE_WSD FuncDef aBuiltinFunc[] = {
 1.91987 +    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
 1.91988 +    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
 1.91989 +    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
 1.91990 +    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
 1.91991 +    FUNCTION(trim,               1, 3, 0, trimFunc         ),
 1.91992 +    FUNCTION(trim,               2, 3, 0, trimFunc         ),
 1.91993 +    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
 1.91994 +    FUNCTION(min,                0, 0, 1, 0                ),
 1.91995 +    AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
 1.91996 +    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
 1.91997 +    FUNCTION(max,                0, 1, 1, 0                ),
 1.91998 +    AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
 1.91999 +    FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
 1.92000 +    FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
 1.92001 +    FUNCTION(instr,              2, 0, 0, instrFunc        ),
 1.92002 +    FUNCTION(substr,             2, 0, 0, substrFunc       ),
 1.92003 +    FUNCTION(substr,             3, 0, 0, substrFunc       ),
 1.92004 +    FUNCTION(printf,            -1, 0, 0, printfFunc       ),
 1.92005 +    FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
 1.92006 +    FUNCTION(char,              -1, 0, 0, charFunc         ),
 1.92007 +    FUNCTION(abs,                1, 0, 0, absFunc          ),
 1.92008 +#ifndef SQLITE_OMIT_FLOATING_POINT
 1.92009 +    FUNCTION(round,              1, 0, 0, roundFunc        ),
 1.92010 +    FUNCTION(round,              2, 0, 0, roundFunc        ),
 1.92011 +#endif
 1.92012 +    FUNCTION(upper,              1, 0, 0, upperFunc        ),
 1.92013 +    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
 1.92014 +    FUNCTION(coalesce,           1, 0, 0, 0                ),
 1.92015 +    FUNCTION(coalesce,           0, 0, 0, 0                ),
 1.92016 +    FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
 1.92017 +    FUNCTION(hex,                1, 0, 0, hexFunc          ),
 1.92018 +    FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
 1.92019 +    FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
 1.92020 +    FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
 1.92021 +    VFUNCTION(random,            0, 0, 0, randomFunc       ),
 1.92022 +    VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
 1.92023 +    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
 1.92024 +    FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
 1.92025 +    FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
 1.92026 +    FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
 1.92027 +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
 1.92028 +    FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
 1.92029 +    FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
 1.92030 +#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
 1.92031 +    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
 1.92032 +    VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
 1.92033 +    VFUNCTION(changes,           0, 0, 0, changes          ),
 1.92034 +    VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
 1.92035 +    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
 1.92036 +    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
 1.92037 +  #ifdef SQLITE_SOUNDEX
 1.92038 +    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
 1.92039 +  #endif
 1.92040 +  #ifndef SQLITE_OMIT_LOAD_EXTENSION
 1.92041 +    FUNCTION(load_extension,     1, 0, 0, loadExt          ),
 1.92042 +    FUNCTION(load_extension,     2, 0, 0, loadExt          ),
 1.92043 +  #endif
 1.92044 +    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
 1.92045 +    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
 1.92046 +    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
 1.92047 + /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
 1.92048 +    {0,SQLITE_UTF8|SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
 1.92049 +    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
 1.92050 +    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
 1.92051 +    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
 1.92052 +  
 1.92053 +    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
 1.92054 +  #ifdef SQLITE_CASE_SENSITIVE_LIKE
 1.92055 +    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
 1.92056 +    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
 1.92057 +  #else
 1.92058 +    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
 1.92059 +    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
 1.92060 +  #endif
 1.92061 +  };
 1.92062 +
 1.92063 +  int i;
 1.92064 +  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
 1.92065 +  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
 1.92066 +
 1.92067 +  for(i=0; i<ArraySize(aBuiltinFunc); i++){
 1.92068 +    sqlite3FuncDefInsert(pHash, &aFunc[i]);
 1.92069 +  }
 1.92070 +  sqlite3RegisterDateTimeFunctions();
 1.92071 +#ifndef SQLITE_OMIT_ALTERTABLE
 1.92072 +  sqlite3AlterFunctions();
 1.92073 +#endif
 1.92074 +#if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
 1.92075 +  sqlite3AnalyzeFunctions();
 1.92076 +#endif
 1.92077 +}
 1.92078 +
 1.92079 +/************** End of func.c ************************************************/
 1.92080 +/************** Begin file fkey.c ********************************************/
 1.92081 +/*
 1.92082 +**
 1.92083 +** The author disclaims copyright to this source code.  In place of
 1.92084 +** a legal notice, here is a blessing:
 1.92085 +**
 1.92086 +**    May you do good and not evil.
 1.92087 +**    May you find forgiveness for yourself and forgive others.
 1.92088 +**    May you share freely, never taking more than you give.
 1.92089 +**
 1.92090 +*************************************************************************
 1.92091 +** This file contains code used by the compiler to add foreign key
 1.92092 +** support to compiled SQL statements.
 1.92093 +*/
 1.92094 +
 1.92095 +#ifndef SQLITE_OMIT_FOREIGN_KEY
 1.92096 +#ifndef SQLITE_OMIT_TRIGGER
 1.92097 +
 1.92098 +/*
 1.92099 +** Deferred and Immediate FKs
 1.92100 +** --------------------------
 1.92101 +**
 1.92102 +** Foreign keys in SQLite come in two flavours: deferred and immediate.
 1.92103 +** If an immediate foreign key constraint is violated,
 1.92104 +** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
 1.92105 +** statement transaction rolled back. If a 
 1.92106 +** deferred foreign key constraint is violated, no action is taken 
 1.92107 +** immediately. However if the application attempts to commit the 
 1.92108 +** transaction before fixing the constraint violation, the attempt fails.
 1.92109 +**
 1.92110 +** Deferred constraints are implemented using a simple counter associated
 1.92111 +** with the database handle. The counter is set to zero each time a 
 1.92112 +** database transaction is opened. Each time a statement is executed 
 1.92113 +** that causes a foreign key violation, the counter is incremented. Each
 1.92114 +** time a statement is executed that removes an existing violation from
 1.92115 +** the database, the counter is decremented. When the transaction is
 1.92116 +** committed, the commit fails if the current value of the counter is
 1.92117 +** greater than zero. This scheme has two big drawbacks:
 1.92118 +**
 1.92119 +**   * When a commit fails due to a deferred foreign key constraint, 
 1.92120 +**     there is no way to tell which foreign constraint is not satisfied,
 1.92121 +**     or which row it is not satisfied for.
 1.92122 +**
 1.92123 +**   * If the database contains foreign key violations when the 
 1.92124 +**     transaction is opened, this may cause the mechanism to malfunction.
 1.92125 +**
 1.92126 +** Despite these problems, this approach is adopted as it seems simpler
 1.92127 +** than the alternatives.
 1.92128 +**
 1.92129 +** INSERT operations:
 1.92130 +**
 1.92131 +**   I.1) For each FK for which the table is the child table, search
 1.92132 +**        the parent table for a match. If none is found increment the
 1.92133 +**        constraint counter.
 1.92134 +**
 1.92135 +**   I.2) For each FK for which the table is the parent table, 
 1.92136 +**        search the child table for rows that correspond to the new
 1.92137 +**        row in the parent table. Decrement the counter for each row
 1.92138 +**        found (as the constraint is now satisfied).
 1.92139 +**
 1.92140 +** DELETE operations:
 1.92141 +**
 1.92142 +**   D.1) For each FK for which the table is the child table, 
 1.92143 +**        search the parent table for a row that corresponds to the 
 1.92144 +**        deleted row in the child table. If such a row is not found, 
 1.92145 +**        decrement the counter.
 1.92146 +**
 1.92147 +**   D.2) For each FK for which the table is the parent table, search 
 1.92148 +**        the child table for rows that correspond to the deleted row 
 1.92149 +**        in the parent table. For each found increment the counter.
 1.92150 +**
 1.92151 +** UPDATE operations:
 1.92152 +**
 1.92153 +**   An UPDATE command requires that all 4 steps above are taken, but only
 1.92154 +**   for FK constraints for which the affected columns are actually 
 1.92155 +**   modified (values must be compared at runtime).
 1.92156 +**
 1.92157 +** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
 1.92158 +** This simplifies the implementation a bit.
 1.92159 +**
 1.92160 +** For the purposes of immediate FK constraints, the OR REPLACE conflict
 1.92161 +** resolution is considered to delete rows before the new row is inserted.
 1.92162 +** If a delete caused by OR REPLACE violates an FK constraint, an exception
 1.92163 +** is thrown, even if the FK constraint would be satisfied after the new 
 1.92164 +** row is inserted.
 1.92165 +**
 1.92166 +** Immediate constraints are usually handled similarly. The only difference 
 1.92167 +** is that the counter used is stored as part of each individual statement
 1.92168 +** object (struct Vdbe). If, after the statement has run, its immediate
 1.92169 +** constraint counter is greater than zero,
 1.92170 +** it returns SQLITE_CONSTRAINT_FOREIGNKEY
 1.92171 +** and the statement transaction is rolled back. An exception is an INSERT
 1.92172 +** statement that inserts a single row only (no triggers). In this case,
 1.92173 +** instead of using a counter, an exception is thrown immediately if the
 1.92174 +** INSERT violates a foreign key constraint. This is necessary as such
 1.92175 +** an INSERT does not open a statement transaction.
 1.92176 +**
 1.92177 +** TODO: How should dropping a table be handled? How should renaming a 
 1.92178 +** table be handled?
 1.92179 +**
 1.92180 +**
 1.92181 +** Query API Notes
 1.92182 +** ---------------
 1.92183 +**
 1.92184 +** Before coding an UPDATE or DELETE row operation, the code-generator
 1.92185 +** for those two operations needs to know whether or not the operation
 1.92186 +** requires any FK processing and, if so, which columns of the original
 1.92187 +** row are required by the FK processing VDBE code (i.e. if FKs were
 1.92188 +** implemented using triggers, which of the old.* columns would be 
 1.92189 +** accessed). No information is required by the code-generator before
 1.92190 +** coding an INSERT operation. The functions used by the UPDATE/DELETE
 1.92191 +** generation code to query for this information are:
 1.92192 +**
 1.92193 +**   sqlite3FkRequired() - Test to see if FK processing is required.
 1.92194 +**   sqlite3FkOldmask()  - Query for the set of required old.* columns.
 1.92195 +**
 1.92196 +**
 1.92197 +** Externally accessible module functions
 1.92198 +** --------------------------------------
 1.92199 +**
 1.92200 +**   sqlite3FkCheck()    - Check for foreign key violations.
 1.92201 +**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
 1.92202 +**   sqlite3FkDelete()   - Delete an FKey structure.
 1.92203 +*/
 1.92204 +
 1.92205 +/*
 1.92206 +** VDBE Calling Convention
 1.92207 +** -----------------------
 1.92208 +**
 1.92209 +** Example:
 1.92210 +**
 1.92211 +**   For the following INSERT statement:
 1.92212 +**
 1.92213 +**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
 1.92214 +**     INSERT INTO t1 VALUES(1, 2, 3.1);
 1.92215 +**
 1.92216 +**   Register (x):        2    (type integer)
 1.92217 +**   Register (x+1):      1    (type integer)
 1.92218 +**   Register (x+2):      NULL (type NULL)
 1.92219 +**   Register (x+3):      3.1  (type real)
 1.92220 +*/
 1.92221 +
 1.92222 +/*
 1.92223 +** A foreign key constraint requires that the key columns in the parent
 1.92224 +** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
 1.92225 +** Given that pParent is the parent table for foreign key constraint pFKey, 
 1.92226 +** search the schema for a unique index on the parent key columns. 
 1.92227 +**
 1.92228 +** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
 1.92229 +** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
 1.92230 +** is set to point to the unique index. 
 1.92231 +** 
 1.92232 +** If the parent key consists of a single column (the foreign key constraint
 1.92233 +** is not a composite foreign key), output variable *paiCol is set to NULL.
 1.92234 +** Otherwise, it is set to point to an allocated array of size N, where
 1.92235 +** N is the number of columns in the parent key. The first element of the
 1.92236 +** array is the index of the child table column that is mapped by the FK
 1.92237 +** constraint to the parent table column stored in the left-most column
 1.92238 +** of index *ppIdx. The second element of the array is the index of the
 1.92239 +** child table column that corresponds to the second left-most column of
 1.92240 +** *ppIdx, and so on.
 1.92241 +**
 1.92242 +** If the required index cannot be found, either because:
 1.92243 +**
 1.92244 +**   1) The named parent key columns do not exist, or
 1.92245 +**
 1.92246 +**   2) The named parent key columns do exist, but are not subject to a
 1.92247 +**      UNIQUE or PRIMARY KEY constraint, or
 1.92248 +**
 1.92249 +**   3) No parent key columns were provided explicitly as part of the
 1.92250 +**      foreign key definition, and the parent table does not have a
 1.92251 +**      PRIMARY KEY, or
 1.92252 +**
 1.92253 +**   4) No parent key columns were provided explicitly as part of the
 1.92254 +**      foreign key definition, and the PRIMARY KEY of the parent table 
 1.92255 +**      consists of a a different number of columns to the child key in 
 1.92256 +**      the child table.
 1.92257 +**
 1.92258 +** then non-zero is returned, and a "foreign key mismatch" error loaded
 1.92259 +** into pParse. If an OOM error occurs, non-zero is returned and the
 1.92260 +** pParse->db->mallocFailed flag is set.
 1.92261 +*/
 1.92262 +SQLITE_PRIVATE int sqlite3FkLocateIndex(
 1.92263 +  Parse *pParse,                  /* Parse context to store any error in */
 1.92264 +  Table *pParent,                 /* Parent table of FK constraint pFKey */
 1.92265 +  FKey *pFKey,                    /* Foreign key to find index for */
 1.92266 +  Index **ppIdx,                  /* OUT: Unique index on parent table */
 1.92267 +  int **paiCol                    /* OUT: Map of index columns in pFKey */
 1.92268 +){
 1.92269 +  Index *pIdx = 0;                    /* Value to return via *ppIdx */
 1.92270 +  int *aiCol = 0;                     /* Value to return via *paiCol */
 1.92271 +  int nCol = pFKey->nCol;             /* Number of columns in parent key */
 1.92272 +  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
 1.92273 +
 1.92274 +  /* The caller is responsible for zeroing output parameters. */
 1.92275 +  assert( ppIdx && *ppIdx==0 );
 1.92276 +  assert( !paiCol || *paiCol==0 );
 1.92277 +  assert( pParse );
 1.92278 +
 1.92279 +  /* If this is a non-composite (single column) foreign key, check if it 
 1.92280 +  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
 1.92281 +  ** and *paiCol set to zero and return early. 
 1.92282 +  **
 1.92283 +  ** Otherwise, for a composite foreign key (more than one column), allocate
 1.92284 +  ** space for the aiCol array (returned via output parameter *paiCol).
 1.92285 +  ** Non-composite foreign keys do not require the aiCol array.
 1.92286 +  */
 1.92287 +  if( nCol==1 ){
 1.92288 +    /* The FK maps to the IPK if any of the following are true:
 1.92289 +    **
 1.92290 +    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
 1.92291 +    **      mapped to the primary key of table pParent, or
 1.92292 +    **   2) The FK is explicitly mapped to a column declared as INTEGER
 1.92293 +    **      PRIMARY KEY.
 1.92294 +    */
 1.92295 +    if( pParent->iPKey>=0 ){
 1.92296 +      if( !zKey ) return 0;
 1.92297 +      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
 1.92298 +    }
 1.92299 +  }else if( paiCol ){
 1.92300 +    assert( nCol>1 );
 1.92301 +    aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
 1.92302 +    if( !aiCol ) return 1;
 1.92303 +    *paiCol = aiCol;
 1.92304 +  }
 1.92305 +
 1.92306 +  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
 1.92307 +    if( pIdx->nKeyCol==nCol && pIdx->onError!=OE_None ){ 
 1.92308 +      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
 1.92309 +      ** of columns. If each indexed column corresponds to a foreign key
 1.92310 +      ** column of pFKey, then this index is a winner.  */
 1.92311 +
 1.92312 +      if( zKey==0 ){
 1.92313 +        /* If zKey is NULL, then this foreign key is implicitly mapped to 
 1.92314 +        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
 1.92315 +        ** identified by the test (Index.autoIndex==2).  */
 1.92316 +        if( pIdx->autoIndex==2 ){
 1.92317 +          if( aiCol ){
 1.92318 +            int i;
 1.92319 +            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
 1.92320 +          }
 1.92321 +          break;
 1.92322 +        }
 1.92323 +      }else{
 1.92324 +        /* If zKey is non-NULL, then this foreign key was declared to
 1.92325 +        ** map to an explicit list of columns in table pParent. Check if this
 1.92326 +        ** index matches those columns. Also, check that the index uses
 1.92327 +        ** the default collation sequences for each column. */
 1.92328 +        int i, j;
 1.92329 +        for(i=0; i<nCol; i++){
 1.92330 +          i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
 1.92331 +          char *zDfltColl;                  /* Def. collation for column */
 1.92332 +          char *zIdxCol;                    /* Name of indexed column */
 1.92333 +
 1.92334 +          /* If the index uses a collation sequence that is different from
 1.92335 +          ** the default collation sequence for the column, this index is
 1.92336 +          ** unusable. Bail out early in this case.  */
 1.92337 +          zDfltColl = pParent->aCol[iCol].zColl;
 1.92338 +          if( !zDfltColl ){
 1.92339 +            zDfltColl = "BINARY";
 1.92340 +          }
 1.92341 +          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
 1.92342 +
 1.92343 +          zIdxCol = pParent->aCol[iCol].zName;
 1.92344 +          for(j=0; j<nCol; j++){
 1.92345 +            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
 1.92346 +              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
 1.92347 +              break;
 1.92348 +            }
 1.92349 +          }
 1.92350 +          if( j==nCol ) break;
 1.92351 +        }
 1.92352 +        if( i==nCol ) break;      /* pIdx is usable */
 1.92353 +      }
 1.92354 +    }
 1.92355 +  }
 1.92356 +
 1.92357 +  if( !pIdx ){
 1.92358 +    if( !pParse->disableTriggers ){
 1.92359 +      sqlite3ErrorMsg(pParse,
 1.92360 +           "foreign key mismatch - \"%w\" referencing \"%w\"",
 1.92361 +           pFKey->pFrom->zName, pFKey->zTo);
 1.92362 +    }
 1.92363 +    sqlite3DbFree(pParse->db, aiCol);
 1.92364 +    return 1;
 1.92365 +  }
 1.92366 +
 1.92367 +  *ppIdx = pIdx;
 1.92368 +  return 0;
 1.92369 +}
 1.92370 +
 1.92371 +/*
 1.92372 +** This function is called when a row is inserted into or deleted from the 
 1.92373 +** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
 1.92374 +** on the child table of pFKey, this function is invoked twice for each row
 1.92375 +** affected - once to "delete" the old row, and then again to "insert" the
 1.92376 +** new row.
 1.92377 +**
 1.92378 +** Each time it is called, this function generates VDBE code to locate the
 1.92379 +** row in the parent table that corresponds to the row being inserted into 
 1.92380 +** or deleted from the child table. If the parent row can be found, no 
 1.92381 +** special action is taken. Otherwise, if the parent row can *not* be
 1.92382 +** found in the parent table:
 1.92383 +**
 1.92384 +**   Operation | FK type   | Action taken
 1.92385 +**   --------------------------------------------------------------------------
 1.92386 +**   INSERT      immediate   Increment the "immediate constraint counter".
 1.92387 +**
 1.92388 +**   DELETE      immediate   Decrement the "immediate constraint counter".
 1.92389 +**
 1.92390 +**   INSERT      deferred    Increment the "deferred constraint counter".
 1.92391 +**
 1.92392 +**   DELETE      deferred    Decrement the "deferred constraint counter".
 1.92393 +**
 1.92394 +** These operations are identified in the comment at the top of this file 
 1.92395 +** (fkey.c) as "I.1" and "D.1".
 1.92396 +*/
 1.92397 +static void fkLookupParent(
 1.92398 +  Parse *pParse,        /* Parse context */
 1.92399 +  int iDb,              /* Index of database housing pTab */
 1.92400 +  Table *pTab,          /* Parent table of FK pFKey */
 1.92401 +  Index *pIdx,          /* Unique index on parent key columns in pTab */
 1.92402 +  FKey *pFKey,          /* Foreign key constraint */
 1.92403 +  int *aiCol,           /* Map from parent key columns to child table columns */
 1.92404 +  int regData,          /* Address of array containing child table row */
 1.92405 +  int nIncr,            /* Increment constraint counter by this */
 1.92406 +  int isIgnore          /* If true, pretend pTab contains all NULL values */
 1.92407 +){
 1.92408 +  int i;                                    /* Iterator variable */
 1.92409 +  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
 1.92410 +  int iCur = pParse->nTab - 1;              /* Cursor number to use */
 1.92411 +  int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
 1.92412 +
 1.92413 +  /* If nIncr is less than zero, then check at runtime if there are any
 1.92414 +  ** outstanding constraints to resolve. If there are not, there is no need
 1.92415 +  ** to check if deleting this row resolves any outstanding violations.
 1.92416 +  **
 1.92417 +  ** Check if any of the key columns in the child table row are NULL. If 
 1.92418 +  ** any are, then the constraint is considered satisfied. No need to 
 1.92419 +  ** search for a matching row in the parent table.  */
 1.92420 +  if( nIncr<0 ){
 1.92421 +    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
 1.92422 +    VdbeCoverage(v);
 1.92423 +  }
 1.92424 +  for(i=0; i<pFKey->nCol; i++){
 1.92425 +    int iReg = aiCol[i] + regData + 1;
 1.92426 +    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
 1.92427 +  }
 1.92428 +
 1.92429 +  if( isIgnore==0 ){
 1.92430 +    if( pIdx==0 ){
 1.92431 +      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
 1.92432 +      ** column of the parent table (table pTab).  */
 1.92433 +      int iMustBeInt;               /* Address of MustBeInt instruction */
 1.92434 +      int regTemp = sqlite3GetTempReg(pParse);
 1.92435 +  
 1.92436 +      /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
 1.92437 +      ** apply the affinity of the parent key). If this fails, then there
 1.92438 +      ** is no matching parent key. Before using MustBeInt, make a copy of
 1.92439 +      ** the value. Otherwise, the value inserted into the child key column
 1.92440 +      ** will have INTEGER affinity applied to it, which may not be correct.  */
 1.92441 +      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
 1.92442 +      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
 1.92443 +      VdbeCoverage(v);
 1.92444 +  
 1.92445 +      /* If the parent table is the same as the child table, and we are about
 1.92446 +      ** to increment the constraint-counter (i.e. this is an INSERT operation),
 1.92447 +      ** then check if the row being inserted matches itself. If so, do not
 1.92448 +      ** increment the constraint-counter.  */
 1.92449 +      if( pTab==pFKey->pFrom && nIncr==1 ){
 1.92450 +        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
 1.92451 +        sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
 1.92452 +      }
 1.92453 +  
 1.92454 +      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
 1.92455 +      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
 1.92456 +      sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
 1.92457 +      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
 1.92458 +      sqlite3VdbeJumpHere(v, iMustBeInt);
 1.92459 +      sqlite3ReleaseTempReg(pParse, regTemp);
 1.92460 +    }else{
 1.92461 +      int nCol = pFKey->nCol;
 1.92462 +      int regTemp = sqlite3GetTempRange(pParse, nCol);
 1.92463 +      int regRec = sqlite3GetTempReg(pParse);
 1.92464 +  
 1.92465 +      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
 1.92466 +      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
 1.92467 +      for(i=0; i<nCol; i++){
 1.92468 +        sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
 1.92469 +      }
 1.92470 +  
 1.92471 +      /* If the parent table is the same as the child table, and we are about
 1.92472 +      ** to increment the constraint-counter (i.e. this is an INSERT operation),
 1.92473 +      ** then check if the row being inserted matches itself. If so, do not
 1.92474 +      ** increment the constraint-counter. 
 1.92475 +      **
 1.92476 +      ** If any of the parent-key values are NULL, then the row cannot match 
 1.92477 +      ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
 1.92478 +      ** of the parent-key values are NULL (at this point it is known that
 1.92479 +      ** none of the child key values are).
 1.92480 +      */
 1.92481 +      if( pTab==pFKey->pFrom && nIncr==1 ){
 1.92482 +        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
 1.92483 +        for(i=0; i<nCol; i++){
 1.92484 +          int iChild = aiCol[i]+1+regData;
 1.92485 +          int iParent = pIdx->aiColumn[i]+1+regData;
 1.92486 +          assert( aiCol[i]!=pTab->iPKey );
 1.92487 +          if( pIdx->aiColumn[i]==pTab->iPKey ){
 1.92488 +            /* The parent key is a composite key that includes the IPK column */
 1.92489 +            iParent = regData;
 1.92490 +          }
 1.92491 +          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
 1.92492 +          sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
 1.92493 +        }
 1.92494 +        sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
 1.92495 +      }
 1.92496 +  
 1.92497 +      sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
 1.92498 +                        sqlite3IndexAffinityStr(v,pIdx), nCol);
 1.92499 +      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
 1.92500 +  
 1.92501 +      sqlite3ReleaseTempReg(pParse, regRec);
 1.92502 +      sqlite3ReleaseTempRange(pParse, regTemp, nCol);
 1.92503 +    }
 1.92504 +  }
 1.92505 +
 1.92506 +  if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
 1.92507 +   && !pParse->pToplevel 
 1.92508 +   && !pParse->isMultiWrite 
 1.92509 +  ){
 1.92510 +    /* Special case: If this is an INSERT statement that will insert exactly
 1.92511 +    ** one row into the table, raise a constraint immediately instead of
 1.92512 +    ** incrementing a counter. This is necessary as the VM code is being
 1.92513 +    ** generated for will not open a statement transaction.  */
 1.92514 +    assert( nIncr==1 );
 1.92515 +    sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
 1.92516 +        OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
 1.92517 +  }else{
 1.92518 +    if( nIncr>0 && pFKey->isDeferred==0 ){
 1.92519 +      sqlite3ParseToplevel(pParse)->mayAbort = 1;
 1.92520 +    }
 1.92521 +    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
 1.92522 +  }
 1.92523 +
 1.92524 +  sqlite3VdbeResolveLabel(v, iOk);
 1.92525 +  sqlite3VdbeAddOp1(v, OP_Close, iCur);
 1.92526 +}
 1.92527 +
 1.92528 +
 1.92529 +/*
 1.92530 +** Return an Expr object that refers to a memory register corresponding
 1.92531 +** to column iCol of table pTab.
 1.92532 +**
 1.92533 +** regBase is the first of an array of register that contains the data
 1.92534 +** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first
 1.92535 +** column.  regBase+2 holds the second column, and so forth.
 1.92536 +*/
 1.92537 +static Expr *exprTableRegister(
 1.92538 +  Parse *pParse,     /* Parsing and code generating context */
 1.92539 +  Table *pTab,       /* The table whose content is at r[regBase]... */
 1.92540 +  int regBase,       /* Contents of table pTab */
 1.92541 +  i16 iCol           /* Which column of pTab is desired */
 1.92542 +){
 1.92543 +  Expr *pExpr;
 1.92544 +  Column *pCol;
 1.92545 +  const char *zColl;
 1.92546 +  sqlite3 *db = pParse->db;
 1.92547 +
 1.92548 +  pExpr = sqlite3Expr(db, TK_REGISTER, 0);
 1.92549 +  if( pExpr ){
 1.92550 +    if( iCol>=0 && iCol!=pTab->iPKey ){
 1.92551 +      pCol = &pTab->aCol[iCol];
 1.92552 +      pExpr->iTable = regBase + iCol + 1;
 1.92553 +      pExpr->affinity = pCol->affinity;
 1.92554 +      zColl = pCol->zColl;
 1.92555 +      if( zColl==0 ) zColl = db->pDfltColl->zName;
 1.92556 +      pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
 1.92557 +    }else{
 1.92558 +      pExpr->iTable = regBase;
 1.92559 +      pExpr->affinity = SQLITE_AFF_INTEGER;
 1.92560 +    }
 1.92561 +  }
 1.92562 +  return pExpr;
 1.92563 +}
 1.92564 +
 1.92565 +/*
 1.92566 +** Return an Expr object that refers to column iCol of table pTab which
 1.92567 +** has cursor iCur.
 1.92568 +*/
 1.92569 +static Expr *exprTableColumn(
 1.92570 +  sqlite3 *db,      /* The database connection */
 1.92571 +  Table *pTab,      /* The table whose column is desired */
 1.92572 +  int iCursor,      /* The open cursor on the table */
 1.92573 +  i16 iCol          /* The column that is wanted */
 1.92574 +){
 1.92575 +  Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
 1.92576 +  if( pExpr ){
 1.92577 +    pExpr->pTab = pTab;
 1.92578 +    pExpr->iTable = iCursor;
 1.92579 +    pExpr->iColumn = iCol;
 1.92580 +  }
 1.92581 +  return pExpr;
 1.92582 +}
 1.92583 +
 1.92584 +/*
 1.92585 +** This function is called to generate code executed when a row is deleted
 1.92586 +** from the parent table of foreign key constraint pFKey and, if pFKey is 
 1.92587 +** deferred, when a row is inserted into the same table. When generating
 1.92588 +** code for an SQL UPDATE operation, this function may be called twice -
 1.92589 +** once to "delete" the old row and once to "insert" the new row.
 1.92590 +**
 1.92591 +** The code generated by this function scans through the rows in the child
 1.92592 +** table that correspond to the parent table row being deleted or inserted.
 1.92593 +** For each child row found, one of the following actions is taken:
 1.92594 +**
 1.92595 +**   Operation | FK type   | Action taken
 1.92596 +**   --------------------------------------------------------------------------
 1.92597 +**   DELETE      immediate   Increment the "immediate constraint counter".
 1.92598 +**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
 1.92599 +**                           throw a "FOREIGN KEY constraint failed" exception.
 1.92600 +**
 1.92601 +**   INSERT      immediate   Decrement the "immediate constraint counter".
 1.92602 +**
 1.92603 +**   DELETE      deferred    Increment the "deferred constraint counter".
 1.92604 +**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
 1.92605 +**                           throw a "FOREIGN KEY constraint failed" exception.
 1.92606 +**
 1.92607 +**   INSERT      deferred    Decrement the "deferred constraint counter".
 1.92608 +**
 1.92609 +** These operations are identified in the comment at the top of this file 
 1.92610 +** (fkey.c) as "I.2" and "D.2".
 1.92611 +*/
 1.92612 +static void fkScanChildren(
 1.92613 +  Parse *pParse,                  /* Parse context */
 1.92614 +  SrcList *pSrc,                  /* The child table to be scanned */
 1.92615 +  Table *pTab,                    /* The parent table */
 1.92616 +  Index *pIdx,                    /* Index on parent covering the foreign key */
 1.92617 +  FKey *pFKey,                    /* The foreign key linking pSrc to pTab */
 1.92618 +  int *aiCol,                     /* Map from pIdx cols to child table cols */
 1.92619 +  int regData,                    /* Parent row data starts here */
 1.92620 +  int nIncr                       /* Amount to increment deferred counter by */
 1.92621 +){
 1.92622 +  sqlite3 *db = pParse->db;       /* Database handle */
 1.92623 +  int i;                          /* Iterator variable */
 1.92624 +  Expr *pWhere = 0;               /* WHERE clause to scan with */
 1.92625 +  NameContext sNameContext;       /* Context used to resolve WHERE clause */
 1.92626 +  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
 1.92627 +  int iFkIfZero = 0;              /* Address of OP_FkIfZero */
 1.92628 +  Vdbe *v = sqlite3GetVdbe(pParse);
 1.92629 +
 1.92630 +  assert( pIdx==0 || pIdx->pTable==pTab );
 1.92631 +  assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
 1.92632 +  assert( pIdx!=0 || pFKey->nCol==1 );
 1.92633 +  assert( pIdx!=0 || HasRowid(pTab) );
 1.92634 +
 1.92635 +  if( nIncr<0 ){
 1.92636 +    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
 1.92637 +    VdbeCoverage(v);
 1.92638 +  }
 1.92639 +
 1.92640 +  /* Create an Expr object representing an SQL expression like:
 1.92641 +  **
 1.92642 +  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
 1.92643 +  **
 1.92644 +  ** The collation sequence used for the comparison should be that of
 1.92645 +  ** the parent key columns. The affinity of the parent key column should
 1.92646 +  ** be applied to each child key value before the comparison takes place.
 1.92647 +  */
 1.92648 +  for(i=0; i<pFKey->nCol; i++){
 1.92649 +    Expr *pLeft;                  /* Value from parent table row */
 1.92650 +    Expr *pRight;                 /* Column ref to child table */
 1.92651 +    Expr *pEq;                    /* Expression (pLeft = pRight) */
 1.92652 +    i16 iCol;                     /* Index of column in child table */ 
 1.92653 +    const char *zCol;             /* Name of column in child table */
 1.92654 +
 1.92655 +    iCol = pIdx ? pIdx->aiColumn[i] : -1;
 1.92656 +    pLeft = exprTableRegister(pParse, pTab, regData, iCol);
 1.92657 +    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
 1.92658 +    assert( iCol>=0 );
 1.92659 +    zCol = pFKey->pFrom->aCol[iCol].zName;
 1.92660 +    pRight = sqlite3Expr(db, TK_ID, zCol);
 1.92661 +    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
 1.92662 +    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
 1.92663 +  }
 1.92664 +
 1.92665 +  /* If the child table is the same as the parent table, then add terms
 1.92666 +  ** to the WHERE clause that prevent this entry from being scanned.
 1.92667 +  ** The added WHERE clause terms are like this:
 1.92668 +  **
 1.92669 +  **     $current_rowid!=rowid
 1.92670 +  **     NOT( $current_a==a AND $current_b==b AND ... )
 1.92671 +  **
 1.92672 +  ** The first form is used for rowid tables.  The second form is used
 1.92673 +  ** for WITHOUT ROWID tables.  In the second form, the primary key is
 1.92674 +  ** (a,b,...)
 1.92675 +  */
 1.92676 +  if( pTab==pFKey->pFrom && nIncr>0 ){
 1.92677 +    Expr *pNe;                    /* Expression (pLeft != pRight) */
 1.92678 +    Expr *pLeft;                  /* Value from parent table row */
 1.92679 +    Expr *pRight;                 /* Column ref to child table */
 1.92680 +    if( HasRowid(pTab) ){
 1.92681 +      pLeft = exprTableRegister(pParse, pTab, regData, -1);
 1.92682 +      pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
 1.92683 +      pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
 1.92684 +    }else{
 1.92685 +      Expr *pEq, *pAll = 0;
 1.92686 +      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
 1.92687 +      assert( pIdx!=0 );
 1.92688 +      for(i=0; i<pPk->nKeyCol; i++){
 1.92689 +        i16 iCol = pIdx->aiColumn[i];
 1.92690 +        pLeft = exprTableRegister(pParse, pTab, regData, iCol);
 1.92691 +        pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
 1.92692 +        pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
 1.92693 +        pAll = sqlite3ExprAnd(db, pAll, pEq);
 1.92694 +      }
 1.92695 +      pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
 1.92696 +    }
 1.92697 +    pWhere = sqlite3ExprAnd(db, pWhere, pNe);
 1.92698 +  }
 1.92699 +
 1.92700 +  /* Resolve the references in the WHERE clause. */
 1.92701 +  memset(&sNameContext, 0, sizeof(NameContext));
 1.92702 +  sNameContext.pSrcList = pSrc;
 1.92703 +  sNameContext.pParse = pParse;
 1.92704 +  sqlite3ResolveExprNames(&sNameContext, pWhere);
 1.92705 +
 1.92706 +  /* Create VDBE to loop through the entries in pSrc that match the WHERE
 1.92707 +  ** clause. If the constraint is not deferred, throw an exception for
 1.92708 +  ** each row found. Otherwise, for deferred constraints, increment the
 1.92709 +  ** deferred constraint counter by nIncr for each row selected.  */
 1.92710 +  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
 1.92711 +  if( nIncr>0 && pFKey->isDeferred==0 ){
 1.92712 +    sqlite3ParseToplevel(pParse)->mayAbort = 1;
 1.92713 +  }
 1.92714 +  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
 1.92715 +  if( pWInfo ){
 1.92716 +    sqlite3WhereEnd(pWInfo);
 1.92717 +  }
 1.92718 +
 1.92719 +  /* Clean up the WHERE clause constructed above. */
 1.92720 +  sqlite3ExprDelete(db, pWhere);
 1.92721 +  if( iFkIfZero ){
 1.92722 +    sqlite3VdbeJumpHere(v, iFkIfZero);
 1.92723 +  }
 1.92724 +}
 1.92725 +
 1.92726 +/*
 1.92727 +** This function returns a linked list of FKey objects (connected by
 1.92728 +** FKey.pNextTo) holding all children of table pTab.  For example,
 1.92729 +** given the following schema:
 1.92730 +**
 1.92731 +**   CREATE TABLE t1(a PRIMARY KEY);
 1.92732 +**   CREATE TABLE t2(b REFERENCES t1(a);
 1.92733 +**
 1.92734 +** Calling this function with table "t1" as an argument returns a pointer
 1.92735 +** to the FKey structure representing the foreign key constraint on table
 1.92736 +** "t2". Calling this function with "t2" as the argument would return a
 1.92737 +** NULL pointer (as there are no FK constraints for which t2 is the parent
 1.92738 +** table).
 1.92739 +*/
 1.92740 +SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
 1.92741 +  int nName = sqlite3Strlen30(pTab->zName);
 1.92742 +  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
 1.92743 +}
 1.92744 +
 1.92745 +/*
 1.92746 +** The second argument is a Trigger structure allocated by the 
 1.92747 +** fkActionTrigger() routine. This function deletes the Trigger structure
 1.92748 +** and all of its sub-components.
 1.92749 +**
 1.92750 +** The Trigger structure or any of its sub-components may be allocated from
 1.92751 +** the lookaside buffer belonging to database handle dbMem.
 1.92752 +*/
 1.92753 +static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
 1.92754 +  if( p ){
 1.92755 +    TriggerStep *pStep = p->step_list;
 1.92756 +    sqlite3ExprDelete(dbMem, pStep->pWhere);
 1.92757 +    sqlite3ExprListDelete(dbMem, pStep->pExprList);
 1.92758 +    sqlite3SelectDelete(dbMem, pStep->pSelect);
 1.92759 +    sqlite3ExprDelete(dbMem, p->pWhen);
 1.92760 +    sqlite3DbFree(dbMem, p);
 1.92761 +  }
 1.92762 +}
 1.92763 +
 1.92764 +/*
 1.92765 +** This function is called to generate code that runs when table pTab is
 1.92766 +** being dropped from the database. The SrcList passed as the second argument
 1.92767 +** to this function contains a single entry guaranteed to resolve to
 1.92768 +** table pTab.
 1.92769 +**
 1.92770 +** Normally, no code is required. However, if either
 1.92771 +**
 1.92772 +**   (a) The table is the parent table of a FK constraint, or
 1.92773 +**   (b) The table is the child table of a deferred FK constraint and it is
 1.92774 +**       determined at runtime that there are outstanding deferred FK 
 1.92775 +**       constraint violations in the database,
 1.92776 +**
 1.92777 +** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
 1.92778 +** the table from the database. Triggers are disabled while running this
 1.92779 +** DELETE, but foreign key actions are not.
 1.92780 +*/
 1.92781 +SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
 1.92782 +  sqlite3 *db = pParse->db;
 1.92783 +  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
 1.92784 +    int iSkip = 0;
 1.92785 +    Vdbe *v = sqlite3GetVdbe(pParse);
 1.92786 +
 1.92787 +    assert( v );                  /* VDBE has already been allocated */
 1.92788 +    if( sqlite3FkReferences(pTab)==0 ){
 1.92789 +      /* Search for a deferred foreign key constraint for which this table
 1.92790 +      ** is the child table. If one cannot be found, return without 
 1.92791 +      ** generating any VDBE code. If one can be found, then jump over
 1.92792 +      ** the entire DELETE if there are no outstanding deferred constraints
 1.92793 +      ** when this statement is run.  */
 1.92794 +      FKey *p;
 1.92795 +      for(p=pTab->pFKey; p; p=p->pNextFrom){
 1.92796 +        if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
 1.92797 +      }
 1.92798 +      if( !p ) return;
 1.92799 +      iSkip = sqlite3VdbeMakeLabel(v);
 1.92800 +      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
 1.92801 +    }
 1.92802 +
 1.92803 +    pParse->disableTriggers = 1;
 1.92804 +    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
 1.92805 +    pParse->disableTriggers = 0;
 1.92806 +
 1.92807 +    /* If the DELETE has generated immediate foreign key constraint 
 1.92808 +    ** violations, halt the VDBE and return an error at this point, before
 1.92809 +    ** any modifications to the schema are made. This is because statement
 1.92810 +    ** transactions are not able to rollback schema changes.  
 1.92811 +    **
 1.92812 +    ** If the SQLITE_DeferFKs flag is set, then this is not required, as
 1.92813 +    ** the statement transaction will not be rolled back even if FK
 1.92814 +    ** constraints are violated.
 1.92815 +    */
 1.92816 +    if( (db->flags & SQLITE_DeferFKs)==0 ){
 1.92817 +      sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
 1.92818 +      VdbeCoverage(v);
 1.92819 +      sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
 1.92820 +          OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
 1.92821 +    }
 1.92822 +
 1.92823 +    if( iSkip ){
 1.92824 +      sqlite3VdbeResolveLabel(v, iSkip);
 1.92825 +    }
 1.92826 +  }
 1.92827 +}
 1.92828 +
 1.92829 +
 1.92830 +/*
 1.92831 +** The second argument points to an FKey object representing a foreign key
 1.92832 +** for which pTab is the child table. An UPDATE statement against pTab
 1.92833 +** is currently being processed. For each column of the table that is 
 1.92834 +** actually updated, the corresponding element in the aChange[] array
 1.92835 +** is zero or greater (if a column is unmodified the corresponding element
 1.92836 +** is set to -1). If the rowid column is modified by the UPDATE statement
 1.92837 +** the bChngRowid argument is non-zero.
 1.92838 +**
 1.92839 +** This function returns true if any of the columns that are part of the
 1.92840 +** child key for FK constraint *p are modified.
 1.92841 +*/
 1.92842 +static int fkChildIsModified(
 1.92843 +  Table *pTab,                    /* Table being updated */
 1.92844 +  FKey *p,                        /* Foreign key for which pTab is the child */
 1.92845 +  int *aChange,                   /* Array indicating modified columns */
 1.92846 +  int bChngRowid                  /* True if rowid is modified by this update */
 1.92847 +){
 1.92848 +  int i;
 1.92849 +  for(i=0; i<p->nCol; i++){
 1.92850 +    int iChildKey = p->aCol[i].iFrom;
 1.92851 +    if( aChange[iChildKey]>=0 ) return 1;
 1.92852 +    if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
 1.92853 +  }
 1.92854 +  return 0;
 1.92855 +}
 1.92856 +
 1.92857 +/*
 1.92858 +** The second argument points to an FKey object representing a foreign key
 1.92859 +** for which pTab is the parent table. An UPDATE statement against pTab
 1.92860 +** is currently being processed. For each column of the table that is 
 1.92861 +** actually updated, the corresponding element in the aChange[] array
 1.92862 +** is zero or greater (if a column is unmodified the corresponding element
 1.92863 +** is set to -1). If the rowid column is modified by the UPDATE statement
 1.92864 +** the bChngRowid argument is non-zero.
 1.92865 +**
 1.92866 +** This function returns true if any of the columns that are part of the
 1.92867 +** parent key for FK constraint *p are modified.
 1.92868 +*/
 1.92869 +static int fkParentIsModified(
 1.92870 +  Table *pTab, 
 1.92871 +  FKey *p, 
 1.92872 +  int *aChange, 
 1.92873 +  int bChngRowid
 1.92874 +){
 1.92875 +  int i;
 1.92876 +  for(i=0; i<p->nCol; i++){
 1.92877 +    char *zKey = p->aCol[i].zCol;
 1.92878 +    int iKey;
 1.92879 +    for(iKey=0; iKey<pTab->nCol; iKey++){
 1.92880 +      if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
 1.92881 +        Column *pCol = &pTab->aCol[iKey];
 1.92882 +        if( zKey ){
 1.92883 +          if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
 1.92884 +        }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
 1.92885 +          return 1;
 1.92886 +        }
 1.92887 +      }
 1.92888 +    }
 1.92889 +  }
 1.92890 +  return 0;
 1.92891 +}
 1.92892 +
 1.92893 +/*
 1.92894 +** This function is called when inserting, deleting or updating a row of
 1.92895 +** table pTab to generate VDBE code to perform foreign key constraint 
 1.92896 +** processing for the operation.
 1.92897 +**
 1.92898 +** For a DELETE operation, parameter regOld is passed the index of the
 1.92899 +** first register in an array of (pTab->nCol+1) registers containing the
 1.92900 +** rowid of the row being deleted, followed by each of the column values
 1.92901 +** of the row being deleted, from left to right. Parameter regNew is passed
 1.92902 +** zero in this case.
 1.92903 +**
 1.92904 +** For an INSERT operation, regOld is passed zero and regNew is passed the
 1.92905 +** first register of an array of (pTab->nCol+1) registers containing the new
 1.92906 +** row data.
 1.92907 +**
 1.92908 +** For an UPDATE operation, this function is called twice. Once before
 1.92909 +** the original record is deleted from the table using the calling convention
 1.92910 +** described for DELETE. Then again after the original record is deleted
 1.92911 +** but before the new record is inserted using the INSERT convention. 
 1.92912 +*/
 1.92913 +SQLITE_PRIVATE void sqlite3FkCheck(
 1.92914 +  Parse *pParse,                  /* Parse context */
 1.92915 +  Table *pTab,                    /* Row is being deleted from this table */ 
 1.92916 +  int regOld,                     /* Previous row data is stored here */
 1.92917 +  int regNew,                     /* New row data is stored here */
 1.92918 +  int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
 1.92919 +  int bChngRowid                  /* True if rowid is UPDATEd */
 1.92920 +){
 1.92921 +  sqlite3 *db = pParse->db;       /* Database handle */
 1.92922 +  FKey *pFKey;                    /* Used to iterate through FKs */
 1.92923 +  int iDb;                        /* Index of database containing pTab */
 1.92924 +  const char *zDb;                /* Name of database containing pTab */
 1.92925 +  int isIgnoreErrors = pParse->disableTriggers;
 1.92926 +
 1.92927 +  /* Exactly one of regOld and regNew should be non-zero. */
 1.92928 +  assert( (regOld==0)!=(regNew==0) );
 1.92929 +
 1.92930 +  /* If foreign-keys are disabled, this function is a no-op. */
 1.92931 +  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
 1.92932 +
 1.92933 +  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
 1.92934 +  zDb = db->aDb[iDb].zName;
 1.92935 +
 1.92936 +  /* Loop through all the foreign key constraints for which pTab is the
 1.92937 +  ** child table (the table that the foreign key definition is part of).  */
 1.92938 +  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
 1.92939 +    Table *pTo;                   /* Parent table of foreign key pFKey */
 1.92940 +    Index *pIdx = 0;              /* Index on key columns in pTo */
 1.92941 +    int *aiFree = 0;
 1.92942 +    int *aiCol;
 1.92943 +    int iCol;
 1.92944 +    int i;
 1.92945 +    int isIgnore = 0;
 1.92946 +
 1.92947 +    if( aChange 
 1.92948 +     && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
 1.92949 +     && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0 
 1.92950 +    ){
 1.92951 +      continue;
 1.92952 +    }
 1.92953 +
 1.92954 +    /* Find the parent table of this foreign key. Also find a unique index 
 1.92955 +    ** on the parent key columns in the parent table. If either of these 
 1.92956 +    ** schema items cannot be located, set an error in pParse and return 
 1.92957 +    ** early.  */
 1.92958 +    if( pParse->disableTriggers ){
 1.92959 +      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
 1.92960 +    }else{
 1.92961 +      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
 1.92962 +    }
 1.92963 +    if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
 1.92964 +      assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
 1.92965 +      if( !isIgnoreErrors || db->mallocFailed ) return;
 1.92966 +      if( pTo==0 ){
 1.92967 +        /* If isIgnoreErrors is true, then a table is being dropped. In this
 1.92968 +        ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
 1.92969 +        ** before actually dropping it in order to check FK constraints.
 1.92970 +        ** If the parent table of an FK constraint on the current table is
 1.92971 +        ** missing, behave as if it is empty. i.e. decrement the relevant
 1.92972 +        ** FK counter for each row of the current table with non-NULL keys.
 1.92973 +        */
 1.92974 +        Vdbe *v = sqlite3GetVdbe(pParse);
 1.92975 +        int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
 1.92976 +        for(i=0; i<pFKey->nCol; i++){
 1.92977 +          int iReg = pFKey->aCol[i].iFrom + regOld + 1;
 1.92978 +          sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
 1.92979 +        }
 1.92980 +        sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
 1.92981 +      }
 1.92982 +      continue;
 1.92983 +    }
 1.92984 +    assert( pFKey->nCol==1 || (aiFree && pIdx) );
 1.92985 +
 1.92986 +    if( aiFree ){
 1.92987 +      aiCol = aiFree;
 1.92988 +    }else{
 1.92989 +      iCol = pFKey->aCol[0].iFrom;
 1.92990 +      aiCol = &iCol;
 1.92991 +    }
 1.92992 +    for(i=0; i<pFKey->nCol; i++){
 1.92993 +      if( aiCol[i]==pTab->iPKey ){
 1.92994 +        aiCol[i] = -1;
 1.92995 +      }
 1.92996 +#ifndef SQLITE_OMIT_AUTHORIZATION
 1.92997 +      /* Request permission to read the parent key columns. If the 
 1.92998 +      ** authorization callback returns SQLITE_IGNORE, behave as if any
 1.92999 +      ** values read from the parent table are NULL. */
 1.93000 +      if( db->xAuth ){
 1.93001 +        int rcauth;
 1.93002 +        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
 1.93003 +        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
 1.93004 +        isIgnore = (rcauth==SQLITE_IGNORE);
 1.93005 +      }
 1.93006 +#endif
 1.93007 +    }
 1.93008 +
 1.93009 +    /* Take a shared-cache advisory read-lock on the parent table. Allocate 
 1.93010 +    ** a cursor to use to search the unique index on the parent key columns 
 1.93011 +    ** in the parent table.  */
 1.93012 +    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
 1.93013 +    pParse->nTab++;
 1.93014 +
 1.93015 +    if( regOld!=0 ){
 1.93016 +      /* A row is being removed from the child table. Search for the parent.
 1.93017 +      ** If the parent does not exist, removing the child row resolves an 
 1.93018 +      ** outstanding foreign key constraint violation. */
 1.93019 +      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
 1.93020 +    }
 1.93021 +    if( regNew!=0 ){
 1.93022 +      /* A row is being added to the child table. If a parent row cannot
 1.93023 +      ** be found, adding the child row has violated the FK constraint. */ 
 1.93024 +      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
 1.93025 +    }
 1.93026 +
 1.93027 +    sqlite3DbFree(db, aiFree);
 1.93028 +  }
 1.93029 +
 1.93030 +  /* Loop through all the foreign key constraints that refer to this table.
 1.93031 +  ** (the "child" constraints) */
 1.93032 +  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
 1.93033 +    Index *pIdx = 0;              /* Foreign key index for pFKey */
 1.93034 +    SrcList *pSrc;
 1.93035 +    int *aiCol = 0;
 1.93036 +
 1.93037 +    if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
 1.93038 +      continue;
 1.93039 +    }
 1.93040 +
 1.93041 +    if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs) 
 1.93042 +     && !pParse->pToplevel && !pParse->isMultiWrite 
 1.93043 +    ){
 1.93044 +      assert( regOld==0 && regNew!=0 );
 1.93045 +      /* Inserting a single row into a parent table cannot cause an immediate
 1.93046 +      ** foreign key violation. So do nothing in this case.  */
 1.93047 +      continue;
 1.93048 +    }
 1.93049 +
 1.93050 +    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
 1.93051 +      if( !isIgnoreErrors || db->mallocFailed ) return;
 1.93052 +      continue;
 1.93053 +    }
 1.93054 +    assert( aiCol || pFKey->nCol==1 );
 1.93055 +
 1.93056 +    /* Create a SrcList structure containing the child table.  We need the
 1.93057 +    ** child table as a SrcList for sqlite3WhereBegin() */
 1.93058 +    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
 1.93059 +    if( pSrc ){
 1.93060 +      struct SrcList_item *pItem = pSrc->a;
 1.93061 +      pItem->pTab = pFKey->pFrom;
 1.93062 +      pItem->zName = pFKey->pFrom->zName;
 1.93063 +      pItem->pTab->nRef++;
 1.93064 +      pItem->iCursor = pParse->nTab++;
 1.93065 +  
 1.93066 +      if( regNew!=0 ){
 1.93067 +        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
 1.93068 +      }
 1.93069 +      if( regOld!=0 ){
 1.93070 +        /* If there is a RESTRICT action configured for the current operation
 1.93071 +        ** on the parent table of this FK, then throw an exception 
 1.93072 +        ** immediately if the FK constraint is violated, even if this is a
 1.93073 +        ** deferred trigger. That's what RESTRICT means. To defer checking
 1.93074 +        ** the constraint, the FK should specify NO ACTION (represented
 1.93075 +        ** using OE_None). NO ACTION is the default.  */
 1.93076 +        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
 1.93077 +      }
 1.93078 +      pItem->zName = 0;
 1.93079 +      sqlite3SrcListDelete(db, pSrc);
 1.93080 +    }
 1.93081 +    sqlite3DbFree(db, aiCol);
 1.93082 +  }
 1.93083 +}
 1.93084 +
 1.93085 +#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
 1.93086 +
 1.93087 +/*
 1.93088 +** This function is called before generating code to update or delete a 
 1.93089 +** row contained in table pTab.
 1.93090 +*/
 1.93091 +SQLITE_PRIVATE u32 sqlite3FkOldmask(
 1.93092 +  Parse *pParse,                  /* Parse context */
 1.93093 +  Table *pTab                     /* Table being modified */
 1.93094 +){
 1.93095 +  u32 mask = 0;
 1.93096 +  if( pParse->db->flags&SQLITE_ForeignKeys ){
 1.93097 +    FKey *p;
 1.93098 +    int i;
 1.93099 +    for(p=pTab->pFKey; p; p=p->pNextFrom){
 1.93100 +      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
 1.93101 +    }
 1.93102 +    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
 1.93103 +      Index *pIdx = 0;
 1.93104 +      sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
 1.93105 +      if( pIdx ){
 1.93106 +        for(i=0; i<pIdx->nKeyCol; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
 1.93107 +      }
 1.93108 +    }
 1.93109 +  }
 1.93110 +  return mask;
 1.93111 +}
 1.93112 +
 1.93113 +
 1.93114 +/*
 1.93115 +** This function is called before generating code to update or delete a 
 1.93116 +** row contained in table pTab. If the operation is a DELETE, then
 1.93117 +** parameter aChange is passed a NULL value. For an UPDATE, aChange points
 1.93118 +** to an array of size N, where N is the number of columns in table pTab.
 1.93119 +** If the i'th column is not modified by the UPDATE, then the corresponding 
 1.93120 +** entry in the aChange[] array is set to -1. If the column is modified,
 1.93121 +** the value is 0 or greater. Parameter chngRowid is set to true if the
 1.93122 +** UPDATE statement modifies the rowid fields of the table.
 1.93123 +**
 1.93124 +** If any foreign key processing will be required, this function returns
 1.93125 +** true. If there is no foreign key related processing, this function 
 1.93126 +** returns false.
 1.93127 +*/
 1.93128 +SQLITE_PRIVATE int sqlite3FkRequired(
 1.93129 +  Parse *pParse,                  /* Parse context */
 1.93130 +  Table *pTab,                    /* Table being modified */
 1.93131 +  int *aChange,                   /* Non-NULL for UPDATE operations */
 1.93132 +  int chngRowid                   /* True for UPDATE that affects rowid */
 1.93133 +){
 1.93134 +  if( pParse->db->flags&SQLITE_ForeignKeys ){
 1.93135 +    if( !aChange ){
 1.93136 +      /* A DELETE operation. Foreign key processing is required if the 
 1.93137 +      ** table in question is either the child or parent table for any 
 1.93138 +      ** foreign key constraint.  */
 1.93139 +      return (sqlite3FkReferences(pTab) || pTab->pFKey);
 1.93140 +    }else{
 1.93141 +      /* This is an UPDATE. Foreign key processing is only required if the
 1.93142 +      ** operation modifies one or more child or parent key columns. */
 1.93143 +      FKey *p;
 1.93144 +
 1.93145 +      /* Check if any child key columns are being modified. */
 1.93146 +      for(p=pTab->pFKey; p; p=p->pNextFrom){
 1.93147 +        if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
 1.93148 +      }
 1.93149 +
 1.93150 +      /* Check if any parent key columns are being modified. */
 1.93151 +      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
 1.93152 +        if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
 1.93153 +      }
 1.93154 +    }
 1.93155 +  }
 1.93156 +  return 0;
 1.93157 +}
 1.93158 +
 1.93159 +/*
 1.93160 +** This function is called when an UPDATE or DELETE operation is being 
 1.93161 +** compiled on table pTab, which is the parent table of foreign-key pFKey.
 1.93162 +** If the current operation is an UPDATE, then the pChanges parameter is
 1.93163 +** passed a pointer to the list of columns being modified. If it is a
 1.93164 +** DELETE, pChanges is passed a NULL pointer.
 1.93165 +**
 1.93166 +** It returns a pointer to a Trigger structure containing a trigger
 1.93167 +** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
 1.93168 +** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
 1.93169 +** returned (these actions require no special handling by the triggers
 1.93170 +** sub-system, code for them is created by fkScanChildren()).
 1.93171 +**
 1.93172 +** For example, if pFKey is the foreign key and pTab is table "p" in 
 1.93173 +** the following schema:
 1.93174 +**
 1.93175 +**   CREATE TABLE p(pk PRIMARY KEY);
 1.93176 +**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
 1.93177 +**
 1.93178 +** then the returned trigger structure is equivalent to:
 1.93179 +**
 1.93180 +**   CREATE TRIGGER ... DELETE ON p BEGIN
 1.93181 +**     DELETE FROM c WHERE ck = old.pk;
 1.93182 +**   END;
 1.93183 +**
 1.93184 +** The returned pointer is cached as part of the foreign key object. It
 1.93185 +** is eventually freed along with the rest of the foreign key object by 
 1.93186 +** sqlite3FkDelete().
 1.93187 +*/
 1.93188 +static Trigger *fkActionTrigger(
 1.93189 +  Parse *pParse,                  /* Parse context */
 1.93190 +  Table *pTab,                    /* Table being updated or deleted from */
 1.93191 +  FKey *pFKey,                    /* Foreign key to get action for */
 1.93192 +  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
 1.93193 +){
 1.93194 +  sqlite3 *db = pParse->db;       /* Database handle */
 1.93195 +  int action;                     /* One of OE_None, OE_Cascade etc. */
 1.93196 +  Trigger *pTrigger;              /* Trigger definition to return */
 1.93197 +  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
 1.93198 +
 1.93199 +  action = pFKey->aAction[iAction];
 1.93200 +  pTrigger = pFKey->apTrigger[iAction];
 1.93201 +
 1.93202 +  if( action!=OE_None && !pTrigger ){
 1.93203 +    u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
 1.93204 +    char const *zFrom;            /* Name of child table */
 1.93205 +    int nFrom;                    /* Length in bytes of zFrom */
 1.93206 +    Index *pIdx = 0;              /* Parent key index for this FK */
 1.93207 +    int *aiCol = 0;               /* child table cols -> parent key cols */
 1.93208 +    TriggerStep *pStep = 0;        /* First (only) step of trigger program */
 1.93209 +    Expr *pWhere = 0;             /* WHERE clause of trigger step */
 1.93210 +    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
 1.93211 +    Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
 1.93212 +    int i;                        /* Iterator variable */
 1.93213 +    Expr *pWhen = 0;              /* WHEN clause for the trigger */
 1.93214 +
 1.93215 +    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
 1.93216 +    assert( aiCol || pFKey->nCol==1 );
 1.93217 +
 1.93218 +    for(i=0; i<pFKey->nCol; i++){
 1.93219 +      Token tOld = { "old", 3 };  /* Literal "old" token */
 1.93220 +      Token tNew = { "new", 3 };  /* Literal "new" token */
 1.93221 +      Token tFromCol;             /* Name of column in child table */
 1.93222 +      Token tToCol;               /* Name of column in parent table */
 1.93223 +      int iFromCol;               /* Idx of column in child table */
 1.93224 +      Expr *pEq;                  /* tFromCol = OLD.tToCol */
 1.93225 +
 1.93226 +      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
 1.93227 +      assert( iFromCol>=0 );
 1.93228 +      tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
 1.93229 +      tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
 1.93230 +
 1.93231 +      tToCol.n = sqlite3Strlen30(tToCol.z);
 1.93232 +      tFromCol.n = sqlite3Strlen30(tFromCol.z);
 1.93233 +
 1.93234 +      /* Create the expression "OLD.zToCol = zFromCol". It is important
 1.93235 +      ** that the "OLD.zToCol" term is on the LHS of the = operator, so
 1.93236 +      ** that the affinity and collation sequence associated with the
 1.93237 +      ** parent table are used for the comparison. */
 1.93238 +      pEq = sqlite3PExpr(pParse, TK_EQ,
 1.93239 +          sqlite3PExpr(pParse, TK_DOT, 
 1.93240 +            sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
 1.93241 +            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
 1.93242 +          , 0),
 1.93243 +          sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
 1.93244 +      , 0);
 1.93245 +      pWhere = sqlite3ExprAnd(db, pWhere, pEq);
 1.93246 +
 1.93247 +      /* For ON UPDATE, construct the next term of the WHEN clause.
 1.93248 +      ** The final WHEN clause will be like this:
 1.93249 +      **
 1.93250 +      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
 1.93251 +      */
 1.93252 +      if( pChanges ){
 1.93253 +        pEq = sqlite3PExpr(pParse, TK_IS,
 1.93254 +            sqlite3PExpr(pParse, TK_DOT, 
 1.93255 +              sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
 1.93256 +              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
 1.93257 +              0),
 1.93258 +            sqlite3PExpr(pParse, TK_DOT, 
 1.93259 +              sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
 1.93260 +              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
 1.93261 +              0),
 1.93262 +            0);
 1.93263 +        pWhen = sqlite3ExprAnd(db, pWhen, pEq);
 1.93264 +      }
 1.93265 +  
 1.93266 +      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
 1.93267 +        Expr *pNew;
 1.93268 +        if( action==OE_Cascade ){
 1.93269 +          pNew = sqlite3PExpr(pParse, TK_DOT, 
 1.93270 +            sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
 1.93271 +            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
 1.93272 +          , 0);
 1.93273 +        }else if( action==OE_SetDflt ){
 1.93274 +          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
 1.93275 +          if( pDflt ){
 1.93276 +            pNew = sqlite3ExprDup(db, pDflt, 0);
 1.93277 +          }else{
 1.93278 +            pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
 1.93279 +          }
 1.93280 +        }else{
 1.93281 +          pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
 1.93282 +        }
 1.93283 +        pList = sqlite3ExprListAppend(pParse, pList, pNew);
 1.93284 +        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
 1.93285 +      }
 1.93286 +    }
 1.93287 +    sqlite3DbFree(db, aiCol);
 1.93288 +
 1.93289 +    zFrom = pFKey->pFrom->zName;
 1.93290 +    nFrom = sqlite3Strlen30(zFrom);
 1.93291 +
 1.93292 +    if( action==OE_Restrict ){
 1.93293 +      Token tFrom;
 1.93294 +      Expr *pRaise; 
 1.93295 +
 1.93296 +      tFrom.z = zFrom;
 1.93297 +      tFrom.n = nFrom;
 1.93298 +      pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
 1.93299 +      if( pRaise ){
 1.93300 +        pRaise->affinity = OE_Abort;
 1.93301 +      }
 1.93302 +      pSelect = sqlite3SelectNew(pParse, 
 1.93303 +          sqlite3ExprListAppend(pParse, 0, pRaise),
 1.93304 +          sqlite3SrcListAppend(db, 0, &tFrom, 0),
 1.93305 +          pWhere,
 1.93306 +          0, 0, 0, 0, 0, 0
 1.93307 +      );
 1.93308 +      pWhere = 0;
 1.93309 +    }
 1.93310 +
 1.93311 +    /* Disable lookaside memory allocation */
 1.93312 +    enableLookaside = db->lookaside.bEnabled;
 1.93313 +    db->lookaside.bEnabled = 0;
 1.93314 +
 1.93315 +    pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
 1.93316 +        sizeof(Trigger) +         /* struct Trigger */
 1.93317 +        sizeof(TriggerStep) +     /* Single step in trigger program */
 1.93318 +        nFrom + 1                 /* Space for pStep->target.z */
 1.93319 +    );
 1.93320 +    if( pTrigger ){
 1.93321 +      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
 1.93322 +      pStep->target.z = (char *)&pStep[1];
 1.93323 +      pStep->target.n = nFrom;
 1.93324 +      memcpy((char *)pStep->target.z, zFrom, nFrom);
 1.93325 +  
 1.93326 +      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
 1.93327 +      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
 1.93328 +      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
 1.93329 +      if( pWhen ){
 1.93330 +        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
 1.93331 +        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
 1.93332 +      }
 1.93333 +    }
 1.93334 +
 1.93335 +    /* Re-enable the lookaside buffer, if it was disabled earlier. */
 1.93336 +    db->lookaside.bEnabled = enableLookaside;
 1.93337 +
 1.93338 +    sqlite3ExprDelete(db, pWhere);
 1.93339 +    sqlite3ExprDelete(db, pWhen);
 1.93340 +    sqlite3ExprListDelete(db, pList);
 1.93341 +    sqlite3SelectDelete(db, pSelect);
 1.93342 +    if( db->mallocFailed==1 ){
 1.93343 +      fkTriggerDelete(db, pTrigger);
 1.93344 +      return 0;
 1.93345 +    }
 1.93346 +    assert( pStep!=0 );
 1.93347 +
 1.93348 +    switch( action ){
 1.93349 +      case OE_Restrict:
 1.93350 +        pStep->op = TK_SELECT; 
 1.93351 +        break;
 1.93352 +      case OE_Cascade: 
 1.93353 +        if( !pChanges ){ 
 1.93354 +          pStep->op = TK_DELETE; 
 1.93355 +          break; 
 1.93356 +        }
 1.93357 +      default:
 1.93358 +        pStep->op = TK_UPDATE;
 1.93359 +    }
 1.93360 +    pStep->pTrig = pTrigger;
 1.93361 +    pTrigger->pSchema = pTab->pSchema;
 1.93362 +    pTrigger->pTabSchema = pTab->pSchema;
 1.93363 +    pFKey->apTrigger[iAction] = pTrigger;
 1.93364 +    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
 1.93365 +  }
 1.93366 +
 1.93367 +  return pTrigger;
 1.93368 +}
 1.93369 +
 1.93370 +/*
 1.93371 +** This function is called when deleting or updating a row to implement
 1.93372 +** any required CASCADE, SET NULL or SET DEFAULT actions.
 1.93373 +*/
 1.93374 +SQLITE_PRIVATE void sqlite3FkActions(
 1.93375 +  Parse *pParse,                  /* Parse context */
 1.93376 +  Table *pTab,                    /* Table being updated or deleted from */
 1.93377 +  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
 1.93378 +  int regOld,                     /* Address of array containing old row */
 1.93379 +  int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
 1.93380 +  int bChngRowid                  /* True if rowid is UPDATEd */
 1.93381 +){
 1.93382 +  /* If foreign-key support is enabled, iterate through all FKs that 
 1.93383 +  ** refer to table pTab. If there is an action associated with the FK 
 1.93384 +  ** for this operation (either update or delete), invoke the associated 
 1.93385 +  ** trigger sub-program.  */
 1.93386 +  if( pParse->db->flags&SQLITE_ForeignKeys ){
 1.93387 +    FKey *pFKey;                  /* Iterator variable */
 1.93388 +    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
 1.93389 +      if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
 1.93390 +        Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
 1.93391 +        if( pAct ){
 1.93392 +          sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
 1.93393 +        }
 1.93394 +      }
 1.93395 +    }
 1.93396 +  }
 1.93397 +}
 1.93398 +
 1.93399 +#endif /* ifndef SQLITE_OMIT_TRIGGER */
 1.93400 +
 1.93401 +/*
 1.93402 +** Free all memory associated with foreign key definitions attached to
 1.93403 +** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
 1.93404 +** hash table.
 1.93405 +*/
 1.93406 +SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
 1.93407 +  FKey *pFKey;                    /* Iterator variable */
 1.93408 +  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
 1.93409 +
 1.93410 +  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
 1.93411 +  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
 1.93412 +
 1.93413 +    /* Remove the FK from the fkeyHash hash table. */
 1.93414 +    if( !db || db->pnBytesFreed==0 ){
 1.93415 +      if( pFKey->pPrevTo ){
 1.93416 +        pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
 1.93417 +      }else{
 1.93418 +        void *p = (void *)pFKey->pNextTo;
 1.93419 +        const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
 1.93420 +        sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
 1.93421 +      }
 1.93422 +      if( pFKey->pNextTo ){
 1.93423 +        pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
 1.93424 +      }
 1.93425 +    }
 1.93426 +
 1.93427 +    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
 1.93428 +    ** classified as either immediate or deferred.
 1.93429 +    */
 1.93430 +    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
 1.93431 +
 1.93432 +    /* Delete any triggers created to implement actions for this FK. */
 1.93433 +#ifndef SQLITE_OMIT_TRIGGER
 1.93434 +    fkTriggerDelete(db, pFKey->apTrigger[0]);
 1.93435 +    fkTriggerDelete(db, pFKey->apTrigger[1]);
 1.93436 +#endif
 1.93437 +
 1.93438 +    pNext = pFKey->pNextFrom;
 1.93439 +    sqlite3DbFree(db, pFKey);
 1.93440 +  }
 1.93441 +}
 1.93442 +#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
 1.93443 +
 1.93444 +/************** End of fkey.c ************************************************/
 1.93445 +/************** Begin file insert.c ******************************************/
 1.93446 +/*
 1.93447 +** 2001 September 15
 1.93448 +**
 1.93449 +** The author disclaims copyright to this source code.  In place of
 1.93450 +** a legal notice, here is a blessing:
 1.93451 +**
 1.93452 +**    May you do good and not evil.
 1.93453 +**    May you find forgiveness for yourself and forgive others.
 1.93454 +**    May you share freely, never taking more than you give.
 1.93455 +**
 1.93456 +*************************************************************************
 1.93457 +** This file contains C code routines that are called by the parser
 1.93458 +** to handle INSERT statements in SQLite.
 1.93459 +*/
 1.93460 +
 1.93461 +/*
 1.93462 +** Generate code that will 
 1.93463 +**
 1.93464 +**   (1) acquire a lock for table pTab then
 1.93465 +**   (2) open pTab as cursor iCur.
 1.93466 +**
 1.93467 +** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
 1.93468 +** for that table that is actually opened.
 1.93469 +*/
 1.93470 +SQLITE_PRIVATE void sqlite3OpenTable(
 1.93471 +  Parse *pParse,  /* Generate code into this VDBE */
 1.93472 +  int iCur,       /* The cursor number of the table */
 1.93473 +  int iDb,        /* The database index in sqlite3.aDb[] */
 1.93474 +  Table *pTab,    /* The table to be opened */
 1.93475 +  int opcode      /* OP_OpenRead or OP_OpenWrite */
 1.93476 +){
 1.93477 +  Vdbe *v;
 1.93478 +  assert( !IsVirtual(pTab) );
 1.93479 +  v = sqlite3GetVdbe(pParse);
 1.93480 +  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
 1.93481 +  sqlite3TableLock(pParse, iDb, pTab->tnum, 
 1.93482 +                   (opcode==OP_OpenWrite)?1:0, pTab->zName);
 1.93483 +  if( HasRowid(pTab) ){
 1.93484 +    sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
 1.93485 +    VdbeComment((v, "%s", pTab->zName));
 1.93486 +  }else{
 1.93487 +    Index *pPk = sqlite3PrimaryKeyIndex(pTab);
 1.93488 +    assert( pPk!=0 );
 1.93489 +    assert( pPk->tnum=pTab->tnum );
 1.93490 +    sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
 1.93491 +    sqlite3VdbeSetP4KeyInfo(pParse, pPk);
 1.93492 +    VdbeComment((v, "%s", pTab->zName));
 1.93493 +  }
 1.93494 +}
 1.93495 +
 1.93496 +/*
 1.93497 +** Return a pointer to the column affinity string associated with index
 1.93498 +** pIdx. A column affinity string has one character for each column in 
 1.93499 +** the table, according to the affinity of the column:
 1.93500 +**
 1.93501 +**  Character      Column affinity
 1.93502 +**  ------------------------------
 1.93503 +**  'a'            TEXT
 1.93504 +**  'b'            NONE
 1.93505 +**  'c'            NUMERIC
 1.93506 +**  'd'            INTEGER
 1.93507 +**  'e'            REAL
 1.93508 +**
 1.93509 +** An extra 'd' is appended to the end of the string to cover the
 1.93510 +** rowid that appears as the last column in every index.
 1.93511 +**
 1.93512 +** Memory for the buffer containing the column index affinity string
 1.93513 +** is managed along with the rest of the Index structure. It will be
 1.93514 +** released when sqlite3DeleteIndex() is called.
 1.93515 +*/
 1.93516 +SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
 1.93517 +  if( !pIdx->zColAff ){
 1.93518 +    /* The first time a column affinity string for a particular index is
 1.93519 +    ** required, it is allocated and populated here. It is then stored as
 1.93520 +    ** a member of the Index structure for subsequent use.
 1.93521 +    **
 1.93522 +    ** The column affinity string will eventually be deleted by
 1.93523 +    ** sqliteDeleteIndex() when the Index structure itself is cleaned
 1.93524 +    ** up.
 1.93525 +    */
 1.93526 +    int n;
 1.93527 +    Table *pTab = pIdx->pTable;
 1.93528 +    sqlite3 *db = sqlite3VdbeDb(v);
 1.93529 +    pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
 1.93530 +    if( !pIdx->zColAff ){
 1.93531 +      db->mallocFailed = 1;
 1.93532 +      return 0;
 1.93533 +    }
 1.93534 +    for(n=0; n<pIdx->nColumn; n++){
 1.93535 +      i16 x = pIdx->aiColumn[n];
 1.93536 +      pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
 1.93537 +    }
 1.93538 +    pIdx->zColAff[n] = 0;
 1.93539 +  }
 1.93540 + 
 1.93541 +  return pIdx->zColAff;
 1.93542 +}
 1.93543 +
 1.93544 +/*
 1.93545 +** Compute the affinity string for table pTab, if it has not already been
 1.93546 +** computed.  As an optimization, omit trailing SQLITE_AFF_NONE affinities.
 1.93547 +**
 1.93548 +** If the affinity exists (if it is no entirely SQLITE_AFF_NONE values) and
 1.93549 +** if iReg>0 then code an OP_Affinity opcode that will set the affinities
 1.93550 +** for register iReg and following.  Or if affinities exists and iReg==0,
 1.93551 +** then just set the P4 operand of the previous opcode (which should  be
 1.93552 +** an OP_MakeRecord) to the affinity string.
 1.93553 +**
 1.93554 +** A column affinity string has one character per column:
 1.93555 +**
 1.93556 +**  Character      Column affinity
 1.93557 +**  ------------------------------
 1.93558 +**  'a'            TEXT
 1.93559 +**  'b'            NONE
 1.93560 +**  'c'            NUMERIC
 1.93561 +**  'd'            INTEGER
 1.93562 +**  'e'            REAL
 1.93563 +*/
 1.93564 +SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
 1.93565 +  int i;
 1.93566 +  char *zColAff = pTab->zColAff;
 1.93567 +  if( zColAff==0 ){
 1.93568 +    sqlite3 *db = sqlite3VdbeDb(v);
 1.93569 +    zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
 1.93570 +    if( !zColAff ){
 1.93571 +      db->mallocFailed = 1;
 1.93572 +      return;
 1.93573 +    }
 1.93574 +
 1.93575 +    for(i=0; i<pTab->nCol; i++){
 1.93576 +      zColAff[i] = pTab->aCol[i].affinity;
 1.93577 +    }
 1.93578 +    do{
 1.93579 +      zColAff[i--] = 0;
 1.93580 +    }while( i>=0 && zColAff[i]==SQLITE_AFF_NONE );
 1.93581 +    pTab->zColAff = zColAff;
 1.93582 +  }
 1.93583 +  i = sqlite3Strlen30(zColAff);
 1.93584 +  if( i ){
 1.93585 +    if( iReg ){
 1.93586 +      sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
 1.93587 +    }else{
 1.93588 +      sqlite3VdbeChangeP4(v, -1, zColAff, i);
 1.93589 +    }
 1.93590 +  }
 1.93591 +}
 1.93592 +
 1.93593 +/*
 1.93594 +** Return non-zero if the table pTab in database iDb or any of its indices
 1.93595 +** have been opened at any point in the VDBE program. This is used to see if 
 1.93596 +** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
 1.93597 +** run without using a temporary table for the results of the SELECT. 
 1.93598 +*/
 1.93599 +static int readsTable(Parse *p, int iDb, Table *pTab){
 1.93600 +  Vdbe *v = sqlite3GetVdbe(p);
 1.93601 +  int i;
 1.93602 +  int iEnd = sqlite3VdbeCurrentAddr(v);
 1.93603 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.93604 +  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
 1.93605 +#endif
 1.93606 +
 1.93607 +  for(i=1; i<iEnd; i++){
 1.93608 +    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
 1.93609 +    assert( pOp!=0 );
 1.93610 +    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
 1.93611 +      Index *pIndex;
 1.93612 +      int tnum = pOp->p2;
 1.93613 +      if( tnum==pTab->tnum ){
 1.93614 +        return 1;
 1.93615 +      }
 1.93616 +      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
 1.93617 +        if( tnum==pIndex->tnum ){
 1.93618 +          return 1;
 1.93619 +        }
 1.93620 +      }
 1.93621 +    }
 1.93622 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.93623 +    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
 1.93624 +      assert( pOp->p4.pVtab!=0 );
 1.93625 +      assert( pOp->p4type==P4_VTAB );
 1.93626 +      return 1;
 1.93627 +    }
 1.93628 +#endif
 1.93629 +  }
 1.93630 +  return 0;
 1.93631 +}
 1.93632 +
 1.93633 +#ifndef SQLITE_OMIT_AUTOINCREMENT
 1.93634 +/*
 1.93635 +** Locate or create an AutoincInfo structure associated with table pTab
 1.93636 +** which is in database iDb.  Return the register number for the register
 1.93637 +** that holds the maximum rowid.
 1.93638 +**
 1.93639 +** There is at most one AutoincInfo structure per table even if the
 1.93640 +** same table is autoincremented multiple times due to inserts within
 1.93641 +** triggers.  A new AutoincInfo structure is created if this is the
 1.93642 +** first use of table pTab.  On 2nd and subsequent uses, the original
 1.93643 +** AutoincInfo structure is used.
 1.93644 +**
 1.93645 +** Three memory locations are allocated:
 1.93646 +**
 1.93647 +**   (1)  Register to hold the name of the pTab table.
 1.93648 +**   (2)  Register to hold the maximum ROWID of pTab.
 1.93649 +**   (3)  Register to hold the rowid in sqlite_sequence of pTab
 1.93650 +**
 1.93651 +** The 2nd register is the one that is returned.  That is all the
 1.93652 +** insert routine needs to know about.
 1.93653 +*/
 1.93654 +static int autoIncBegin(
 1.93655 +  Parse *pParse,      /* Parsing context */
 1.93656 +  int iDb,            /* Index of the database holding pTab */
 1.93657 +  Table *pTab         /* The table we are writing to */
 1.93658 +){
 1.93659 +  int memId = 0;      /* Register holding maximum rowid */
 1.93660 +  if( pTab->tabFlags & TF_Autoincrement ){
 1.93661 +    Parse *pToplevel = sqlite3ParseToplevel(pParse);
 1.93662 +    AutoincInfo *pInfo;
 1.93663 +
 1.93664 +    pInfo = pToplevel->pAinc;
 1.93665 +    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
 1.93666 +    if( pInfo==0 ){
 1.93667 +      pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
 1.93668 +      if( pInfo==0 ) return 0;
 1.93669 +      pInfo->pNext = pToplevel->pAinc;
 1.93670 +      pToplevel->pAinc = pInfo;
 1.93671 +      pInfo->pTab = pTab;
 1.93672 +      pInfo->iDb = iDb;
 1.93673 +      pToplevel->nMem++;                  /* Register to hold name of table */
 1.93674 +      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
 1.93675 +      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
 1.93676 +    }
 1.93677 +    memId = pInfo->regCtr;
 1.93678 +  }
 1.93679 +  return memId;
 1.93680 +}
 1.93681 +
 1.93682 +/*
 1.93683 +** This routine generates code that will initialize all of the
 1.93684 +** register used by the autoincrement tracker.  
 1.93685 +*/
 1.93686 +SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
 1.93687 +  AutoincInfo *p;            /* Information about an AUTOINCREMENT */
 1.93688 +  sqlite3 *db = pParse->db;  /* The database connection */
 1.93689 +  Db *pDb;                   /* Database only autoinc table */
 1.93690 +  int memId;                 /* Register holding max rowid */
 1.93691 +  int addr;                  /* A VDBE address */
 1.93692 +  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
 1.93693 +
 1.93694 +  /* This routine is never called during trigger-generation.  It is
 1.93695 +  ** only called from the top-level */
 1.93696 +  assert( pParse->pTriggerTab==0 );
 1.93697 +  assert( pParse==sqlite3ParseToplevel(pParse) );
 1.93698 +
 1.93699 +  assert( v );   /* We failed long ago if this is not so */
 1.93700 +  for(p = pParse->pAinc; p; p = p->pNext){
 1.93701 +    pDb = &db->aDb[p->iDb];
 1.93702 +    memId = p->regCtr;
 1.93703 +    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
 1.93704 +    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
 1.93705 +    sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
 1.93706 +    addr = sqlite3VdbeCurrentAddr(v);
 1.93707 +    sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
 1.93708 +    sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v);
 1.93709 +    sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
 1.93710 +    sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v);
 1.93711 +    sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
 1.93712 +    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
 1.93713 +    sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
 1.93714 +    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
 1.93715 +    sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v);
 1.93716 +    sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
 1.93717 +    sqlite3VdbeAddOp0(v, OP_Close);
 1.93718 +  }
 1.93719 +}
 1.93720 +
 1.93721 +/*
 1.93722 +** Update the maximum rowid for an autoincrement calculation.
 1.93723 +**
 1.93724 +** This routine should be called when the top of the stack holds a
 1.93725 +** new rowid that is about to be inserted.  If that new rowid is
 1.93726 +** larger than the maximum rowid in the memId memory cell, then the
 1.93727 +** memory cell is updated.  The stack is unchanged.
 1.93728 +*/
 1.93729 +static void autoIncStep(Parse *pParse, int memId, int regRowid){
 1.93730 +  if( memId>0 ){
 1.93731 +    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
 1.93732 +  }
 1.93733 +}
 1.93734 +
 1.93735 +/*
 1.93736 +** This routine generates the code needed to write autoincrement
 1.93737 +** maximum rowid values back into the sqlite_sequence register.
 1.93738 +** Every statement that might do an INSERT into an autoincrement
 1.93739 +** table (either directly or through triggers) needs to call this
 1.93740 +** routine just before the "exit" code.
 1.93741 +*/
 1.93742 +SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
 1.93743 +  AutoincInfo *p;
 1.93744 +  Vdbe *v = pParse->pVdbe;
 1.93745 +  sqlite3 *db = pParse->db;
 1.93746 +
 1.93747 +  assert( v );
 1.93748 +  for(p = pParse->pAinc; p; p = p->pNext){
 1.93749 +    Db *pDb = &db->aDb[p->iDb];
 1.93750 +    int j1;
 1.93751 +    int iRec;
 1.93752 +    int memId = p->regCtr;
 1.93753 +
 1.93754 +    iRec = sqlite3GetTempReg(pParse);
 1.93755 +    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
 1.93756 +    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
 1.93757 +    j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v);
 1.93758 +    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
 1.93759 +    sqlite3VdbeJumpHere(v, j1);
 1.93760 +    sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
 1.93761 +    sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
 1.93762 +    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
 1.93763 +    sqlite3VdbeAddOp0(v, OP_Close);
 1.93764 +    sqlite3ReleaseTempReg(pParse, iRec);
 1.93765 +  }
 1.93766 +}
 1.93767 +#else
 1.93768 +/*
 1.93769 +** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
 1.93770 +** above are all no-ops
 1.93771 +*/
 1.93772 +# define autoIncBegin(A,B,C) (0)
 1.93773 +# define autoIncStep(A,B,C)
 1.93774 +#endif /* SQLITE_OMIT_AUTOINCREMENT */
 1.93775 +
 1.93776 +
 1.93777 +/* Forward declaration */
 1.93778 +static int xferOptimization(
 1.93779 +  Parse *pParse,        /* Parser context */
 1.93780 +  Table *pDest,         /* The table we are inserting into */
 1.93781 +  Select *pSelect,      /* A SELECT statement to use as the data source */
 1.93782 +  int onError,          /* How to handle constraint errors */
 1.93783 +  int iDbDest           /* The database of pDest */
 1.93784 +);
 1.93785 +
 1.93786 +/*
 1.93787 +** This routine is called to handle SQL of the following forms:
 1.93788 +**
 1.93789 +**    insert into TABLE (IDLIST) values(EXPRLIST)
 1.93790 +**    insert into TABLE (IDLIST) select
 1.93791 +**
 1.93792 +** The IDLIST following the table name is always optional.  If omitted,
 1.93793 +** then a list of all columns for the table is substituted.  The IDLIST
 1.93794 +** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
 1.93795 +**
 1.93796 +** The pList parameter holds EXPRLIST in the first form of the INSERT
 1.93797 +** statement above, and pSelect is NULL.  For the second form, pList is
 1.93798 +** NULL and pSelect is a pointer to the select statement used to generate
 1.93799 +** data for the insert.
 1.93800 +**
 1.93801 +** The code generated follows one of four templates.  For a simple
 1.93802 +** insert with data coming from a VALUES clause, the code executes
 1.93803 +** once straight down through.  Pseudo-code follows (we call this
 1.93804 +** the "1st template"):
 1.93805 +**
 1.93806 +**         open write cursor to <table> and its indices
 1.93807 +**         put VALUES clause expressions into registers
 1.93808 +**         write the resulting record into <table>
 1.93809 +**         cleanup
 1.93810 +**
 1.93811 +** The three remaining templates assume the statement is of the form
 1.93812 +**
 1.93813 +**   INSERT INTO <table> SELECT ...
 1.93814 +**
 1.93815 +** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
 1.93816 +** in other words if the SELECT pulls all columns from a single table
 1.93817 +** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
 1.93818 +** if <table2> and <table1> are distinct tables but have identical
 1.93819 +** schemas, including all the same indices, then a special optimization
 1.93820 +** is invoked that copies raw records from <table2> over to <table1>.
 1.93821 +** See the xferOptimization() function for the implementation of this
 1.93822 +** template.  This is the 2nd template.
 1.93823 +**
 1.93824 +**         open a write cursor to <table>
 1.93825 +**         open read cursor on <table2>
 1.93826 +**         transfer all records in <table2> over to <table>
 1.93827 +**         close cursors
 1.93828 +**         foreach index on <table>
 1.93829 +**           open a write cursor on the <table> index
 1.93830 +**           open a read cursor on the corresponding <table2> index
 1.93831 +**           transfer all records from the read to the write cursors
 1.93832 +**           close cursors
 1.93833 +**         end foreach
 1.93834 +**
 1.93835 +** The 3rd template is for when the second template does not apply
 1.93836 +** and the SELECT clause does not read from <table> at any time.
 1.93837 +** The generated code follows this template:
 1.93838 +**
 1.93839 +**         X <- A
 1.93840 +**         goto B
 1.93841 +**      A: setup for the SELECT
 1.93842 +**         loop over the rows in the SELECT
 1.93843 +**           load values into registers R..R+n
 1.93844 +**           yield X
 1.93845 +**         end loop
 1.93846 +**         cleanup after the SELECT
 1.93847 +**         end-coroutine X
 1.93848 +**      B: open write cursor to <table> and its indices
 1.93849 +**      C: yield X, at EOF goto D
 1.93850 +**         insert the select result into <table> from R..R+n
 1.93851 +**         goto C
 1.93852 +**      D: cleanup
 1.93853 +**
 1.93854 +** The 4th template is used if the insert statement takes its
 1.93855 +** values from a SELECT but the data is being inserted into a table
 1.93856 +** that is also read as part of the SELECT.  In the third form,
 1.93857 +** we have to use a intermediate table to store the results of
 1.93858 +** the select.  The template is like this:
 1.93859 +**
 1.93860 +**         X <- A
 1.93861 +**         goto B
 1.93862 +**      A: setup for the SELECT
 1.93863 +**         loop over the tables in the SELECT
 1.93864 +**           load value into register R..R+n
 1.93865 +**           yield X
 1.93866 +**         end loop
 1.93867 +**         cleanup after the SELECT
 1.93868 +**         end co-routine R
 1.93869 +**      B: open temp table
 1.93870 +**      L: yield X, at EOF goto M
 1.93871 +**         insert row from R..R+n into temp table
 1.93872 +**         goto L
 1.93873 +**      M: open write cursor to <table> and its indices
 1.93874 +**         rewind temp table
 1.93875 +**      C: loop over rows of intermediate table
 1.93876 +**           transfer values form intermediate table into <table>
 1.93877 +**         end loop
 1.93878 +**      D: cleanup
 1.93879 +*/
 1.93880 +SQLITE_PRIVATE void sqlite3Insert(
 1.93881 +  Parse *pParse,        /* Parser context */
 1.93882 +  SrcList *pTabList,    /* Name of table into which we are inserting */
 1.93883 +  Select *pSelect,      /* A SELECT statement to use as the data source */
 1.93884 +  IdList *pColumn,      /* Column names corresponding to IDLIST. */
 1.93885 +  int onError           /* How to handle constraint errors */
 1.93886 +){
 1.93887 +  sqlite3 *db;          /* The main database structure */
 1.93888 +  Table *pTab;          /* The table to insert into.  aka TABLE */
 1.93889 +  char *zTab;           /* Name of the table into which we are inserting */
 1.93890 +  const char *zDb;      /* Name of the database holding this table */
 1.93891 +  int i, j, idx;        /* Loop counters */
 1.93892 +  Vdbe *v;              /* Generate code into this virtual machine */
 1.93893 +  Index *pIdx;          /* For looping over indices of the table */
 1.93894 +  int nColumn;          /* Number of columns in the data */
 1.93895 +  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
 1.93896 +  int iDataCur = 0;     /* VDBE cursor that is the main data repository */
 1.93897 +  int iIdxCur = 0;      /* First index cursor */
 1.93898 +  int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
 1.93899 +  int endOfLoop;        /* Label for the end of the insertion loop */
 1.93900 +  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
 1.93901 +  int addrInsTop = 0;   /* Jump to label "D" */
 1.93902 +  int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
 1.93903 +  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
 1.93904 +  int iDb;              /* Index of database holding TABLE */
 1.93905 +  Db *pDb;              /* The database containing table being inserted into */
 1.93906 +  u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
 1.93907 +  u8 appendFlag = 0;    /* True if the insert is likely to be an append */
 1.93908 +  u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
 1.93909 +  u8 bIdListInOrder = 1; /* True if IDLIST is in table order */
 1.93910 +  ExprList *pList = 0;  /* List of VALUES() to be inserted  */
 1.93911 +
 1.93912 +  /* Register allocations */
 1.93913 +  int regFromSelect = 0;/* Base register for data coming from SELECT */
 1.93914 +  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
 1.93915 +  int regRowCount = 0;  /* Memory cell used for the row counter */
 1.93916 +  int regIns;           /* Block of regs holding rowid+data being inserted */
 1.93917 +  int regRowid;         /* registers holding insert rowid */
 1.93918 +  int regData;          /* register holding first column to insert */
 1.93919 +  int *aRegIdx = 0;     /* One register allocated to each index */
 1.93920 +
 1.93921 +#ifndef SQLITE_OMIT_TRIGGER
 1.93922 +  int isView;                 /* True if attempting to insert into a view */
 1.93923 +  Trigger *pTrigger;          /* List of triggers on pTab, if required */
 1.93924 +  int tmask;                  /* Mask of trigger times */
 1.93925 +#endif
 1.93926 +
 1.93927 +  db = pParse->db;
 1.93928 +  memset(&dest, 0, sizeof(dest));
 1.93929 +  if( pParse->nErr || db->mallocFailed ){
 1.93930 +    goto insert_cleanup;
 1.93931 +  }
 1.93932 +
 1.93933 +  /* If the Select object is really just a simple VALUES() list with a
 1.93934 +  ** single row values (the common case) then keep that one row of values
 1.93935 +  ** and go ahead and discard the Select object
 1.93936 +  */
 1.93937 +  if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
 1.93938 +    pList = pSelect->pEList;
 1.93939 +    pSelect->pEList = 0;
 1.93940 +    sqlite3SelectDelete(db, pSelect);
 1.93941 +    pSelect = 0;
 1.93942 +  }
 1.93943 +
 1.93944 +  /* Locate the table into which we will be inserting new information.
 1.93945 +  */
 1.93946 +  assert( pTabList->nSrc==1 );
 1.93947 +  zTab = pTabList->a[0].zName;
 1.93948 +  if( NEVER(zTab==0) ) goto insert_cleanup;
 1.93949 +  pTab = sqlite3SrcListLookup(pParse, pTabList);
 1.93950 +  if( pTab==0 ){
 1.93951 +    goto insert_cleanup;
 1.93952 +  }
 1.93953 +  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
 1.93954 +  assert( iDb<db->nDb );
 1.93955 +  pDb = &db->aDb[iDb];
 1.93956 +  zDb = pDb->zName;
 1.93957 +  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
 1.93958 +    goto insert_cleanup;
 1.93959 +  }
 1.93960 +  withoutRowid = !HasRowid(pTab);
 1.93961 +
 1.93962 +  /* Figure out if we have any triggers and if the table being
 1.93963 +  ** inserted into is a view
 1.93964 +  */
 1.93965 +#ifndef SQLITE_OMIT_TRIGGER
 1.93966 +  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
 1.93967 +  isView = pTab->pSelect!=0;
 1.93968 +#else
 1.93969 +# define pTrigger 0
 1.93970 +# define tmask 0
 1.93971 +# define isView 0
 1.93972 +#endif
 1.93973 +#ifdef SQLITE_OMIT_VIEW
 1.93974 +# undef isView
 1.93975 +# define isView 0
 1.93976 +#endif
 1.93977 +  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
 1.93978 +
 1.93979 +  /* If pTab is really a view, make sure it has been initialized.
 1.93980 +  ** ViewGetColumnNames() is a no-op if pTab is not a view.
 1.93981 +  */
 1.93982 +  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
 1.93983 +    goto insert_cleanup;
 1.93984 +  }
 1.93985 +
 1.93986 +  /* Cannot insert into a read-only table.
 1.93987 +  */
 1.93988 +  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
 1.93989 +    goto insert_cleanup;
 1.93990 +  }
 1.93991 +
 1.93992 +  /* Allocate a VDBE
 1.93993 +  */
 1.93994 +  v = sqlite3GetVdbe(pParse);
 1.93995 +  if( v==0 ) goto insert_cleanup;
 1.93996 +  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
 1.93997 +  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
 1.93998 +
 1.93999 +#ifndef SQLITE_OMIT_XFER_OPT
 1.94000 +  /* If the statement is of the form
 1.94001 +  **
 1.94002 +  **       INSERT INTO <table1> SELECT * FROM <table2>;
 1.94003 +  **
 1.94004 +  ** Then special optimizations can be applied that make the transfer
 1.94005 +  ** very fast and which reduce fragmentation of indices.
 1.94006 +  **
 1.94007 +  ** This is the 2nd template.
 1.94008 +  */
 1.94009 +  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
 1.94010 +    assert( !pTrigger );
 1.94011 +    assert( pList==0 );
 1.94012 +    goto insert_end;
 1.94013 +  }
 1.94014 +#endif /* SQLITE_OMIT_XFER_OPT */
 1.94015 +
 1.94016 +  /* If this is an AUTOINCREMENT table, look up the sequence number in the
 1.94017 +  ** sqlite_sequence table and store it in memory cell regAutoinc.
 1.94018 +  */
 1.94019 +  regAutoinc = autoIncBegin(pParse, iDb, pTab);
 1.94020 +
 1.94021 +  /* Allocate registers for holding the rowid of the new row,
 1.94022 +  ** the content of the new row, and the assemblied row record.
 1.94023 +  */
 1.94024 +  regRowid = regIns = pParse->nMem+1;
 1.94025 +  pParse->nMem += pTab->nCol + 1;
 1.94026 +  if( IsVirtual(pTab) ){
 1.94027 +    regRowid++;
 1.94028 +    pParse->nMem++;
 1.94029 +  }
 1.94030 +  regData = regRowid+1;
 1.94031 +
 1.94032 +  /* If the INSERT statement included an IDLIST term, then make sure
 1.94033 +  ** all elements of the IDLIST really are columns of the table and 
 1.94034 +  ** remember the column indices.
 1.94035 +  **
 1.94036 +  ** If the table has an INTEGER PRIMARY KEY column and that column
 1.94037 +  ** is named in the IDLIST, then record in the ipkColumn variable
 1.94038 +  ** the index into IDLIST of the primary key column.  ipkColumn is
 1.94039 +  ** the index of the primary key as it appears in IDLIST, not as
 1.94040 +  ** is appears in the original table.  (The index of the INTEGER
 1.94041 +  ** PRIMARY KEY in the original table is pTab->iPKey.)
 1.94042 +  */
 1.94043 +  if( pColumn ){
 1.94044 +    for(i=0; i<pColumn->nId; i++){
 1.94045 +      pColumn->a[i].idx = -1;
 1.94046 +    }
 1.94047 +    for(i=0; i<pColumn->nId; i++){
 1.94048 +      for(j=0; j<pTab->nCol; j++){
 1.94049 +        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
 1.94050 +          pColumn->a[i].idx = j;
 1.94051 +          if( i!=j ) bIdListInOrder = 0;
 1.94052 +          if( j==pTab->iPKey ){
 1.94053 +            ipkColumn = i;  assert( !withoutRowid );
 1.94054 +          }
 1.94055 +          break;
 1.94056 +        }
 1.94057 +      }
 1.94058 +      if( j>=pTab->nCol ){
 1.94059 +        if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
 1.94060 +          ipkColumn = i;
 1.94061 +        }else{
 1.94062 +          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
 1.94063 +              pTabList, 0, pColumn->a[i].zName);
 1.94064 +          pParse->checkSchema = 1;
 1.94065 +          goto insert_cleanup;
 1.94066 +        }
 1.94067 +      }
 1.94068 +    }
 1.94069 +  }
 1.94070 +
 1.94071 +  /* Figure out how many columns of data are supplied.  If the data
 1.94072 +  ** is coming from a SELECT statement, then generate a co-routine that
 1.94073 +  ** produces a single row of the SELECT on each invocation.  The
 1.94074 +  ** co-routine is the common header to the 3rd and 4th templates.
 1.94075 +  */
 1.94076 +  if( pSelect ){
 1.94077 +    /* Data is coming from a SELECT.  Generate a co-routine to run the SELECT */
 1.94078 +    int regYield;       /* Register holding co-routine entry-point */
 1.94079 +    int addrTop;        /* Top of the co-routine */
 1.94080 +    int rc;             /* Result code */
 1.94081 +
 1.94082 +    regYield = ++pParse->nMem;
 1.94083 +    addrTop = sqlite3VdbeCurrentAddr(v) + 1;
 1.94084 +    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
 1.94085 +    sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
 1.94086 +    dest.iSdst = bIdListInOrder ? regData : 0;
 1.94087 +    dest.nSdst = pTab->nCol;
 1.94088 +    rc = sqlite3Select(pParse, pSelect, &dest);
 1.94089 +    regFromSelect = dest.iSdst;
 1.94090 +    assert( pParse->nErr==0 || rc );
 1.94091 +    if( rc || db->mallocFailed ) goto insert_cleanup;
 1.94092 +    sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
 1.94093 +    sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
 1.94094 +    assert( pSelect->pEList );
 1.94095 +    nColumn = pSelect->pEList->nExpr;
 1.94096 +
 1.94097 +    /* Set useTempTable to TRUE if the result of the SELECT statement
 1.94098 +    ** should be written into a temporary table (template 4).  Set to
 1.94099 +    ** FALSE if each output row of the SELECT can be written directly into
 1.94100 +    ** the destination table (template 3).
 1.94101 +    **
 1.94102 +    ** A temp table must be used if the table being updated is also one
 1.94103 +    ** of the tables being read by the SELECT statement.  Also use a 
 1.94104 +    ** temp table in the case of row triggers.
 1.94105 +    */
 1.94106 +    if( pTrigger || readsTable(pParse, iDb, pTab) ){
 1.94107 +      useTempTable = 1;
 1.94108 +    }
 1.94109 +
 1.94110 +    if( useTempTable ){
 1.94111 +      /* Invoke the coroutine to extract information from the SELECT
 1.94112 +      ** and add it to a transient table srcTab.  The code generated
 1.94113 +      ** here is from the 4th template:
 1.94114 +      **
 1.94115 +      **      B: open temp table
 1.94116 +      **      L: yield X, goto M at EOF
 1.94117 +      **         insert row from R..R+n into temp table
 1.94118 +      **         goto L
 1.94119 +      **      M: ...
 1.94120 +      */
 1.94121 +      int regRec;          /* Register to hold packed record */
 1.94122 +      int regTempRowid;    /* Register to hold temp table ROWID */
 1.94123 +      int addrL;           /* Label "L" */
 1.94124 +
 1.94125 +      srcTab = pParse->nTab++;
 1.94126 +      regRec = sqlite3GetTempReg(pParse);
 1.94127 +      regTempRowid = sqlite3GetTempReg(pParse);
 1.94128 +      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
 1.94129 +      addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
 1.94130 +      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
 1.94131 +      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
 1.94132 +      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
 1.94133 +      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrL);
 1.94134 +      sqlite3VdbeJumpHere(v, addrL);
 1.94135 +      sqlite3ReleaseTempReg(pParse, regRec);
 1.94136 +      sqlite3ReleaseTempReg(pParse, regTempRowid);
 1.94137 +    }
 1.94138 +  }else{
 1.94139 +    /* This is the case if the data for the INSERT is coming from a VALUES
 1.94140 +    ** clause
 1.94141 +    */
 1.94142 +    NameContext sNC;
 1.94143 +    memset(&sNC, 0, sizeof(sNC));
 1.94144 +    sNC.pParse = pParse;
 1.94145 +    srcTab = -1;
 1.94146 +    assert( useTempTable==0 );
 1.94147 +    nColumn = pList ? pList->nExpr : 0;
 1.94148 +    for(i=0; i<nColumn; i++){
 1.94149 +      if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
 1.94150 +        goto insert_cleanup;
 1.94151 +      }
 1.94152 +    }
 1.94153 +  }
 1.94154 +
 1.94155 +  /* If there is no IDLIST term but the table has an integer primary
 1.94156 +  ** key, the set the ipkColumn variable to the integer primary key 
 1.94157 +  ** column index in the original table definition.
 1.94158 +  */
 1.94159 +  if( pColumn==0 && nColumn>0 ){
 1.94160 +    ipkColumn = pTab->iPKey;
 1.94161 +  }
 1.94162 +
 1.94163 +  /* Make sure the number of columns in the source data matches the number
 1.94164 +  ** of columns to be inserted into the table.
 1.94165 +  */
 1.94166 +  if( IsVirtual(pTab) ){
 1.94167 +    for(i=0; i<pTab->nCol; i++){
 1.94168 +      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
 1.94169 +    }
 1.94170 +  }
 1.94171 +  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
 1.94172 +    sqlite3ErrorMsg(pParse, 
 1.94173 +       "table %S has %d columns but %d values were supplied",
 1.94174 +       pTabList, 0, pTab->nCol-nHidden, nColumn);
 1.94175 +    goto insert_cleanup;
 1.94176 +  }
 1.94177 +  if( pColumn!=0 && nColumn!=pColumn->nId ){
 1.94178 +    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
 1.94179 +    goto insert_cleanup;
 1.94180 +  }
 1.94181 +    
 1.94182 +  /* Initialize the count of rows to be inserted
 1.94183 +  */
 1.94184 +  if( db->flags & SQLITE_CountRows ){
 1.94185 +    regRowCount = ++pParse->nMem;
 1.94186 +    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
 1.94187 +  }
 1.94188 +
 1.94189 +  /* If this is not a view, open the table and and all indices */
 1.94190 +  if( !isView ){
 1.94191 +    int nIdx;
 1.94192 +    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0,
 1.94193 +                                      &iDataCur, &iIdxCur);
 1.94194 +    aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
 1.94195 +    if( aRegIdx==0 ){
 1.94196 +      goto insert_cleanup;
 1.94197 +    }
 1.94198 +    for(i=0; i<nIdx; i++){
 1.94199 +      aRegIdx[i] = ++pParse->nMem;
 1.94200 +    }
 1.94201 +  }
 1.94202 +
 1.94203 +  /* This is the top of the main insertion loop */
 1.94204 +  if( useTempTable ){
 1.94205 +    /* This block codes the top of loop only.  The complete loop is the
 1.94206 +    ** following pseudocode (template 4):
 1.94207 +    **
 1.94208 +    **         rewind temp table, if empty goto D
 1.94209 +    **      C: loop over rows of intermediate table
 1.94210 +    **           transfer values form intermediate table into <table>
 1.94211 +    **         end loop
 1.94212 +    **      D: ...
 1.94213 +    */
 1.94214 +    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
 1.94215 +    addrCont = sqlite3VdbeCurrentAddr(v);
 1.94216 +  }else if( pSelect ){
 1.94217 +    /* This block codes the top of loop only.  The complete loop is the
 1.94218 +    ** following pseudocode (template 3):
 1.94219 +    **
 1.94220 +    **      C: yield X, at EOF goto D
 1.94221 +    **         insert the select result into <table> from R..R+n
 1.94222 +    **         goto C
 1.94223 +    **      D: ...
 1.94224 +    */
 1.94225 +    addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
 1.94226 +    VdbeCoverage(v);
 1.94227 +  }
 1.94228 +
 1.94229 +  /* Run the BEFORE and INSTEAD OF triggers, if there are any
 1.94230 +  */
 1.94231 +  endOfLoop = sqlite3VdbeMakeLabel(v);
 1.94232 +  if( tmask & TRIGGER_BEFORE ){
 1.94233 +    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
 1.94234 +
 1.94235 +    /* build the NEW.* reference row.  Note that if there is an INTEGER
 1.94236 +    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
 1.94237 +    ** translated into a unique ID for the row.  But on a BEFORE trigger,
 1.94238 +    ** we do not know what the unique ID will be (because the insert has
 1.94239 +    ** not happened yet) so we substitute a rowid of -1
 1.94240 +    */
 1.94241 +    if( ipkColumn<0 ){
 1.94242 +      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
 1.94243 +    }else{
 1.94244 +      int j1;
 1.94245 +      assert( !withoutRowid );
 1.94246 +      if( useTempTable ){
 1.94247 +        sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
 1.94248 +      }else{
 1.94249 +        assert( pSelect==0 );  /* Otherwise useTempTable is true */
 1.94250 +        sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
 1.94251 +      }
 1.94252 +      j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
 1.94253 +      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
 1.94254 +      sqlite3VdbeJumpHere(v, j1);
 1.94255 +      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
 1.94256 +    }
 1.94257 +
 1.94258 +    /* Cannot have triggers on a virtual table. If it were possible,
 1.94259 +    ** this block would have to account for hidden column.
 1.94260 +    */
 1.94261 +    assert( !IsVirtual(pTab) );
 1.94262 +
 1.94263 +    /* Create the new column data
 1.94264 +    */
 1.94265 +    for(i=0; i<pTab->nCol; i++){
 1.94266 +      if( pColumn==0 ){
 1.94267 +        j = i;
 1.94268 +      }else{
 1.94269 +        for(j=0; j<pColumn->nId; j++){
 1.94270 +          if( pColumn->a[j].idx==i ) break;
 1.94271 +        }
 1.94272 +      }
 1.94273 +      if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
 1.94274 +        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
 1.94275 +      }else if( useTempTable ){
 1.94276 +        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
 1.94277 +      }else{
 1.94278 +        assert( pSelect==0 ); /* Otherwise useTempTable is true */
 1.94279 +        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
 1.94280 +      }
 1.94281 +    }
 1.94282 +
 1.94283 +    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
 1.94284 +    ** do not attempt any conversions before assembling the record.
 1.94285 +    ** If this is a real table, attempt conversions as required by the
 1.94286 +    ** table column affinities.
 1.94287 +    */
 1.94288 +    if( !isView ){
 1.94289 +      sqlite3TableAffinity(v, pTab, regCols+1);
 1.94290 +    }
 1.94291 +
 1.94292 +    /* Fire BEFORE or INSTEAD OF triggers */
 1.94293 +    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
 1.94294 +        pTab, regCols-pTab->nCol-1, onError, endOfLoop);
 1.94295 +
 1.94296 +    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
 1.94297 +  }
 1.94298 +
 1.94299 +  /* Compute the content of the next row to insert into a range of
 1.94300 +  ** registers beginning at regIns.
 1.94301 +  */
 1.94302 +  if( !isView ){
 1.94303 +    if( IsVirtual(pTab) ){
 1.94304 +      /* The row that the VUpdate opcode will delete: none */
 1.94305 +      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
 1.94306 +    }
 1.94307 +    if( ipkColumn>=0 ){
 1.94308 +      if( useTempTable ){
 1.94309 +        sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
 1.94310 +      }else if( pSelect ){
 1.94311 +        sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
 1.94312 +      }else{
 1.94313 +        VdbeOp *pOp;
 1.94314 +        sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
 1.94315 +        pOp = sqlite3VdbeGetOp(v, -1);
 1.94316 +        if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
 1.94317 +          appendFlag = 1;
 1.94318 +          pOp->opcode = OP_NewRowid;
 1.94319 +          pOp->p1 = iDataCur;
 1.94320 +          pOp->p2 = regRowid;
 1.94321 +          pOp->p3 = regAutoinc;
 1.94322 +        }
 1.94323 +      }
 1.94324 +      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
 1.94325 +      ** to generate a unique primary key value.
 1.94326 +      */
 1.94327 +      if( !appendFlag ){
 1.94328 +        int j1;
 1.94329 +        if( !IsVirtual(pTab) ){
 1.94330 +          j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
 1.94331 +          sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
 1.94332 +          sqlite3VdbeJumpHere(v, j1);
 1.94333 +        }else{
 1.94334 +          j1 = sqlite3VdbeCurrentAddr(v);
 1.94335 +          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); VdbeCoverage(v);
 1.94336 +        }
 1.94337 +        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
 1.94338 +      }
 1.94339 +    }else if( IsVirtual(pTab) || withoutRowid ){
 1.94340 +      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
 1.94341 +    }else{
 1.94342 +      sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
 1.94343 +      appendFlag = 1;
 1.94344 +    }
 1.94345 +    autoIncStep(pParse, regAutoinc, regRowid);
 1.94346 +
 1.94347 +    /* Compute data for all columns of the new entry, beginning
 1.94348 +    ** with the first column.
 1.94349 +    */
 1.94350 +    nHidden = 0;
 1.94351 +    for(i=0; i<pTab->nCol; i++){
 1.94352 +      int iRegStore = regRowid+1+i;
 1.94353 +      if( i==pTab->iPKey ){
 1.94354 +        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
 1.94355 +        ** Whenever this column is read, the rowid will be substituted
 1.94356 +        ** in its place.  Hence, fill this column with a NULL to avoid
 1.94357 +        ** taking up data space with information that will never be used.
 1.94358 +        ** As there may be shallow copies of this value, make it a soft-NULL */
 1.94359 +        sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
 1.94360 +        continue;
 1.94361 +      }
 1.94362 +      if( pColumn==0 ){
 1.94363 +        if( IsHiddenColumn(&pTab->aCol[i]) ){
 1.94364 +          assert( IsVirtual(pTab) );
 1.94365 +          j = -1;
 1.94366 +          nHidden++;
 1.94367 +        }else{
 1.94368 +          j = i - nHidden;
 1.94369 +        }
 1.94370 +      }else{
 1.94371 +        for(j=0; j<pColumn->nId; j++){
 1.94372 +          if( pColumn->a[j].idx==i ) break;
 1.94373 +        }
 1.94374 +      }
 1.94375 +      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
 1.94376 +        sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
 1.94377 +      }else if( useTempTable ){
 1.94378 +        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
 1.94379 +      }else if( pSelect ){
 1.94380 +        if( regFromSelect!=regData ){
 1.94381 +          sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
 1.94382 +        }
 1.94383 +      }else{
 1.94384 +        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
 1.94385 +      }
 1.94386 +    }
 1.94387 +
 1.94388 +    /* Generate code to check constraints and generate index keys and
 1.94389 +    ** do the insertion.
 1.94390 +    */
 1.94391 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.94392 +    if( IsVirtual(pTab) ){
 1.94393 +      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
 1.94394 +      sqlite3VtabMakeWritable(pParse, pTab);
 1.94395 +      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
 1.94396 +      sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
 1.94397 +      sqlite3MayAbort(pParse);
 1.94398 +    }else
 1.94399 +#endif
 1.94400 +    {
 1.94401 +      int isReplace;    /* Set to true if constraints may cause a replace */
 1.94402 +      sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
 1.94403 +          regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
 1.94404 +      );
 1.94405 +      sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
 1.94406 +      sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
 1.94407 +                               regIns, aRegIdx, 0, appendFlag, isReplace==0);
 1.94408 +    }
 1.94409 +  }
 1.94410 +
 1.94411 +  /* Update the count of rows that are inserted
 1.94412 +  */
 1.94413 +  if( (db->flags & SQLITE_CountRows)!=0 ){
 1.94414 +    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
 1.94415 +  }
 1.94416 +
 1.94417 +  if( pTrigger ){
 1.94418 +    /* Code AFTER triggers */
 1.94419 +    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
 1.94420 +        pTab, regData-2-pTab->nCol, onError, endOfLoop);
 1.94421 +  }
 1.94422 +
 1.94423 +  /* The bottom of the main insertion loop, if the data source
 1.94424 +  ** is a SELECT statement.
 1.94425 +  */
 1.94426 +  sqlite3VdbeResolveLabel(v, endOfLoop);
 1.94427 +  if( useTempTable ){
 1.94428 +    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
 1.94429 +    sqlite3VdbeJumpHere(v, addrInsTop);
 1.94430 +    sqlite3VdbeAddOp1(v, OP_Close, srcTab);
 1.94431 +  }else if( pSelect ){
 1.94432 +    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
 1.94433 +    sqlite3VdbeJumpHere(v, addrInsTop);
 1.94434 +  }
 1.94435 +
 1.94436 +  if( !IsVirtual(pTab) && !isView ){
 1.94437 +    /* Close all tables opened */
 1.94438 +    if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
 1.94439 +    for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
 1.94440 +      sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
 1.94441 +    }
 1.94442 +  }
 1.94443 +
 1.94444 +insert_end:
 1.94445 +  /* Update the sqlite_sequence table by storing the content of the
 1.94446 +  ** maximum rowid counter values recorded while inserting into
 1.94447 +  ** autoincrement tables.
 1.94448 +  */
 1.94449 +  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
 1.94450 +    sqlite3AutoincrementEnd(pParse);
 1.94451 +  }
 1.94452 +
 1.94453 +  /*
 1.94454 +  ** Return the number of rows inserted. If this routine is 
 1.94455 +  ** generating code because of a call to sqlite3NestedParse(), do not
 1.94456 +  ** invoke the callback function.
 1.94457 +  */
 1.94458 +  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
 1.94459 +    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
 1.94460 +    sqlite3VdbeSetNumCols(v, 1);
 1.94461 +    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
 1.94462 +  }
 1.94463 +
 1.94464 +insert_cleanup:
 1.94465 +  sqlite3SrcListDelete(db, pTabList);
 1.94466 +  sqlite3ExprListDelete(db, pList);
 1.94467 +  sqlite3SelectDelete(db, pSelect);
 1.94468 +  sqlite3IdListDelete(db, pColumn);
 1.94469 +  sqlite3DbFree(db, aRegIdx);
 1.94470 +}
 1.94471 +
 1.94472 +/* Make sure "isView" and other macros defined above are undefined. Otherwise
 1.94473 +** thely may interfere with compilation of other functions in this file
 1.94474 +** (or in another file, if this file becomes part of the amalgamation).  */
 1.94475 +#ifdef isView
 1.94476 + #undef isView
 1.94477 +#endif
 1.94478 +#ifdef pTrigger
 1.94479 + #undef pTrigger
 1.94480 +#endif
 1.94481 +#ifdef tmask
 1.94482 + #undef tmask
 1.94483 +#endif
 1.94484 +
 1.94485 +/*
 1.94486 +** Generate code to do constraint checks prior to an INSERT or an UPDATE
 1.94487 +** on table pTab.
 1.94488 +**
 1.94489 +** The regNewData parameter is the first register in a range that contains
 1.94490 +** the data to be inserted or the data after the update.  There will be
 1.94491 +** pTab->nCol+1 registers in this range.  The first register (the one
 1.94492 +** that regNewData points to) will contain the new rowid, or NULL in the
 1.94493 +** case of a WITHOUT ROWID table.  The second register in the range will
 1.94494 +** contain the content of the first table column.  The third register will
 1.94495 +** contain the content of the second table column.  And so forth.
 1.94496 +**
 1.94497 +** The regOldData parameter is similar to regNewData except that it contains
 1.94498 +** the data prior to an UPDATE rather than afterwards.  regOldData is zero
 1.94499 +** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
 1.94500 +** checking regOldData for zero.
 1.94501 +**
 1.94502 +** For an UPDATE, the pkChng boolean is true if the true primary key (the
 1.94503 +** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
 1.94504 +** might be modified by the UPDATE.  If pkChng is false, then the key of
 1.94505 +** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
 1.94506 +**
 1.94507 +** For an INSERT, the pkChng boolean indicates whether or not the rowid
 1.94508 +** was explicitly specified as part of the INSERT statement.  If pkChng
 1.94509 +** is zero, it means that the either rowid is computed automatically or
 1.94510 +** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
 1.94511 +** pkChng will only be true if the INSERT statement provides an integer
 1.94512 +** value for either the rowid column or its INTEGER PRIMARY KEY alias.
 1.94513 +**
 1.94514 +** The code generated by this routine will store new index entries into
 1.94515 +** registers identified by aRegIdx[].  No index entry is created for
 1.94516 +** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
 1.94517 +** the same as the order of indices on the linked list of indices
 1.94518 +** at pTab->pIndex.
 1.94519 +**
 1.94520 +** The caller must have already opened writeable cursors on the main
 1.94521 +** table and all applicable indices (that is to say, all indices for which
 1.94522 +** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
 1.94523 +** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
 1.94524 +** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
 1.94525 +** for the first index in the pTab->pIndex list.  Cursors for other indices
 1.94526 +** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
 1.94527 +**
 1.94528 +** This routine also generates code to check constraints.  NOT NULL,
 1.94529 +** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
 1.94530 +** then the appropriate action is performed.  There are five possible
 1.94531 +** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
 1.94532 +**
 1.94533 +**  Constraint type  Action       What Happens
 1.94534 +**  ---------------  ----------   ----------------------------------------
 1.94535 +**  any              ROLLBACK     The current transaction is rolled back and
 1.94536 +**                                sqlite3_step() returns immediately with a
 1.94537 +**                                return code of SQLITE_CONSTRAINT.
 1.94538 +**
 1.94539 +**  any              ABORT        Back out changes from the current command
 1.94540 +**                                only (do not do a complete rollback) then
 1.94541 +**                                cause sqlite3_step() to return immediately
 1.94542 +**                                with SQLITE_CONSTRAINT.
 1.94543 +**
 1.94544 +**  any              FAIL         Sqlite3_step() returns immediately with a
 1.94545 +**                                return code of SQLITE_CONSTRAINT.  The
 1.94546 +**                                transaction is not rolled back and any
 1.94547 +**                                changes to prior rows are retained.
 1.94548 +**
 1.94549 +**  any              IGNORE       The attempt in insert or update the current
 1.94550 +**                                row is skipped, without throwing an error.
 1.94551 +**                                Processing continues with the next row.
 1.94552 +**                                (There is an immediate jump to ignoreDest.)
 1.94553 +**
 1.94554 +**  NOT NULL         REPLACE      The NULL value is replace by the default
 1.94555 +**                                value for that column.  If the default value
 1.94556 +**                                is NULL, the action is the same as ABORT.
 1.94557 +**
 1.94558 +**  UNIQUE           REPLACE      The other row that conflicts with the row
 1.94559 +**                                being inserted is removed.
 1.94560 +**
 1.94561 +**  CHECK            REPLACE      Illegal.  The results in an exception.
 1.94562 +**
 1.94563 +** Which action to take is determined by the overrideError parameter.
 1.94564 +** Or if overrideError==OE_Default, then the pParse->onError parameter
 1.94565 +** is used.  Or if pParse->onError==OE_Default then the onError value
 1.94566 +** for the constraint is used.
 1.94567 +*/
 1.94568 +SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
 1.94569 +  Parse *pParse,       /* The parser context */
 1.94570 +  Table *pTab,         /* The table being inserted or updated */
 1.94571 +  int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
 1.94572 +  int iDataCur,        /* Canonical data cursor (main table or PK index) */
 1.94573 +  int iIdxCur,         /* First index cursor */
 1.94574 +  int regNewData,      /* First register in a range holding values to insert */
 1.94575 +  int regOldData,      /* Previous content.  0 for INSERTs */
 1.94576 +  u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
 1.94577 +  u8 overrideError,    /* Override onError to this if not OE_Default */
 1.94578 +  int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
 1.94579 +  int *pbMayReplace    /* OUT: Set to true if constraint may cause a replace */
 1.94580 +){
 1.94581 +  Vdbe *v;             /* VDBE under constrution */
 1.94582 +  Index *pIdx;         /* Pointer to one of the indices */
 1.94583 +  Index *pPk = 0;      /* The PRIMARY KEY index */
 1.94584 +  sqlite3 *db;         /* Database connection */
 1.94585 +  int i;               /* loop counter */
 1.94586 +  int ix;              /* Index loop counter */
 1.94587 +  int nCol;            /* Number of columns */
 1.94588 +  int onError;         /* Conflict resolution strategy */
 1.94589 +  int j1;              /* Addresss of jump instruction */
 1.94590 +  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
 1.94591 +  int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
 1.94592 +  int ipkTop = 0;      /* Top of the rowid change constraint check */
 1.94593 +  int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
 1.94594 +  u8 isUpdate;         /* True if this is an UPDATE operation */
 1.94595 +  u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
 1.94596 +  int regRowid = -1;   /* Register holding ROWID value */
 1.94597 +
 1.94598 +  isUpdate = regOldData!=0;
 1.94599 +  db = pParse->db;
 1.94600 +  v = sqlite3GetVdbe(pParse);
 1.94601 +  assert( v!=0 );
 1.94602 +  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
 1.94603 +  nCol = pTab->nCol;
 1.94604 +  
 1.94605 +  /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
 1.94606 +  ** normal rowid tables.  nPkField is the number of key fields in the 
 1.94607 +  ** pPk index or 1 for a rowid table.  In other words, nPkField is the
 1.94608 +  ** number of fields in the true primary key of the table. */
 1.94609 +  if( HasRowid(pTab) ){
 1.94610 +    pPk = 0;
 1.94611 +    nPkField = 1;
 1.94612 +  }else{
 1.94613 +    pPk = sqlite3PrimaryKeyIndex(pTab);
 1.94614 +    nPkField = pPk->nKeyCol;
 1.94615 +  }
 1.94616 +
 1.94617 +  /* Record that this module has started */
 1.94618 +  VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
 1.94619 +                     iDataCur, iIdxCur, regNewData, regOldData, pkChng));
 1.94620 +
 1.94621 +  /* Test all NOT NULL constraints.
 1.94622 +  */
 1.94623 +  for(i=0; i<nCol; i++){
 1.94624 +    if( i==pTab->iPKey ){
 1.94625 +      continue;
 1.94626 +    }
 1.94627 +    onError = pTab->aCol[i].notNull;
 1.94628 +    if( onError==OE_None ) continue;
 1.94629 +    if( overrideError!=OE_Default ){
 1.94630 +      onError = overrideError;
 1.94631 +    }else if( onError==OE_Default ){
 1.94632 +      onError = OE_Abort;
 1.94633 +    }
 1.94634 +    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
 1.94635 +      onError = OE_Abort;
 1.94636 +    }
 1.94637 +    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
 1.94638 +        || onError==OE_Ignore || onError==OE_Replace );
 1.94639 +    switch( onError ){
 1.94640 +      case OE_Abort:
 1.94641 +        sqlite3MayAbort(pParse);
 1.94642 +        /* Fall through */
 1.94643 +      case OE_Rollback:
 1.94644 +      case OE_Fail: {
 1.94645 +        char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
 1.94646 +                                    pTab->aCol[i].zName);
 1.94647 +        sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
 1.94648 +                          regNewData+1+i, zMsg, P4_DYNAMIC);
 1.94649 +        sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
 1.94650 +        VdbeCoverage(v);
 1.94651 +        break;
 1.94652 +      }
 1.94653 +      case OE_Ignore: {
 1.94654 +        sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
 1.94655 +        VdbeCoverage(v);
 1.94656 +        break;
 1.94657 +      }
 1.94658 +      default: {
 1.94659 +        assert( onError==OE_Replace );
 1.94660 +        j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); VdbeCoverage(v);
 1.94661 +        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
 1.94662 +        sqlite3VdbeJumpHere(v, j1);
 1.94663 +        break;
 1.94664 +      }
 1.94665 +    }
 1.94666 +  }
 1.94667 +
 1.94668 +  /* Test all CHECK constraints
 1.94669 +  */
 1.94670 +#ifndef SQLITE_OMIT_CHECK
 1.94671 +  if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
 1.94672 +    ExprList *pCheck = pTab->pCheck;
 1.94673 +    pParse->ckBase = regNewData+1;
 1.94674 +    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
 1.94675 +    for(i=0; i<pCheck->nExpr; i++){
 1.94676 +      int allOk = sqlite3VdbeMakeLabel(v);
 1.94677 +      sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
 1.94678 +      if( onError==OE_Ignore ){
 1.94679 +        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
 1.94680 +      }else{
 1.94681 +        char *zName = pCheck->a[i].zName;
 1.94682 +        if( zName==0 ) zName = pTab->zName;
 1.94683 +        if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
 1.94684 +        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
 1.94685 +                              onError, zName, P4_TRANSIENT,
 1.94686 +                              P5_ConstraintCheck);
 1.94687 +      }
 1.94688 +      sqlite3VdbeResolveLabel(v, allOk);
 1.94689 +    }
 1.94690 +  }
 1.94691 +#endif /* !defined(SQLITE_OMIT_CHECK) */
 1.94692 +
 1.94693 +  /* If rowid is changing, make sure the new rowid does not previously
 1.94694 +  ** exist in the table.
 1.94695 +  */
 1.94696 +  if( pkChng && pPk==0 ){
 1.94697 +    int addrRowidOk = sqlite3VdbeMakeLabel(v);
 1.94698 +
 1.94699 +    /* Figure out what action to take in case of a rowid collision */
 1.94700 +    onError = pTab->keyConf;
 1.94701 +    if( overrideError!=OE_Default ){
 1.94702 +      onError = overrideError;
 1.94703 +    }else if( onError==OE_Default ){
 1.94704 +      onError = OE_Abort;
 1.94705 +    }
 1.94706 +
 1.94707 +    if( isUpdate ){
 1.94708 +      /* pkChng!=0 does not mean that the rowid has change, only that
 1.94709 +      ** it might have changed.  Skip the conflict logic below if the rowid
 1.94710 +      ** is unchanged. */
 1.94711 +      sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
 1.94712 +      sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
 1.94713 +      VdbeCoverage(v);
 1.94714 +    }
 1.94715 +
 1.94716 +    /* If the response to a rowid conflict is REPLACE but the response
 1.94717 +    ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
 1.94718 +    ** to defer the running of the rowid conflict checking until after
 1.94719 +    ** the UNIQUE constraints have run.
 1.94720 +    */
 1.94721 +    if( onError==OE_Replace && overrideError!=OE_Replace ){
 1.94722 +      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
 1.94723 +        if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
 1.94724 +          ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
 1.94725 +          break;
 1.94726 +        }
 1.94727 +      }
 1.94728 +    }
 1.94729 +
 1.94730 +    /* Check to see if the new rowid already exists in the table.  Skip
 1.94731 +    ** the following conflict logic if it does not. */
 1.94732 +    sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
 1.94733 +    VdbeCoverage(v);
 1.94734 +
 1.94735 +    /* Generate code that deals with a rowid collision */
 1.94736 +    switch( onError ){
 1.94737 +      default: {
 1.94738 +        onError = OE_Abort;
 1.94739 +        /* Fall thru into the next case */
 1.94740 +      }
 1.94741 +      case OE_Rollback:
 1.94742 +      case OE_Abort:
 1.94743 +      case OE_Fail: {
 1.94744 +        sqlite3RowidConstraint(pParse, onError, pTab);
 1.94745 +        break;
 1.94746 +      }
 1.94747 +      case OE_Replace: {
 1.94748 +        /* If there are DELETE triggers on this table and the
 1.94749 +        ** recursive-triggers flag is set, call GenerateRowDelete() to
 1.94750 +        ** remove the conflicting row from the table. This will fire
 1.94751 +        ** the triggers and remove both the table and index b-tree entries.
 1.94752 +        **
 1.94753 +        ** Otherwise, if there are no triggers or the recursive-triggers
 1.94754 +        ** flag is not set, but the table has one or more indexes, call 
 1.94755 +        ** GenerateRowIndexDelete(). This removes the index b-tree entries 
 1.94756 +        ** only. The table b-tree entry will be replaced by the new entry 
 1.94757 +        ** when it is inserted.  
 1.94758 +        **
 1.94759 +        ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
 1.94760 +        ** also invoke MultiWrite() to indicate that this VDBE may require
 1.94761 +        ** statement rollback (if the statement is aborted after the delete
 1.94762 +        ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
 1.94763 +        ** but being more selective here allows statements like:
 1.94764 +        **
 1.94765 +        **   REPLACE INTO t(rowid) VALUES($newrowid)
 1.94766 +        **
 1.94767 +        ** to run without a statement journal if there are no indexes on the
 1.94768 +        ** table.
 1.94769 +        */
 1.94770 +        Trigger *pTrigger = 0;
 1.94771 +        if( db->flags&SQLITE_RecTriggers ){
 1.94772 +          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
 1.94773 +        }
 1.94774 +        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
 1.94775 +          sqlite3MultiWrite(pParse);
 1.94776 +          sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
 1.94777 +                                   regNewData, 1, 0, OE_Replace, 1);
 1.94778 +        }else if( pTab->pIndex ){
 1.94779 +          sqlite3MultiWrite(pParse);
 1.94780 +          sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
 1.94781 +        }
 1.94782 +        seenReplace = 1;
 1.94783 +        break;
 1.94784 +      }
 1.94785 +      case OE_Ignore: {
 1.94786 +        /*assert( seenReplace==0 );*/
 1.94787 +        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
 1.94788 +        break;
 1.94789 +      }
 1.94790 +    }
 1.94791 +    sqlite3VdbeResolveLabel(v, addrRowidOk);
 1.94792 +    if( ipkTop ){
 1.94793 +      ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
 1.94794 +      sqlite3VdbeJumpHere(v, ipkTop);
 1.94795 +    }
 1.94796 +  }
 1.94797 +
 1.94798 +  /* Test all UNIQUE constraints by creating entries for each UNIQUE
 1.94799 +  ** index and making sure that duplicate entries do not already exist.
 1.94800 +  ** Compute the revised record entries for indices as we go.
 1.94801 +  **
 1.94802 +  ** This loop also handles the case of the PRIMARY KEY index for a
 1.94803 +  ** WITHOUT ROWID table.
 1.94804 +  */
 1.94805 +  for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
 1.94806 +    int regIdx;          /* Range of registers hold conent for pIdx */
 1.94807 +    int regR;            /* Range of registers holding conflicting PK */
 1.94808 +    int iThisCur;        /* Cursor for this UNIQUE index */
 1.94809 +    int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
 1.94810 +
 1.94811 +    if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
 1.94812 +    if( bAffinityDone==0 ){
 1.94813 +      sqlite3TableAffinity(v, pTab, regNewData+1);
 1.94814 +      bAffinityDone = 1;
 1.94815 +    }
 1.94816 +    iThisCur = iIdxCur+ix;
 1.94817 +    addrUniqueOk = sqlite3VdbeMakeLabel(v);
 1.94818 +
 1.94819 +    /* Skip partial indices for which the WHERE clause is not true */
 1.94820 +    if( pIdx->pPartIdxWhere ){
 1.94821 +      sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
 1.94822 +      pParse->ckBase = regNewData+1;
 1.94823 +      sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
 1.94824 +                         SQLITE_JUMPIFNULL);
 1.94825 +      pParse->ckBase = 0;
 1.94826 +    }
 1.94827 +
 1.94828 +    /* Create a record for this index entry as it should appear after
 1.94829 +    ** the insert or update.  Store that record in the aRegIdx[ix] register
 1.94830 +    */
 1.94831 +    regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
 1.94832 +    for(i=0; i<pIdx->nColumn; i++){
 1.94833 +      int iField = pIdx->aiColumn[i];
 1.94834 +      int x;
 1.94835 +      if( iField<0 || iField==pTab->iPKey ){
 1.94836 +        if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
 1.94837 +        x = regNewData;
 1.94838 +        regRowid =  pIdx->pPartIdxWhere ? -1 : regIdx+i;
 1.94839 +      }else{
 1.94840 +        x = iField + regNewData + 1;
 1.94841 +      }
 1.94842 +      sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
 1.94843 +      VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
 1.94844 +    }
 1.94845 +    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
 1.94846 +    VdbeComment((v, "for %s", pIdx->zName));
 1.94847 +    sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
 1.94848 +
 1.94849 +    /* In an UPDATE operation, if this index is the PRIMARY KEY index 
 1.94850 +    ** of a WITHOUT ROWID table and there has been no change the
 1.94851 +    ** primary key, then no collision is possible.  The collision detection
 1.94852 +    ** logic below can all be skipped. */
 1.94853 +    if( isUpdate && pPk==pIdx && pkChng==0 ){
 1.94854 +      sqlite3VdbeResolveLabel(v, addrUniqueOk);
 1.94855 +      continue;
 1.94856 +    }
 1.94857 +
 1.94858 +    /* Find out what action to take in case there is a uniqueness conflict */
 1.94859 +    onError = pIdx->onError;
 1.94860 +    if( onError==OE_None ){ 
 1.94861 +      sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
 1.94862 +      sqlite3VdbeResolveLabel(v, addrUniqueOk);
 1.94863 +      continue;  /* pIdx is not a UNIQUE index */
 1.94864 +    }
 1.94865 +    if( overrideError!=OE_Default ){
 1.94866 +      onError = overrideError;
 1.94867 +    }else if( onError==OE_Default ){
 1.94868 +      onError = OE_Abort;
 1.94869 +    }
 1.94870 +    
 1.94871 +    /* Check to see if the new index entry will be unique */
 1.94872 +    sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
 1.94873 +                         regIdx, pIdx->nKeyCol); VdbeCoverage(v);
 1.94874 +
 1.94875 +    /* Generate code to handle collisions */
 1.94876 +    regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
 1.94877 +    if( isUpdate || onError==OE_Replace ){
 1.94878 +      if( HasRowid(pTab) ){
 1.94879 +        sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
 1.94880 +        /* Conflict only if the rowid of the existing index entry
 1.94881 +        ** is different from old-rowid */
 1.94882 +        if( isUpdate ){
 1.94883 +          sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
 1.94884 +          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
 1.94885 +          VdbeCoverage(v);
 1.94886 +        }
 1.94887 +      }else{
 1.94888 +        int x;
 1.94889 +        /* Extract the PRIMARY KEY from the end of the index entry and
 1.94890 +        ** store it in registers regR..regR+nPk-1 */
 1.94891 +        if( pIdx!=pPk ){
 1.94892 +          for(i=0; i<pPk->nKeyCol; i++){
 1.94893 +            x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
 1.94894 +            sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
 1.94895 +            VdbeComment((v, "%s.%s", pTab->zName,
 1.94896 +                         pTab->aCol[pPk->aiColumn[i]].zName));
 1.94897 +          }
 1.94898 +        }
 1.94899 +        if( isUpdate ){
 1.94900 +          /* If currently processing the PRIMARY KEY of a WITHOUT ROWID 
 1.94901 +          ** table, only conflict if the new PRIMARY KEY values are actually
 1.94902 +          ** different from the old.
 1.94903 +          **
 1.94904 +          ** For a UNIQUE index, only conflict if the PRIMARY KEY values
 1.94905 +          ** of the matched index row are different from the original PRIMARY
 1.94906 +          ** KEY values of this row before the update.  */
 1.94907 +          int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
 1.94908 +          int op = OP_Ne;
 1.94909 +          int regCmp = (pIdx->autoIndex==2 ? regIdx : regR);
 1.94910 +  
 1.94911 +          for(i=0; i<pPk->nKeyCol; i++){
 1.94912 +            char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
 1.94913 +            x = pPk->aiColumn[i];
 1.94914 +            if( i==(pPk->nKeyCol-1) ){
 1.94915 +              addrJump = addrUniqueOk;
 1.94916 +              op = OP_Eq;
 1.94917 +            }
 1.94918 +            sqlite3VdbeAddOp4(v, op, 
 1.94919 +                regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
 1.94920 +            );
 1.94921 +            sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
 1.94922 +            VdbeCoverageIf(v, op==OP_Eq);
 1.94923 +            VdbeCoverageIf(v, op==OP_Ne);
 1.94924 +          }
 1.94925 +        }
 1.94926 +      }
 1.94927 +    }
 1.94928 +
 1.94929 +    /* Generate code that executes if the new index entry is not unique */
 1.94930 +    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
 1.94931 +        || onError==OE_Ignore || onError==OE_Replace );
 1.94932 +    switch( onError ){
 1.94933 +      case OE_Rollback:
 1.94934 +      case OE_Abort:
 1.94935 +      case OE_Fail: {
 1.94936 +        sqlite3UniqueConstraint(pParse, onError, pIdx);
 1.94937 +        break;
 1.94938 +      }
 1.94939 +      case OE_Ignore: {
 1.94940 +        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
 1.94941 +        break;
 1.94942 +      }
 1.94943 +      default: {
 1.94944 +        Trigger *pTrigger = 0;
 1.94945 +        assert( onError==OE_Replace );
 1.94946 +        sqlite3MultiWrite(pParse);
 1.94947 +        if( db->flags&SQLITE_RecTriggers ){
 1.94948 +          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
 1.94949 +        }
 1.94950 +        sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
 1.94951 +                                 regR, nPkField, 0, OE_Replace, pIdx==pPk);
 1.94952 +        seenReplace = 1;
 1.94953 +        break;
 1.94954 +      }
 1.94955 +    }
 1.94956 +    sqlite3VdbeResolveLabel(v, addrUniqueOk);
 1.94957 +    sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
 1.94958 +    if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
 1.94959 +  }
 1.94960 +  if( ipkTop ){
 1.94961 +    sqlite3VdbeAddOp2(v, OP_Goto, 0, ipkTop+1);
 1.94962 +    sqlite3VdbeJumpHere(v, ipkBottom);
 1.94963 +  }
 1.94964 +  
 1.94965 +  *pbMayReplace = seenReplace;
 1.94966 +  VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
 1.94967 +}
 1.94968 +
 1.94969 +/*
 1.94970 +** This routine generates code to finish the INSERT or UPDATE operation
 1.94971 +** that was started by a prior call to sqlite3GenerateConstraintChecks.
 1.94972 +** A consecutive range of registers starting at regNewData contains the
 1.94973 +** rowid and the content to be inserted.
 1.94974 +**
 1.94975 +** The arguments to this routine should be the same as the first six
 1.94976 +** arguments to sqlite3GenerateConstraintChecks.
 1.94977 +*/
 1.94978 +SQLITE_PRIVATE void sqlite3CompleteInsertion(
 1.94979 +  Parse *pParse,      /* The parser context */
 1.94980 +  Table *pTab,        /* the table into which we are inserting */
 1.94981 +  int iDataCur,       /* Cursor of the canonical data source */
 1.94982 +  int iIdxCur,        /* First index cursor */
 1.94983 +  int regNewData,     /* Range of content */
 1.94984 +  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
 1.94985 +  int isUpdate,       /* True for UPDATE, False for INSERT */
 1.94986 +  int appendBias,     /* True if this is likely to be an append */
 1.94987 +  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
 1.94988 +){
 1.94989 +  Vdbe *v;            /* Prepared statements under construction */
 1.94990 +  Index *pIdx;        /* An index being inserted or updated */
 1.94991 +  u8 pik_flags;       /* flag values passed to the btree insert */
 1.94992 +  int regData;        /* Content registers (after the rowid) */
 1.94993 +  int regRec;         /* Register holding assemblied record for the table */
 1.94994 +  int i;              /* Loop counter */
 1.94995 +  u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
 1.94996 +
 1.94997 +  v = sqlite3GetVdbe(pParse);
 1.94998 +  assert( v!=0 );
 1.94999 +  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
 1.95000 +  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
 1.95001 +    if( aRegIdx[i]==0 ) continue;
 1.95002 +    bAffinityDone = 1;
 1.95003 +    if( pIdx->pPartIdxWhere ){
 1.95004 +      sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
 1.95005 +      VdbeCoverage(v);
 1.95006 +    }
 1.95007 +    sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
 1.95008 +    pik_flags = 0;
 1.95009 +    if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
 1.95010 +    if( pIdx->autoIndex==2 && !HasRowid(pTab) ){
 1.95011 +      assert( pParse->nested==0 );
 1.95012 +      pik_flags |= OPFLAG_NCHANGE;
 1.95013 +    }
 1.95014 +    if( pik_flags )  sqlite3VdbeChangeP5(v, pik_flags);
 1.95015 +  }
 1.95016 +  if( !HasRowid(pTab) ) return;
 1.95017 +  regData = regNewData + 1;
 1.95018 +  regRec = sqlite3GetTempReg(pParse);
 1.95019 +  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
 1.95020 +  if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
 1.95021 +  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
 1.95022 +  if( pParse->nested ){
 1.95023 +    pik_flags = 0;
 1.95024 +  }else{
 1.95025 +    pik_flags = OPFLAG_NCHANGE;
 1.95026 +    pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
 1.95027 +  }
 1.95028 +  if( appendBias ){
 1.95029 +    pik_flags |= OPFLAG_APPEND;
 1.95030 +  }
 1.95031 +  if( useSeekResult ){
 1.95032 +    pik_flags |= OPFLAG_USESEEKRESULT;
 1.95033 +  }
 1.95034 +  sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
 1.95035 +  if( !pParse->nested ){
 1.95036 +    sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
 1.95037 +  }
 1.95038 +  sqlite3VdbeChangeP5(v, pik_flags);
 1.95039 +}
 1.95040 +
 1.95041 +/*
 1.95042 +** Allocate cursors for the pTab table and all its indices and generate
 1.95043 +** code to open and initialized those cursors.
 1.95044 +**
 1.95045 +** The cursor for the object that contains the complete data (normally
 1.95046 +** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
 1.95047 +** ROWID table) is returned in *piDataCur.  The first index cursor is
 1.95048 +** returned in *piIdxCur.  The number of indices is returned.
 1.95049 +**
 1.95050 +** Use iBase as the first cursor (either the *piDataCur for rowid tables
 1.95051 +** or the first index for WITHOUT ROWID tables) if it is non-negative.
 1.95052 +** If iBase is negative, then allocate the next available cursor.
 1.95053 +**
 1.95054 +** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
 1.95055 +** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
 1.95056 +** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
 1.95057 +** pTab->pIndex list.
 1.95058 +*/
 1.95059 +SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
 1.95060 +  Parse *pParse,   /* Parsing context */
 1.95061 +  Table *pTab,     /* Table to be opened */
 1.95062 +  int op,          /* OP_OpenRead or OP_OpenWrite */
 1.95063 +  int iBase,       /* Use this for the table cursor, if there is one */
 1.95064 +  u8 *aToOpen,     /* If not NULL: boolean for each table and index */
 1.95065 +  int *piDataCur,  /* Write the database source cursor number here */
 1.95066 +  int *piIdxCur    /* Write the first index cursor number here */
 1.95067 +){
 1.95068 +  int i;
 1.95069 +  int iDb;
 1.95070 +  int iDataCur;
 1.95071 +  Index *pIdx;
 1.95072 +  Vdbe *v;
 1.95073 +
 1.95074 +  assert( op==OP_OpenRead || op==OP_OpenWrite );
 1.95075 +  if( IsVirtual(pTab) ){
 1.95076 +    assert( aToOpen==0 );
 1.95077 +    *piDataCur = 0;
 1.95078 +    *piIdxCur = 1;
 1.95079 +    return 0;
 1.95080 +  }
 1.95081 +  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
 1.95082 +  v = sqlite3GetVdbe(pParse);
 1.95083 +  assert( v!=0 );
 1.95084 +  if( iBase<0 ) iBase = pParse->nTab;
 1.95085 +  iDataCur = iBase++;
 1.95086 +  if( piDataCur ) *piDataCur = iDataCur;
 1.95087 +  if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
 1.95088 +    sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
 1.95089 +  }else{
 1.95090 +    sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
 1.95091 +  }
 1.95092 +  if( piIdxCur ) *piIdxCur = iBase;
 1.95093 +  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
 1.95094 +    int iIdxCur = iBase++;
 1.95095 +    assert( pIdx->pSchema==pTab->pSchema );
 1.95096 +    if( pIdx->autoIndex==2 && !HasRowid(pTab) && piDataCur ){
 1.95097 +      *piDataCur = iIdxCur;
 1.95098 +    }
 1.95099 +    if( aToOpen==0 || aToOpen[i+1] ){
 1.95100 +      sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
 1.95101 +      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
 1.95102 +      VdbeComment((v, "%s", pIdx->zName));
 1.95103 +    }
 1.95104 +  }
 1.95105 +  if( iBase>pParse->nTab ) pParse->nTab = iBase;
 1.95106 +  return i;
 1.95107 +}
 1.95108 +
 1.95109 +
 1.95110 +#ifdef SQLITE_TEST
 1.95111 +/*
 1.95112 +** The following global variable is incremented whenever the
 1.95113 +** transfer optimization is used.  This is used for testing
 1.95114 +** purposes only - to make sure the transfer optimization really
 1.95115 +** is happening when it is suppose to.
 1.95116 +*/
 1.95117 +SQLITE_API int sqlite3_xferopt_count;
 1.95118 +#endif /* SQLITE_TEST */
 1.95119 +
 1.95120 +
 1.95121 +#ifndef SQLITE_OMIT_XFER_OPT
 1.95122 +/*
 1.95123 +** Check to collation names to see if they are compatible.
 1.95124 +*/
 1.95125 +static int xferCompatibleCollation(const char *z1, const char *z2){
 1.95126 +  if( z1==0 ){
 1.95127 +    return z2==0;
 1.95128 +  }
 1.95129 +  if( z2==0 ){
 1.95130 +    return 0;
 1.95131 +  }
 1.95132 +  return sqlite3StrICmp(z1, z2)==0;
 1.95133 +}
 1.95134 +
 1.95135 +
 1.95136 +/*
 1.95137 +** Check to see if index pSrc is compatible as a source of data
 1.95138 +** for index pDest in an insert transfer optimization.  The rules
 1.95139 +** for a compatible index:
 1.95140 +**
 1.95141 +**    *   The index is over the same set of columns
 1.95142 +**    *   The same DESC and ASC markings occurs on all columns
 1.95143 +**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
 1.95144 +**    *   The same collating sequence on each column
 1.95145 +**    *   The index has the exact same WHERE clause
 1.95146 +*/
 1.95147 +static int xferCompatibleIndex(Index *pDest, Index *pSrc){
 1.95148 +  int i;
 1.95149 +  assert( pDest && pSrc );
 1.95150 +  assert( pDest->pTable!=pSrc->pTable );
 1.95151 +  if( pDest->nKeyCol!=pSrc->nKeyCol ){
 1.95152 +    return 0;   /* Different number of columns */
 1.95153 +  }
 1.95154 +  if( pDest->onError!=pSrc->onError ){
 1.95155 +    return 0;   /* Different conflict resolution strategies */
 1.95156 +  }
 1.95157 +  for(i=0; i<pSrc->nKeyCol; i++){
 1.95158 +    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
 1.95159 +      return 0;   /* Different columns indexed */
 1.95160 +    }
 1.95161 +    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
 1.95162 +      return 0;   /* Different sort orders */
 1.95163 +    }
 1.95164 +    if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
 1.95165 +      return 0;   /* Different collating sequences */
 1.95166 +    }
 1.95167 +  }
 1.95168 +  if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
 1.95169 +    return 0;     /* Different WHERE clauses */
 1.95170 +  }
 1.95171 +
 1.95172 +  /* If no test above fails then the indices must be compatible */
 1.95173 +  return 1;
 1.95174 +}
 1.95175 +
 1.95176 +/*
 1.95177 +** Attempt the transfer optimization on INSERTs of the form
 1.95178 +**
 1.95179 +**     INSERT INTO tab1 SELECT * FROM tab2;
 1.95180 +**
 1.95181 +** The xfer optimization transfers raw records from tab2 over to tab1.  
 1.95182 +** Columns are not decoded and reassemblied, which greatly improves
 1.95183 +** performance.  Raw index records are transferred in the same way.
 1.95184 +**
 1.95185 +** The xfer optimization is only attempted if tab1 and tab2 are compatible.
 1.95186 +** There are lots of rules for determining compatibility - see comments
 1.95187 +** embedded in the code for details.
 1.95188 +**
 1.95189 +** This routine returns TRUE if the optimization is guaranteed to be used.
 1.95190 +** Sometimes the xfer optimization will only work if the destination table
 1.95191 +** is empty - a factor that can only be determined at run-time.  In that
 1.95192 +** case, this routine generates code for the xfer optimization but also
 1.95193 +** does a test to see if the destination table is empty and jumps over the
 1.95194 +** xfer optimization code if the test fails.  In that case, this routine
 1.95195 +** returns FALSE so that the caller will know to go ahead and generate
 1.95196 +** an unoptimized transfer.  This routine also returns FALSE if there
 1.95197 +** is no chance that the xfer optimization can be applied.
 1.95198 +**
 1.95199 +** This optimization is particularly useful at making VACUUM run faster.
 1.95200 +*/
 1.95201 +static int xferOptimization(
 1.95202 +  Parse *pParse,        /* Parser context */
 1.95203 +  Table *pDest,         /* The table we are inserting into */
 1.95204 +  Select *pSelect,      /* A SELECT statement to use as the data source */
 1.95205 +  int onError,          /* How to handle constraint errors */
 1.95206 +  int iDbDest           /* The database of pDest */
 1.95207 +){
 1.95208 +  ExprList *pEList;                /* The result set of the SELECT */
 1.95209 +  Table *pSrc;                     /* The table in the FROM clause of SELECT */
 1.95210 +  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
 1.95211 +  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
 1.95212 +  int i;                           /* Loop counter */
 1.95213 +  int iDbSrc;                      /* The database of pSrc */
 1.95214 +  int iSrc, iDest;                 /* Cursors from source and destination */
 1.95215 +  int addr1, addr2;                /* Loop addresses */
 1.95216 +  int emptyDestTest = 0;           /* Address of test for empty pDest */
 1.95217 +  int emptySrcTest = 0;            /* Address of test for empty pSrc */
 1.95218 +  Vdbe *v;                         /* The VDBE we are building */
 1.95219 +  int regAutoinc;                  /* Memory register used by AUTOINC */
 1.95220 +  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
 1.95221 +  int regData, regRowid;           /* Registers holding data and rowid */
 1.95222 +
 1.95223 +  if( pSelect==0 ){
 1.95224 +    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
 1.95225 +  }
 1.95226 +  if( pParse->pWith || pSelect->pWith ){
 1.95227 +    /* Do not attempt to process this query if there are an WITH clauses
 1.95228 +    ** attached to it. Proceeding may generate a false "no such table: xxx"
 1.95229 +    ** error if pSelect reads from a CTE named "xxx".  */
 1.95230 +    return 0;
 1.95231 +  }
 1.95232 +  if( sqlite3TriggerList(pParse, pDest) ){
 1.95233 +    return 0;   /* tab1 must not have triggers */
 1.95234 +  }
 1.95235 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.95236 +  if( pDest->tabFlags & TF_Virtual ){
 1.95237 +    return 0;   /* tab1 must not be a virtual table */
 1.95238 +  }
 1.95239 +#endif
 1.95240 +  if( onError==OE_Default ){
 1.95241 +    if( pDest->iPKey>=0 ) onError = pDest->keyConf;
 1.95242 +    if( onError==OE_Default ) onError = OE_Abort;
 1.95243 +  }
 1.95244 +  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
 1.95245 +  if( pSelect->pSrc->nSrc!=1 ){
 1.95246 +    return 0;   /* FROM clause must have exactly one term */
 1.95247 +  }
 1.95248 +  if( pSelect->pSrc->a[0].pSelect ){
 1.95249 +    return 0;   /* FROM clause cannot contain a subquery */
 1.95250 +  }
 1.95251 +  if( pSelect->pWhere ){
 1.95252 +    return 0;   /* SELECT may not have a WHERE clause */
 1.95253 +  }
 1.95254 +  if( pSelect->pOrderBy ){
 1.95255 +    return 0;   /* SELECT may not have an ORDER BY clause */
 1.95256 +  }
 1.95257 +  /* Do not need to test for a HAVING clause.  If HAVING is present but
 1.95258 +  ** there is no ORDER BY, we will get an error. */
 1.95259 +  if( pSelect->pGroupBy ){
 1.95260 +    return 0;   /* SELECT may not have a GROUP BY clause */
 1.95261 +  }
 1.95262 +  if( pSelect->pLimit ){
 1.95263 +    return 0;   /* SELECT may not have a LIMIT clause */
 1.95264 +  }
 1.95265 +  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
 1.95266 +  if( pSelect->pPrior ){
 1.95267 +    return 0;   /* SELECT may not be a compound query */
 1.95268 +  }
 1.95269 +  if( pSelect->selFlags & SF_Distinct ){
 1.95270 +    return 0;   /* SELECT may not be DISTINCT */
 1.95271 +  }
 1.95272 +  pEList = pSelect->pEList;
 1.95273 +  assert( pEList!=0 );
 1.95274 +  if( pEList->nExpr!=1 ){
 1.95275 +    return 0;   /* The result set must have exactly one column */
 1.95276 +  }
 1.95277 +  assert( pEList->a[0].pExpr );
 1.95278 +  if( pEList->a[0].pExpr->op!=TK_ALL ){
 1.95279 +    return 0;   /* The result set must be the special operator "*" */
 1.95280 +  }
 1.95281 +
 1.95282 +  /* At this point we have established that the statement is of the
 1.95283 +  ** correct syntactic form to participate in this optimization.  Now
 1.95284 +  ** we have to check the semantics.
 1.95285 +  */
 1.95286 +  pItem = pSelect->pSrc->a;
 1.95287 +  pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
 1.95288 +  if( pSrc==0 ){
 1.95289 +    return 0;   /* FROM clause does not contain a real table */
 1.95290 +  }
 1.95291 +  if( pSrc==pDest ){
 1.95292 +    return 0;   /* tab1 and tab2 may not be the same table */
 1.95293 +  }
 1.95294 +  if( HasRowid(pDest)!=HasRowid(pSrc) ){
 1.95295 +    return 0;   /* source and destination must both be WITHOUT ROWID or not */
 1.95296 +  }
 1.95297 +#ifndef SQLITE_OMIT_VIRTUALTABLE
 1.95298 +  if( pSrc->tabFlags & TF_Virtual ){
 1.95299 +    return 0;   /* tab2 must not be a virtual table */
 1.95300 +  }
 1.95301 +#endif
 1.95302 +  if( pSrc->pSelect ){
 1.95303 +    return 0;   /* tab2 may not be a view */
 1.95304 +  }
 1.95305 +  if( pDest->nCol!=pSrc->nCol ){
 1.95306 +    return 0;   /* Number of columns must be the same in tab1 and tab2 */
 1.95307 +  }
 1.95308 +  if( pDest->iPKey!=pSrc->iPKey ){
 1.95309 +    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
 1.95310 +  }
 1.95311 +  for(i=0; i<pDest->nCol; i++){
 1.95312 +    if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
 1.95313 +      return 0;    /* Affinity must be the same on all columns */
 1.95314 +    }
 1.95315 +    if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
 1.95316 +      return 0;    /* Collating sequence must be the same on all columns */
 1.95317 +    }
 1.95318 +    if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
 1.95319 +      return 0;    /* tab2 must be NOT NULL if tab1 is */
 1.95320 +    }
 1.95321 +  }
 1.95322 +  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
 1.95323 +    if( pDestIdx->onError!=OE_None ){
 1.95324 +      destHasUniqueIdx = 1;
 1.95325 +    }
 1.95326 +    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
 1.95327 +      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
 1.95328 +    }
 1.95329 +    if( pSrcIdx==0 ){
 1.95330 +      return 0;    /* pDestIdx has no corresponding index in pSrc */
 1.95331 +    }
 1.95332 +  }
 1.95333 +#ifndef SQLITE_OMIT_CHECK
 1.95334 +  if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
 1.95335 +    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
 1.95336 +  }
 1.95337 +#endif
 1.95338 +#ifndef SQLITE_OMIT_FOREIGN_KEY
 1.95339 +  /* Disallow the transfer optimization if the destination table constains
 1.95340 +  ** any foreign key constraints.  This is more restrictive than necessary.
 1.95341 +  ** But the main beneficiary of the transfer optimization is the VACUUM 
 1.95342 +  ** command, and the VACUUM command disables foreign key constraints.  So
 1.95343 +  ** the extra complication to make this rule less restrictive is probably
 1.95344 +  ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
 1.95345 +  */
 1.95346 +  if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
 1.95347 +    return 0;
 1.95348 +  }
 1.95349 +#endif
 1.95350 +  if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
 1.95351 +    return 0;  /* xfer opt does not play well with PRAGMA count_changes */
 1.95352 +  }
 1.95353 +
 1.95354 +  /* If we get this far, it means that the xfer optimization is at
 1.95355 +  ** least a possibility, though it might only work if the destination
 1.95356 +  ** table (tab1) is initially empty.
 1.95357 +  */
 1.95358 +#ifdef SQLITE_TEST
 1.95359 +  sqlite3_xferopt_count++;
 1.95360 +#endif
 1.95361 +  iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
 1.95362 +  v = sqlite3GetVdbe(pParse);
 1.95363 +  sqlite3CodeVerifySchema(pParse, iDbSrc);
 1.95364 +  iSrc = pParse->nTab++;
 1.95365 +  iDest = pParse->nTab++;
 1.95366 +  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
 1.95367 +  regData = sqlite3GetTempReg(pParse);
 1.95368 +  regRowid = sqlite3GetTempReg(pParse);
 1.95369 +  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
 1.95370 +  assert( HasRowid(pDest) || destHasUniqueIdx );
 1.95371 +  if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
 1.95372 +   || destHasUniqueIdx                              /* (2) */
 1.95373 +   || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
 1.95374 +  ){
 1.95375 +    /* In some circumstances, we are able to run the xfer optimization
 1.95376 +    ** only if the destination table is initially empty.  This code makes
 1.95377 +    ** that determination.  Conditions under which the destination must
 1.95378 +    ** be empty:
 1.95379 +    **
 1.95380 +    ** (1) There is no INTEGER PRIMARY KEY but there are indices.
 1.95381 +    **     (If the destination is not initially empty, the rowid fields
 1.95382 +    **     of index entries might need to change.)
 1.95383 +    **
 1.95384 +    ** (2) The destination has a unique index.  (The xfer optimization 
 1.95385 +    **     is unable to test uniqueness.)
 1.95386 +    **
 1.95387 +    ** (3) onError is something other than OE_Abort and OE_Rollback.
 1.95388 +    */
 1.95389 +    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
 1.95390 +    emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
 1.95391 +    sqlite3VdbeJumpHere(v, addr1);
 1.95392 +  }
 1.95393 +  if( HasRowid(pSrc) ){
 1.95394 +    sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
 1.95395 +    emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
 1.95396 +    if( pDest->iPKey>=0 ){
 1.95397 +      addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
 1.95398 +      addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
 1.95399 +      VdbeCoverage(v);
 1.95400 +      sqlite3RowidConstraint(pParse, onError, pDest);
 1.95401 +      sqlite3VdbeJumpHere(v, addr2);
 1.95402 +      autoIncStep(pParse, regAutoinc, regRowid);
 1.95403 +    }else if( pDest->pIndex==0 ){
 1.95404 +      addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
 1.95405 +    }else{
 1.95406 +      addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
 1.95407 +      assert( (pDest->tabFlags & TF_Autoincrement)==0 );
 1.95408 +    }
 1.95409 +    sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
 1.95410 +    sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
 1.95411 +    sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
 1.95412 +    sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
 1.95413 +    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
 1.95414 +    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
 1.95415 +    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
 1.95416 +  }else{
 1.95417 +    sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
 1.95418 +    sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
 1.95419 +  }
 1.95420 +  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
 1.95421 +    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
 1.95422 +      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
 1.95423 +    }
 1.95424 +    assert( pSrcIdx );
 1.95425 +    sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
 1.95426 +    sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
 1.95427 +    VdbeComment((v, "%s", pSrcIdx->zName));
 1.95428 +    sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
 1.95429 +    sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
 1.95430 +    sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
 1.95431 +    VdbeComment((v, "%s", pDestIdx->zName));
 1.95432 +    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
 1.95433 +    sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
 1.95434 +    sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
 1.95435 +    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
 1.95436 +    sqlite3VdbeJumpHere(v, addr1);
 1.95437 +    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
 1.95438 +    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
 1.95439 +  }
 1.95440 +  if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
 1.95441 +  sqlite3ReleaseTempReg(pParse, regRowid);
 1.95442 +  sqlite3ReleaseTempReg(pParse, regData);
 1.95443 +  if( emptyDestTest ){
 1.95444 +    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
 1.95445 +    sqlite3VdbeJumpHere(v, emptyDestTest);
 1.95446 +    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
 1.95447 +    return 0;
 1.95448 +  }else{
 1.95449 +    return 1;
 1.95450 +  }
 1.95451 +}
 1.95452 +#endif /* SQLITE_OMIT_XFER_OPT */
 1.95453 +
 1.95454 +/************** End of insert.c **********************************************/
 1.95455 +/************** Begin file legacy.c ******************************************/
 1.95456 +/*
 1.95457 +** 2001 September 15
 1.95458 +**
 1.95459 +** The author disclaims copyright to this source code.  In place of
 1.95460 +** a legal notice, here is a blessing:
 1.95461 +**
 1.95462 +**    May you do good and not evil.
 1.95463 +**    May you find forgiveness for yourself and forgive others.
 1.95464 +**    May you share freely, never taking more than you give.
 1.95465 +**
 1.95466 +*************************************************************************
 1.95467 +** Main file for the SQLite library.  The routines in this file
 1.95468 +** implement the programmer interface to the library.  Routines in
 1.95469 +** other files are for internal use by SQLite and should not be
 1.95470 +** accessed by users of the library.
 1.95471 +*/
 1.95472 +
 1.95473 +
 1.95474 +/*
 1.95475 +** Execute SQL code.  Return one of the SQLITE_ success/failure
 1.95476 +** codes.  Also write an error message into memory obtained from
 1.95477 +** malloc() and make *pzErrMsg point to that message.
 1.95478 +**
 1.95479 +** If the SQL is a query, then for each row in the query result
 1.95480 +** the xCallback() function is called.  pArg becomes the first
 1.95481 +** argument to xCallback().  If xCallback=NULL then no callback
 1.95482 +** is invoked, even for queries.
 1.95483 +*/
 1.95484 +SQLITE_API int sqlite3_exec(
 1.95485 +  sqlite3 *db,                /* The database on which the SQL executes */
 1.95486 +  const char *zSql,           /* The SQL to be executed */
 1.95487 +  sqlite3_callback xCallback, /* Invoke this callback routine */
 1.95488 +  void *pArg,                 /* First argument to xCallback() */
 1.95489 +  char **pzErrMsg             /* Write error messages here */
 1.95490 +){
 1.95491 +  int rc = SQLITE_OK;         /* Return code */
 1.95492 +  const char *zLeftover;      /* Tail of unprocessed SQL */
 1.95493 +  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
 1.95494 +  char **azCols = 0;          /* Names of result columns */
 1.95495 +  int callbackIsInit;         /* True if callback data is initialized */
 1.95496 +
 1.95497 +  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
 1.95498 +  if( zSql==0 ) zSql = "";
 1.95499 +
 1.95500 +  sqlite3_mutex_enter(db->mutex);
 1.95501 +  sqlite3Error(db, SQLITE_OK, 0);
 1.95502 +  while( rc==SQLITE_OK && zSql[0] ){
 1.95503 +    int nCol;
 1.95504 +    char **azVals = 0;
 1.95505 +
 1.95506 +    pStmt = 0;
 1.95507 +    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
 1.95508 +    assert( rc==SQLITE_OK || pStmt==0 );
 1.95509 +    if( rc!=SQLITE_OK ){
 1.95510 +      continue;
 1.95511 +    }
 1.95512 +    if( !pStmt ){
 1.95513 +      /* this happens for a comment or white-space */
 1.95514 +      zSql = zLeftover;
 1.95515 +      continue;
 1.95516 +    }
 1.95517 +
 1.95518 +    callbackIsInit = 0;
 1.95519 +    nCol = sqlite3_column_count(pStmt);
 1.95520 +
 1.95521 +    while( 1 ){
 1.95522 +      int i;
 1.95523 +      rc = sqlite3_step(pStmt);
 1.95524 +
 1.95525 +      /* Invoke the callback function if required */
 1.95526 +      if( xCallback && (SQLITE_ROW==rc || 
 1.95527 +          (SQLITE_DONE==rc && !callbackIsInit
 1.95528 +                           && db->flags&SQLITE_NullCallback)) ){
 1.95529 +        if( !callbackIsInit ){
 1.95530 +          azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
 1.95531 +          if( azCols==0 ){
 1.95532 +            goto exec_out;
 1.95533 +          }
 1.95534 +          for(i=0; i<nCol; i++){
 1.95535 +            azCols[i] = (char *)sqlite3_column_name(pStmt, i);
 1.95536 +            /* sqlite3VdbeSetColName() installs column names as UTF8
 1.95537 +            ** strings so there is no way for sqlite3_column_name() to fail. */
 1.95538 +            assert( azCols[i]!=0 );
 1.95539 +          }
 1.95540 +          callbackIsInit = 1;
 1.95541 +        }
 1.95542 +        if( rc==SQLITE_ROW ){
 1.95543 +          azVals = &azCols[nCol];
 1.95544 +          for(i=0; i<nCol; i++){
 1.95545 +            azVals[i] = (char *)sqlite3_column_text(pStmt, i);
 1.95546 +            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
 1.95547 +              db->mallocFailed = 1;
 1.95548 +              goto exec_out;
 1.95549 +            }
 1.95550 +          }
 1.95551 +        }
 1.95552 +        if( xCallback(pArg, nCol, azVals, azCols) ){
 1.95553 +          rc = SQLITE_ABORT;
 1.95554 +          sqlite3VdbeFinalize((Vdbe *)pStmt);
 1.95555 +          pStmt = 0;
 1.95556 +          sqlite3Error(db, SQLITE_ABORT, 0);
 1.95557 +          goto exec_out;
 1.95558 +        }
 1.95559 +      }
 1.95560 +
 1.95561 +      if( rc!=SQLITE_ROW ){
 1.95562 +        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
 1.95563 +        pStmt = 0;
 1.95564 +        zSql = zLeftover;
 1.95565 +        while( sqlite3Isspace(zSql[0]) ) zSql++;
 1.95566 +        break;
 1.95567 +      }
 1.95568 +    }
 1.95569 +
 1.95570 +    sqlite3DbFree(db, azCols);
 1.95571 +    azCols = 0;
 1.95572 +  }
 1.95573 +
 1.95574 +exec_out:
 1.95575 +  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
 1.95576 +  sqlite3DbFree(db, azCols);
 1.95577 +
 1.95578 +  rc = sqlite3ApiExit(db, rc);
 1.95579 +  if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
 1.95580 +    int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
 1.95581 +    *pzErrMsg = sqlite3Malloc(nErrMsg);
 1.95582 +    if( *pzErrMsg ){
 1.95583 +      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
 1.95584 +    }else{
 1.95585 +      rc = SQLITE_NOMEM;
 1.95586 +      sqlite3Error(db, SQLITE_NOMEM, 0);
 1.95587 +    }
 1.95588 +  }else if( pzErrMsg ){
 1.95589 +    *pzErrMsg = 0;
 1.95590 +  }
 1.95591 +
 1.95592 +  assert( (rc&db->errMask)==rc );
 1.95593 +  sqlite3_mutex_leave(db->mutex);
 1.95594 +  return rc;
 1.95595 +}
 1.95596 +
 1.95597 +/************** End of legacy.c **********************************************/
 1.95598 +/************** Begin file loadext.c *****************************************/
 1.95599 +/*
 1.95600 +** 2006 June 7
 1.95601 +**
 1.95602 +** The author disclaims copyright to this source code.  In place of
 1.95603 +** a legal notice, here is a blessing:
 1.95604 +**
 1.95605 +**    May you do good and not evil.
 1.95606 +**    May you find forgiveness for yourself and forgive others.
 1.95607 +**    May you share freely, never taking more than you give.
 1.95608 +**
 1.95609 +*************************************************************************
 1.95610 +** This file contains code used to dynamically load extensions into
 1.95611 +** the SQLite library.
 1.95612 +*/
 1.95613 +
 1.95614 +#ifndef SQLITE_CORE
 1.95615 +  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
 1.95616 +#endif
 1.95617 +/************** Include sqlite3ext.h in the middle of loadext.c **************/
 1.95618 +/************** Begin file sqlite3ext.h **************************************/
 1.95619 +/*
 1.95620 +** 2006 June 7
 1.95621 +**
 1.95622 +** The author disclaims copyright to this source code.  In place of
 1.95623 +** a legal notice, here is a blessing:
 1.95624 +**
 1.95625 +**    May you do good and not evil.
 1.95626 +**    May you find forgiveness for yourself and forgive others.
 1.95627 +**    May you share freely, never taking more than you give.
 1.95628 +**
 1.95629 +*************************************************************************
 1.95630 +** This header file defines the SQLite interface for use by
 1.95631 +** shared libraries that want to be imported as extensions into
 1.95632 +** an SQLite instance.  Shared libraries that intend to be loaded
 1.95633 +** as extensions by SQLite should #include this file instead of 
 1.95634 +** sqlite3.h.
 1.95635 +*/
 1.95636 +#ifndef _SQLITE3EXT_H_
 1.95637 +#define _SQLITE3EXT_H_
 1.95638 +
 1.95639 +typedef struct sqlite3_api_routines sqlite3_api_routines;
 1.95640 +
 1.95641 +/*
 1.95642 +** The following structure holds pointers to all of the SQLite API
 1.95643 +** routines.
 1.95644 +**
 1.95645 +** WARNING:  In order to maintain backwards compatibility, add new
 1.95646 +** interfaces to the end of this structure only.  If you insert new
 1.95647 +** interfaces in the middle of this structure, then older different
 1.95648 +** versions of SQLite will not be able to load each others' shared
 1.95649 +** libraries!
 1.95650 +*/
 1.95651 +struct sqlite3_api_routines {
 1.95652 +  void * (*aggregate_context)(sqlite3_context*,int nBytes);
 1.95653 +  int  (*aggregate_count)(sqlite3_context*);
 1.95654 +  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
 1.95655 +  int  (*bind_double)(sqlite3_stmt*,int,double);
 1.95656 +  int  (*bind_int)(sqlite3_stmt*,int,int);
 1.95657 +  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
 1.95658 +  int  (*bind_null)(sqlite3_stmt*,int);
 1.95659 +  int  (*bind_parameter_count)(sqlite3_stmt*);
 1.95660 +  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
 1.95661 +  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
 1.95662 +  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
 1.95663 +  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
 1.95664 +  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
 1.95665 +  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
 1.95666 +  int  (*busy_timeout)(sqlite3*,int ms);
 1.95667 +  int  (*changes)(sqlite3*);
 1.95668 +  int  (*close)(sqlite3*);
 1.95669 +  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
 1.95670 +                           int eTextRep,const char*));
 1.95671 +  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
 1.95672 +                             int eTextRep,const void*));
 1.95673 +  const void * (*column_blob)(sqlite3_stmt*,int iCol);
 1.95674 +  int  (*column_bytes)(sqlite3_stmt*,int iCol);
 1.95675 +  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
 1.95676 +  int  (*column_count)(sqlite3_stmt*pStmt);
 1.95677 +  const char * (*column_database_name)(sqlite3_stmt*,int);
 1.95678 +  const void * (*column_database_name16)(sqlite3_stmt*,int);
 1.95679 +  const char * (*column_decltype)(sqlite3_stmt*,int i);
 1.95680 +  const void * (*column_decltype16)(sqlite3_stmt*,int);
 1.95681 +  double  (*column_double)(sqlite3_stmt*,int iCol);
 1.95682 +  int  (*column_int)(sqlite3_stmt*,int iCol);
 1.95683 +  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
 1.95684 +  const char * (*column_name)(sqlite3_stmt*,int);
 1.95685 +  const void * (*column_name16)(sqlite3_stmt*,int);
 1.95686 +  const char * (*column_origin_name)(sqlite3_stmt*,int);
 1.95687 +  const void * (*column_origin_name16)(sqlite3_stmt*,int);
 1.95688 +  const char * (*column_table_name)(sqlite3_stmt*,int);
 1.95689 +  const void * (*column_table_name16)(sqlite3_stmt*,int);
 1.95690 +  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
 1.95691 +  const void * (*column_text16)(sqlite3_stmt*,int iCol);
 1.95692 +  int  (*column_type)(sqlite3_stmt*,int iCol);
 1.95693 +  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
 1.95694 +  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
 1.95695 +  int  (*complete)(const char*sql);
 1.95696 +  int  (*complete16)(const void*sql);
 1.95697 +  int  (*create_collation)(sqlite3*,const char*,int,void*,
 1.95698 +                           int(*)(void*,int,const void*,int,const void*));
 1.95699 +  int  (*create_collation16)(sqlite3*,const void*,int,void*,
 1.95700 +                             int(*)(void*,int,const void*,int,const void*));
 1.95701 +  int  (*create_function)(sqlite3*,const char*,int,int,void*,
 1.95702 +                          void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
 1.95703 +                          void (*xStep)(sqlite3_context*,int,sqlite3_value**),
 1.95704 +                          void (*xFinal)(sqlite3_context*));
 1.95705 +  int  (*create_function16)(sqlite3*,const void*,int,int,void*,
 1.95706 +                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
 1.95707 +                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
 1.95708 +                            void (*xFinal)(sqlite3_context*));
 1.95709 +  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
 1.95710 +  int  (*data_count)(sqlite3_stmt*pStmt);
 1.95711 +  sqlite3 * (*db_handle)(sqlite3_stmt*);
 1.95712 +  int (*declare_vtab)(sqlite3*,const char*);
 1.95713 +  int  (*enable_shared_cache)(int);
 1.95714 +  int  (*errcode)(sqlite3*db);
 1.95715 +  const char * (*errmsg)(sqlite3*);
 1.95716 +  const void * (*errmsg16)(sqlite3*);
 1.95717 +  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
 1.95718 +  int  (*expired)(sqlite3_stmt*);
 1.95719 +  int  (*finalize)(sqlite3_stmt*pStmt);
 1.95720 +  void  (*free)(void*);
 1.95721 +  void  (*free_table)(char**result);
 1.95722 +  int  (*get_autocommit)(sqlite3*);
 1.95723 +  void * (*get_auxdata)(sqlite3_context*,int);
 1.95724 +  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
 1.95725 +  int  (*global_recover)(void);
 1.95726 +  void  (*interruptx)(sqlite3*);
 1.95727 +  sqlite_int64  (*last_insert_rowid)(sqlite3*);
 1.95728 +  const char * (*libversion)(void);
 1.95729 +  int  (*libversion_number)(void);
 1.95730 +  void *(*malloc)(int);
 1.95731 +  char * (*mprintf)(const char*,...);
 1.95732 +  int  (*open)(const char*,sqlite3**);
 1.95733 +  int  (*open16)(const void*,sqlite3**);
 1.95734 +  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
 1.95735 +  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
 1.95736 +  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
 1.95737 +  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
 1.95738 +  void *(*realloc)(void*,int);
 1.95739 +  int  (*reset)(sqlite3_stmt*pStmt);
 1.95740 +  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
 1.95741 +  void  (*result_double)(sqlite3_context*,double);
 1.95742 +  void  (*result_error)(sqlite3_context*,const char*,int);
 1.95743 +  void  (*result_error16)(sqlite3_context*,const void*,int);
 1.95744 +  void  (*result_int)(sqlite3_context*,int);
 1.95745 +  void  (*result_int64)(sqlite3_context*,sqlite_int64);
 1.95746 +  void  (*result_null)(sqlite3_context*);
 1.95747 +  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
 1.95748 +  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
 1.95749 +  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
 1.95750 +  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
 1.95751 +  void  (*result_value)(sqlite3_context*,sqlite3_value*);
 1.95752 +  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
 1.95753 +  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
 1.95754 +                         const char*,const char*),void*);
 1.95755 +  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
 1.95756 +  char * (*snprintf)(int,char*,const char*,...);
 1.95757 +  int  (*step)(sqlite3_stmt*);
 1.95758 +  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
 1.95759 +                                char const**,char const**,int*,int*,int*);
 1.95760 +  void  (*thread_cleanup)(void);
 1.95761 +  int  (*total_changes)(sqlite3*);
 1.95762 +  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
 1.95763 +  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
 1.95764 +  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
 1.95765 +                                         sqlite_int64),void*);
 1.95766 +  void * (*user_data)(sqlite3_context*);
 1.95767 +  const void * (*value_blob)(sqlite3_value*);
 1.95768 +  int  (*value_bytes)(sqlite3_value*);
 1.95769 +  int  (*value_bytes16)(sqlite3_value*);
 1.95770 +  double  (*value_double)(sqlite3_value*);
 1.95771 +  int  (*value_int)(sqlite3_value*);
 1.95772 +  sqlite_int64  (*value_int64)(sqlite3_value*);
 1.95773 +  int  (*value_numeric_type)(sqlite3_value*);
 1.95774 +  const unsigned char * (*value_text)(sqlite3_value*);
 1.95775 +  const void * (*value_text16)(sqlite3_value*);
 1.95776 +  const void * (*value_text16be)(sqlite3_value*);
 1.95777 +  const void * (*value_text16le)(sqlite3_value*);
 1.95778 +  int  (*value_type)(sqlite3_value*);
 1.95779 +  char *(*vmprintf)(const char*,va_list);
 1.95780 +  /* Added ??? */
 1.95781 +  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
 1.95782 +  /* Added by 3.3.13 */
 1.95783 +  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
 1.95784 +  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
 1.95785 +  int (*clear_bindings)(sqlite3_stmt*);
 1.95786 +  /* Added by 3.4.1 */
 1.95787 +  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
 1.95788 +                          void (*xDestroy)(void *));
 1.95789 +  /* Added by 3.5.0 */
 1.95790 +  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
 1.95791 +  int (*blob_bytes)(sqlite3_blob*);
 1.95792 +  int (*blob_close)(sqlite3_blob*);
 1.95793 +  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
 1.95794 +                   int,sqlite3_blob**);
 1.95795 +  int (*blob_read)(sqlite3_blob*,void*,int,int);
 1.95796 +  int (*blob_write)(sqlite3_blob*,const void*,int,int);
 1.95797 +  int (*create_collation_v2)(sqlite3*,const char*,int,void*,
 1.95798 +                             int(*)(void*,int,const void*,int,const void*),
 1.95799 +                             void(*)(void*));
 1.95800 +  int (*file_control)(sqlite3*,const char*,int,void*);
 1.95801 +  sqlite3_int64 (*memory_highwater)(int);
 1.95802 +  sqlite3_int64 (*memory_used)(void);
 1.95803 +  sqlite3_mutex *(*mutex_alloc)(int);
 1.95804 +  void (*mutex_enter)(sqlite3_mutex*);
 1.95805 +  void (*mutex_free)(sqlite3_mutex*);
 1.95806 +  void (*mutex_leave)(sqlite3_mutex*);
 1.95807 +  int (*mutex_try)(sqlite3_mutex*);
 1.95808 +  int (*open_v2)(const char*,sqlite3**,int,const char*);
 1.95809 +  int (*release_memory)(int);
 1.95810 +  void (*result_error_nomem)(sqlite3_context*);
 1.95811 +  void (*result_error_toobig)(sqlite3_context*);
 1.95812 +  int (*sleep)(int);
 1.95813 +  void (*soft_heap_limit)(int);
 1.95814 +  sqlite3_vfs *(*vfs_find)(const char*);
 1.95815 +  int (*vfs_register)(sqlite3_vfs*,int);
 1.95816 +  int (*vfs_unregister)(sqlite3_vfs*);
 1.95817 +  int (*xthreadsafe)(void);
 1.95818 +  void (*result_zeroblob)(sqlite3_context*,int);
 1.95819 +  void (*result_error_code)(sqlite3_context*,int);
 1.95820 +  int (*test_control)(int, ...);
 1.95821 +  void (*randomness)(int,void*);
 1.95822 +  sqlite3 *(*context_db_handle)(sqlite3_context*);
 1.95823 +  int (*extended_result_codes)(sqlite3*,int);
 1.95824 +  int (*limit)(sqlite3*,int,int);
 1.95825 +  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
 1.95826 +  const char *(*sql)(sqlite3_stmt*);
 1.95827 +  int (*status)(int,int*,int*,int);
 1.95828 +  int (*backup_finish)(sqlite3_backup*);
 1.95829 +  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
 1.95830 +  int (*backup_pagecount)(sqlite3_backup*);
 1.95831 +  int (*backup_remaining)(sqlite3_backup*);
 1.95832 +  int (*backup_step)(sqlite3_backup*,int);
 1.95833 +  const char *(*compileoption_get)(int);
 1.95834 +  int (*compileoption_used)(const char*);
 1.95835 +  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
 1.95836 +                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
 1.95837 +                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
 1.95838 +                            void (*xFinal)(sqlite3_context*),
 1.95839 +                            void(*xDestroy)(void*));
 1.95840 +  int (*db_config)(sqlite3*,int,...);
 1.95841 +  sqlite3_mutex *(*db_mutex)(sqlite3*);
 1.95842 +  int (*db_status)(sqlite3*,int,int*,int*,int);
 1.95843 +  int (*extended_errcode)(sqlite3*);
 1.95844 +  void (*log)(int,const char*,...);
 1.95845 +  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
 1.95846 +  const char *(*sourceid)(void);
 1.95847 +  int (*stmt_status)(sqlite3_stmt*,int,int);
 1.95848 +  int (*strnicmp)(const char*,const char*,int);
 1.95849 +  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
 1.95850 +  int (*wal_autocheckpoint)(sqlite3*,int);
 1.95851 +  int (*wal_checkpoint)(sqlite3*,const char*);
 1.95852 +  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
 1.95853 +  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
 1.95854 +  int (*vtab_config)(sqlite3*,int op,...);
 1.95855 +  int (*vtab_on_conflict)(sqlite3*);
 1.95856 +  /* Version 3.7.16 and later */
 1.95857 +  int (*close_v2)(sqlite3*);
 1.95858 +  const char *(*db_filename)(sqlite3*,const char*);
 1.95859 +  int (*db_readonly)(sqlite3*,const char*);
 1.95860 +  int (*db_release_memory)(sqlite3*);
 1.95861 +  const char *(*errstr)(int);
 1.95862 +  int (*stmt_busy)(sqlite3_stmt*);
 1.95863 +  int (*stmt_readonly)(sqlite3_stmt*);
 1.95864 +  int (*stricmp)(const char*,const char*);
 1.95865 +  int (*uri_boolean)(const char*,const char*,int);
 1.95866 +  sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
 1.95867 +  const char *(*uri_parameter)(const char*,const char*);
 1.95868 +  char *(*vsnprintf)(int,char*,const char*,va_list);
 1.95869 +  int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
 1.95870 +};
 1.95871 +
 1.95872 +/*
 1.95873 +** The following macros redefine the API routines so that they are
 1.95874 +** redirected throught the global sqlite3_api structure.
 1.95875 +**
 1.95876 +** This header file is also used by the loadext.c source file
 1.95877 +** (part of the main SQLite library - not an extension) so that
 1.95878 +** it can get access to the sqlite3_api_routines structure
 1.95879 +** definition.  But the main library does not want to redefine
 1.95880 +** the API.  So the redefinition macros are only valid if the
 1.95881 +** SQLITE_CORE macros is undefined.
 1.95882 +*/
 1.95883 +#ifndef SQLITE_CORE
 1.95884 +#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
 1.95885 +#ifndef SQLITE_OMIT_DEPRECATED
 1.95886 +#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
 1.95887 +#endif
 1.95888 +#define sqlite3_bind_blob              sqlite3_api->bind_blob
 1.95889 +#define sqlite3_bind_double            sqlite3_api->bind_double
 1.95890 +#define sqlite3_bind_int               sqlite3_api->bind_int
 1.95891 +#define sqlite3_bind_int64             sqlite3_api->bind_int64
 1.95892 +#define sqlite3_bind_null              sqlite3_api->bind_null
 1.95893 +#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
 1.95894 +#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
 1.95895 +#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
 1.95896 +#define sqlite3_bind_text              sqlite3_api->bind_text
 1.95897 +#define sqlite3_bind_text16            sqlite3_api->bind_text16
 1.95898 +#define sqlite3_bind_value             sqlite3_api->bind_value
 1.95899 +#define sqlite3_busy_handler           sqlite3_api->busy_handler
 1.95900 +#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
 1.95901 +#define sqlite3_changes                sqlite3_api->changes
 1.95902 +#define sqlite3_close                  sqlite3_api->close
 1.95903 +#define sqlite3_collation_needed       sqlite3_api->collation_needed
 1.95904 +#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
 1.95905 +#define sqlite3_column_blob            sqlite3_api->column_blob
 1.95906 +#define sqlite3_column_bytes           sqlite3_api->column_bytes
 1.95907 +#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
 1.95908 +#define sqlite3_column_count           sqlite3_api->column_count
 1.95909 +#define sqlite3_column_database_name   sqlite3_api->column_database_name
 1.95910 +#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
 1.95911 +#define sqlite3_column_decltype        sqlite3_api->column_decltype
 1.95912 +#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
 1.95913 +#define sqlite3_column_double          sqlite3_api->column_double
 1.95914 +#define sqlite3_column_int             sqlite3_api->column_int
 1.95915 +#define sqlite3_column_int64           sqlite3_api->column_int64
 1.95916 +#define sqlite3_column_name            sqlite3_api->column_name
 1.95917 +#define sqlite3_column_name16          sqlite3_api->column_name16
 1.95918 +#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
 1.95919 +#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
 1.95920 +#define sqlite3_column_table_name      sqlite3_api->column_table_name
 1.95921 +#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
 1.95922 +#define sqlite3_column_text            sqlite3_api->column_text
 1.95923 +#define sqlite3_column_text16          sqlite3_api->column_text16
 1.95924 +#define sqlite3_column_type            sqlite3_api->column_type
 1.95925 +#define sqlite3_column_value           sqlite3_api->column_value
 1.95926 +#define sqlite3_commit_hook            sqlite3_api->commit_hook
 1.95927 +#define sqlite3_complete               sqlite3_api->complete
 1.95928 +#define sqlite3_complete16             sqlite3_api->complete16
 1.95929 +#define sqlite3_create_collation       sqlite3_api->create_collation
 1.95930 +#define sqlite3_create_collation16     sqlite3_api->create_collation16
 1.95931 +#define sqlite3_create_function        sqlite3_api->create_function
 1.95932 +#define sqlite3_create_function16      sqlite3_api->create_function16
 1.95933 +#define sqlite3_create_module          sqlite3_api->create_module
 1.95934 +#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
 1.95935 +#define sqlite3_data_count             sqlite3_api->data_count
 1.95936 +#define sqlite3_db_handle              sqlite3_api->db_handle
 1.95937 +#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
 1.95938 +#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
 1.95939 +#define sqlite3_errcode                sqlite3_api->errcode
 1.95940 +#define sqlite3_errmsg                 sqlite3_api->errmsg
 1.95941 +#define sqlite3_errmsg16               sqlite3_api->errmsg16
 1.95942 +#define sqlite3_exec                   sqlite3_api->exec
 1.95943 +#ifndef SQLITE_OMIT_DEPRECATED
 1.95944 +#define sqlite3_expired                sqlite3_api->expired
 1.95945 +#endif
 1.95946 +#define sqlite3_finalize               sqlite3_api->finalize
 1.95947 +#define sqlite3_free                   sqlite3_api->free
 1.95948 +#define sqlite3_free_table             sqlite3_api->free_table
 1.95949 +#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
 1.95950 +#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
 1.95951 +#define sqlite3_get_table              sqlite3_api->get_table
 1.95952 +#ifndef SQLITE_OMIT_DEPRECATED
 1.95953 +#define sqlite3_global_recover         sqlite3_api->global_recover
 1.95954 +#endif
 1.95955 +#define sqlite3_interrupt              sqlite3_api->interruptx
 1.95956 +#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
 1.95957 +#define sqlite3_libversion             sqlite3_api->libversion
 1.95958 +#define sqlite3_libversion_number      sqlite3_api->libversion_number
 1.95959 +#define sqlite3_malloc                 sqlite3_api->malloc
 1.95960 +#define sqlite3_mprintf                sqlite3_api->mprintf
 1.95961 +#define sqlite3_open                   sqlite3_api->open
 1.95962 +#define sqlite3_open16                 sqlite3_api->open16
 1.95963 +#define sqlite3_prepare                sqlite3_api->prepare
 1.95964 +#define sqlite3_prepare16              sqlite3_api->prepare16
 1.95965 +#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
 1.95966 +#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
 1.95967 +#define sqlite3_profile                sqlite3_api->profile
 1.95968 +#define sqlite3_progress_handler       sqlite3_api->progress_handler
 1.95969 +#define sqlite3_realloc                sqlite3_api->realloc
 1.95970 +#define sqlite3_reset                  sqlite3_api->reset
 1.95971 +#define sqlite3_result_blob            sqlite3_api->result_blob
 1.95972 +#define sqlite3_result_double          sqlite3_api->result_double
 1.95973 +#define sqlite3_result_error           sqlite3_api->result_error
 1.95974 +#define sqlite3_result_error16         sqlite3_api->result_error16
 1.95975 +#define sqlite3_result_int             sqlite3_api->result_int
 1.95976 +#define sqlite3_result_int64           sqlite3_api->result_int64
 1.95977 +#define sqlite3_result_null            sqlite3_api->result_null
 1.95978 +#define sqlite3_result_text            sqlite3_api->result_text
 1.95979 +#define sqlite3_result_text16          sqlite3_api->result_text16
 1.95980 +#define sqlite3_result_text16be        sqlite3_api->result_text16be
 1.95981 +#define sqlite3_result_text16le        sqlite3_api->result_text16le
 1.95982 +#define sqlite3_result_value           sqlite3_api->result_value
 1.95983 +#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
 1.95984 +#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
 1.95985 +#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
 1.95986 +#define sqlite3_snprintf               sqlite3_api->snprintf
 1.95987 +#define sqlite3_step                   sqlite3_api->step
 1.95988 +#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
 1.95989 +#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
 1.95990 +#define sqlite3_total_changes          sqlite3_api->total_changes
 1.95991 +#define sqlite3_trace                  sqlite3_api->trace
 1.95992 +#ifndef SQLITE_OMIT_DEPRECATED
 1.95993 +#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
 1.95994 +#endif
 1.95995 +#define sqlite3_update_hook            sqlite3_api->update_hook
 1.95996 +#define sqlite3_user_data              sqlite3_api->user_data
 1.95997 +#define sqlite3_value_blob             sqlite3_api->value_blob
 1.95998 +#define sqlite3_value_bytes            sqlite3_api->value_bytes
 1.95999 +#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
 1.96000 +#define sqlite3_value_double           sqlite3_api->value_double
 1.96001 +#define sqlite3_value_int              sqlite3_api->value_int
 1.96002 +#define sqlite3_value_int64            sqlite3_api->value_int64
 1.96003 +#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
 1.96004 +#define sqlite3_value_text             sqlite3_api->value_text
 1.96005 +#define sqlite3_value_text16           sqlite3_api->value_text16
 1.96006 +#define sqlite3_value_text16be         sqlite3_api->value_text16be
 1.96007 +#define sqlite3_value_text16le         sqlite3_api->value_text16le
 1.96008 +#define sqlite3_value_type             sqlite3_api->value_type
 1.96009 +#define sqlite3_vmprintf               sqlite3_api->vmprintf
 1.96010 +#define sqlite3_overload_function      sqlite3_api->overload_function
 1.96011 +#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
 1.96012 +#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
 1.96013 +#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
 1.96014 +#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
 1.96015 +#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
 1.96016 +#define sqlite3_blob_close             sqlite3_api->blob_close
 1.96017 +#define sqlite3_blob_open              sqlite3_api->blob_open
 1.96018 +#define sqlite3_blob_read              sqlite3_api->blob_read
 1.96019 +#define sqlite3_blob_write             sqlite3_api->blob_write
 1.96020 +#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
 1.96021 +#define sqlite3_file_control           sqlite3_api->file_control
 1.96022 +#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
 1.96023 +#define sqlite3_memory_used            sqlite3_api->memory_used
 1.96024 +#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
 1.96025 +#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
 1.96026 +#define sqlite3_mutex_free             sqlite3_api->mutex_free
 1.96027 +#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
 1.96028 +#define sqlite3_mutex_try              sqlite3_api->mutex_try
 1.96029 +#define sqlite3_open_v2                sqlite3_api->open_v2
 1.96030 +#define sqlite3_release_memory         sqlite3_api->release_memory
 1.96031 +#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
 1.96032 +#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
 1.96033 +#define sqlite3_sleep                  sqlite3_api->sleep
 1.96034 +#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
 1.96035 +#define sqlite3_vfs_find               sqlite3_api->vfs_find
 1.96036 +#define sqlite3_vfs_register           sqlite3_api->vfs_register
 1.96037 +#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
 1.96038 +#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
 1.96039 +#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
 1.96040 +#define sqlite3_result_error_code      sqlite3_api->result_error_code
 1.96041 +#define sqlite3_test_control           sqlite3_api->test_control
 1.96042 +#define sqlite3_randomness             sqlite3_api->randomness
 1.96043 +#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
 1.96044 +#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
 1.96045 +#define sqlite3_limit                  sqlite3_api->limit
 1.96046 +#define sqlite3_next_stmt              sqlite3_api->next_stmt
 1.96047 +#define sqlite3_sql                    sqlite3_api->sql
 1.96048 +#define sqlite3_status                 sqlite3_api->status
 1.96049 +#define sqlite3_backup_finish          sqlite3_api->backup_finish
 1.96050 +#define sqlite3_backup_init            sqlite3_api->backup_init
 1.96051 +#define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
 1.96052 +#define sqlite3_backup_remaining       sqlite3_api->backup_remaining
 1.96053 +#define sqlite3_backup_step            sqlite3_api->backup_step
 1.96054 +#define sqlite3_compileoption_get      sqlite3_api->compileoption_get
 1.96055 +#define sqlite3_compileoption_used     sqlite3_api->compileoption_used
 1.96056 +#define sqlite3_create_function_v2     sqlite3_api->create_function_v2
 1.96057 +#define sqlite3_db_config              sqlite3_api->db_config
 1.96058 +#define sqlite3_db_mutex               sqlite3_api->db_mutex
 1.96059 +#define sqlite3_db_status              sqlite3_api->db_status
 1.96060 +#define sqlite3_extended_errcode       sqlite3_api->extended_errcode
 1.96061 +#define sqlite3_log                    sqlite3_api->log
 1.96062 +#define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
 1.96063 +#define sqlite3_sourceid               sqlite3_api->sourceid
 1.96064 +#define sqlite3_stmt_status            sqlite3_api->stmt_status
 1.96065 +#define sqlite3_strnicmp               sqlite3_api->strnicmp
 1.96066 +#define sqlite3_unlock_notify          sqlite3_api->unlock_notify
 1.96067 +#define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
 1.96068 +#define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
 1.96069 +#define sqlite3_wal_hook               sqlite3_api->wal_hook
 1.96070 +#define sqlite3_blob_reopen            sqlite3_api->blob_reopen
 1.96071 +#define sqlite3_vtab_config            sqlite3_api->vtab_config
 1.96072 +#define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
 1.96073 +/* Version 3.7.16 and later */
 1.96074 +#define sqlite3_close_v2               sqlite3_api->close_v2
 1.96075 +#define sqlite3_db_filename            sqlite3_api->db_filename
 1.96076 +#define sqlite3_db_readonly            sqlite3_api->db_readonly
 1.96077 +#define sqlite3_db_release_memory      sqlite3_api->db_release_memory
 1.96078 +#define sqlite3_errstr                 sqlite3_api->errstr
 1.96079 +#define sqlite3_stmt_busy              sqlite3_api->stmt_busy
 1.96080 +#define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
 1.96081 +#define sqlite3_stricmp                sqlite3_api->stricmp
 1.96082 +#define sqlite3_uri_boolean            sqlite3_api->uri_boolean
 1.96083 +#define sqlite3_uri_int64              sqlite3_api->uri_int64
 1.96084 +#define sqlite3_uri_parameter          sqlite3_api->uri_parameter
 1.96085 +#define sqlite3_uri_vsnprintf          sqlite3_api->vsnprintf
 1.96086 +#define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
 1.96087 +#endif /* SQLITE_CORE */
 1.96088 +
 1.96089 +#ifndef SQLITE_CORE
 1.96090 +  /* This case when the file really is being compiled as a loadable 
 1.96091 +  ** extension */
 1.96092 +# define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
 1.96093 +# define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
 1.96094 +# define SQLITE_EXTENSION_INIT3     \
 1.96095 +    extern const sqlite3_api_routines *sqlite3_api;
 1.96096 +#else
 1.96097 +  /* This case when the file is being statically linked into the 
 1.96098 +  ** application */
 1.96099 +# define SQLITE_EXTENSION_INIT1     /*no-op*/
 1.96100 +# define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
 1.96101 +# define SQLITE_EXTENSION_INIT3     /*no-op*/
 1.96102 +#endif
 1.96103 +
 1.96104 +#endif /* _SQLITE3EXT_H_ */
 1.96105 +
 1.96106 +/************** End of sqlite3ext.h ******************************************/
 1.96107 +/************** Continuing where we left off in loadext.c ********************/
 1.96108 +/* #include <string.h> */
 1.96109 +
 1.96110 +#ifndef SQLITE_OMIT_LOAD_EXTENSION
 1.96111 +
 1.96112 +/*
 1.96113 +** Some API routines are omitted when various features are
 1.96114 +** excluded from a build of SQLite.  Substitute a NULL pointer
 1.96115 +** for any missing APIs.
 1.96116 +*/
 1.96117 +#ifndef SQLITE_ENABLE_COLUMN_METADATA
 1.96118 +# define sqlite3_column_database_name   0
 1.96119 +# define sqlite3_column_database_name16 0
 1.96120 +# define sqlite3_column_table_name      0
 1.96121 +# define sqlite3_column_table_name16    0
 1.96122 +# define sqlite3_column_origin_name     0
 1.96123 +# define sqlite3_column_origin_name16   0
 1.96124 +# define sqlite3_table_column_metadata  0
 1.96125 +#endif
 1.96126 +
 1.96127 +#ifdef SQLITE_OMIT_AUTHORIZATION
 1.96128 +# define sqlite3_set_authorizer         0
 1.96129 +#endif
 1.96130 +
 1.96131 +#ifdef SQLITE_OMIT_UTF16
 1.96132 +# define sqlite3_bind_text16            0
 1.96133 +# define sqlite3_collation_needed16     0
 1.96134 +# define sqlite3_column_decltype16      0
 1.96135 +# define sqlite3_column_name16          0
 1.96136 +# define sqlite3_column_text16          0
 1.96137 +# define sqlite3_complete16             0
 1.96138 +# define sqlite3_create_collation16     0
 1.96139 +# define sqlite3_create_function16      0
 1.96140 +# define sqlite3_errmsg16               0
 1.96141 +# define sqlite3_open16                 0
 1.96142 +# define sqlite3_prepare16              0
 1.96143 +# define sqlite3_prepare16_v2           0
 1.96144 +# define sqlite3_result_error16         0
 1.96145 +# define sqlite3_result_text16          0
 1.96146 +# define sqlite3_result_text16be        0
 1.96147 +# define sqlite3_result_text16le        0
 1.96148 +# define sqlite3_value_text16           0
 1.96149 +# define sqlite3_value_text16be         0
 1.96150 +# define sqlite3_value_text16le         0
 1.96151 +# define sqlite3_column_database_name16 0
 1.96152 +# define sqlite3_column_table_name16    0
 1.96153 +# define sqlite3_column_origin_name16   0
 1.96154 +#endif
 1.96155 +
 1.96156 +#ifdef SQLITE_OMIT_COMPLETE
 1.96157 +# define sqlite3_complete 0
 1.96158 +# define sqlite3_complete16 0
 1.96159 +#endif
 1.96160 +
 1.96161 +#ifdef SQLITE_OMIT_DECLTYPE
 1.96162 +# define sqlite3_column_decltype16      0
 1.96163 +# define sqlite3_column_decltype        0
 1.96164 +#endif
 1.96165 +
 1.96166 +#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
 1.96167 +# define sqlite3_progress_handler 0
 1.96168 +#endif
 1.96169 +
 1.96170 +#ifdef SQLITE_OMIT_VIRTUALTABLE
 1.96171 +# define sqlite3_create_module 0
 1.96172 +# define sqlite3_create_module_v2 0
 1.96173 +# define sqlite3_declare_vtab 0
 1.96174 +# define sqlite3_vtab_config 0
 1.96175 +# define sqlite3_vtab_on_conflict 0
 1.96176 +#endif
 1.96177 +
 1.96178 +#ifdef SQLITE_OMIT_SHARED_CACHE
 1.96179 +# define sqlite3_enable_shared_cache 0
 1.96180 +#endif
 1.96181 +
 1.96182 +#ifdef SQLITE_OMIT_TRACE
 1.96183 +# define sqlite3_profile       0
 1.96184 +# define sqlite3_trace         0
 1.96185 +#endif
 1.96186 +
 1.96187 +#ifdef SQLITE_OMIT_GET_TABLE
 1.96188 +# define sqlite3_free_table    0
 1.96189 +# define sqlite3_get_table     0
 1.96190 +#endif
 1.96191 +
 1.96192 +#ifdef SQLITE_OMIT_INCRBLOB
 1.96193 +#define sqlite3_bind_zeroblob  0
 1.96194 +#define sqlite3_blob_bytes     0
 1.96195 +#define sqlite3_blob_close     0
 1.96196 +#define sqlite3_blob_open      0
 1.96197 +#define sqlite3_blob_read      0
 1.96198 +#define sqlite3_blob_write     0
 1.96199 +#define sqlite3_blob_reopen    0
 1.96200 +#endif
 1.96201 +
 1.96202 +/*
 1.96203 +** The following structure contains pointers to all SQLite API routines.
 1.96204 +** A pointer to this structure is passed into extensions when they are
 1.96205 +** loaded so that the extension can make calls back into the SQLite
 1.96206 +** library.
 1.96207 +**
 1.96208 +** When adding new APIs, add them to the bottom of this structure
 1.96209 +** in order to preserve backwards compatibility.
 1.96210 +**
 1.96211 +** Extensions that use newer APIs should first call the
 1.96212 +** sqlite3_libversion_number() to make sure that the API they
 1.96213 +** intend to use is supported by the library.  Extensions should
 1.96214 +** also check to make sure that the pointer to the function is
 1.96215 +** not NULL before calling it.
 1.96216 +*/
 1.96217 +static const sqlite3_api_routines sqlite3Apis = {
 1.96218 +  sqlite3_aggregate_context,
 1.96219 +#ifndef SQLITE_OMIT_DEPRECATED
 1.96220 +  sqlite3_aggregate_count,
 1.96221 +#else
 1.96222 +  0,
 1.96223 +#endif
 1.96224 +  sqlite3_bind_blob,
 1.96225 +  sqlite3_bind_double,
 1.96226 +  sqlite3_bind_int,
 1.96227 +  sqlite3_bind_int64,
 1.96228 +  sqlite3_bind_null,
 1.96229 +  sqlite3_bind_parameter_count,
 1.96230 +  sqlite3_bind_parameter_index,
 1.96231 +  sqlite3_bind_parameter_name,
 1.96232 +  sqlite3_bind_text,
 1.96233 +  sqlite3_bind_text16,
 1.96234 +  sqlite3_bind_value,
 1.96235 +  sqlite3_busy_handler,
 1.96236 +  sqlite3_busy_timeout,
 1.96237 +  sqlite3_changes,
 1.96238 +  sqlite3_close,
 1.96239 +  sqlite3_collation_needed,
 1.96240 +  sqlite3_collation_needed16,
 1.96241 +  sqlite3_column_blob,
 1.96242 +  sqlite3_column_bytes,
 1.96243 +  sqlite3_column_bytes16,
 1.96244 +  sqlite3_column_count,
 1.96245 +  sqlite3_column_database_name,
 1.96246 +  sqlite3_column_database_name16,
 1.96247 +  sqlite3_column_decltype,
 1.96248 +  sqlite3_column_decltype16,
 1.96249 +  sqlite3_column_double,
 1.96250 +  sqlite3_column_int,
 1.96251 +  sqlite3_column_int64,
 1.96252 +  sqlite3_column_name,
 1.96253 +  sqlite3_column_name16,
 1.96254 +  sqlite3_column_origin_name,
 1.96255 +  sqlite3_column_origin_name16,
 1.96256 +  sqlite3_column_table_name,
 1.96257 +  sqlite3_column_table_name16,
 1.96258 +  sqlite3_column_text,
 1.96259 +  sqlite3_column_text16,
 1.96260 +  sqlite3_column_type,
 1.96261 +  sqlite3_column_value,
 1.96262 +  sqlite3_commit_hook,
 1.96263 +  sqlite3_complete,
 1.96264 +  sqlite3_complete16,
 1.96265 +  sqlite3_create_collation,
 1.96266 +  sqlite3_create_collation16,
 1.96267 +  sqlite3_create_function,
 1.96268 +  sqlite3_create_function16,
 1.96269 +  sqlite3_create_module,
 1.96270 +  sqlite3_data_count,
 1.96271 +  sqlite3_db_handle,
 1.96272 +  sqlite3_declare_vtab,
 1.96273 +  sqlite3_enable_shared_cache,
 1.96274 +  sqlite3_errcode,
 1.96275 +  sqlite3_errmsg,
 1.96276 +  sqlite3_errmsg16,
 1.96277 +  sqlite3_exec,
 1.96278 +#ifndef SQLITE_OMIT_DEPRECATED
 1.96279 +  sqlite3_expired,
 1.96280 +#else
 1.96281 +  0,
 1.96282 +#endif
 1.96283 +  sqlite3_finalize,
 1.96284 +  sqlite3_free,
 1.96285 +  sqlite3_free_table,
 1.96286 +  sqlite3_get_autocommit,
 1.96287 +  sqlite3_get_auxdata,
 1.96288 +  sqlite3_get_table,
 1.96289 +  0,     /* Was sqlite3_global_recover(), but that function is deprecated */
 1.96290 +  sqlite3_interrupt,
 1.96291 +  sqlite3_last_insert_rowid,
 1.96292 +  sqlite3_libversion,
 1.96293 +  sqlite3_libversion_number,
 1.96294 +  sqlite3_malloc,
 1.96295 +  sqlite3_mprintf,
 1.96296 +  sqlite3_open,
 1.96297 +  sqlite3_open16,
 1.96298 +  sqlite3_prepare,
 1.96299 +  sqlite3_prepare16,
 1.96300 +  sqlite3_profile,
 1.96301 +  sqlite3_progress_handler,
 1.96302 +  sqlite3_realloc,
 1.96303 +  sqlite3_reset,
 1.96304 +  sqlite3_result_blob,
 1.96305 +  sqlite3_result_double,
 1.96306 +  sqlite3_result_error,
 1.96307 +  sqlite3_result_error16,
 1.96308 +  sqlite3_result_int,
 1.96309 +  sqlite3_result_int64,
 1.96310 +  sqlite3_result_null,
 1.96311 +  sqlite3_result_text,
 1.96312 +  sqlite3_result_text16,
 1.96313 +  sqlite3_result_text16be,
 1.96314 +  sqlite3_result_text16le,
 1.96315 +  sqlite3_result_value,
 1.96316 +  sqlite3_rollback_hook,
 1.96317 +  sqlite3_set_authorizer,
 1.96318 +  sqlite3_set_auxdata,
 1.96319 +  sqlite3_snprintf,
 1.96320 +  sqlite3_step,
 1.96321 +  sqlite3_table_column_metadata,
 1.96322 +#ifndef SQLITE_OMIT_DEPRECATED
 1.96323 +  sqlite3_thread_cleanup,
 1.96324 +#else
 1.96325 +  0,
 1.96326 +#endif
 1.96327 +  sqlite3_total_changes,
 1.96328 +  sqlite3_trace,
 1.96329 +#ifndef SQLITE_OMIT_DEPRECATED
 1.96330 +  sqlite3_transfer_bindings,
 1.96331 +#else
 1.96332 +  0,
 1.96333 +#endif
 1.96334 +  sqlite3_update_hook,
 1.96335 +  sqlite3_user_data,
 1.96336 +  sqlite3_value_blob,
 1.96337 +  sqlite3_value_bytes,
 1.96338 +  sqlite3_value_bytes16,
 1.96339 +  sqlite3_value_double,
 1.96340 +  sqlite3_value_int,
 1.96341 +  sqlite3_value_int64,
 1.96342 +  sqlite3_value_numeric_type,
 1.96343 +  sqlite3_value_text,
 1.96344 +  sqlite3_value_text16,
 1.96345 +  sqlite3_value_text16be,
 1.96346 +  sqlite3_value_text16le,
 1.96347 +  sqlite3_value_type,
 1.96348 +  sqlite3_vmprintf,
 1.96349 +  /*
 1.96350 +  ** The original API set ends here.  All extensions can call any
 1.96351 +  ** of the APIs above provided that the pointer is not NULL.  But
 1.96352 +  ** before calling APIs that follow, extension should check the
 1.96353 +  ** sqlite3_libversion_number() to make sure they are dealing with
 1.96354 +  ** a library that is new enough to support that API.
 1.96355 +  *************************************************************************
 1.96356 +  */
 1.96357 +  sqlite3_overload_function,
 1.96358 +
 1.96359 +  /*
 1.96360 +  ** Added after 3.3.13
 1.96361 +  */
 1.96362 +  sqlite3_prepare_v2,
 1.96363 +  sqlite3_prepare16_v2,
 1.96364 +  sqlite3_clear_bindings,
 1.96365 +
 1.96366 +  /*
 1.96367 +  ** Added for 3.4.1
 1.96368 +  */
 1.96369 +  sqlite3_create_module_v2,
 1.96370 +
 1.96371 +  /*
 1.96372 +  ** Added for 3.5.0
 1.96373 +  */
 1.96374 +  sqlite3_bind_zeroblob,
 1.96375 +  sqlite3_blob_bytes,
 1.96376 +  sqlite3_blob_close,
 1.96377 +  sqlite3_blob_open,
 1.96378 +  sqlite3_blob_read,
 1.96379 +  sqlite3_blob_write,
 1.96380 +  sqlite3_create_collation_v2,
 1.96381 +  sqlite3_file_control,
 1.96382 +  sqlite3_memory_highwater,
 1.96383 +  sqlite3_memory_used,
 1.96384 +#ifdef SQLITE_MUTEX_OMIT
 1.96385 +  0, 
 1.96386 +  0, 
 1.96387 +  0,
 1.96388 +  0,
 1.96389 +  0,
 1.96390 +#else
 1.96391 +  sqlite3_mutex_alloc,
 1.96392 +  sqlite3_mutex_enter,
 1.96393 +  sqlite3_mutex_free,
 1.96394 +  sqlite3_mutex_leave,
 1.96395 +  sqlite3_mutex_try,
 1.96396 +#endif
 1.96397 +  sqlite3_open_v2,
 1.96398 +  sqlite3_release_memory,
 1.96399 +  sqlite3_result_error_nomem,
 1.96400 +  sqlite3_result_error_toobig,
 1.96401 +  sqlite3_sleep,
 1.96402 +  sqlite3_soft_heap_limit,
 1.96403 +  sqlite3_vfs_find,
 1.96404 +  sqlite3_vfs_register,
 1.96405 +  sqlite3_vfs_unregister,
 1.96406 +
 1.96407 +  /*
 1.96408 +  ** Added for 3.5.8
 1.96409 +  */
 1.96410 +  sqlite3_threadsafe,
 1.96411 +  sqlite3_result_zeroblob,
 1.96412 +  sqlite3_result_error_code,
 1.96413 +  sqlite3_test_control,
 1.96414 +  sqlite3_randomness,
 1.96415 +  sqlite3_context_db_handle,
 1.96416 +
 1.96417 +  /*
 1.96418 +  ** Added for 3.6.0
 1.96419 +  */
 1.96420 +  sqlite3_extended_result_codes,
 1.96421 +  sqlite3_limit,
 1.96422 +  sqlite3_next_stmt,
 1.96423 +  sqlite3_sql,
 1.96424 +  sqlite3_status,
 1.96425 +
 1.96426 +  /*
 1.96427 +  ** Added for 3.7.4
 1.96428 +  */
 1.96429 +  sqlite3_backup_finish,
 1.96430 +  sqlite3_backup_init,
 1.96431 +  sqlite3_backup_pagecount,
 1.96432 +  sqlite3_backup_remaining,
 1.96433 +  sqlite3_backup_step,
 1.96434 +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
 1.96435 +  sqlite3_compileoption_get,
 1.96436 +  sqlite3_compileoption_used,
 1.96437 +#else
 1.96438 +  0,
 1.96439 +  0,
 1.96440 +#endif
 1.96441 +  sqlite3_create_function_v2,
 1.96442 +  sqlite3_db_config,
 1.96443 +  sqlite3_db_mutex,
 1.96444 +  sqlite3_db_status,
 1.96445 +  sqlite3_extended_errcode,
 1.96446 +  sqlite3_log,
 1.96447 +  sqlite3_soft_heap_limit64,
 1.96448 +  sqlite3_sourceid,
 1.96449 +  sqlite3_stmt_status,
 1.96450 +  sqlite3_strnicmp,
 1.96451 +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
 1.96452 +  sqlite3_unlock_notify,
 1.96453 +#else
 1.96454 +  0,
 1.96455 +#endif
 1.96456 +#ifndef SQLITE_OMIT_WAL
 1.96457 +  sqlite3_wal_autocheckpoint,
 1.96458 +  sqlite3_wal_checkpoint,
 1.96459 +  sqlite3_wal_hook,
 1.96460 +#else
 1.96461 +  0,
 1.96462 +  0,
 1.96463 +  0,
 1.96464 +#endif
 1.96465 +  sqlite3_blob_reopen,
 1.96466 +  sqlite3_vtab_config,
 1.96467 +  sqlite3_vtab_on_conflict,
 1.96468 +  sqlite3_close_v2,
 1.96469 +  sqlite3_db_filename,
 1.96470 +  sqlite3_db_readonly,
 1.96471 +  sqlite3_db_release_memory,
 1.96472 +  sqlite3_errstr,
 1.96473 +  sqlite3_stmt_busy,
 1.96474 +  sqlite3_stmt_readonly,
 1.96475 +  sqlite3_stricmp,
 1.96476 +  sqlite3_uri_boolean,
 1.96477 +  sqlite3_uri_int64,
 1.96478 +  sqlite3_uri_parameter,
 1.96479 +  sqlite3_vsnprintf,
 1.96480 +  sqlite3_wal_checkpoint_v2
 1.96481 +};
 1.96482 +
 1.96483 +/*
 1.96484 +** Attempt to load an SQLite extension library contained in the file
 1.96485 +** zFile.  The entry point is zProc.  zProc may be 0 in which case a
 1.96486 +** default entry point name (sqlite3_extension_init) is used.  Use
 1.96487 +** of the default name is recommended.
 1.96488 +**
 1.96489 +** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
 1.96490 +**
 1.96491 +** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
 1.96492 +** error message text.  The calling function should free this memory
 1.96493 +** by calling sqlite3DbFree(db, ).
 1.96494 +*/
 1.96495 +static int sqlite3LoadExtension(
 1.96496 +  sqlite3 *db,          /* Load the extension into this database connection */
 1.96497 +  const char *zFile,    /* Name of the shared library containing extension */
 1.96498 +  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
 1.96499 +  char **pzErrMsg       /* Put error message here if not 0 */
 1.96500 +){
 1.96501 +  sqlite3_vfs *pVfs = db->pVfs;
 1.96502 +  void *handle;
 1.96503 +  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
 1.96504 +  char *zErrmsg = 0;
 1.96505 +  const char *zEntry;
 1.96506 +  char *zAltEntry = 0;
 1.96507 +  void **aHandle;
 1.96508 +  int nMsg = 300 + sqlite3Strlen30(zFile);
 1.96509 +  int ii;
 1.96510 +
 1.96511 +  /* Shared library endings to try if zFile cannot be loaded as written */
 1.96512 +  static const char *azEndings[] = {
 1.96513 +#if SQLITE_OS_WIN
 1.96514 +     "dll"   
 1.96515 +#elif defined(__APPLE__)
 1.96516 +     "dylib"
 1.96517 +#else
 1.96518 +     "so"
 1.96519 +#endif
 1.96520 +  };
 1.96521 +
 1.96522 +
 1.96523 +  if( pzErrMsg ) *pzErrMsg = 0;
 1.96524 +
 1.96525 +  /* Ticket #1863.  To avoid a creating security problems for older
 1.96526 +  ** applications that relink against newer versions of SQLite, the
 1.96527 +  ** ability to run load_extension is turned off by default.  One
 1.96528 +  ** must call sqlite3_enable_load_extension() to turn on extension
 1.96529 +  ** loading.  Otherwise you get the following error.
 1.96530 +  */
 1.96531 +  if( (db->flags & SQLITE_LoadExtension)==0 ){
 1.96532 +    if( pzErrMsg ){
 1.96533 +      *pzErrMsg = sqlite3_mprintf("not authorized");
 1.96534 +    }
 1.96535 +    return SQLITE_ERROR;
 1.96536 +  }
 1.96537 +
 1.96538 +  zEntry = zProc ? zProc : "sqlite3_extension_init";
 1.96539 +
 1.96540 +  handle = sqlite3OsDlOpen(pVfs, zFile);
 1.96541 +#if SQLITE_OS_UNIX || SQLITE_OS_WIN
 1.96542 +  for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
 1.96543 +    char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
 1.96544 +    if( zAltFile==0 ) return SQLITE_NOMEM;
 1.96545 +    handle = sqlite3OsDlOpen(pVfs, zAltFile);
 1.96546 +    sqlite3_free(zAltFile);
 1.96547 +  }
 1.96548 +#endif
 1.96549 +  if( handle==0 ){
 1.96550 +    if( pzErrMsg ){
 1.96551 +      *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
 1.96552 +      if( zErrmsg ){
 1.96553 +        sqlite3_snprintf(nMsg, zErrmsg, 
 1.96554 +            "unable to open shared library [%s]", zFile);
 1.96555 +        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
 1.96556 +      }
 1.96557 +    }
 1.96558 +    return SQLITE_ERROR;
 1.96559 +  }
 1.96560 +  xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
 1.96561 +                   sqlite3OsDlSym(pVfs, handle, zEntry);
 1.96562 +
 1.96563 +  /* If no entry point was specified and the default legacy
 1.96564 +  ** entry point name "sqlite3_extension_init" was not found, then
 1.96565 +  ** construct an entry point name "sqlite3_X_init" where the X is
 1.96566 +  ** replaced by the lowercase value of every ASCII alphabetic 
 1.96567 +  ** character in the filename after the last "/" upto the first ".",
 1.96568 +  ** and eliding the first three characters if they are "lib".  
 1.96569 +  ** Examples:
 1.96570 +  **
 1.96571 +  **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
 1.96572 +  **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init
 1.96573 +  */
 1.96574 +  if( xInit==0 && zProc==0 ){
 1.96575 +    int iFile, iEntry, c;
 1.96576 +    int ncFile = sqlite3Strlen30(zFile);
 1.96577 +    zAltEntry = sqlite3_malloc(ncFile+30);
 1.96578 +    if( zAltEntry==0 ){
 1.96579 +      sqlite3OsDlClose(pVfs, handle);
 1.96580 +      return SQLITE_NOMEM;
 1.96581 +    }
 1.96582 +    memcpy(zAltEntry, "sqlite3_", 8);
 1.96583 +    for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
 1.96584 +    iFile++;
 1.96585 +    if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
 1.96586 +    for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
 1.96587 +      if( sqlite3Isalpha(c) ){
 1.96588 +        zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
 1.96589 +      }
 1.96590 +    }
 1.96591 +    memcpy(zAltEntry+iEntry, "_init", 6);
 1.96592 +    zEntry = zAltEntry;
 1.96593 +    xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
 1.96594 +                     sqlite3OsDlSym(pVfs, handle, zEntry);
 1.96595 +  }
 1.96596 +  if( xInit==0 ){
 1.96597 +    if( pzErrMsg ){
 1.96598 +      nMsg += sqlite3Strlen30(zEntry);
 1.96599 +      *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
 1.96600 +      if( zErrmsg ){
 1.96601 +        sqlite3_snprintf(nMsg, zErrmsg,
 1.96602 +            "no entry point [%s] in shared library [%s]", zEntry, zFile);
 1.96603 +        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
 1.96604 +      }
 1.96605 +    }
 1.96606 +    sqlite3OsDlClose(pVfs, handle);
 1.96607 +    sqlite3_free(zAltEntry);
 1.96608 +    return SQLITE_ERROR;
 1.96609 +  }
 1.96610 +  sqlite3_free(zAltEntry);
 1.96611 +  if( xInit(db, &zErrmsg, &sqlite3Apis) ){
 1.96612 +    if( pzErrMsg ){
 1.96613 +      *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
 1.96614 +    }
 1.96615 +    sqlite3_free(zErrmsg);
 1.96616 +    sqlite3OsDlClose(pVfs, handle);
 1.96617 +    return SQLITE_ERROR;
 1.96618 +  }
 1.96619 +
 1.96620 +  /* Append the new shared library handle to the db->aExtension array. */
 1.96621 +  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
 1.96622 +  if( aHandle==0 ){
 1.96623 +    return SQLITE_NOMEM;
 1.96624 +  }
 1.96625 +  if( db->nExtension>0 ){
 1.96626 +    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
 1.96627 +  }
 1.96628 +  sqlite3DbFree(db, db->aExtension);
 1.96629 +  db->aExtension = aHandle;
 1.96630 +
 1.96631 +  db->aExtension[db->nExtension++] = handle;
 1.96632 +  return SQLITE_OK;
 1.96633 +}
 1.96634 +SQLITE_API int sqlite3_load_extension(
 1.96635 +  sqlite3 *db,          /* Load the extension into this database connection */
 1.96636 +  const char *zFile,    /* Name of the shared library containing extension */
 1.96637 +  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
 1.96638 +  char **pzErrMsg       /* Put error message here if not 0 */
 1.96639 +){
 1.96640 +  int rc;
 1.96641 +  sqlite3_mutex_enter(db->mutex);
 1.96642 +  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
 1.96643 +  rc = sqlite3ApiExit(db, rc);
 1.96644 +  sqlite3_mutex_leave(db->mutex);
 1.96645 +  return rc;
 1.96646 +}
 1.96647 +
 1.96648 +/*
 1.96649 +** Call this routine when the database connection is closing in order
 1.96650 +** to clean up loaded extensions
 1.96651 +*/
 1.96652 +SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
 1.96653 +  int i;
 1.96654 +  assert( sqlite3_mutex_held(db->mutex) );
 1.96655 +  for(i=0; i<db->nExtension; i++){
 1.96656 +    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
 1.96657 +  }
 1.96658 +  sqlite3DbFree(db, db->aExtension);
 1.96659 +}
 1.96660 +
 1.96661 +/*
 1.96662 +** Enable or disable extension loading.  Extension loading is disabled by
 1.96663 +** default so as not to open security holes in older applications.
 1.96664 +*/
 1.96665 +SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
 1.96666 +  sqlite3_mutex_enter(db->mutex);
 1.96667 +  if( onoff ){
 1.96668 +    db->flags |= SQLITE_LoadExtension;
 1.96669 +  }else{
 1.96670 +    db->flags &= ~SQLITE_LoadExtension;
 1.96671 +  }
 1.96672 +  sqlite3_mutex_leave(db->mutex);
 1.96673 +  return SQLITE_OK;
 1.96674 +}
 1.96675 +
 1.96676 +#endif /* SQLITE_OMIT_LOAD_EXTENSION */
 1.96677 +
 1.96678 +/*
 1.96679 +** The auto-extension code added regardless of whether or not extension
 1.96680 +** loading is supported.  We need a dummy sqlite3Apis pointer for that
 1.96681 +** code if regular extension loading is not available.  This is that
 1.96682 +** dummy pointer.
 1.96683 +*/
 1.96684 +#ifdef SQLITE_OMIT_LOAD_EXTENSION
 1.96685 +static const sqlite3_api_routines sqlite3Apis = { 0 };
 1.96686 +#endif
 1.96687 +
 1.96688 +
 1.96689 +/*
 1.96690 +** The following object holds the list of automatically loaded
 1.96691 +** extensions.
 1.96692 +**
 1.96693 +** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
 1.96694 +** mutex must be held while accessing this list.
 1.96695 +*/
 1.96696 +typedef struct sqlite3AutoExtList sqlite3AutoExtList;
 1.96697 +static SQLITE_WSD struct sqlite3AutoExtList {
 1.96698 +  int nExt;              /* Number of entries in aExt[] */          
 1.96699 +  void (**aExt)(void);   /* Pointers to the extension init functions */
 1.96700 +} sqlite3Autoext = { 0, 0 };
 1.96701 +
 1.96702 +/* The "wsdAutoext" macro will resolve to the autoextension
 1.96703 +** state vector.  If writable static data is unsupported on the target,
 1.96704 +** we have to locate the state vector at run-time.  In the more common
 1.96705 +** case where writable static data is supported, wsdStat can refer directly
 1.96706 +** to the "sqlite3Autoext" state vector declared above.
 1.96707 +*/
 1.96708 +#ifdef SQLITE_OMIT_WSD
 1.96709 +# define wsdAutoextInit \
 1.96710 +  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
 1.96711 +# define wsdAutoext x[0]
 1.96712 +#else
 1.96713 +# define wsdAutoextInit
 1.96714 +# define wsdAutoext sqlite3Autoext
 1.96715 +#endif
 1.96716 +
 1.96717 +
 1.96718 +/*
 1.96719 +** Register a statically linked extension that is automatically
 1.96720 +** loaded by every new database connection.
 1.96721 +*/
 1.96722 +SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
 1.96723 +  int rc = SQLITE_OK;
 1.96724 +#ifndef SQLITE_OMIT_AUTOINIT
 1.96725 +  rc = sqlite3_initialize();
 1.96726 +  if( rc ){
 1.96727 +    return rc;
 1.96728 +  }else
 1.96729 +#endif
 1.96730 +  {
 1.96731 +    int i;
 1.96732 +#if SQLITE_THREADSAFE
 1.96733 +    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
 1.96734 +#endif
 1.96735 +    wsdAutoextInit;
 1.96736 +    sqlite3_mutex_enter(mutex);
 1.96737 +    for(i=0; i<wsdAutoext.nExt; i++){
 1.96738 +      if( wsdAutoext.aExt[i]==xInit ) break;
 1.96739 +    }
 1.96740 +    if( i==wsdAutoext.nExt ){
 1.96741 +      int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
 1.96742 +      void (**aNew)(void);
 1.96743 +      aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
 1.96744 +      if( aNew==0 ){
 1.96745 +        rc = SQLITE_NOMEM;
 1.96746 +      }else{
 1.96747 +        wsdAutoext.aExt = aNew;
 1.96748 +        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
 1.96749 +        wsdAutoext.nExt++;
 1.96750 +      }
 1.96751 +    }
 1.96752 +    sqlite3_mutex_leave(mutex);
 1.96753 +    assert( (rc&0xff)==rc );
 1.96754 +    return rc;
 1.96755 +  }
 1.96756 +}
 1.96757 +
 1.96758 +/*
 1.96759 +** Cancel a prior call to sqlite3_auto_extension.  Remove xInit from the
 1.96760 +** set of routines that is invoked for each new database connection, if it
 1.96761 +** is currently on the list.  If xInit is not on the list, then this
 1.96762 +** routine is a no-op.
 1.96763 +**
 1.96764 +** Return 1 if xInit was found on the list and removed.  Return 0 if xInit
 1.96765 +** was not on the list.
 1.96766 +*/
 1.96767 +SQLITE_API int sqlite3_cancel_auto_extension(void (*xInit)(void)){
 1.96768 +#if SQLITE_THREADSAFE
 1.96769 +  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
 1.96770 +#endif
 1.96771 +  int i;
 1.96772 +  int n = 0;
 1.96773 +  wsdAutoextInit;
 1.96774 +  sqlite3_mutex_enter(mutex);
 1.96775 +  for(i=wsdAutoext.nExt-1; i>=0; i--){
 1.96776 +    if( wsdAutoext.aExt[i]==xInit ){
 1.96777 +      wsdAutoext.nExt--;
 1.96778 +      wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
 1.96779 +      n++;
 1.96780 +      break;
 1.96781 +    }
 1.96782 +  }
 1.96783 +  sqlite3_mutex_leave(mutex);
 1.96784 +  return n;
 1.96785 +}
 1.96786 +
 1.96787 +/*
 1.96788 +** Reset the automatic extension loading mechanism.
 1.96789 +*/
 1.96790 +SQLITE_API void sqlite3_reset_auto_extension(void){
 1.96791 +#ifndef SQLITE_OMIT_AUTOINIT
 1.96792 +  if( sqlite3_initialize()==SQLITE_OK )
 1.96793 +#endif
 1.96794 +  {
 1.96795 +#if SQLITE_THREADSAFE
 1.96796 +    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
 1.96797 +#endif
 1.96798 +    wsdAutoextInit;
 1.96799 +    sqlite3_mutex_enter(mutex);
 1.96800 +    sqlite3_free(wsdAutoext.aExt);
 1.96801 +    wsdAutoext.aExt = 0;
 1.96802 +    wsdAutoext.nExt = 0;
 1.96803 +    sqlite3_mutex_leave(mutex);
 1.96804 +  }
 1.96805 +}
 1.96806 +
 1.96807 +/*
 1.96808 +** Load all automatic extensions.
 1.96809 +**
 1.96810 +** If anything goes wrong, set an error in the database connection.
 1.96811 +*/
 1.96812 +SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
 1.96813 +  int i;
 1.96814 +  int go = 1;
 1.96815 +  int rc;
 1.96816 +  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
 1.96817 +
 1.96818 +  wsdAutoextInit;
 1.96819 +  if( wsdAutoext.nExt==0 ){
 1.96820 +    /* Common case: early out without every having to acquire a mutex */
 1.96821 +    return;
 1.96822 +  }
 1.96823 +  for(i=0; go; i++){
 1.96824 +    char *zErrmsg;
 1.96825 +#if SQLITE_THREADSAFE
 1.96826 +    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
 1.96827 +#endif
 1.96828 +    sqlite3_mutex_enter(mutex);
 1.96829 +    if( i>=wsdAutoext.nExt ){
 1.96830 +      xInit = 0;
 1.96831 +      go = 0;
 1.96832 +    }else{
 1.96833 +      xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
 1.96834 +              wsdAutoext.aExt[i];
 1.96835 +    }
 1.96836 +    sqlite3_mutex_leave(mutex);
 1.96837 +    zErrmsg = 0;
 1.96838 +    if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
 1.96839 +      sqlite3Error(db, rc,
 1.96840 +            "automatic extension loading failed: %s", zErrmsg);
 1.96841 +      go = 0;
 1.96842 +    }
 1.96843 +    sqlite3_free(zErrmsg);
 1.96844 +  }
 1.96845 +}
 1.96846 +
 1.96847 +/************** End of loadext.c *********************************************/
 1.96848 +/************** Begin file pragma.c ******************************************/
 1.96849 +/*
 1.96850 +** 2003 April 6
 1.96851 +**
 1.96852 +** The author disclaims copyright to this source code.  In place of
 1.96853 +** a legal notice, here is a blessing:
 1.96854 +**
 1.96855 +**    May you do good and not evil.
 1.96856 +**    May you find forgiveness for yourself and forgive others.
 1.96857 +**    May you share freely, never taking more than you give.
 1.96858 +**
 1.96859 +*************************************************************************
 1.96860 +** This file contains code used to implement the PRAGMA command.
 1.96861 +*/
 1.96862 +
 1.96863 +#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
 1.96864 +#  if defined(__APPLE__)
 1.96865 +#    define SQLITE_ENABLE_LOCKING_STYLE 1
 1.96866 +#  else
 1.96867 +#    define SQLITE_ENABLE_LOCKING_STYLE 0
 1.96868 +#  endif
 1.96869 +#endif
 1.96870 +
 1.96871 +/***************************************************************************
 1.96872 +** The next block of code, including the PragTyp_XXXX macro definitions and
 1.96873 +** the aPragmaName[] object is composed of generated code. DO NOT EDIT.
 1.96874 +**
 1.96875 +** To add new pragmas, edit the code in ../tool/mkpragmatab.tcl and rerun
 1.96876 +** that script.  Then copy/paste the output in place of the following:
 1.96877 +*/
 1.96878 +#define PragTyp_HEADER_VALUE                   0
 1.96879 +#define PragTyp_AUTO_VACUUM                    1
 1.96880 +#define PragTyp_FLAG                           2
 1.96881 +#define PragTyp_BUSY_TIMEOUT                   3
 1.96882 +#define PragTyp_CACHE_SIZE                     4
 1.96883 +#define PragTyp_CASE_SENSITIVE_LIKE            5
 1.96884 +#define PragTyp_COLLATION_LIST                 6
 1.96885 +#define PragTyp_COMPILE_OPTIONS                7
 1.96886 +#define PragTyp_DATA_STORE_DIRECTORY           8
 1.96887 +#define PragTyp_DATABASE_LIST                  9
 1.96888 +#define PragTyp_DEFAULT_CACHE_SIZE            10
 1.96889 +#define PragTyp_ENCODING                      11
 1.96890 +#define PragTyp_FOREIGN_KEY_CHECK             12
 1.96891 +#define PragTyp_FOREIGN_KEY_LIST              13
 1.96892 +#define PragTyp_INCREMENTAL_VACUUM            14
 1.96893 +#define PragTyp_INDEX_INFO                    15
 1.96894 +#define PragTyp_INDEX_LIST                    16
 1.96895 +#define PragTyp_INTEGRITY_CHECK               17
 1.96896 +#define PragTyp_JOURNAL_MODE                  18
 1.96897 +#define PragTyp_JOURNAL_SIZE_LIMIT            19
 1.96898 +#define PragTyp_LOCK_PROXY_FILE               20
 1.96899 +#define PragTyp_LOCKING_MODE                  21
 1.96900 +#define PragTyp_PAGE_COUNT                    22
 1.96901 +#define PragTyp_MMAP_SIZE                     23
 1.96902 +#define PragTyp_PAGE_SIZE                     24
 1.96903 +#define PragTyp_SECURE_DELETE                 25
 1.96904 +#define PragTyp_SHRINK_MEMORY                 26
 1.96905 +#define PragTyp_SOFT_HEAP_LIMIT               27
 1.96906 +#define PragTyp_STATS                         28
 1.96907 +#define PragTyp_SYNCHRONOUS                   29
 1.96908 +#define PragTyp_TABLE_INFO                    30
 1.96909 +#define PragTyp_TEMP_STORE                    31
 1.96910 +#define PragTyp_TEMP_STORE_DIRECTORY          32
 1.96911 +#define PragTyp_WAL_AUTOCHECKPOINT            33
 1.96912 +#define PragTyp_WAL_CHECKPOINT                34
 1.96913 +#define PragTyp_ACTIVATE_EXTENSIONS           35
 1.96914 +#define PragTyp_HEXKEY                        36
 1.96915 +#define PragTyp_KEY                           37
 1.96916 +#define PragTyp_REKEY                         38
 1.96917 +#define PragTyp_LOCK_STATUS                   39
 1.96918 +#define PragTyp_PARSER_TRACE                  40
 1.96919 +#define PragFlag_NeedSchema           0x01
 1.96920 +static const struct sPragmaNames {
 1.96921 +  const char *const zName;  /* Name of pragma */
 1.96922 +  u8 ePragTyp;              /* PragTyp_XXX value */
 1.96923 +  u8 mPragFlag;             /* Zero or more PragFlag_XXX values */
 1.96924 +  u32 iArg;                 /* Extra argument */
 1.96925 +} aPragmaNames[] = {
 1.96926 +#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
 1.96927 +  { /* zName:     */ "activate_extensions",
 1.96928 +    /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
 1.96929 +    /* ePragFlag: */ 0,
 1.96930 +    /* iArg:      */ 0 },
 1.96931 +#endif
 1.96932 +#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
 1.96933 +  { /* zName:     */ "application_id",
 1.96934 +    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
 1.96935 +    /* ePragFlag: */ 0,
 1.96936 +    /* iArg:      */ 0 },
 1.96937 +#endif
 1.96938 +#if !defined(SQLITE_OMIT_AUTOVACUUM)
 1.96939 +  { /* zName:     */ "auto_vacuum",
 1.96940 +    /* ePragTyp:  */ PragTyp_AUTO_VACUUM,
 1.96941 +    /* ePragFlag: */ PragFlag_NeedSchema,
 1.96942 +    /* iArg:      */ 0 },
 1.96943 +#endif
 1.96944 +#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
 1.96945 +#if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
 1.96946 +  { /* zName:     */ "automatic_index",
 1.96947 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.96948 +    /* ePragFlag: */ 0,
 1.96949 +    /* iArg:      */ SQLITE_AutoIndex },
 1.96950 +#endif
 1.96951 +#endif
 1.96952 +  { /* zName:     */ "busy_timeout",
 1.96953 +    /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
 1.96954 +    /* ePragFlag: */ 0,
 1.96955 +    /* iArg:      */ 0 },
 1.96956 +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
 1.96957 +  { /* zName:     */ "cache_size",
 1.96958 +    /* ePragTyp:  */ PragTyp_CACHE_SIZE,
 1.96959 +    /* ePragFlag: */ PragFlag_NeedSchema,
 1.96960 +    /* iArg:      */ 0 },
 1.96961 +#endif
 1.96962 +#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
 1.96963 +  { /* zName:     */ "cache_spill",
 1.96964 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.96965 +    /* ePragFlag: */ 0,
 1.96966 +    /* iArg:      */ SQLITE_CacheSpill },
 1.96967 +#endif
 1.96968 +  { /* zName:     */ "case_sensitive_like",
 1.96969 +    /* ePragTyp:  */ PragTyp_CASE_SENSITIVE_LIKE,
 1.96970 +    /* ePragFlag: */ 0,
 1.96971 +    /* iArg:      */ 0 },
 1.96972 +#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
 1.96973 +  { /* zName:     */ "checkpoint_fullfsync",
 1.96974 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.96975 +    /* ePragFlag: */ 0,
 1.96976 +    /* iArg:      */ SQLITE_CkptFullFSync },
 1.96977 +#endif
 1.96978 +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
 1.96979 +  { /* zName:     */ "collation_list",
 1.96980 +    /* ePragTyp:  */ PragTyp_COLLATION_LIST,
 1.96981 +    /* ePragFlag: */ 0,
 1.96982 +    /* iArg:      */ 0 },
 1.96983 +#endif
 1.96984 +#if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
 1.96985 +  { /* zName:     */ "compile_options",
 1.96986 +    /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,
 1.96987 +    /* ePragFlag: */ 0,
 1.96988 +    /* iArg:      */ 0 },
 1.96989 +#endif
 1.96990 +#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
 1.96991 +  { /* zName:     */ "count_changes",
 1.96992 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.96993 +    /* ePragFlag: */ 0,
 1.96994 +    /* iArg:      */ SQLITE_CountRows },
 1.96995 +#endif
 1.96996 +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
 1.96997 +  { /* zName:     */ "data_store_directory",
 1.96998 +    /* ePragTyp:  */ PragTyp_DATA_STORE_DIRECTORY,
 1.96999 +    /* ePragFlag: */ 0,
 1.97000 +    /* iArg:      */ 0 },
 1.97001 +#endif
 1.97002 +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
 1.97003 +  { /* zName:     */ "database_list",
 1.97004 +    /* ePragTyp:  */ PragTyp_DATABASE_LIST,
 1.97005 +    /* ePragFlag: */ PragFlag_NeedSchema,
 1.97006 +    /* iArg:      */ 0 },
 1.97007 +#endif
 1.97008 +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
 1.97009 +  { /* zName:     */ "default_cache_size",
 1.97010 +    /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
 1.97011 +    /* ePragFlag: */ PragFlag_NeedSchema,
 1.97012 +    /* iArg:      */ 0 },
 1.97013 +#endif
 1.97014 +#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
 1.97015 +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
 1.97016 +  { /* zName:     */ "defer_foreign_keys",
 1.97017 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.97018 +    /* ePragFlag: */ 0,
 1.97019 +    /* iArg:      */ SQLITE_DeferFKs },
 1.97020 +#endif
 1.97021 +#endif
 1.97022 +#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
 1.97023 +  { /* zName:     */ "empty_result_callbacks",
 1.97024 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.97025 +    /* ePragFlag: */ 0,
 1.97026 +    /* iArg:      */ SQLITE_NullCallback },
 1.97027 +#endif
 1.97028 +#if !defined(SQLITE_OMIT_UTF16)
 1.97029 +  { /* zName:     */ "encoding",
 1.97030 +    /* ePragTyp:  */ PragTyp_ENCODING,
 1.97031 +    /* ePragFlag: */ 0,
 1.97032 +    /* iArg:      */ 0 },
 1.97033 +#endif
 1.97034 +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
 1.97035 +  { /* zName:     */ "foreign_key_check",
 1.97036 +    /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
 1.97037 +    /* ePragFlag: */ PragFlag_NeedSchema,
 1.97038 +    /* iArg:      */ 0 },
 1.97039 +#endif
 1.97040 +#if !defined(SQLITE_OMIT_FOREIGN_KEY)
 1.97041 +  { /* zName:     */ "foreign_key_list",
 1.97042 +    /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,
 1.97043 +    /* ePragFlag: */ PragFlag_NeedSchema,
 1.97044 +    /* iArg:      */ 0 },
 1.97045 +#endif
 1.97046 +#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
 1.97047 +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
 1.97048 +  { /* zName:     */ "foreign_keys",
 1.97049 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.97050 +    /* ePragFlag: */ 0,
 1.97051 +    /* iArg:      */ SQLITE_ForeignKeys },
 1.97052 +#endif
 1.97053 +#endif
 1.97054 +#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
 1.97055 +  { /* zName:     */ "freelist_count",
 1.97056 +    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
 1.97057 +    /* ePragFlag: */ 0,
 1.97058 +    /* iArg:      */ 0 },
 1.97059 +#endif
 1.97060 +#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
 1.97061 +  { /* zName:     */ "full_column_names",
 1.97062 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.97063 +    /* ePragFlag: */ 0,
 1.97064 +    /* iArg:      */ SQLITE_FullColNames },
 1.97065 +  { /* zName:     */ "fullfsync",
 1.97066 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.97067 +    /* ePragFlag: */ 0,
 1.97068 +    /* iArg:      */ SQLITE_FullFSync },
 1.97069 +#endif
 1.97070 +#if defined(SQLITE_HAS_CODEC)
 1.97071 +  { /* zName:     */ "hexkey",
 1.97072 +    /* ePragTyp:  */ PragTyp_HEXKEY,
 1.97073 +    /* ePragFlag: */ 0,
 1.97074 +    /* iArg:      */ 0 },
 1.97075 +  { /* zName:     */ "hexrekey",
 1.97076 +    /* ePragTyp:  */ PragTyp_HEXKEY,
 1.97077 +    /* ePragFlag: */ 0,
 1.97078 +    /* iArg:      */ 0 },
 1.97079 +#endif
 1.97080 +#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
 1.97081 +#if !defined(SQLITE_OMIT_CHECK)
 1.97082 +  { /* zName:     */ "ignore_check_constraints",
 1.97083 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.97084 +    /* ePragFlag: */ 0,
 1.97085 +    /* iArg:      */ SQLITE_IgnoreChecks },
 1.97086 +#endif
 1.97087 +#endif
 1.97088 +#if !defined(SQLITE_OMIT_AUTOVACUUM)
 1.97089 +  { /* zName:     */ "incremental_vacuum",
 1.97090 +    /* ePragTyp:  */ PragTyp_INCREMENTAL_VACUUM,
 1.97091 +    /* ePragFlag: */ PragFlag_NeedSchema,
 1.97092 +    /* iArg:      */ 0 },
 1.97093 +#endif
 1.97094 +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
 1.97095 +  { /* zName:     */ "index_info",
 1.97096 +    /* ePragTyp:  */ PragTyp_INDEX_INFO,
 1.97097 +    /* ePragFlag: */ PragFlag_NeedSchema,
 1.97098 +    /* iArg:      */ 0 },
 1.97099 +  { /* zName:     */ "index_list",
 1.97100 +    /* ePragTyp:  */ PragTyp_INDEX_LIST,
 1.97101 +    /* ePragFlag: */ PragFlag_NeedSchema,
 1.97102 +    /* iArg:      */ 0 },
 1.97103 +#endif
 1.97104 +#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
 1.97105 +  { /* zName:     */ "integrity_check",
 1.97106 +    /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
 1.97107 +    /* ePragFlag: */ PragFlag_NeedSchema,
 1.97108 +    /* iArg:      */ 0 },
 1.97109 +#endif
 1.97110 +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
 1.97111 +  { /* zName:     */ "journal_mode",
 1.97112 +    /* ePragTyp:  */ PragTyp_JOURNAL_MODE,
 1.97113 +    /* ePragFlag: */ PragFlag_NeedSchema,
 1.97114 +    /* iArg:      */ 0 },
 1.97115 +  { /* zName:     */ "journal_size_limit",
 1.97116 +    /* ePragTyp:  */ PragTyp_JOURNAL_SIZE_LIMIT,
 1.97117 +    /* ePragFlag: */ 0,
 1.97118 +    /* iArg:      */ 0 },
 1.97119 +#endif
 1.97120 +#if defined(SQLITE_HAS_CODEC)
 1.97121 +  { /* zName:     */ "key",
 1.97122 +    /* ePragTyp:  */ PragTyp_KEY,
 1.97123 +    /* ePragFlag: */ 0,
 1.97124 +    /* iArg:      */ 0 },
 1.97125 +#endif
 1.97126 +#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
 1.97127 +  { /* zName:     */ "legacy_file_format",
 1.97128 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.97129 +    /* ePragFlag: */ 0,
 1.97130 +    /* iArg:      */ SQLITE_LegacyFileFmt },
 1.97131 +#endif
 1.97132 +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
 1.97133 +  { /* zName:     */ "lock_proxy_file",
 1.97134 +    /* ePragTyp:  */ PragTyp_LOCK_PROXY_FILE,
 1.97135 +    /* ePragFlag: */ 0,
 1.97136 +    /* iArg:      */ 0 },
 1.97137 +#endif
 1.97138 +#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
 1.97139 +  { /* zName:     */ "lock_status",
 1.97140 +    /* ePragTyp:  */ PragTyp_LOCK_STATUS,
 1.97141 +    /* ePragFlag: */ 0,
 1.97142 +    /* iArg:      */ 0 },
 1.97143 +#endif
 1.97144 +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
 1.97145 +  { /* zName:     */ "locking_mode",
 1.97146 +    /* ePragTyp:  */ PragTyp_LOCKING_MODE,
 1.97147 +    /* ePragFlag: */ 0,
 1.97148 +    /* iArg:      */ 0 },
 1.97149 +  { /* zName:     */ "max_page_count",
 1.97150 +    /* ePragTyp:  */ PragTyp_PAGE_COUNT,
 1.97151 +    /* ePragFlag: */ PragFlag_NeedSchema,
 1.97152 +    /* iArg:      */ 0 },
 1.97153 +  { /* zName:     */ "mmap_size",
 1.97154 +    /* ePragTyp:  */ PragTyp_MMAP_SIZE,
 1.97155 +    /* ePragFlag: */ 0,
 1.97156 +    /* iArg:      */ 0 },
 1.97157 +  { /* zName:     */ "page_count",
 1.97158 +    /* ePragTyp:  */ PragTyp_PAGE_COUNT,
 1.97159 +    /* ePragFlag: */ PragFlag_NeedSchema,
 1.97160 +    /* iArg:      */ 0 },
 1.97161 +  { /* zName:     */ "page_size",
 1.97162 +    /* ePragTyp:  */ PragTyp_PAGE_SIZE,
 1.97163 +    /* ePragFlag: */ 0,
 1.97164 +    /* iArg:      */ 0 },
 1.97165 +#endif
 1.97166 +#if defined(SQLITE_DEBUG)
 1.97167 +  { /* zName:     */ "parser_trace",
 1.97168 +    /* ePragTyp:  */ PragTyp_PARSER_TRACE,
 1.97169 +    /* ePragFlag: */ 0,
 1.97170 +    /* iArg:      */ 0 },
 1.97171 +#endif
 1.97172 +#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
 1.97173 +  { /* zName:     */ "query_only",
 1.97174 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.97175 +    /* ePragFlag: */ 0,
 1.97176 +    /* iArg:      */ SQLITE_QueryOnly },
 1.97177 +#endif
 1.97178 +#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
 1.97179 +  { /* zName:     */ "quick_check",
 1.97180 +    /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
 1.97181 +    /* ePragFlag: */ PragFlag_NeedSchema,
 1.97182 +    /* iArg:      */ 0 },
 1.97183 +#endif
 1.97184 +#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
 1.97185 +  { /* zName:     */ "read_uncommitted",
 1.97186 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.97187 +    /* ePragFlag: */ 0,
 1.97188 +    /* iArg:      */ SQLITE_ReadUncommitted },
 1.97189 +  { /* zName:     */ "recursive_triggers",
 1.97190 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.97191 +    /* ePragFlag: */ 0,
 1.97192 +    /* iArg:      */ SQLITE_RecTriggers },
 1.97193 +#endif
 1.97194 +#if defined(SQLITE_HAS_CODEC)
 1.97195 +  { /* zName:     */ "rekey",
 1.97196 +    /* ePragTyp:  */ PragTyp_REKEY,
 1.97197 +    /* ePragFlag: */ 0,
 1.97198 +    /* iArg:      */ 0 },
 1.97199 +#endif
 1.97200 +#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
 1.97201 +  { /* zName:     */ "reverse_unordered_selects",
 1.97202 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.97203 +    /* ePragFlag: */ 0,
 1.97204 +    /* iArg:      */ SQLITE_ReverseOrder },
 1.97205 +#endif
 1.97206 +#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
 1.97207 +  { /* zName:     */ "schema_version",
 1.97208 +    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
 1.97209 +    /* ePragFlag: */ 0,
 1.97210 +    /* iArg:      */ 0 },
 1.97211 +#endif
 1.97212 +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
 1.97213 +  { /* zName:     */ "secure_delete",
 1.97214 +    /* ePragTyp:  */ PragTyp_SECURE_DELETE,
 1.97215 +    /* ePragFlag: */ 0,
 1.97216 +    /* iArg:      */ 0 },
 1.97217 +#endif
 1.97218 +#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
 1.97219 +  { /* zName:     */ "short_column_names",
 1.97220 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.97221 +    /* ePragFlag: */ 0,
 1.97222 +    /* iArg:      */ SQLITE_ShortColNames },
 1.97223 +#endif
 1.97224 +  { /* zName:     */ "shrink_memory",
 1.97225 +    /* ePragTyp:  */ PragTyp_SHRINK_MEMORY,
 1.97226 +    /* ePragFlag: */ 0,
 1.97227 +    /* iArg:      */ 0 },
 1.97228 +  { /* zName:     */ "soft_heap_limit",
 1.97229 +    /* ePragTyp:  */ PragTyp_SOFT_HEAP_LIMIT,
 1.97230 +    /* ePragFlag: */ 0,
 1.97231 +    /* iArg:      */ 0 },
 1.97232 +#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
 1.97233 +#if defined(SQLITE_DEBUG)
 1.97234 +  { /* zName:     */ "sql_trace",
 1.97235 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.97236 +    /* ePragFlag: */ 0,
 1.97237 +    /* iArg:      */ SQLITE_SqlTrace },
 1.97238 +#endif
 1.97239 +#endif
 1.97240 +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
 1.97241 +  { /* zName:     */ "stats",
 1.97242 +    /* ePragTyp:  */ PragTyp_STATS,
 1.97243 +    /* ePragFlag: */ PragFlag_NeedSchema,
 1.97244 +    /* iArg:      */ 0 },
 1.97245 +#endif
 1.97246 +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
 1.97247 +  { /* zName:     */ "synchronous",
 1.97248 +    /* ePragTyp:  */ PragTyp_SYNCHRONOUS,
 1.97249 +    /* ePragFlag: */ PragFlag_NeedSchema,
 1.97250 +    /* iArg:      */ 0 },
 1.97251 +#endif
 1.97252 +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
 1.97253 +  { /* zName:     */ "table_info",
 1.97254 +    /* ePragTyp:  */ PragTyp_TABLE_INFO,
 1.97255 +    /* ePragFlag: */ PragFlag_NeedSchema,
 1.97256 +    /* iArg:      */ 0 },
 1.97257 +#endif
 1.97258 +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
 1.97259 +  { /* zName:     */ "temp_store",
 1.97260 +    /* ePragTyp:  */ PragTyp_TEMP_STORE,
 1.97261 +    /* ePragFlag: */ 0,
 1.97262 +    /* iArg:      */ 0 },
 1.97263 +  { /* zName:     */ "temp_store_directory",
 1.97264 +    /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,
 1.97265 +    /* ePragFlag: */ 0,
 1.97266 +    /* iArg:      */ 0 },
 1.97267 +#endif
 1.97268 +#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
 1.97269 +  { /* zName:     */ "user_version",
 1.97270 +    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
 1.97271 +    /* ePragFlag: */ 0,
 1.97272 +    /* iArg:      */ 0 },
 1.97273 +#endif
 1.97274 +#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
 1.97275 +#if defined(SQLITE_DEBUG)
 1.97276 +  { /* zName:     */ "vdbe_addoptrace",
 1.97277 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.97278 +    /* ePragFlag: */ 0,
 1.97279 +    /* iArg:      */ SQLITE_VdbeAddopTrace },
 1.97280 +  { /* zName:     */ "vdbe_debug",
 1.97281 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.97282 +    /* ePragFlag: */ 0,
 1.97283 +    /* iArg:      */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
 1.97284 +  { /* zName:     */ "vdbe_eqp",
 1.97285 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.97286 +    /* ePragFlag: */ 0,
 1.97287 +    /* iArg:      */ SQLITE_VdbeEQP },
 1.97288 +  { /* zName:     */ "vdbe_listing",
 1.97289 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.97290 +    /* ePragFlag: */ 0,
 1.97291 +    /* iArg:      */ SQLITE_VdbeListing },
 1.97292 +  { /* zName:     */ "vdbe_trace",
 1.97293 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.97294 +    /* ePragFlag: */ 0,
 1.97295 +    /* iArg:      */ SQLITE_VdbeTrace },
 1.97296 +#endif
 1.97297 +#endif
 1.97298 +#if !defined(SQLITE_OMIT_WAL)
 1.97299 +  { /* zName:     */ "wal_autocheckpoint",
 1.97300 +    /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,
 1.97301 +    /* ePragFlag: */ 0,
 1.97302 +    /* iArg:      */ 0 },
 1.97303 +  { /* zName:     */ "wal_checkpoint",
 1.97304 +    /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
 1.97305 +    /* ePragFlag: */ PragFlag_NeedSchema,
 1.97306 +    /* iArg:      */ 0 },
 1.97307 +#endif
 1.97308 +#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
 1.97309 +  { /* zName:     */ "writable_schema",
 1.97310 +    /* ePragTyp:  */ PragTyp_FLAG,
 1.97311 +    /* ePragFlag: */ 0,
 1.97312 +    /* iArg:      */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
 1.97313 +#endif
 1.97314 +};
 1.97315 +/* Number of pragmas: 56 on by default, 69 total. */
 1.97316 +/* End of the automatically generated pragma table.
 1.97317 +***************************************************************************/
 1.97318 +
 1.97319 +/*
 1.97320 +** Interpret the given string as a safety level.  Return 0 for OFF,
 1.97321 +** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
 1.97322 +** unrecognized string argument.  The FULL option is disallowed
 1.97323 +** if the omitFull parameter it 1.
 1.97324 +**
 1.97325 +** Note that the values returned are one less that the values that
 1.97326 +** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
 1.97327 +** to support legacy SQL code.  The safety level used to be boolean
 1.97328 +** and older scripts may have used numbers 0 for OFF and 1 for ON.
 1.97329 +*/
 1.97330 +static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
 1.97331 +                             /* 123456789 123456789 */
 1.97332 +  static const char zText[] = "onoffalseyestruefull";
 1.97333 +  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
 1.97334 +  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
 1.97335 +  static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
 1.97336 +  int i, n;
 1.97337 +  if( sqlite3Isdigit(*z) ){
 1.97338 +    return (u8)sqlite3Atoi(z);
 1.97339 +  }
 1.97340 +  n = sqlite3Strlen30(z);
 1.97341 +  for(i=0; i<ArraySize(iLength)-omitFull; i++){
 1.97342 +    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
 1.97343 +      return iValue[i];
 1.97344 +    }
 1.97345 +  }
 1.97346 +  return dflt;
 1.97347 +}
 1.97348 +
 1.97349 +/*
 1.97350 +** Interpret the given string as a boolean value.
 1.97351 +*/
 1.97352 +SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
 1.97353 +  return getSafetyLevel(z,1,dflt)!=0;
 1.97354 +}
 1.97355 +
 1.97356 +/* The sqlite3GetBoolean() function is used by other modules but the
 1.97357 +** remainder of this file is specific to PRAGMA processing.  So omit
 1.97358 +** the rest of the file if PRAGMAs are omitted from the build.
 1.97359 +*/
 1.97360 +#if !defined(SQLITE_OMIT_PRAGMA)
 1.97361 +
 1.97362 +/*
 1.97363 +** Interpret the given string as a locking mode value.
 1.97364 +*/
 1.97365 +static int getLockingMode(const char *z){
 1.97366 +  if( z ){
 1.97367 +    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
 1.97368 +    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
 1.97369 +  }
 1.97370 +  return PAGER_LOCKINGMODE_QUERY;
 1.97371 +}
 1.97372 +
 1.97373 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.97374 +/*
 1.97375 +** Interpret the given string as an auto-vacuum mode value.
 1.97376 +**
 1.97377 +** The following strings, "none", "full" and "incremental" are 
 1.97378 +** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
 1.97379 +*/
 1.97380 +static int getAutoVacuum(const char *z){
 1.97381 +  int i;
 1.97382 +  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
 1.97383 +  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
 1.97384 +  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
 1.97385 +  i = sqlite3Atoi(z);
 1.97386 +  return (u8)((i>=0&&i<=2)?i:0);
 1.97387 +}
 1.97388 +#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
 1.97389 +
 1.97390 +#ifndef SQLITE_OMIT_PAGER_PRAGMAS
 1.97391 +/*
 1.97392 +** Interpret the given string as a temp db location. Return 1 for file
 1.97393 +** backed temporary databases, 2 for the Red-Black tree in memory database
 1.97394 +** and 0 to use the compile-time default.
 1.97395 +*/
 1.97396 +static int getTempStore(const char *z){
 1.97397 +  if( z[0]>='0' && z[0]<='2' ){
 1.97398 +    return z[0] - '0';
 1.97399 +  }else if( sqlite3StrICmp(z, "file")==0 ){
 1.97400 +    return 1;
 1.97401 +  }else if( sqlite3StrICmp(z, "memory")==0 ){
 1.97402 +    return 2;
 1.97403 +  }else{
 1.97404 +    return 0;
 1.97405 +  }
 1.97406 +}
 1.97407 +#endif /* SQLITE_PAGER_PRAGMAS */
 1.97408 +
 1.97409 +#ifndef SQLITE_OMIT_PAGER_PRAGMAS
 1.97410 +/*
 1.97411 +** Invalidate temp storage, either when the temp storage is changed
 1.97412 +** from default, or when 'file' and the temp_store_directory has changed
 1.97413 +*/
 1.97414 +static int invalidateTempStorage(Parse *pParse){
 1.97415 +  sqlite3 *db = pParse->db;
 1.97416 +  if( db->aDb[1].pBt!=0 ){
 1.97417 +    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
 1.97418 +      sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
 1.97419 +        "from within a transaction");
 1.97420 +      return SQLITE_ERROR;
 1.97421 +    }
 1.97422 +    sqlite3BtreeClose(db->aDb[1].pBt);
 1.97423 +    db->aDb[1].pBt = 0;
 1.97424 +    sqlite3ResetAllSchemasOfConnection(db);
 1.97425 +  }
 1.97426 +  return SQLITE_OK;
 1.97427 +}
 1.97428 +#endif /* SQLITE_PAGER_PRAGMAS */
 1.97429 +
 1.97430 +#ifndef SQLITE_OMIT_PAGER_PRAGMAS
 1.97431 +/*
 1.97432 +** If the TEMP database is open, close it and mark the database schema
 1.97433 +** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
 1.97434 +** or DEFAULT_TEMP_STORE pragmas.
 1.97435 +*/
 1.97436 +static int changeTempStorage(Parse *pParse, const char *zStorageType){
 1.97437 +  int ts = getTempStore(zStorageType);
 1.97438 +  sqlite3 *db = pParse->db;
 1.97439 +  if( db->temp_store==ts ) return SQLITE_OK;
 1.97440 +  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
 1.97441 +    return SQLITE_ERROR;
 1.97442 +  }
 1.97443 +  db->temp_store = (u8)ts;
 1.97444 +  return SQLITE_OK;
 1.97445 +}
 1.97446 +#endif /* SQLITE_PAGER_PRAGMAS */
 1.97447 +
 1.97448 +/*
 1.97449 +** Generate code to return a single integer value.
 1.97450 +*/
 1.97451 +static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
 1.97452 +  Vdbe *v = sqlite3GetVdbe(pParse);
 1.97453 +  int mem = ++pParse->nMem;
 1.97454 +  i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
 1.97455 +  if( pI64 ){
 1.97456 +    memcpy(pI64, &value, sizeof(value));
 1.97457 +  }
 1.97458 +  sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
 1.97459 +  sqlite3VdbeSetNumCols(v, 1);
 1.97460 +  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
 1.97461 +  sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
 1.97462 +}
 1.97463 +
 1.97464 +
 1.97465 +/*
 1.97466 +** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
 1.97467 +** set these values for all pagers.
 1.97468 +*/
 1.97469 +#ifndef SQLITE_OMIT_PAGER_PRAGMAS
 1.97470 +static void setAllPagerFlags(sqlite3 *db){
 1.97471 +  if( db->autoCommit ){
 1.97472 +    Db *pDb = db->aDb;
 1.97473 +    int n = db->nDb;
 1.97474 +    assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
 1.97475 +    assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
 1.97476 +    assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
 1.97477 +    assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
 1.97478 +             ==  PAGER_FLAGS_MASK );
 1.97479 +    assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
 1.97480 +    while( (n--) > 0 ){
 1.97481 +      if( pDb->pBt ){
 1.97482 +        sqlite3BtreeSetPagerFlags(pDb->pBt,
 1.97483 +                 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
 1.97484 +      }
 1.97485 +      pDb++;
 1.97486 +    }
 1.97487 +  }
 1.97488 +}
 1.97489 +#else
 1.97490 +# define setAllPagerFlags(X)  /* no-op */
 1.97491 +#endif
 1.97492 +
 1.97493 +
 1.97494 +/*
 1.97495 +** Return a human-readable name for a constraint resolution action.
 1.97496 +*/
 1.97497 +#ifndef SQLITE_OMIT_FOREIGN_KEY
 1.97498 +static const char *actionName(u8 action){
 1.97499 +  const char *zName;
 1.97500 +  switch( action ){
 1.97501 +    case OE_SetNull:  zName = "SET NULL";        break;
 1.97502 +    case OE_SetDflt:  zName = "SET DEFAULT";     break;
 1.97503 +    case OE_Cascade:  zName = "CASCADE";         break;
 1.97504 +    case OE_Restrict: zName = "RESTRICT";        break;
 1.97505 +    default:          zName = "NO ACTION";  
 1.97506 +                      assert( action==OE_None ); break;
 1.97507 +  }
 1.97508 +  return zName;
 1.97509 +}
 1.97510 +#endif
 1.97511 +
 1.97512 +
 1.97513 +/*
 1.97514 +** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
 1.97515 +** defined in pager.h. This function returns the associated lowercase
 1.97516 +** journal-mode name.
 1.97517 +*/
 1.97518 +SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
 1.97519 +  static char * const azModeName[] = {
 1.97520 +    "delete", "persist", "off", "truncate", "memory"
 1.97521 +#ifndef SQLITE_OMIT_WAL
 1.97522 +     , "wal"
 1.97523 +#endif
 1.97524 +  };
 1.97525 +  assert( PAGER_JOURNALMODE_DELETE==0 );
 1.97526 +  assert( PAGER_JOURNALMODE_PERSIST==1 );
 1.97527 +  assert( PAGER_JOURNALMODE_OFF==2 );
 1.97528 +  assert( PAGER_JOURNALMODE_TRUNCATE==3 );
 1.97529 +  assert( PAGER_JOURNALMODE_MEMORY==4 );
 1.97530 +  assert( PAGER_JOURNALMODE_WAL==5 );
 1.97531 +  assert( eMode>=0 && eMode<=ArraySize(azModeName) );
 1.97532 +
 1.97533 +  if( eMode==ArraySize(azModeName) ) return 0;
 1.97534 +  return azModeName[eMode];
 1.97535 +}
 1.97536 +
 1.97537 +/*
 1.97538 +** Process a pragma statement.  
 1.97539 +**
 1.97540 +** Pragmas are of this form:
 1.97541 +**
 1.97542 +**      PRAGMA [database.]id [= value]
 1.97543 +**
 1.97544 +** The identifier might also be a string.  The value is a string, and
 1.97545 +** identifier, or a number.  If minusFlag is true, then the value is
 1.97546 +** a number that was preceded by a minus sign.
 1.97547 +**
 1.97548 +** If the left side is "database.id" then pId1 is the database name
 1.97549 +** and pId2 is the id.  If the left side is just "id" then pId1 is the
 1.97550 +** id and pId2 is any empty string.
 1.97551 +*/
 1.97552 +SQLITE_PRIVATE void sqlite3Pragma(
 1.97553 +  Parse *pParse, 
 1.97554 +  Token *pId1,        /* First part of [database.]id field */
 1.97555 +  Token *pId2,        /* Second part of [database.]id field, or NULL */
 1.97556 +  Token *pValue,      /* Token for <value>, or NULL */
 1.97557 +  int minusFlag       /* True if a '-' sign preceded <value> */
 1.97558 +){
 1.97559 +  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
 1.97560 +  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
 1.97561 +  const char *zDb = 0;   /* The database name */
 1.97562 +  Token *pId;            /* Pointer to <id> token */
 1.97563 +  char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
 1.97564 +  int iDb;               /* Database index for <database> */
 1.97565 +  int lwr, upr, mid;           /* Binary search bounds */
 1.97566 +  int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
 1.97567 +  sqlite3 *db = pParse->db;    /* The database connection */
 1.97568 +  Db *pDb;                     /* The specific database being pragmaed */
 1.97569 +  Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
 1.97570 +
 1.97571 +  if( v==0 ) return;
 1.97572 +  sqlite3VdbeRunOnlyOnce(v);
 1.97573 +  pParse->nMem = 2;
 1.97574 +
 1.97575 +  /* Interpret the [database.] part of the pragma statement. iDb is the
 1.97576 +  ** index of the database this pragma is being applied to in db.aDb[]. */
 1.97577 +  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
 1.97578 +  if( iDb<0 ) return;
 1.97579 +  pDb = &db->aDb[iDb];
 1.97580 +
 1.97581 +  /* If the temp database has been explicitly named as part of the 
 1.97582 +  ** pragma, make sure it is open. 
 1.97583 +  */
 1.97584 +  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
 1.97585 +    return;
 1.97586 +  }
 1.97587 +
 1.97588 +  zLeft = sqlite3NameFromToken(db, pId);
 1.97589 +  if( !zLeft ) return;
 1.97590 +  if( minusFlag ){
 1.97591 +    zRight = sqlite3MPrintf(db, "-%T", pValue);
 1.97592 +  }else{
 1.97593 +    zRight = sqlite3NameFromToken(db, pValue);
 1.97594 +  }
 1.97595 +
 1.97596 +  assert( pId2 );
 1.97597 +  zDb = pId2->n>0 ? pDb->zName : 0;
 1.97598 +  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
 1.97599 +    goto pragma_out;
 1.97600 +  }
 1.97601 +
 1.97602 +  /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
 1.97603 +  ** connection.  If it returns SQLITE_OK, then assume that the VFS
 1.97604 +  ** handled the pragma and generate a no-op prepared statement.
 1.97605 +  */
 1.97606 +  aFcntl[0] = 0;
 1.97607 +  aFcntl[1] = zLeft;
 1.97608 +  aFcntl[2] = zRight;
 1.97609 +  aFcntl[3] = 0;
 1.97610 +  db->busyHandler.nBusy = 0;
 1.97611 +  rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
 1.97612 +  if( rc==SQLITE_OK ){
 1.97613 +    if( aFcntl[0] ){
 1.97614 +      int mem = ++pParse->nMem;
 1.97615 +      sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
 1.97616 +      sqlite3VdbeSetNumCols(v, 1);
 1.97617 +      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
 1.97618 +      sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
 1.97619 +      sqlite3_free(aFcntl[0]);
 1.97620 +    }
 1.97621 +    goto pragma_out;
 1.97622 +  }
 1.97623 +  if( rc!=SQLITE_NOTFOUND ){
 1.97624 +    if( aFcntl[0] ){
 1.97625 +      sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
 1.97626 +      sqlite3_free(aFcntl[0]);
 1.97627 +    }
 1.97628 +    pParse->nErr++;
 1.97629 +    pParse->rc = rc;
 1.97630 +    goto pragma_out;
 1.97631 +  }
 1.97632 +
 1.97633 +  /* Locate the pragma in the lookup table */
 1.97634 +  lwr = 0;
 1.97635 +  upr = ArraySize(aPragmaNames)-1;
 1.97636 +  while( lwr<=upr ){
 1.97637 +    mid = (lwr+upr)/2;
 1.97638 +    rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
 1.97639 +    if( rc==0 ) break;
 1.97640 +    if( rc<0 ){
 1.97641 +      upr = mid - 1;
 1.97642 +    }else{
 1.97643 +      lwr = mid + 1;
 1.97644 +    }
 1.97645 +  }
 1.97646 +  if( lwr>upr ) goto pragma_out;
 1.97647 +
 1.97648 +  /* Make sure the database schema is loaded if the pragma requires that */
 1.97649 +  if( (aPragmaNames[mid].mPragFlag & PragFlag_NeedSchema)!=0 ){
 1.97650 +    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
 1.97651 +  }
 1.97652 +
 1.97653 +  /* Jump to the appropriate pragma handler */
 1.97654 +  switch( aPragmaNames[mid].ePragTyp ){
 1.97655 +  
 1.97656 +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
 1.97657 +  /*
 1.97658 +  **  PRAGMA [database.]default_cache_size
 1.97659 +  **  PRAGMA [database.]default_cache_size=N
 1.97660 +  **
 1.97661 +  ** The first form reports the current persistent setting for the
 1.97662 +  ** page cache size.  The value returned is the maximum number of
 1.97663 +  ** pages in the page cache.  The second form sets both the current
 1.97664 +  ** page cache size value and the persistent page cache size value
 1.97665 +  ** stored in the database file.
 1.97666 +  **
 1.97667 +  ** Older versions of SQLite would set the default cache size to a
 1.97668 +  ** negative number to indicate synchronous=OFF.  These days, synchronous
 1.97669 +  ** is always on by default regardless of the sign of the default cache
 1.97670 +  ** size.  But continue to take the absolute value of the default cache
 1.97671 +  ** size of historical compatibility.
 1.97672 +  */
 1.97673 +  case PragTyp_DEFAULT_CACHE_SIZE: {
 1.97674 +    static const int iLn = VDBE_OFFSET_LINENO(2);
 1.97675 +    static const VdbeOpList getCacheSize[] = {
 1.97676 +      { OP_Transaction, 0, 0,        0},                         /* 0 */
 1.97677 +      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
 1.97678 +      { OP_IfPos,       1, 8,        0},
 1.97679 +      { OP_Integer,     0, 2,        0},
 1.97680 +      { OP_Subtract,    1, 2,        1},
 1.97681 +      { OP_IfPos,       1, 8,        0},
 1.97682 +      { OP_Integer,     0, 1,        0},                         /* 6 */
 1.97683 +      { OP_Noop,        0, 0,        0},
 1.97684 +      { OP_ResultRow,   1, 1,        0},
 1.97685 +    };
 1.97686 +    int addr;
 1.97687 +    sqlite3VdbeUsesBtree(v, iDb);
 1.97688 +    if( !zRight ){
 1.97689 +      sqlite3VdbeSetNumCols(v, 1);
 1.97690 +      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
 1.97691 +      pParse->nMem += 2;
 1.97692 +      addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize,iLn);
 1.97693 +      sqlite3VdbeChangeP1(v, addr, iDb);
 1.97694 +      sqlite3VdbeChangeP1(v, addr+1, iDb);
 1.97695 +      sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
 1.97696 +    }else{
 1.97697 +      int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
 1.97698 +      sqlite3BeginWriteOperation(pParse, 0, iDb);
 1.97699 +      sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
 1.97700 +      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
 1.97701 +      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 1.97702 +      pDb->pSchema->cache_size = size;
 1.97703 +      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
 1.97704 +    }
 1.97705 +    break;
 1.97706 +  }
 1.97707 +#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
 1.97708 +
 1.97709 +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
 1.97710 +  /*
 1.97711 +  **  PRAGMA [database.]page_size
 1.97712 +  **  PRAGMA [database.]page_size=N
 1.97713 +  **
 1.97714 +  ** The first form reports the current setting for the
 1.97715 +  ** database page size in bytes.  The second form sets the
 1.97716 +  ** database page size value.  The value can only be set if
 1.97717 +  ** the database has not yet been created.
 1.97718 +  */
 1.97719 +  case PragTyp_PAGE_SIZE: {
 1.97720 +    Btree *pBt = pDb->pBt;
 1.97721 +    assert( pBt!=0 );
 1.97722 +    if( !zRight ){
 1.97723 +      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
 1.97724 +      returnSingleInt(pParse, "page_size", size);
 1.97725 +    }else{
 1.97726 +      /* Malloc may fail when setting the page-size, as there is an internal
 1.97727 +      ** buffer that the pager module resizes using sqlite3_realloc().
 1.97728 +      */
 1.97729 +      db->nextPagesize = sqlite3Atoi(zRight);
 1.97730 +      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
 1.97731 +        db->mallocFailed = 1;
 1.97732 +      }
 1.97733 +    }
 1.97734 +    break;
 1.97735 +  }
 1.97736 +
 1.97737 +  /*
 1.97738 +  **  PRAGMA [database.]secure_delete
 1.97739 +  **  PRAGMA [database.]secure_delete=ON/OFF
 1.97740 +  **
 1.97741 +  ** The first form reports the current setting for the
 1.97742 +  ** secure_delete flag.  The second form changes the secure_delete
 1.97743 +  ** flag setting and reports thenew value.
 1.97744 +  */
 1.97745 +  case PragTyp_SECURE_DELETE: {
 1.97746 +    Btree *pBt = pDb->pBt;
 1.97747 +    int b = -1;
 1.97748 +    assert( pBt!=0 );
 1.97749 +    if( zRight ){
 1.97750 +      b = sqlite3GetBoolean(zRight, 0);
 1.97751 +    }
 1.97752 +    if( pId2->n==0 && b>=0 ){
 1.97753 +      int ii;
 1.97754 +      for(ii=0; ii<db->nDb; ii++){
 1.97755 +        sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
 1.97756 +      }
 1.97757 +    }
 1.97758 +    b = sqlite3BtreeSecureDelete(pBt, b);
 1.97759 +    returnSingleInt(pParse, "secure_delete", b);
 1.97760 +    break;
 1.97761 +  }
 1.97762 +
 1.97763 +  /*
 1.97764 +  **  PRAGMA [database.]max_page_count
 1.97765 +  **  PRAGMA [database.]max_page_count=N
 1.97766 +  **
 1.97767 +  ** The first form reports the current setting for the
 1.97768 +  ** maximum number of pages in the database file.  The 
 1.97769 +  ** second form attempts to change this setting.  Both
 1.97770 +  ** forms return the current setting.
 1.97771 +  **
 1.97772 +  ** The absolute value of N is used.  This is undocumented and might
 1.97773 +  ** change.  The only purpose is to provide an easy way to test
 1.97774 +  ** the sqlite3AbsInt32() function.
 1.97775 +  **
 1.97776 +  **  PRAGMA [database.]page_count
 1.97777 +  **
 1.97778 +  ** Return the number of pages in the specified database.
 1.97779 +  */
 1.97780 +  case PragTyp_PAGE_COUNT: {
 1.97781 +    int iReg;
 1.97782 +    sqlite3CodeVerifySchema(pParse, iDb);
 1.97783 +    iReg = ++pParse->nMem;
 1.97784 +    if( sqlite3Tolower(zLeft[0])=='p' ){
 1.97785 +      sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
 1.97786 +    }else{
 1.97787 +      sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, 
 1.97788 +                        sqlite3AbsInt32(sqlite3Atoi(zRight)));
 1.97789 +    }
 1.97790 +    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
 1.97791 +    sqlite3VdbeSetNumCols(v, 1);
 1.97792 +    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
 1.97793 +    break;
 1.97794 +  }
 1.97795 +
 1.97796 +  /*
 1.97797 +  **  PRAGMA [database.]locking_mode
 1.97798 +  **  PRAGMA [database.]locking_mode = (normal|exclusive)
 1.97799 +  */
 1.97800 +  case PragTyp_LOCKING_MODE: {
 1.97801 +    const char *zRet = "normal";
 1.97802 +    int eMode = getLockingMode(zRight);
 1.97803 +
 1.97804 +    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
 1.97805 +      /* Simple "PRAGMA locking_mode;" statement. This is a query for
 1.97806 +      ** the current default locking mode (which may be different to
 1.97807 +      ** the locking-mode of the main database).
 1.97808 +      */
 1.97809 +      eMode = db->dfltLockMode;
 1.97810 +    }else{
 1.97811 +      Pager *pPager;
 1.97812 +      if( pId2->n==0 ){
 1.97813 +        /* This indicates that no database name was specified as part
 1.97814 +        ** of the PRAGMA command. In this case the locking-mode must be
 1.97815 +        ** set on all attached databases, as well as the main db file.
 1.97816 +        **
 1.97817 +        ** Also, the sqlite3.dfltLockMode variable is set so that
 1.97818 +        ** any subsequently attached databases also use the specified
 1.97819 +        ** locking mode.
 1.97820 +        */
 1.97821 +        int ii;
 1.97822 +        assert(pDb==&db->aDb[0]);
 1.97823 +        for(ii=2; ii<db->nDb; ii++){
 1.97824 +          pPager = sqlite3BtreePager(db->aDb[ii].pBt);
 1.97825 +          sqlite3PagerLockingMode(pPager, eMode);
 1.97826 +        }
 1.97827 +        db->dfltLockMode = (u8)eMode;
 1.97828 +      }
 1.97829 +      pPager = sqlite3BtreePager(pDb->pBt);
 1.97830 +      eMode = sqlite3PagerLockingMode(pPager, eMode);
 1.97831 +    }
 1.97832 +
 1.97833 +    assert( eMode==PAGER_LOCKINGMODE_NORMAL
 1.97834 +            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
 1.97835 +    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
 1.97836 +      zRet = "exclusive";
 1.97837 +    }
 1.97838 +    sqlite3VdbeSetNumCols(v, 1);
 1.97839 +    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
 1.97840 +    sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
 1.97841 +    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
 1.97842 +    break;
 1.97843 +  }
 1.97844 +
 1.97845 +  /*
 1.97846 +  **  PRAGMA [database.]journal_mode
 1.97847 +  **  PRAGMA [database.]journal_mode =
 1.97848 +  **                      (delete|persist|off|truncate|memory|wal|off)
 1.97849 +  */
 1.97850 +  case PragTyp_JOURNAL_MODE: {
 1.97851 +    int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
 1.97852 +    int ii;           /* Loop counter */
 1.97853 +
 1.97854 +    sqlite3VdbeSetNumCols(v, 1);
 1.97855 +    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
 1.97856 +
 1.97857 +    if( zRight==0 ){
 1.97858 +      /* If there is no "=MODE" part of the pragma, do a query for the
 1.97859 +      ** current mode */
 1.97860 +      eMode = PAGER_JOURNALMODE_QUERY;
 1.97861 +    }else{
 1.97862 +      const char *zMode;
 1.97863 +      int n = sqlite3Strlen30(zRight);
 1.97864 +      for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
 1.97865 +        if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
 1.97866 +      }
 1.97867 +      if( !zMode ){
 1.97868 +        /* If the "=MODE" part does not match any known journal mode,
 1.97869 +        ** then do a query */
 1.97870 +        eMode = PAGER_JOURNALMODE_QUERY;
 1.97871 +      }
 1.97872 +    }
 1.97873 +    if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
 1.97874 +      /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
 1.97875 +      iDb = 0;
 1.97876 +      pId2->n = 1;
 1.97877 +    }
 1.97878 +    for(ii=db->nDb-1; ii>=0; ii--){
 1.97879 +      if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
 1.97880 +        sqlite3VdbeUsesBtree(v, ii);
 1.97881 +        sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
 1.97882 +      }
 1.97883 +    }
 1.97884 +    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
 1.97885 +    break;
 1.97886 +  }
 1.97887 +
 1.97888 +  /*
 1.97889 +  **  PRAGMA [database.]journal_size_limit
 1.97890 +  **  PRAGMA [database.]journal_size_limit=N
 1.97891 +  **
 1.97892 +  ** Get or set the size limit on rollback journal files.
 1.97893 +  */
 1.97894 +  case PragTyp_JOURNAL_SIZE_LIMIT: {
 1.97895 +    Pager *pPager = sqlite3BtreePager(pDb->pBt);
 1.97896 +    i64 iLimit = -2;
 1.97897 +    if( zRight ){
 1.97898 +      sqlite3Atoi64(zRight, &iLimit, sqlite3Strlen30(zRight), SQLITE_UTF8);
 1.97899 +      if( iLimit<-1 ) iLimit = -1;
 1.97900 +    }
 1.97901 +    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
 1.97902 +    returnSingleInt(pParse, "journal_size_limit", iLimit);
 1.97903 +    break;
 1.97904 +  }
 1.97905 +
 1.97906 +#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
 1.97907 +
 1.97908 +  /*
 1.97909 +  **  PRAGMA [database.]auto_vacuum
 1.97910 +  **  PRAGMA [database.]auto_vacuum=N
 1.97911 +  **
 1.97912 +  ** Get or set the value of the database 'auto-vacuum' parameter.
 1.97913 +  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
 1.97914 +  */
 1.97915 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.97916 +  case PragTyp_AUTO_VACUUM: {
 1.97917 +    Btree *pBt = pDb->pBt;
 1.97918 +    assert( pBt!=0 );
 1.97919 +    if( !zRight ){
 1.97920 +      returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
 1.97921 +    }else{
 1.97922 +      int eAuto = getAutoVacuum(zRight);
 1.97923 +      assert( eAuto>=0 && eAuto<=2 );
 1.97924 +      db->nextAutovac = (u8)eAuto;
 1.97925 +      /* Call SetAutoVacuum() to set initialize the internal auto and
 1.97926 +      ** incr-vacuum flags. This is required in case this connection
 1.97927 +      ** creates the database file. It is important that it is created
 1.97928 +      ** as an auto-vacuum capable db.
 1.97929 +      */
 1.97930 +      rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
 1.97931 +      if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
 1.97932 +        /* When setting the auto_vacuum mode to either "full" or 
 1.97933 +        ** "incremental", write the value of meta[6] in the database
 1.97934 +        ** file. Before writing to meta[6], check that meta[3] indicates
 1.97935 +        ** that this really is an auto-vacuum capable database.
 1.97936 +        */
 1.97937 +        static const int iLn = VDBE_OFFSET_LINENO(2);
 1.97938 +        static const VdbeOpList setMeta6[] = {
 1.97939 +          { OP_Transaction,    0,         1,                 0},    /* 0 */
 1.97940 +          { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
 1.97941 +          { OP_If,             1,         0,                 0},    /* 2 */
 1.97942 +          { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
 1.97943 +          { OP_Integer,        0,         1,                 0},    /* 4 */
 1.97944 +          { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
 1.97945 +        };
 1.97946 +        int iAddr;
 1.97947 +        iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
 1.97948 +        sqlite3VdbeChangeP1(v, iAddr, iDb);
 1.97949 +        sqlite3VdbeChangeP1(v, iAddr+1, iDb);
 1.97950 +        sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
 1.97951 +        sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
 1.97952 +        sqlite3VdbeChangeP1(v, iAddr+5, iDb);
 1.97953 +        sqlite3VdbeUsesBtree(v, iDb);
 1.97954 +      }
 1.97955 +    }
 1.97956 +    break;
 1.97957 +  }
 1.97958 +#endif
 1.97959 +
 1.97960 +  /*
 1.97961 +  **  PRAGMA [database.]incremental_vacuum(N)
 1.97962 +  **
 1.97963 +  ** Do N steps of incremental vacuuming on a database.
 1.97964 +  */
 1.97965 +#ifndef SQLITE_OMIT_AUTOVACUUM
 1.97966 +  case PragTyp_INCREMENTAL_VACUUM: {
 1.97967 +    int iLimit, addr;
 1.97968 +    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
 1.97969 +      iLimit = 0x7fffffff;
 1.97970 +    }
 1.97971 +    sqlite3BeginWriteOperation(pParse, 0, iDb);
 1.97972 +    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
 1.97973 +    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
 1.97974 +    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
 1.97975 +    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
 1.97976 +    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
 1.97977 +    sqlite3VdbeJumpHere(v, addr);
 1.97978 +    break;
 1.97979 +  }
 1.97980 +#endif
 1.97981 +
 1.97982 +#ifndef SQLITE_OMIT_PAGER_PRAGMAS
 1.97983 +  /*
 1.97984 +  **  PRAGMA [database.]cache_size
 1.97985 +  **  PRAGMA [database.]cache_size=N
 1.97986 +  **
 1.97987 +  ** The first form reports the current local setting for the
 1.97988 +  ** page cache size. The second form sets the local
 1.97989 +  ** page cache size value.  If N is positive then that is the
 1.97990 +  ** number of pages in the cache.  If N is negative, then the
 1.97991 +  ** number of pages is adjusted so that the cache uses -N kibibytes
 1.97992 +  ** of memory.
 1.97993 +  */
 1.97994 +  case PragTyp_CACHE_SIZE: {
 1.97995 +    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 1.97996 +    if( !zRight ){
 1.97997 +      returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
 1.97998 +    }else{
 1.97999 +      int size = sqlite3Atoi(zRight);
 1.98000 +      pDb->pSchema->cache_size = size;
 1.98001 +      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
 1.98002 +    }
 1.98003 +    break;
 1.98004 +  }
 1.98005 +
 1.98006 +  /*
 1.98007 +  **  PRAGMA [database.]mmap_size(N)
 1.98008 +  **
 1.98009 +  ** Used to set mapping size limit. The mapping size limit is
 1.98010 +  ** used to limit the aggregate size of all memory mapped regions of the
 1.98011 +  ** database file. If this parameter is set to zero, then memory mapping
 1.98012 +  ** is not used at all.  If N is negative, then the default memory map
 1.98013 +  ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
 1.98014 +  ** The parameter N is measured in bytes.
 1.98015 +  **
 1.98016 +  ** This value is advisory.  The underlying VFS is free to memory map
 1.98017 +  ** as little or as much as it wants.  Except, if N is set to 0 then the
 1.98018 +  ** upper layers will never invoke the xFetch interfaces to the VFS.
 1.98019 +  */
 1.98020 +  case PragTyp_MMAP_SIZE: {
 1.98021 +    sqlite3_int64 sz;
 1.98022 +#if SQLITE_MAX_MMAP_SIZE>0
 1.98023 +    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 1.98024 +    if( zRight ){
 1.98025 +      int ii;
 1.98026 +      sqlite3Atoi64(zRight, &sz, sqlite3Strlen30(zRight), SQLITE_UTF8);
 1.98027 +      if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
 1.98028 +      if( pId2->n==0 ) db->szMmap = sz;
 1.98029 +      for(ii=db->nDb-1; ii>=0; ii--){
 1.98030 +        if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
 1.98031 +          sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
 1.98032 +        }
 1.98033 +      }
 1.98034 +    }
 1.98035 +    sz = -1;
 1.98036 +    rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
 1.98037 +#else
 1.98038 +    sz = 0;
 1.98039 +    rc = SQLITE_OK;
 1.98040 +#endif
 1.98041 +    if( rc==SQLITE_OK ){
 1.98042 +      returnSingleInt(pParse, "mmap_size", sz);
 1.98043 +    }else if( rc!=SQLITE_NOTFOUND ){
 1.98044 +      pParse->nErr++;
 1.98045 +      pParse->rc = rc;
 1.98046 +    }
 1.98047 +    break;
 1.98048 +  }
 1.98049 +
 1.98050 +  /*
 1.98051 +  **   PRAGMA temp_store
 1.98052 +  **   PRAGMA temp_store = "default"|"memory"|"file"
 1.98053 +  **
 1.98054 +  ** Return or set the local value of the temp_store flag.  Changing
 1.98055 +  ** the local value does not make changes to the disk file and the default
 1.98056 +  ** value will be restored the next time the database is opened.
 1.98057 +  **
 1.98058 +  ** Note that it is possible for the library compile-time options to
 1.98059 +  ** override this setting
 1.98060 +  */
 1.98061 +  case PragTyp_TEMP_STORE: {
 1.98062 +    if( !zRight ){
 1.98063 +      returnSingleInt(pParse, "temp_store", db->temp_store);
 1.98064 +    }else{
 1.98065 +      changeTempStorage(pParse, zRight);
 1.98066 +    }
 1.98067 +    break;
 1.98068 +  }
 1.98069 +
 1.98070 +  /*
 1.98071 +  **   PRAGMA temp_store_directory
 1.98072 +  **   PRAGMA temp_store_directory = ""|"directory_name"
 1.98073 +  **
 1.98074 +  ** Return or set the local value of the temp_store_directory flag.  Changing
 1.98075 +  ** the value sets a specific directory to be used for temporary files.
 1.98076 +  ** Setting to a null string reverts to the default temporary directory search.
 1.98077 +  ** If temporary directory is changed, then invalidateTempStorage.
 1.98078 +  **
 1.98079 +  */
 1.98080 +  case PragTyp_TEMP_STORE_DIRECTORY: {
 1.98081 +    if( !zRight ){
 1.98082 +      if( sqlite3_temp_directory ){
 1.98083 +        sqlite3VdbeSetNumCols(v, 1);
 1.98084 +        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
 1.98085 +            "temp_store_directory", SQLITE_STATIC);
 1.98086 +        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
 1.98087 +        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
 1.98088 +      }
 1.98089 +    }else{
 1.98090 +#ifndef SQLITE_OMIT_WSD
 1.98091 +      if( zRight[0] ){
 1.98092 +        int res;
 1.98093 +        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
 1.98094 +        if( rc!=SQLITE_OK || res==0 ){
 1.98095 +          sqlite3ErrorMsg(pParse, "not a writable directory");
 1.98096 +          goto pragma_out;
 1.98097 +        }
 1.98098 +      }
 1.98099 +      if( SQLITE_TEMP_STORE==0
 1.98100 +       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
 1.98101 +       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
 1.98102 +      ){
 1.98103 +        invalidateTempStorage(pParse);
 1.98104 +      }
 1.98105 +      sqlite3_free(sqlite3_temp_directory);
 1.98106 +      if( zRight[0] ){
 1.98107 +        sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
 1.98108 +      }else{
 1.98109 +        sqlite3_temp_directory = 0;
 1.98110 +      }
 1.98111 +#endif /* SQLITE_OMIT_WSD */
 1.98112 +    }
 1.98113 +    break;
 1.98114 +  }
 1.98115 +
 1.98116 +#if SQLITE_OS_WIN
 1.98117 +  /*
 1.98118 +  **   PRAGMA data_store_directory
 1.98119 +  **   PRAGMA data_store_directory = ""|"directory_name"
 1.98120 +  **
 1.98121 +  ** Return or set the local value of the data_store_directory flag.  Changing
 1.98122 +  ** the value sets a specific directory to be used for database files that
 1.98123 +  ** were specified with a relative pathname.  Setting to a null string reverts
 1.98124 +  ** to the default database directory, which for database files specified with
 1.98125 +  ** a relative path will probably be based on the current directory for the
 1.98126 +  ** process.  Database file specified with an absolute path are not impacted
 1.98127 +  ** by this setting, regardless of its value.
 1.98128 +  **
 1.98129 +  */
 1.98130 +  case PragTyp_DATA_STORE_DIRECTORY: {
 1.98131 +    if( !zRight ){
 1.98132 +      if( sqlite3_data_directory ){
 1.98133 +        sqlite3VdbeSetNumCols(v, 1);
 1.98134 +        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
 1.98135 +            "data_store_directory", SQLITE_STATIC);
 1.98136 +        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
 1.98137 +        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
 1.98138 +      }
 1.98139 +    }else{
 1.98140 +#ifndef SQLITE_OMIT_WSD
 1.98141 +      if( zRight[0] ){
 1.98142 +        int res;
 1.98143 +        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
 1.98144 +        if( rc!=SQLITE_OK || res==0 ){
 1.98145 +          sqlite3ErrorMsg(pParse, "not a writable directory");
 1.98146 +          goto pragma_out;
 1.98147 +        }
 1.98148 +      }
 1.98149 +      sqlite3_free(sqlite3_data_directory);
 1.98150 +      if( zRight[0] ){
 1.98151 +        sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
 1.98152 +      }else{
 1.98153 +        sqlite3_data_directory = 0;
 1.98154 +      }
 1.98155 +#endif /* SQLITE_OMIT_WSD */
 1.98156 +    }
 1.98157 +    break;
 1.98158 +  }
 1.98159 +#endif
 1.98160 +
 1.98161 +#if SQLITE_ENABLE_LOCKING_STYLE
 1.98162 +  /*
 1.98163 +  **   PRAGMA [database.]lock_proxy_file
 1.98164 +  **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
 1.98165 +  **
 1.98166 +  ** Return or set the value of the lock_proxy_file flag.  Changing
 1.98167 +  ** the value sets a specific file to be used for database access locks.
 1.98168 +  **
 1.98169 +  */
 1.98170 +  case PragTyp_LOCK_PROXY_FILE: {
 1.98171 +    if( !zRight ){
 1.98172 +      Pager *pPager = sqlite3BtreePager(pDb->pBt);
 1.98173 +      char *proxy_file_path = NULL;
 1.98174 +      sqlite3_file *pFile = sqlite3PagerFile(pPager);
 1.98175 +      sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, 
 1.98176 +                           &proxy_file_path);
 1.98177 +      
 1.98178 +      if( proxy_file_path ){
 1.98179 +        sqlite3VdbeSetNumCols(v, 1);
 1.98180 +        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
 1.98181 +                              "lock_proxy_file", SQLITE_STATIC);
 1.98182 +        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
 1.98183 +        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
 1.98184 +      }
 1.98185 +    }else{
 1.98186 +      Pager *pPager = sqlite3BtreePager(pDb->pBt);
 1.98187 +      sqlite3_file *pFile = sqlite3PagerFile(pPager);
 1.98188 +      int res;
 1.98189 +      if( zRight[0] ){
 1.98190 +        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
 1.98191 +                                     zRight);
 1.98192 +      } else {
 1.98193 +        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
 1.98194 +                                     NULL);
 1.98195 +      }
 1.98196 +      if( res!=SQLITE_OK ){
 1.98197 +        sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
 1.98198 +        goto pragma_out;
 1.98199 +      }
 1.98200 +    }
 1.98201 +    break;
 1.98202 +  }
 1.98203 +#endif /* SQLITE_ENABLE_LOCKING_STYLE */      
 1.98204 +    
 1.98205 +  /*
 1.98206 +  **   PRAGMA [database.]synchronous
 1.98207 +  **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
 1.98208 +  **
 1.98209 +  ** Return or set the local value of the synchronous flag.  Changing
 1.98210 +  ** the local value does not make changes to the disk file and the
 1.98211 +  ** default value will be restored the next time the database is
 1.98212 +  ** opened.
 1.98213 +  */
 1.98214 +  case PragTyp_SYNCHRONOUS: {
 1.98215 +    if( !zRight ){
 1.98216 +      returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
 1.98217 +    }else{
 1.98218 +      if( !db->autoCommit ){
 1.98219 +        sqlite3ErrorMsg(pParse, 
 1.98220 +            "Safety level may not be changed inside a transaction");
 1.98221 +      }else{
 1.98222 +        pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
 1.98223 +        setAllPagerFlags(db);
 1.98224 +      }
 1.98225 +    }
 1.98226 +    break;
 1.98227 +  }
 1.98228 +#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
 1.98229 +
 1.98230 +#ifndef SQLITE_OMIT_FLAG_PRAGMAS
 1.98231 +  case PragTyp_FLAG: {
 1.98232 +    if( zRight==0 ){
 1.98233 +      returnSingleInt(pParse, aPragmaNames[mid].zName,
 1.98234 +                     (db->flags & aPragmaNames[mid].iArg)!=0 );
 1.98235 +    }else{
 1.98236 +      int mask = aPragmaNames[mid].iArg;    /* Mask of bits to set or clear. */
 1.98237 +      if( db->autoCommit==0 ){
 1.98238 +        /* Foreign key support may not be enabled or disabled while not
 1.98239 +        ** in auto-commit mode.  */
 1.98240 +        mask &= ~(SQLITE_ForeignKeys);
 1.98241 +      }
 1.98242 +
 1.98243 +      if( sqlite3GetBoolean(zRight, 0) ){
 1.98244 +        db->flags |= mask;
 1.98245 +      }else{
 1.98246 +        db->flags &= ~mask;
 1.98247 +        if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
 1.98248 +      }
 1.98249 +
 1.98250 +      /* Many of the flag-pragmas modify the code generated by the SQL 
 1.98251 +      ** compiler (eg. count_changes). So add an opcode to expire all
 1.98252 +      ** compiled SQL statements after modifying a pragma value.
 1.98253 +      */
 1.98254 +      sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
 1.98255 +      setAllPagerFlags(db);
 1.98256 +    }
 1.98257 +    break;
 1.98258 +  }
 1.98259 +#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
 1.98260 +
 1.98261 +#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
 1.98262 +  /*
 1.98263 +  **   PRAGMA table_info(<table>)
 1.98264 +  **
 1.98265 +  ** Return a single row for each column of the named table. The columns of
 1.98266 +  ** the returned data set are:
 1.98267 +  **
 1.98268 +  ** cid:        Column id (numbered from left to right, starting at 0)
 1.98269 +  ** name:       Column name
 1.98270 +  ** type:       Column declaration type.
 1.98271 +  ** notnull:    True if 'NOT NULL' is part of column declaration
 1.98272 +  ** dflt_value: The default value for the column, if any.
 1.98273 +  */
 1.98274 +  case PragTyp_TABLE_INFO: if( zRight ){
 1.98275 +    Table *pTab;
 1.98276 +    pTab = sqlite3FindTable(db, zRight, zDb);
 1.98277 +    if( pTab ){
 1.98278 +      int i, k;
 1.98279 +      int nHidden = 0;
 1.98280 +      Column *pCol;
 1.98281 +      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
 1.98282 +      sqlite3VdbeSetNumCols(v, 6);
 1.98283 +      pParse->nMem = 6;
 1.98284 +      sqlite3CodeVerifySchema(pParse, iDb);
 1.98285 +      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
 1.98286 +      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
 1.98287 +      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
 1.98288 +      sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
 1.98289 +      sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
 1.98290 +      sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
 1.98291 +      sqlite3ViewGetColumnNames(pParse, pTab);
 1.98292 +      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
 1.98293 +        if( IsHiddenColumn(pCol) ){
 1.98294 +          nHidden++;
 1.98295 +          continue;
 1.98296 +        }
 1.98297 +        sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
 1.98298 +        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
 1.98299 +        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
 1.98300 +           pCol->zType ? pCol->zType : "", 0);
 1.98301 +        sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
 1.98302 +        if( pCol->zDflt ){
 1.98303 +          sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
 1.98304 +        }else{
 1.98305 +          sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
 1.98306 +        }
 1.98307 +        if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
 1.98308 +          k = 0;
 1.98309 +        }else if( pPk==0 ){
 1.98310 +          k = 1;
 1.98311 +        }else{
 1.98312 +          for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
 1.98313 +        }
 1.98314 +        sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
 1.98315 +        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
 1.98316 +      }
 1.98317 +    }
 1.98318 +  }
 1.98319 +  break;
 1.98320 +
 1.98321 +  case PragTyp_STATS: {
 1.98322 +    Index *pIdx;
 1.98323 +    HashElem *i;
 1.98324 +    v = sqlite3GetVdbe(pParse);
 1.98325 +    sqlite3VdbeSetNumCols(v, 4);
 1.98326 +    pParse->nMem = 4;
 1.98327 +    sqlite3CodeVerifySchema(pParse, iDb);
 1.98328 +    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
 1.98329 +    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC);
 1.98330 +    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC);
 1.98331 +    sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC);
 1.98332 +    for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
 1.98333 +      Table *pTab = sqliteHashData(i);
 1.98334 +      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0);
 1.98335 +      sqlite3VdbeAddOp2(v, OP_Null, 0, 2);
 1.98336 +      sqlite3VdbeAddOp2(v, OP_Integer,
 1.98337 +                           (int)sqlite3LogEstToInt(pTab->szTabRow), 3);
 1.98338 +      sqlite3VdbeAddOp2(v, OP_Integer, (int)pTab->nRowEst, 4);
 1.98339 +      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
 1.98340 +      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
 1.98341 +        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
 1.98342 +        sqlite3VdbeAddOp2(v, OP_Integer,
 1.98343 +                             (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3);
 1.98344 +        sqlite3VdbeAddOp2(v, OP_Integer, (int)pIdx->aiRowEst[0], 4);
 1.98345 +        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
 1.98346 +      }
 1.98347 +    }
 1.98348 +  }
 1.98349 +  break;
 1.98350 +
 1.98351 +  case PragTyp_INDEX_INFO: if( zRight ){
 1.98352 +    Index *pIdx;
 1.98353 +    Table *pTab;
 1.98354 +    pIdx = sqlite3FindIndex(db, zRight, zDb);
 1.98355 +    if( pIdx ){
 1.98356 +      int i;
 1.98357 +      pTab = pIdx->pTable;
 1.98358 +      sqlite3VdbeSetNumCols(v, 3);
 1.98359 +      pParse->nMem = 3;
 1.98360 +      sqlite3CodeVerifySchema(pParse, iDb);
 1.98361 +      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
 1.98362 +      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
 1.98363 +      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
 1.98364 +      for(i=0; i<pIdx->nKeyCol; i++){
 1.98365 +        i16 cnum = pIdx->aiColumn[i];
 1.98366 +        sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
 1.98367 +        sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
 1.98368 +        assert( pTab->nCol>cnum );
 1.98369 +        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
 1.98370 +        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
 1.98371 +      }
 1.98372 +    }
 1.98373 +  }
 1.98374 +  break;
 1.98375 +
 1.98376 +  case PragTyp_INDEX_LIST: if( zRight ){
 1.98377 +    Index *pIdx;
 1.98378 +    Table *pTab;
 1.98379 +    int i;
 1.98380 +    pTab = sqlite3FindTable(db, zRight, zDb);
 1.98381 +    if( pTab ){
 1.98382 +      v = sqlite3GetVdbe(pParse);
 1.98383 +      sqlite3VdbeSetNumCols(v, 3);
 1.98384 +      pParse->nMem = 3;
 1.98385 +      sqlite3CodeVerifySchema(pParse, iDb);
 1.98386 +      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
 1.98387 +      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
 1.98388 +      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
 1.98389 +      for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
 1.98390 +        sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
 1.98391 +        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
 1.98392 +        sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
 1.98393 +        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
 1.98394 +      }
 1.98395 +    }
 1.98396 +  }
 1.98397 +  break;
 1.98398 +
 1.98399 +  case PragTyp_DATABASE_LIST: {
 1.98400 +    int i;
 1.98401 +    sqlite3VdbeSetNumCols(v, 3);
 1.98402 +    pParse->nMem = 3;
 1.98403 +    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
 1.98404 +    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
 1.98405 +    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
 1.98406 +    for(i=0; i<db->nDb; i++){
 1.98407 +      if( db->aDb[i].pBt==0 ) continue;
 1.98408 +      assert( db->aDb[i].zName!=0 );
 1.98409 +      sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
 1.98410 +      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
 1.98411 +      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
 1.98412 +           sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
 1.98413 +      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
 1.98414 +    }
 1.98415 +  }
 1.98416 +  break;
 1.98417 +
 1.98418 +  case PragTyp_COLLATION_LIST: {
 1.98419 +    int i = 0;
 1.98420 +    HashElem *p;
 1.98421 +    sqlite3VdbeSetNumCols(v, 2);
 1.98422 +    pParse->nMem = 2;
 1.98423 +    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
 1.98424 +    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
 1.98425 +    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
 1.98426 +      CollSeq *pColl = (CollSeq *)sqliteHashData(p);
 1.98427 +      sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
 1.98428 +      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
 1.98429 +      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
 1.98430 +    }
 1.98431 +  }
 1.98432 +  break;
 1.98433 +#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
 1.98434 +
 1.98435 +#ifndef SQLITE_OMIT_FOREIGN_KEY
 1.98436 +  case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
 1.98437 +    FKey *pFK;
 1.98438 +    Table *pTab;
 1.98439 +    pTab = sqlite3FindTable(db, zRight, zDb);
 1.98440 +    if( pTab ){
 1.98441 +      v = sqlite3GetVdbe(pParse);
 1.98442 +      pFK = pTab->pFKey;
 1.98443 +      if( pFK ){
 1.98444 +        int i = 0; 
 1.98445 +        sqlite3VdbeSetNumCols(v, 8);
 1.98446 +        pParse->nMem = 8;
 1.98447 +        sqlite3CodeVerifySchema(pParse, iDb);
 1.98448 +        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
 1.98449 +        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
 1.98450 +        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
 1.98451 +        sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
 1.98452 +        sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
 1.98453 +        sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
 1.98454 +        sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
 1.98455 +        sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
 1.98456 +        while(pFK){
 1.98457 +          int j;
 1.98458 +          for(j=0; j<pFK->nCol; j++){
 1.98459 +            char *zCol = pFK->aCol[j].zCol;
 1.98460 +            char *zOnDelete = (char *)actionName(pFK->aAction[0]);
 1.98461 +            char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
 1.98462 +            sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
 1.98463 +            sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
 1.98464 +            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
 1.98465 +            sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
 1.98466 +                              pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
 1.98467 +            sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
 1.98468 +            sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
 1.98469 +            sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
 1.98470 +            sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
 1.98471 +            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
 1.98472 +          }
 1.98473 +          ++i;
 1.98474 +          pFK = pFK->pNextFrom;
 1.98475 +        }
 1.98476 +      }
 1.98477 +    }
 1.98478 +  }
 1.98479 +  break;
 1.98480 +#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
 1.98481 +
 1.98482 +#ifndef SQLITE_OMIT_FOREIGN_KEY
 1.98483 +#ifndef SQLITE_OMIT_TRIGGER
 1.98484 +  case PragTyp_FOREIGN_KEY_CHECK: {
 1.98485 +    FKey *pFK;             /* A foreign key constraint */
 1.98486 +    Table *pTab;           /* Child table contain "REFERENCES" keyword */
 1.98487 +    Table *pParent;        /* Parent table that child points to */
 1.98488 +    Index *pIdx;           /* Index in the parent table */
 1.98489 +    int i;                 /* Loop counter:  Foreign key number for pTab */
 1.98490 +    int j;                 /* Loop counter:  Field of the foreign key */
 1.98491 +    HashElem *k;           /* Loop counter:  Next table in schema */
 1.98492 +    int x;                 /* result variable */
 1.98493 +    int regResult;         /* 3 registers to hold a result row */
 1.98494 +    int regKey;            /* Register to hold key for checking the FK */
 1.98495 +    int regRow;            /* Registers to hold a row from pTab */
 1.98496 +    int addrTop;           /* Top of a loop checking foreign keys */
 1.98497 +    int addrOk;            /* Jump here if the key is OK */
 1.98498 +    int *aiCols;           /* child to parent column mapping */
 1.98499 +
 1.98500 +    regResult = pParse->nMem+1;
 1.98501 +    pParse->nMem += 4;
 1.98502 +    regKey = ++pParse->nMem;
 1.98503 +    regRow = ++pParse->nMem;
 1.98504 +    v = sqlite3GetVdbe(pParse);
 1.98505 +    sqlite3VdbeSetNumCols(v, 4);
 1.98506 +    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
 1.98507 +    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
 1.98508 +    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
 1.98509 +    sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
 1.98510 +    sqlite3CodeVerifySchema(pParse, iDb);
 1.98511 +    k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
 1.98512 +    while( k ){
 1.98513 +      if( zRight ){
 1.98514 +        pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
 1.98515 +        k = 0;
 1.98516 +      }else{
 1.98517 +        pTab = (Table*)sqliteHashData(k);
 1.98518 +        k = sqliteHashNext(k);
 1.98519 +      }
 1.98520 +      if( pTab==0 || pTab->pFKey==0 ) continue;
 1.98521 +      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
 1.98522 +      if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
 1.98523 +      sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
 1.98524 +      sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
 1.98525 +                        P4_TRANSIENT);
 1.98526 +      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
 1.98527 +        pParent = sqlite3FindTable(db, pFK->zTo, zDb);
 1.98528 +        if( pParent==0 ) continue;
 1.98529 +        pIdx = 0;
 1.98530 +        sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
 1.98531 +        x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
 1.98532 +        if( x==0 ){
 1.98533 +          if( pIdx==0 ){
 1.98534 +            sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
 1.98535 +          }else{
 1.98536 +            sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
 1.98537 +            sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
 1.98538 +          }
 1.98539 +        }else{
 1.98540 +          k = 0;
 1.98541 +          break;
 1.98542 +        }
 1.98543 +      }
 1.98544 +      assert( pParse->nErr>0 || pFK==0 );
 1.98545 +      if( pFK ) break;
 1.98546 +      if( pParse->nTab<i ) pParse->nTab = i;
 1.98547 +      addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
 1.98548 +      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
 1.98549 +        pParent = sqlite3FindTable(db, pFK->zTo, zDb);
 1.98550 +        pIdx = 0;
 1.98551 +        aiCols = 0;
 1.98552 +        if( pParent ){
 1.98553 +          x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
 1.98554 +          assert( x==0 );
 1.98555 +        }
 1.98556 +        addrOk = sqlite3VdbeMakeLabel(v);
 1.98557 +        if( pParent && pIdx==0 ){
 1.98558 +          int iKey = pFK->aCol[0].iFrom;
 1.98559 +          assert( iKey>=0 && iKey<pTab->nCol );
 1.98560 +          if( iKey!=pTab->iPKey ){
 1.98561 +            sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
 1.98562 +            sqlite3ColumnDefault(v, pTab, iKey, regRow);
 1.98563 +            sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
 1.98564 +            sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow, 
 1.98565 +               sqlite3VdbeCurrentAddr(v)+3); VdbeCoverage(v);
 1.98566 +          }else{
 1.98567 +            sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
 1.98568 +          }
 1.98569 +          sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
 1.98570 +          sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
 1.98571 +          sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
 1.98572 +        }else{
 1.98573 +          for(j=0; j<pFK->nCol; j++){
 1.98574 +            sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
 1.98575 +                            aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
 1.98576 +            sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
 1.98577 +          }
 1.98578 +          if( pParent ){
 1.98579 +            sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
 1.98580 +                              sqlite3IndexAffinityStr(v,pIdx), pFK->nCol);
 1.98581 +            sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
 1.98582 +            VdbeCoverage(v);
 1.98583 +          }
 1.98584 +        }
 1.98585 +        sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
 1.98586 +        sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0, 
 1.98587 +                          pFK->zTo, P4_TRANSIENT);
 1.98588 +        sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
 1.98589 +        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
 1.98590 +        sqlite3VdbeResolveLabel(v, addrOk);
 1.98591 +        sqlite3DbFree(db, aiCols);
 1.98592 +      }
 1.98593 +      sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
 1.98594 +      sqlite3VdbeJumpHere(v, addrTop);
 1.98595 +    }
 1.98596 +  }
 1.98597 +  break;
 1.98598 +#endif /* !defined(SQLITE_OMIT_TRIGGER) */
 1.98599 +#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
 1.98600 +
 1.98601 +#ifndef NDEBUG
 1.98602 +  case PragTyp_PARSER_TRACE: {
 1.98603 +    if( zRight ){
 1.98604 +      if( sqlite3GetBoolean(zRight, 0) ){
 1.98605 +        sqlite3ParserTrace(stderr, "parser: ");
 1.98606 +      }else{
 1.98607 +        sqlite3ParserTrace(0, 0);
 1.98608 +      }
 1.98609 +    }
 1.98610 +  }
 1.98611 +  break;
 1.98612 +#endif
 1.98613 +
 1.98614 +  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
 1.98615 +  ** used will be case sensitive or not depending on the RHS.
 1.98616 +  */
 1.98617 +  case PragTyp_CASE_SENSITIVE_LIKE: {
 1.98618 +    if( zRight ){
 1.98619 +      sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
 1.98620 +    }
 1.98621 +  }
 1.98622 +  break;
 1.98623 +
 1.98624 +#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
 1.98625 +# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
 1.98626 +#endif
 1.98627 +
 1.98628 +#ifndef SQLITE_OMIT_INTEGRITY_CHECK
 1.98629 +  /* Pragma "quick_check" is reduced version of 
 1.98630 +  ** integrity_check designed to detect most database corruption
 1.98631 +  ** without most of the overhead of a full integrity-check.
 1.98632 +  */
 1.98633 +  case PragTyp_INTEGRITY_CHECK: {
 1.98634 +    int i, j, addr, mxErr;
 1.98635 +
 1.98636 +    /* Code that appears at the end of the integrity check.  If no error
 1.98637 +    ** messages have been generated, output OK.  Otherwise output the
 1.98638 +    ** error message
 1.98639 +    */
 1.98640 +    static const int iLn = VDBE_OFFSET_LINENO(2);
 1.98641 +    static const VdbeOpList endCode[] = {
 1.98642 +      { OP_AddImm,      1, 0,        0},    /* 0 */
 1.98643 +      { OP_IfNeg,       1, 0,        0},    /* 1 */
 1.98644 +      { OP_String8,     0, 3,        0},    /* 2 */
 1.98645 +      { OP_ResultRow,   3, 1,        0},
 1.98646 +    };
 1.98647 +
 1.98648 +    int isQuick = (sqlite3Tolower(zLeft[0])=='q');
 1.98649 +
 1.98650 +    /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
 1.98651 +    ** then iDb is set to the index of the database identified by <db>.
 1.98652 +    ** In this case, the integrity of database iDb only is verified by
 1.98653 +    ** the VDBE created below.
 1.98654 +    **
 1.98655 +    ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
 1.98656 +    ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
 1.98657 +    ** to -1 here, to indicate that the VDBE should verify the integrity
 1.98658 +    ** of all attached databases.  */
 1.98659 +    assert( iDb>=0 );
 1.98660 +    assert( iDb==0 || pId2->z );
 1.98661 +    if( pId2->z==0 ) iDb = -1;
 1.98662 +
 1.98663 +    /* Initialize the VDBE program */
 1.98664 +    pParse->nMem = 6;
 1.98665 +    sqlite3VdbeSetNumCols(v, 1);
 1.98666 +    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
 1.98667 +
 1.98668 +    /* Set the maximum error count */
 1.98669 +    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
 1.98670 +    if( zRight ){
 1.98671 +      sqlite3GetInt32(zRight, &mxErr);
 1.98672 +      if( mxErr<=0 ){
 1.98673 +        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
 1.98674 +      }
 1.98675 +    }
 1.98676 +    sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
 1.98677 +
 1.98678 +    /* Do an integrity check on each database file */
 1.98679 +    for(i=0; i<db->nDb; i++){
 1.98680 +      HashElem *x;
 1.98681 +      Hash *pTbls;
 1.98682 +      int cnt = 0;
 1.98683 +
 1.98684 +      if( OMIT_TEMPDB && i==1 ) continue;
 1.98685 +      if( iDb>=0 && i!=iDb ) continue;
 1.98686 +
 1.98687 +      sqlite3CodeVerifySchema(pParse, i);
 1.98688 +      addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
 1.98689 +      VdbeCoverage(v);
 1.98690 +      sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
 1.98691 +      sqlite3VdbeJumpHere(v, addr);
 1.98692 +
 1.98693 +      /* Do an integrity check of the B-Tree
 1.98694 +      **
 1.98695 +      ** Begin by filling registers 2, 3, ... with the root pages numbers
 1.98696 +      ** for all tables and indices in the database.
 1.98697 +      */
 1.98698 +      assert( sqlite3SchemaMutexHeld(db, i, 0) );
 1.98699 +      pTbls = &db->aDb[i].pSchema->tblHash;
 1.98700 +      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
 1.98701 +        Table *pTab = sqliteHashData(x);
 1.98702 +        Index *pIdx;
 1.98703 +        if( HasRowid(pTab) ){
 1.98704 +          sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
 1.98705 +          VdbeComment((v, "%s", pTab->zName));
 1.98706 +          cnt++;
 1.98707 +        }
 1.98708 +        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
 1.98709 +          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
 1.98710 +          VdbeComment((v, "%s", pIdx->zName));
 1.98711 +          cnt++;
 1.98712 +        }
 1.98713 +      }
 1.98714 +
 1.98715 +      /* Make sure sufficient number of registers have been allocated */
 1.98716 +      pParse->nMem = MAX( pParse->nMem, cnt+8 );
 1.98717 +
 1.98718 +      /* Do the b-tree integrity checks */
 1.98719 +      sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
 1.98720 +      sqlite3VdbeChangeP5(v, (u8)i);
 1.98721 +      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
 1.98722 +      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
 1.98723 +         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
 1.98724 +         P4_DYNAMIC);
 1.98725 +      sqlite3VdbeAddOp2(v, OP_Move, 2, 4);
 1.98726 +      sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
 1.98727 +      sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
 1.98728 +      sqlite3VdbeJumpHere(v, addr);
 1.98729 +
 1.98730 +      /* Make sure all the indices are constructed correctly.
 1.98731 +      */
 1.98732 +      for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
 1.98733 +        Table *pTab = sqliteHashData(x);
 1.98734 +        Index *pIdx, *pPk;
 1.98735 +        Index *pPrior = 0;
 1.98736 +        int loopTop;
 1.98737 +        int iDataCur, iIdxCur;
 1.98738 +        int r1 = -1;
 1.98739 +
 1.98740 +        if( pTab->pIndex==0 ) continue;
 1.98741 +        pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
 1.98742 +        addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
 1.98743 +        VdbeCoverage(v);
 1.98744 +        sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
 1.98745 +        sqlite3VdbeJumpHere(v, addr);
 1.98746 +        sqlite3ExprCacheClear(pParse);
 1.98747 +        sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead,
 1.98748 +                                   1, 0, &iDataCur, &iIdxCur);
 1.98749 +        sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
 1.98750 +        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
 1.98751 +          sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
 1.98752 +        }
 1.98753 +        pParse->nMem = MAX(pParse->nMem, 8+j);
 1.98754 +        sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
 1.98755 +        loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
 1.98756 +        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
 1.98757 +          int jmp2, jmp3, jmp4;
 1.98758 +          if( pPk==pIdx ) continue;
 1.98759 +          r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
 1.98760 +                                       pPrior, r1);
 1.98761 +          pPrior = pIdx;
 1.98762 +          sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);  /* increment entry count */
 1.98763 +          jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, 0, r1,
 1.98764 +                                      pIdx->nColumn); VdbeCoverage(v);
 1.98765 +          sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
 1.98766 +          sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, "row ", P4_STATIC);
 1.98767 +          sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
 1.98768 +          sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0, " missing from index ",
 1.98769 +                            P4_STATIC);
 1.98770 +          sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
 1.98771 +          sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0, pIdx->zName, P4_TRANSIENT);
 1.98772 +          sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
 1.98773 +          sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
 1.98774 +          jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
 1.98775 +          sqlite3VdbeAddOp0(v, OP_Halt);
 1.98776 +          sqlite3VdbeJumpHere(v, jmp4);
 1.98777 +          sqlite3VdbeJumpHere(v, jmp2);
 1.98778 +          sqlite3VdbeResolveLabel(v, jmp3);
 1.98779 +        }
 1.98780 +        sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
 1.98781 +        sqlite3VdbeJumpHere(v, loopTop-1);
 1.98782 +#ifndef SQLITE_OMIT_BTREECOUNT
 1.98783 +        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, 
 1.98784 +                     "wrong # of entries in index ", P4_STATIC);
 1.98785 +        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
 1.98786 +          if( pPk==pIdx ) continue;
 1.98787 +          addr = sqlite3VdbeCurrentAddr(v);
 1.98788 +          sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
 1.98789 +          sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
 1.98790 +          sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
 1.98791 +          sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
 1.98792 +          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
 1.98793 +          sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
 1.98794 +          sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
 1.98795 +          sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
 1.98796 +          sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
 1.98797 +        }
 1.98798 +#endif /* SQLITE_OMIT_BTREECOUNT */
 1.98799 +      } 
 1.98800 +    }
 1.98801 +    addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
 1.98802 +    sqlite3VdbeChangeP2(v, addr, -mxErr);
 1.98803 +    sqlite3VdbeJumpHere(v, addr+1);
 1.98804 +    sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
 1.98805 +  }
 1.98806 +  break;
 1.98807 +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
 1.98808 +
 1.98809 +#ifndef SQLITE_OMIT_UTF16
 1.98810 +  /*
 1.98811 +  **   PRAGMA encoding
 1.98812 +  **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
 1.98813 +  **
 1.98814 +  ** In its first form, this pragma returns the encoding of the main
 1.98815 +  ** database. If the database is not initialized, it is initialized now.
 1.98816 +  **
 1.98817 +  ** The second form of this pragma is a no-op if the main database file
 1.98818 +  ** has not already been initialized. In this case it sets the default
 1.98819 +  ** encoding that will be used for the main database file if a new file
 1.98820 +  ** is created. If an existing main database file is opened, then the
 1.98821 +  ** default text encoding for the existing database is used.
 1.98822 +  ** 
 1.98823 +  ** In all cases new databases created using the ATTACH command are
 1.98824 +  ** created to use the same default text encoding as the main database. If
 1.98825 +  ** the main database has not been initialized and/or created when ATTACH
 1.98826 +  ** is executed, this is done before the ATTACH operation.
 1.98827 +  **
 1.98828 +  ** In the second form this pragma sets the text encoding to be used in
 1.98829 +  ** new database files created using this database handle. It is only
 1.98830 +  ** useful if invoked immediately after the main database i
 1.98831 +  */
 1.98832 +  case PragTyp_ENCODING: {
 1.98833 +    static const struct EncName {
 1.98834 +      char *zName;
 1.98835 +      u8 enc;
 1.98836 +    } encnames[] = {
 1.98837 +      { "UTF8",     SQLITE_UTF8        },
 1.98838 +      { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
 1.98839 +      { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
 1.98840 +      { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
 1.98841 +      { "UTF16le",  SQLITE_UTF16LE     },
 1.98842 +      { "UTF16be",  SQLITE_UTF16BE     },
 1.98843 +      { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
 1.98844 +      { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
 1.98845 +      { 0, 0 }
 1.98846 +    };
 1.98847 +    const struct EncName *pEnc;
 1.98848 +    if( !zRight ){    /* "PRAGMA encoding" */
 1.98849 +      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
 1.98850 +      sqlite3VdbeSetNumCols(v, 1);
 1.98851 +      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
 1.98852 +      sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
 1.98853 +      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
 1.98854 +      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
 1.98855 +      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
 1.98856 +      sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
 1.98857 +      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
 1.98858 +    }else{                        /* "PRAGMA encoding = XXX" */
 1.98859 +      /* Only change the value of sqlite.enc if the database handle is not
 1.98860 +      ** initialized. If the main database exists, the new sqlite.enc value
 1.98861 +      ** will be overwritten when the schema is next loaded. If it does not
 1.98862 +      ** already exists, it will be created to use the new encoding value.
 1.98863 +      */
 1.98864 +      if( 
 1.98865 +        !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
 1.98866 +        DbHasProperty(db, 0, DB_Empty) 
 1.98867 +      ){
 1.98868 +        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
 1.98869 +          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
 1.98870 +            ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
 1.98871 +            break;
 1.98872 +          }
 1.98873 +        }
 1.98874 +        if( !pEnc->zName ){
 1.98875 +          sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
 1.98876 +        }
 1.98877 +      }
 1.98878 +    }
 1.98879 +  }
 1.98880 +  break;
 1.98881 +#endif /* SQLITE_OMIT_UTF16 */
 1.98882 +
 1.98883 +#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
 1.98884 +  /*
 1.98885 +  **   PRAGMA [database.]schema_version
 1.98886 +  **   PRAGMA [database.]schema_version = <integer>
 1.98887 +  **
 1.98888 +  **   PRAGMA [database.]user_version
 1.98889 +  **   PRAGMA [database.]user_version = <integer>
 1.98890 +  **
 1.98891 +  **   PRAGMA [database.]freelist_count = <integer>
 1.98892 +  **
 1.98893 +  **   PRAGMA [database.]application_id
 1.98894 +  **   PRAGMA [database.]application_id = <integer>
 1.98895 +  **
 1.98896 +  ** The pragma's schema_version and user_version are used to set or get
 1.98897 +  ** the value of the schema-version and user-version, respectively. Both
 1.98898 +  ** the schema-version and the user-version are 32-bit signed integers
 1.98899 +  ** stored in the database header.
 1.98900 +  **
 1.98901 +  ** The schema-cookie is usually only manipulated internally by SQLite. It
 1.98902 +  ** is incremented by SQLite whenever the database schema is modified (by
 1.98903 +  ** creating or dropping a table or index). The schema version is used by
 1.98904 +  ** SQLite each time a query is executed to ensure that the internal cache
 1.98905 +  ** of the schema used when compiling the SQL query matches the schema of
 1.98906 +  ** the database against which the compiled query is actually executed.
 1.98907 +  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
 1.98908 +  ** the schema-version is potentially dangerous and may lead to program
 1.98909 +  ** crashes or database corruption. Use with caution!
 1.98910 +  **
 1.98911 +  ** The user-version is not used internally by SQLite. It may be used by
 1.98912 +  ** applications for any purpose.
 1.98913 +  */
 1.98914 +  case PragTyp_HEADER_VALUE: {
 1.98915 +    int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
 1.98916 +    sqlite3VdbeUsesBtree(v, iDb);
 1.98917 +    switch( zLeft[0] ){
 1.98918 +      case 'a': case 'A':
 1.98919 +        iCookie = BTREE_APPLICATION_ID;
 1.98920 +        break;
 1.98921 +      case 'f': case 'F':
 1.98922 +        iCookie = BTREE_FREE_PAGE_COUNT;
 1.98923 +        break;
 1.98924 +      case 's': case 'S':
 1.98925 +        iCookie = BTREE_SCHEMA_VERSION;
 1.98926 +        break;
 1.98927 +      default:
 1.98928 +        iCookie = BTREE_USER_VERSION;
 1.98929 +        break;
 1.98930 +    }
 1.98931 +
 1.98932 +    if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
 1.98933 +      /* Write the specified cookie value */
 1.98934 +      static const VdbeOpList setCookie[] = {
 1.98935 +        { OP_Transaction,    0,  1,  0},    /* 0 */
 1.98936 +        { OP_Integer,        0,  1,  0},    /* 1 */
 1.98937 +        { OP_SetCookie,      0,  0,  1},    /* 2 */
 1.98938 +      };
 1.98939 +      int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
 1.98940 +      sqlite3VdbeChangeP1(v, addr, iDb);
 1.98941 +      sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
 1.98942 +      sqlite3VdbeChangeP1(v, addr+2, iDb);
 1.98943 +      sqlite3VdbeChangeP2(v, addr+2, iCookie);
 1.98944 +    }else{
 1.98945 +      /* Read the specified cookie value */
 1.98946 +      static const VdbeOpList readCookie[] = {
 1.98947 +        { OP_Transaction,     0,  0,  0},    /* 0 */
 1.98948 +        { OP_ReadCookie,      0,  1,  0},    /* 1 */
 1.98949 +        { OP_ResultRow,       1,  1,  0}
 1.98950 +      };
 1.98951 +      int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie, 0);
 1.98952 +      sqlite3VdbeChangeP1(v, addr, iDb);
 1.98953 +      sqlite3VdbeChangeP1(v, addr+1, iDb);
 1.98954 +      sqlite3VdbeChangeP3(v, addr+1, iCookie);
 1.98955 +      sqlite3VdbeSetNumCols(v, 1);
 1.98956 +      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
 1.98957 +    }
 1.98958 +  }
 1.98959 +  break;
 1.98960 +#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
 1.98961 +
 1.98962 +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
 1.98963 +  /*
 1.98964 +  **   PRAGMA compile_options
 1.98965 +  **
 1.98966 +  ** Return the names of all compile-time options used in this build,
 1.98967 +  ** one option per row.
 1.98968 +  */
 1.98969 +  case PragTyp_COMPILE_OPTIONS: {
 1.98970 +    int i = 0;
 1.98971 +    const char *zOpt;
 1.98972 +    sqlite3VdbeSetNumCols(v, 1);
 1.98973 +    pParse->nMem = 1;
 1.98974 +    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
 1.98975 +    while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
 1.98976 +      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
 1.98977 +      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
 1.98978 +    }
 1.98979 +  }
 1.98980 +  break;
 1.98981 +#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
 1.98982 +
 1.98983 +#ifndef SQLITE_OMIT_WAL
 1.98984 +  /*
 1.98985 +  **   PRAGMA [database.]wal_checkpoint = passive|full|restart
 1.98986 +  **
 1.98987 +  ** Checkpoint the database.
 1.98988 +  */
 1.98989 +  case PragTyp_WAL_CHECKPOINT: {
 1.98990 +    int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
 1.98991 +    int eMode = SQLITE_CHECKPOINT_PASSIVE;
 1.98992 +    if( zRight ){
 1.98993 +      if( sqlite3StrICmp(zRight, "full")==0 ){
 1.98994 +        eMode = SQLITE_CHECKPOINT_FULL;
 1.98995 +      }else if( sqlite3StrICmp(zRight, "restart")==0 ){
 1.98996 +        eMode = SQLITE_CHECKPOINT_RESTART;
 1.98997 +      }
 1.98998 +    }
 1.98999 +    sqlite3VdbeSetNumCols(v, 3);
 1.99000 +    pParse->nMem = 3;
 1.99001 +    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
 1.99002 +    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
 1.99003 +    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
 1.99004 +
 1.99005 +    sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
 1.99006 +    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
 1.99007 +  }
 1.99008 +  break;
 1.99009 +
 1.99010 +  /*
 1.99011 +  **   PRAGMA wal_autocheckpoint
 1.99012 +  **   PRAGMA wal_autocheckpoint = N
 1.99013 +  **
 1.99014 +  ** Configure a database connection to automatically checkpoint a database
 1.99015 +  ** after accumulating N frames in the log. Or query for the current value
 1.99016 +  ** of N.
 1.99017 +  */
 1.99018 +  case PragTyp_WAL_AUTOCHECKPOINT: {
 1.99019 +    if( zRight ){
 1.99020 +      sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
 1.99021 +    }
 1.99022 +    returnSingleInt(pParse, "wal_autocheckpoint", 
 1.99023 +       db->xWalCallback==sqlite3WalDefaultHook ? 
 1.99024 +           SQLITE_PTR_TO_INT(db->pWalArg) : 0);
 1.99025 +  }
 1.99026 +  break;
 1.99027 +#endif
 1.99028 +
 1.99029 +  /*
 1.99030 +  **  PRAGMA shrink_memory
 1.99031 +  **
 1.99032 +  ** This pragma attempts to free as much memory as possible from the
 1.99033 +  ** current database connection.
 1.99034 +  */
 1.99035 +  case PragTyp_SHRINK_MEMORY: {
 1.99036 +    sqlite3_db_release_memory(db);
 1.99037 +    break;
 1.99038 +  }
 1.99039 +
 1.99040 +  /*
 1.99041 +  **   PRAGMA busy_timeout
 1.99042 +  **   PRAGMA busy_timeout = N
 1.99043 +  **
 1.99044 +  ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
 1.99045 +  ** if one is set.  If no busy handler or a different busy handler is set
 1.99046 +  ** then 0 is returned.  Setting the busy_timeout to 0 or negative
 1.99047 +  ** disables the timeout.
 1.99048 +  */
 1.99049 +  /*case PragTyp_BUSY_TIMEOUT*/ default: {
 1.99050 +    assert( aPragmaNames[mid].ePragTyp==PragTyp_BUSY_TIMEOUT );
 1.99051 +    if( zRight ){
 1.99052 +      sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
 1.99053 +    }
 1.99054 +    returnSingleInt(pParse, "timeout",  db->busyTimeout);
 1.99055 +    break;
 1.99056 +  }
 1.99057 +
 1.99058 +  /*
 1.99059 +  **   PRAGMA soft_heap_limit
 1.99060 +  **   PRAGMA soft_heap_limit = N
 1.99061 +  **
 1.99062 +  ** Call sqlite3_soft_heap_limit64(N).  Return the result.  If N is omitted,
 1.99063 +  ** use -1.
 1.99064 +  */
 1.99065 +  case PragTyp_SOFT_HEAP_LIMIT: {
 1.99066 +    sqlite3_int64 N;
 1.99067 +    if( zRight && sqlite3Atoi64(zRight, &N, 1000000, SQLITE_UTF8)==SQLITE_OK ){
 1.99068 +      sqlite3_soft_heap_limit64(N);
 1.99069 +    }
 1.99070 +    returnSingleInt(pParse, "soft_heap_limit",  sqlite3_soft_heap_limit64(-1));
 1.99071 +    break;
 1.99072 +  }
 1.99073 +
 1.99074 +#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
 1.99075 +  /*
 1.99076 +  ** Report the current state of file logs for all databases
 1.99077 +  */
 1.99078 +  case PragTyp_LOCK_STATUS: {
 1.99079 +    static const char *const azLockName[] = {
 1.99080 +      "unlocked", "shared", "reserved", "pending", "exclusive"
 1.99081 +    };
 1.99082 +    int i;
 1.99083 +    sqlite3VdbeSetNumCols(v, 2);
 1.99084 +    pParse->nMem = 2;
 1.99085 +    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
 1.99086 +    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
 1.99087 +    for(i=0; i<db->nDb; i++){
 1.99088 +      Btree *pBt;
 1.99089 +      const char *zState = "unknown";
 1.99090 +      int j;
 1.99091 +      if( db->aDb[i].zName==0 ) continue;
 1.99092 +      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
 1.99093 +      pBt = db->aDb[i].pBt;
 1.99094 +      if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
 1.99095 +        zState = "closed";
 1.99096 +      }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
 1.99097 +                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
 1.99098 +         zState = azLockName[j];
 1.99099 +      }
 1.99100 +      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
 1.99101 +      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
 1.99102 +    }
 1.99103 +    break;
 1.99104 +  }
 1.99105 +#endif
 1.99106 +
 1.99107 +#ifdef SQLITE_HAS_CODEC
 1.99108 +  case PragTyp_KEY: {
 1.99109 +    if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
 1.99110 +    break;
 1.99111 +  }
 1.99112 +  case PragTyp_REKEY: {
 1.99113 +    if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
 1.99114 +    break;
 1.99115 +  }
 1.99116 +  case PragTyp_HEXKEY: {
 1.99117 +    if( zRight ){
 1.99118 +      u8 iByte;
 1.99119 +      int i;
 1.99120 +      char zKey[40];
 1.99121 +      for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
 1.99122 +        iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
 1.99123 +        if( (i&1)!=0 ) zKey[i/2] = iByte;
 1.99124 +      }
 1.99125 +      if( (zLeft[3] & 0xf)==0xb ){
 1.99126 +        sqlite3_key_v2(db, zDb, zKey, i/2);
 1.99127 +      }else{
 1.99128 +        sqlite3_rekey_v2(db, zDb, zKey, i/2);
 1.99129 +      }
 1.99130 +    }
 1.99131 +    break;
 1.99132 +  }
 1.99133 +#endif
 1.99134 +#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
 1.99135 +  case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
 1.99136 +#ifdef SQLITE_HAS_CODEC
 1.99137 +    if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
 1.99138 +      sqlite3_activate_see(&zRight[4]);
 1.99139 +    }
 1.99140 +#endif
 1.99141 +#ifdef SQLITE_ENABLE_CEROD
 1.99142 +    if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
 1.99143 +      sqlite3_activate_cerod(&zRight[6]);
 1.99144 +    }
 1.99145 +#endif
 1.99146 +  }
 1.99147 +  break;
 1.99148 +#endif
 1.99149 +
 1.99150 +  } /* End of the PRAGMA switch */
 1.99151 +
 1.99152 +pragma_out:
 1.99153 +  sqlite3DbFree(db, zLeft);
 1.99154 +  sqlite3DbFree(db, zRight);
 1.99155 +}
 1.99156 +
 1.99157 +#endif /* SQLITE_OMIT_PRAGMA */
 1.99158 +
 1.99159 +/************** End of pragma.c **********************************************/
 1.99160 +/************** Begin file prepare.c *****************************************/
 1.99161 +/*
 1.99162 +** 2005 May 25
 1.99163 +**
 1.99164 +** The author disclaims copyright to this source code.  In place of
 1.99165 +** a legal notice, here is a blessing:
 1.99166 +**
 1.99167 +**    May you do good and not evil.
 1.99168 +**    May you find forgiveness for yourself and forgive others.
 1.99169 +**    May you share freely, never taking more than you give.
 1.99170 +**
 1.99171 +*************************************************************************
 1.99172 +** This file contains the implementation of the sqlite3_prepare()
 1.99173 +** interface, and routines that contribute to loading the database schema
 1.99174 +** from disk.
 1.99175 +*/
 1.99176 +
 1.99177 +/*
 1.99178 +** Fill the InitData structure with an error message that indicates
 1.99179 +** that the database is corrupt.
 1.99180 +*/
 1.99181 +static void corruptSchema(
 1.99182 +  InitData *pData,     /* Initialization context */
 1.99183 +  const char *zObj,    /* Object being parsed at the point of error */
 1.99184 +  const char *zExtra   /* Error information */
 1.99185 +){
 1.99186 +  sqlite3 *db = pData->db;
 1.99187 +  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
 1.99188 +    if( zObj==0 ) zObj = "?";
 1.99189 +    sqlite3SetString(pData->pzErrMsg, db,
 1.99190 +      "malformed database schema (%s)", zObj);
 1.99191 +    if( zExtra ){
 1.99192 +      *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, 
 1.99193 +                                 "%s - %s", *pData->pzErrMsg, zExtra);
 1.99194 +    }
 1.99195 +  }
 1.99196 +  pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
 1.99197 +}
 1.99198 +
 1.99199 +/*
 1.99200 +** This is the callback routine for the code that initializes the
 1.99201 +** database.  See sqlite3Init() below for additional information.
 1.99202 +** This routine is also called from the OP_ParseSchema opcode of the VDBE.
 1.99203 +**
 1.99204 +** Each callback contains the following information:
 1.99205 +**
 1.99206 +**     argv[0] = name of thing being created
 1.99207 +**     argv[1] = root page number for table or index. 0 for trigger or view.
 1.99208 +**     argv[2] = SQL text for the CREATE statement.
 1.99209 +**
 1.99210 +*/
 1.99211 +SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
 1.99212 +  InitData *pData = (InitData*)pInit;
 1.99213 +  sqlite3 *db = pData->db;
 1.99214 +  int iDb = pData->iDb;
 1.99215 +
 1.99216 +  assert( argc==3 );
 1.99217 +  UNUSED_PARAMETER2(NotUsed, argc);
 1.99218 +  assert( sqlite3_mutex_held(db->mutex) );
 1.99219 +  DbClearProperty(db, iDb, DB_Empty);
 1.99220 +  if( db->mallocFailed ){
 1.99221 +    corruptSchema(pData, argv[0], 0);
 1.99222 +    return 1;
 1.99223 +  }
 1.99224 +
 1.99225 +  assert( iDb>=0 && iDb<db->nDb );
 1.99226 +  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
 1.99227 +  if( argv[1]==0 ){
 1.99228 +    corruptSchema(pData, argv[0], 0);
 1.99229 +  }else if( argv[2] && argv[2][0] ){
 1.99230 +    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
 1.99231 +    ** But because db->init.busy is set to 1, no VDBE code is generated
 1.99232 +    ** or executed.  All the parser does is build the internal data
 1.99233 +    ** structures that describe the table, index, or view.
 1.99234 +    */
 1.99235 +    int rc;
 1.99236 +    sqlite3_stmt *pStmt;
 1.99237 +    TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
 1.99238 +
 1.99239 +    assert( db->init.busy );
 1.99240 +    db->init.iDb = iDb;
 1.99241 +    db->init.newTnum = sqlite3Atoi(argv[1]);
 1.99242 +    db->init.orphanTrigger = 0;
 1.99243 +    TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
 1.99244 +    rc = db->errCode;
 1.99245 +    assert( (rc&0xFF)==(rcp&0xFF) );
 1.99246 +    db->init.iDb = 0;
 1.99247 +    if( SQLITE_OK!=rc ){
 1.99248 +      if( db->init.orphanTrigger ){
 1.99249 +        assert( iDb==1 );
 1.99250 +      }else{
 1.99251 +        pData->rc = rc;
 1.99252 +        if( rc==SQLITE_NOMEM ){
 1.99253 +          db->mallocFailed = 1;
 1.99254 +        }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
 1.99255 +          corruptSchema(pData, argv[0], sqlite3_errmsg(db));
 1.99256 +        }
 1.99257 +      }
 1.99258 +    }
 1.99259 +    sqlite3_finalize(pStmt);
 1.99260 +  }else if( argv[0]==0 ){
 1.99261 +    corruptSchema(pData, 0, 0);
 1.99262 +  }else{
 1.99263 +    /* If the SQL column is blank it means this is an index that
 1.99264 +    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
 1.99265 +    ** constraint for a CREATE TABLE.  The index should have already
 1.99266 +    ** been created when we processed the CREATE TABLE.  All we have
 1.99267 +    ** to do here is record the root page number for that index.
 1.99268 +    */
 1.99269 +    Index *pIndex;
 1.99270 +    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
 1.99271 +    if( pIndex==0 ){
 1.99272 +      /* This can occur if there exists an index on a TEMP table which
 1.99273 +      ** has the same name as another index on a permanent index.  Since
 1.99274 +      ** the permanent table is hidden by the TEMP table, we can also
 1.99275 +      ** safely ignore the index on the permanent table.
 1.99276 +      */
 1.99277 +      /* Do Nothing */;
 1.99278 +    }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
 1.99279 +      corruptSchema(pData, argv[0], "invalid rootpage");
 1.99280 +    }
 1.99281 +  }
 1.99282 +  return 0;
 1.99283 +}
 1.99284 +
 1.99285 +/*
 1.99286 +** Attempt to read the database schema and initialize internal
 1.99287 +** data structures for a single database file.  The index of the
 1.99288 +** database file is given by iDb.  iDb==0 is used for the main
 1.99289 +** database.  iDb==1 should never be used.  iDb>=2 is used for
 1.99290 +** auxiliary databases.  Return one of the SQLITE_ error codes to
 1.99291 +** indicate success or failure.
 1.99292 +*/
 1.99293 +static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
 1.99294 +  int rc;
 1.99295 +  int i;
 1.99296 +#ifndef SQLITE_OMIT_DEPRECATED
 1.99297 +  int size;
 1.99298 +#endif
 1.99299 +  Table *pTab;
 1.99300 +  Db *pDb;
 1.99301 +  char const *azArg[4];
 1.99302 +  int meta[5];
 1.99303 +  InitData initData;
 1.99304 +  char const *zMasterSchema;
 1.99305 +  char const *zMasterName;
 1.99306 +  int openedTransaction = 0;
 1.99307 +
 1.99308 +  /*
 1.99309 +  ** The master database table has a structure like this
 1.99310 +  */
 1.99311 +  static const char master_schema[] = 
 1.99312 +     "CREATE TABLE sqlite_master(\n"
 1.99313 +     "  type text,\n"
 1.99314 +     "  name text,\n"
 1.99315 +     "  tbl_name text,\n"
 1.99316 +     "  rootpage integer,\n"
 1.99317 +     "  sql text\n"
 1.99318 +     ")"
 1.99319 +  ;
 1.99320 +#ifndef SQLITE_OMIT_TEMPDB
 1.99321 +  static const char temp_master_schema[] = 
 1.99322 +     "CREATE TEMP TABLE sqlite_temp_master(\n"
 1.99323 +     "  type text,\n"
 1.99324 +     "  name text,\n"
 1.99325 +     "  tbl_name text,\n"
 1.99326 +     "  rootpage integer,\n"
 1.99327 +     "  sql text\n"
 1.99328 +     ")"
 1.99329 +  ;
 1.99330 +#else
 1.99331 +  #define temp_master_schema 0
 1.99332 +#endif
 1.99333 +
 1.99334 +  assert( iDb>=0 && iDb<db->nDb );
 1.99335 +  assert( db->aDb[iDb].pSchema );
 1.99336 +  assert( sqlite3_mutex_held(db->mutex) );
 1.99337 +  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
 1.99338 +
 1.99339 +  /* zMasterSchema and zInitScript are set to point at the master schema
 1.99340 +  ** and initialisation script appropriate for the database being
 1.99341 +  ** initialized. zMasterName is the name of the master table.
 1.99342 +  */
 1.99343 +  if( !OMIT_TEMPDB && iDb==1 ){
 1.99344 +    zMasterSchema = temp_master_schema;
 1.99345 +  }else{
 1.99346 +    zMasterSchema = master_schema;
 1.99347 +  }
 1.99348 +  zMasterName = SCHEMA_TABLE(iDb);
 1.99349 +
 1.99350 +  /* Construct the schema tables.  */
 1.99351 +  azArg[0] = zMasterName;
 1.99352 +  azArg[1] = "1";
 1.99353 +  azArg[2] = zMasterSchema;
 1.99354 +  azArg[3] = 0;
 1.99355 +  initData.db = db;
 1.99356 +  initData.iDb = iDb;
 1.99357 +  initData.rc = SQLITE_OK;
 1.99358 +  initData.pzErrMsg = pzErrMsg;
 1.99359 +  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
 1.99360 +  if( initData.rc ){
 1.99361 +    rc = initData.rc;
 1.99362 +    goto error_out;
 1.99363 +  }
 1.99364 +  pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
 1.99365 +  if( ALWAYS(pTab) ){
 1.99366 +    pTab->tabFlags |= TF_Readonly;
 1.99367 +  }
 1.99368 +
 1.99369 +  /* Create a cursor to hold the database open
 1.99370 +  */
 1.99371 +  pDb = &db->aDb[iDb];
 1.99372 +  if( pDb->pBt==0 ){
 1.99373 +    if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
 1.99374 +      DbSetProperty(db, 1, DB_SchemaLoaded);
 1.99375 +    }
 1.99376 +    return SQLITE_OK;
 1.99377 +  }
 1.99378 +
 1.99379 +  /* If there is not already a read-only (or read-write) transaction opened
 1.99380 +  ** on the b-tree database, open one now. If a transaction is opened, it 
 1.99381 +  ** will be closed before this function returns.  */
 1.99382 +  sqlite3BtreeEnter(pDb->pBt);
 1.99383 +  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
 1.99384 +    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
 1.99385 +    if( rc!=SQLITE_OK ){
 1.99386 +      sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
 1.99387 +      goto initone_error_out;
 1.99388 +    }
 1.99389 +    openedTransaction = 1;
 1.99390 +  }
 1.99391 +
 1.99392 +  /* Get the database meta information.
 1.99393 +  **
 1.99394 +  ** Meta values are as follows:
 1.99395 +  **    meta[0]   Schema cookie.  Changes with each schema change.
 1.99396 +  **    meta[1]   File format of schema layer.
 1.99397 +  **    meta[2]   Size of the page cache.
 1.99398 +  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
 1.99399 +  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
 1.99400 +  **    meta[5]   User version
 1.99401 +  **    meta[6]   Incremental vacuum mode
 1.99402 +  **    meta[7]   unused
 1.99403 +  **    meta[8]   unused
 1.99404 +  **    meta[9]   unused
 1.99405 +  **
 1.99406 +  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
 1.99407 +  ** the possible values of meta[4].
 1.99408 +  */
 1.99409 +  for(i=0; i<ArraySize(meta); i++){
 1.99410 +    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
 1.99411 +  }
 1.99412 +  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
 1.99413 +
 1.99414 +  /* If opening a non-empty database, check the text encoding. For the
 1.99415 +  ** main database, set sqlite3.enc to the encoding of the main database.
 1.99416 +  ** For an attached db, it is an error if the encoding is not the same
 1.99417 +  ** as sqlite3.enc.
 1.99418 +  */
 1.99419 +  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
 1.99420 +    if( iDb==0 ){
 1.99421 +#ifndef SQLITE_OMIT_UTF16
 1.99422 +      u8 encoding;
 1.99423 +      /* If opening the main database, set ENC(db). */
 1.99424 +      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
 1.99425 +      if( encoding==0 ) encoding = SQLITE_UTF8;
 1.99426 +      ENC(db) = encoding;
 1.99427 +#else
 1.99428 +      ENC(db) = SQLITE_UTF8;
 1.99429 +#endif
 1.99430 +    }else{
 1.99431 +      /* If opening an attached database, the encoding much match ENC(db) */
 1.99432 +      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
 1.99433 +        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
 1.99434 +            " text encoding as main database");
 1.99435 +        rc = SQLITE_ERROR;
 1.99436 +        goto initone_error_out;
 1.99437 +      }
 1.99438 +    }
 1.99439 +  }else{
 1.99440 +    DbSetProperty(db, iDb, DB_Empty);
 1.99441 +  }
 1.99442 +  pDb->pSchema->enc = ENC(db);
 1.99443 +
 1.99444 +  if( pDb->pSchema->cache_size==0 ){
 1.99445 +#ifndef SQLITE_OMIT_DEPRECATED
 1.99446 +    size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
 1.99447 +    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
 1.99448 +    pDb->pSchema->cache_size = size;
 1.99449 +#else
 1.99450 +    pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
 1.99451 +#endif
 1.99452 +    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
 1.99453 +  }
 1.99454 +
 1.99455 +  /*
 1.99456 +  ** file_format==1    Version 3.0.0.
 1.99457 +  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
 1.99458 +  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
 1.99459 +  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
 1.99460 +  */
 1.99461 +  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
 1.99462 +  if( pDb->pSchema->file_format==0 ){
 1.99463 +    pDb->pSchema->file_format = 1;
 1.99464 +  }
 1.99465 +  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
 1.99466 +    sqlite3SetString(pzErrMsg, db, "unsupported file format");
 1.99467 +    rc = SQLITE_ERROR;
 1.99468 +    goto initone_error_out;
 1.99469 +  }
 1.99470 +
 1.99471 +  /* Ticket #2804:  When we open a database in the newer file format,
 1.99472 +  ** clear the legacy_file_format pragma flag so that a VACUUM will
 1.99473 +  ** not downgrade the database and thus invalidate any descending
 1.99474 +  ** indices that the user might have created.
 1.99475 +  */
 1.99476 +  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
 1.99477 +    db->flags &= ~SQLITE_LegacyFileFmt;
 1.99478 +  }
 1.99479 +
 1.99480 +  /* Read the schema information out of the schema tables
 1.99481 +  */
 1.99482 +  assert( db->init.busy );
 1.99483 +  {
 1.99484 +    char *zSql;
 1.99485 +    zSql = sqlite3MPrintf(db, 
 1.99486 +        "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
 1.99487 +        db->aDb[iDb].zName, zMasterName);
 1.99488 +#ifndef SQLITE_OMIT_AUTHORIZATION
 1.99489 +    {
 1.99490 +      int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
 1.99491 +      xAuth = db->xAuth;
 1.99492 +      db->xAuth = 0;
 1.99493 +#endif
 1.99494 +      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
 1.99495 +#ifndef SQLITE_OMIT_AUTHORIZATION
 1.99496 +      db->xAuth = xAuth;
 1.99497 +    }
 1.99498 +#endif
 1.99499 +    if( rc==SQLITE_OK ) rc = initData.rc;
 1.99500 +    sqlite3DbFree(db, zSql);
 1.99501 +#ifndef SQLITE_OMIT_ANALYZE
 1.99502 +    if( rc==SQLITE_OK ){
 1.99503 +      sqlite3AnalysisLoad(db, iDb);
 1.99504 +    }
 1.99505 +#endif
 1.99506 +  }
 1.99507 +  if( db->mallocFailed ){
 1.99508 +    rc = SQLITE_NOMEM;
 1.99509 +    sqlite3ResetAllSchemasOfConnection(db);
 1.99510 +  }
 1.99511 +  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
 1.99512 +    /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
 1.99513 +    ** the schema loaded, even if errors occurred. In this situation the 
 1.99514 +    ** current sqlite3_prepare() operation will fail, but the following one
 1.99515 +    ** will attempt to compile the supplied statement against whatever subset
 1.99516 +    ** of the schema was loaded before the error occurred. The primary
 1.99517 +    ** purpose of this is to allow access to the sqlite_master table
 1.99518 +    ** even when its contents have been corrupted.
 1.99519 +    */
 1.99520 +    DbSetProperty(db, iDb, DB_SchemaLoaded);
 1.99521 +    rc = SQLITE_OK;
 1.99522 +  }
 1.99523 +
 1.99524 +  /* Jump here for an error that occurs after successfully allocating
 1.99525 +  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
 1.99526 +  ** before that point, jump to error_out.
 1.99527 +  */
 1.99528 +initone_error_out:
 1.99529 +  if( openedTransaction ){
 1.99530 +    sqlite3BtreeCommit(pDb->pBt);
 1.99531 +  }
 1.99532 +  sqlite3BtreeLeave(pDb->pBt);
 1.99533 +
 1.99534 +error_out:
 1.99535 +  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
 1.99536 +    db->mallocFailed = 1;
 1.99537 +  }
 1.99538 +  return rc;
 1.99539 +}
 1.99540 +
 1.99541 +/*
 1.99542 +** Initialize all database files - the main database file, the file
 1.99543 +** used to store temporary tables, and any additional database files
 1.99544 +** created using ATTACH statements.  Return a success code.  If an
 1.99545 +** error occurs, write an error message into *pzErrMsg.
 1.99546 +**
 1.99547 +** After a database is initialized, the DB_SchemaLoaded bit is set
 1.99548 +** bit is set in the flags field of the Db structure. If the database
 1.99549 +** file was of zero-length, then the DB_Empty flag is also set.
 1.99550 +*/
 1.99551 +SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
 1.99552 +  int i, rc;
 1.99553 +  int commit_internal = !(db->flags&SQLITE_InternChanges);
 1.99554 +  
 1.99555 +  assert( sqlite3_mutex_held(db->mutex) );
 1.99556 +  rc = SQLITE_OK;
 1.99557 +  db->init.busy = 1;
 1.99558 +  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
 1.99559 +    if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
 1.99560 +    rc = sqlite3InitOne(db, i, pzErrMsg);
 1.99561 +    if( rc ){
 1.99562 +      sqlite3ResetOneSchema(db, i);
 1.99563 +    }
 1.99564 +  }
 1.99565 +
 1.99566 +  /* Once all the other databases have been initialized, load the schema
 1.99567 +  ** for the TEMP database. This is loaded last, as the TEMP database
 1.99568 +  ** schema may contain references to objects in other databases.
 1.99569 +  */
 1.99570 +#ifndef SQLITE_OMIT_TEMPDB
 1.99571 +  if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
 1.99572 +                    && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
 1.99573 +    rc = sqlite3InitOne(db, 1, pzErrMsg);
 1.99574 +    if( rc ){
 1.99575 +      sqlite3ResetOneSchema(db, 1);
 1.99576 +    }
 1.99577 +  }
 1.99578 +#endif
 1.99579 +
 1.99580 +  db->init.busy = 0;
 1.99581 +  if( rc==SQLITE_OK && commit_internal ){
 1.99582 +    sqlite3CommitInternalChanges(db);
 1.99583 +  }
 1.99584 +
 1.99585 +  return rc; 
 1.99586 +}
 1.99587 +
 1.99588 +/*
 1.99589 +** This routine is a no-op if the database schema is already initialized.
 1.99590 +** Otherwise, the schema is loaded. An error code is returned.
 1.99591 +*/
 1.99592 +SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
 1.99593 +  int rc = SQLITE_OK;
 1.99594 +  sqlite3 *db = pParse->db;
 1.99595 +  assert( sqlite3_mutex_held(db->mutex) );
 1.99596 +  if( !db->init.busy ){
 1.99597 +    rc = sqlite3Init(db, &pParse->zErrMsg);
 1.99598 +  }
 1.99599 +  if( rc!=SQLITE_OK ){
 1.99600 +    pParse->rc = rc;
 1.99601 +    pParse->nErr++;
 1.99602 +  }
 1.99603 +  return rc;
 1.99604 +}
 1.99605 +
 1.99606 +
 1.99607 +/*
 1.99608 +** Check schema cookies in all databases.  If any cookie is out
 1.99609 +** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
 1.99610 +** make no changes to pParse->rc.
 1.99611 +*/
 1.99612 +static void schemaIsValid(Parse *pParse){
 1.99613 +  sqlite3 *db = pParse->db;
 1.99614 +  int iDb;
 1.99615 +  int rc;
 1.99616 +  int cookie;
 1.99617 +
 1.99618 +  assert( pParse->checkSchema );
 1.99619 +  assert( sqlite3_mutex_held(db->mutex) );
 1.99620 +  for(iDb=0; iDb<db->nDb; iDb++){
 1.99621 +    int openedTransaction = 0;         /* True if a transaction is opened */
 1.99622 +    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
 1.99623 +    if( pBt==0 ) continue;
 1.99624 +
 1.99625 +    /* If there is not already a read-only (or read-write) transaction opened
 1.99626 +    ** on the b-tree database, open one now. If a transaction is opened, it 
 1.99627 +    ** will be closed immediately after reading the meta-value. */
 1.99628 +    if( !sqlite3BtreeIsInReadTrans(pBt) ){
 1.99629 +      rc = sqlite3BtreeBeginTrans(pBt, 0);
 1.99630 +      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
 1.99631 +        db->mallocFailed = 1;
 1.99632 +      }
 1.99633 +      if( rc!=SQLITE_OK ) return;
 1.99634 +      openedTransaction = 1;
 1.99635 +    }
 1.99636 +
 1.99637 +    /* Read the schema cookie from the database. If it does not match the 
 1.99638 +    ** value stored as part of the in-memory schema representation,
 1.99639 +    ** set Parse.rc to SQLITE_SCHEMA. */
 1.99640 +    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
 1.99641 +    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 1.99642 +    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
 1.99643 +      sqlite3ResetOneSchema(db, iDb);
 1.99644 +      pParse->rc = SQLITE_SCHEMA;
 1.99645 +    }
 1.99646 +
 1.99647 +    /* Close the transaction, if one was opened. */
 1.99648 +    if( openedTransaction ){
 1.99649 +      sqlite3BtreeCommit(pBt);
 1.99650 +    }
 1.99651 +  }
 1.99652 +}
 1.99653 +
 1.99654 +/*
 1.99655 +** Convert a schema pointer into the iDb index that indicates
 1.99656 +** which database file in db->aDb[] the schema refers to.
 1.99657 +**
 1.99658 +** If the same database is attached more than once, the first
 1.99659 +** attached database is returned.
 1.99660 +*/
 1.99661 +SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
 1.99662 +  int i = -1000000;
 1.99663 +
 1.99664 +  /* If pSchema is NULL, then return -1000000. This happens when code in 
 1.99665 +  ** expr.c is trying to resolve a reference to a transient table (i.e. one
 1.99666 +  ** created by a sub-select). In this case the return value of this 
 1.99667 +  ** function should never be used.
 1.99668 +  **
 1.99669 +  ** We return -1000000 instead of the more usual -1 simply because using
 1.99670 +  ** -1000000 as the incorrect index into db->aDb[] is much 
 1.99671 +  ** more likely to cause a segfault than -1 (of course there are assert()
 1.99672 +  ** statements too, but it never hurts to play the odds).
 1.99673 +  */
 1.99674 +  assert( sqlite3_mutex_held(db->mutex) );
 1.99675 +  if( pSchema ){
 1.99676 +    for(i=0; ALWAYS(i<db->nDb); i++){
 1.99677 +      if( db->aDb[i].pSchema==pSchema ){
 1.99678 +        break;
 1.99679 +      }
 1.99680 +    }
 1.99681 +    assert( i>=0 && i<db->nDb );
 1.99682 +  }
 1.99683 +  return i;
 1.99684 +}
 1.99685 +
 1.99686 +/*
 1.99687 +** Free all memory allocations in the pParse object
 1.99688 +*/
 1.99689 +SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
 1.99690 +  if( pParse ){
 1.99691 +    sqlite3 *db = pParse->db;
 1.99692 +    sqlite3DbFree(db, pParse->aLabel);
 1.99693 +    sqlite3ExprListDelete(db, pParse->pConstExpr);
 1.99694 +  }
 1.99695 +}
 1.99696 +
 1.99697 +/*
 1.99698 +** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
 1.99699 +*/
 1.99700 +static int sqlite3Prepare(
 1.99701 +  sqlite3 *db,              /* Database handle. */
 1.99702 +  const char *zSql,         /* UTF-8 encoded SQL statement. */
 1.99703 +  int nBytes,               /* Length of zSql in bytes. */
 1.99704 +  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
 1.99705 +  Vdbe *pReprepare,         /* VM being reprepared */
 1.99706 +  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
 1.99707 +  const char **pzTail       /* OUT: End of parsed string */
 1.99708 +){
 1.99709 +  Parse *pParse;            /* Parsing context */
 1.99710 +  char *zErrMsg = 0;        /* Error message */
 1.99711 +  int rc = SQLITE_OK;       /* Result code */
 1.99712 +  int i;                    /* Loop counter */
 1.99713 +
 1.99714 +  /* Allocate the parsing context */
 1.99715 +  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
 1.99716 +  if( pParse==0 ){
 1.99717 +    rc = SQLITE_NOMEM;
 1.99718 +    goto end_prepare;
 1.99719 +  }
 1.99720 +  pParse->pReprepare = pReprepare;
 1.99721 +  assert( ppStmt && *ppStmt==0 );
 1.99722 +  assert( !db->mallocFailed );
 1.99723 +  assert( sqlite3_mutex_held(db->mutex) );
 1.99724 +
 1.99725 +  /* Check to verify that it is possible to get a read lock on all
 1.99726 +  ** database schemas.  The inability to get a read lock indicates that
 1.99727 +  ** some other database connection is holding a write-lock, which in
 1.99728 +  ** turn means that the other connection has made uncommitted changes
 1.99729 +  ** to the schema.
 1.99730 +  **
 1.99731 +  ** Were we to proceed and prepare the statement against the uncommitted
 1.99732 +  ** schema changes and if those schema changes are subsequently rolled
 1.99733 +  ** back and different changes are made in their place, then when this
 1.99734 +  ** prepared statement goes to run the schema cookie would fail to detect
 1.99735 +  ** the schema change.  Disaster would follow.
 1.99736 +  **
 1.99737 +  ** This thread is currently holding mutexes on all Btrees (because
 1.99738 +  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
 1.99739 +  ** is not possible for another thread to start a new schema change
 1.99740 +  ** while this routine is running.  Hence, we do not need to hold 
 1.99741 +  ** locks on the schema, we just need to make sure nobody else is 
 1.99742 +  ** holding them.
 1.99743 +  **
 1.99744 +  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
 1.99745 +  ** but it does *not* override schema lock detection, so this all still
 1.99746 +  ** works even if READ_UNCOMMITTED is set.
 1.99747 +  */
 1.99748 +  for(i=0; i<db->nDb; i++) {
 1.99749 +    Btree *pBt = db->aDb[i].pBt;
 1.99750 +    if( pBt ){
 1.99751 +      assert( sqlite3BtreeHoldsMutex(pBt) );
 1.99752 +      rc = sqlite3BtreeSchemaLocked(pBt);
 1.99753 +      if( rc ){
 1.99754 +        const char *zDb = db->aDb[i].zName;
 1.99755 +        sqlite3Error(db, rc, "database schema is locked: %s", zDb);
 1.99756 +        testcase( db->flags & SQLITE_ReadUncommitted );
 1.99757 +        goto end_prepare;
 1.99758 +      }
 1.99759 +    }
 1.99760 +  }
 1.99761 +
 1.99762 +  sqlite3VtabUnlockList(db);
 1.99763 +
 1.99764 +  pParse->db = db;
 1.99765 +  pParse->nQueryLoop = 0;  /* Logarithmic, so 0 really means 1 */
 1.99766 +  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
 1.99767 +    char *zSqlCopy;
 1.99768 +    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
 1.99769 +    testcase( nBytes==mxLen );
 1.99770 +    testcase( nBytes==mxLen+1 );
 1.99771 +    if( nBytes>mxLen ){
 1.99772 +      sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
 1.99773 +      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
 1.99774 +      goto end_prepare;
 1.99775 +    }
 1.99776 +    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
 1.99777 +    if( zSqlCopy ){
 1.99778 +      sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
 1.99779 +      sqlite3DbFree(db, zSqlCopy);
 1.99780 +      pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
 1.99781 +    }else{
 1.99782 +      pParse->zTail = &zSql[nBytes];
 1.99783 +    }
 1.99784 +  }else{
 1.99785 +    sqlite3RunParser(pParse, zSql, &zErrMsg);
 1.99786 +  }
 1.99787 +  assert( 0==pParse->nQueryLoop );
 1.99788 +
 1.99789 +  if( db->mallocFailed ){
 1.99790 +    pParse->rc = SQLITE_NOMEM;
 1.99791 +  }
 1.99792 +  if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
 1.99793 +  if( pParse->checkSchema ){
 1.99794 +    schemaIsValid(pParse);
 1.99795 +  }
 1.99796 +  if( db->mallocFailed ){
 1.99797 +    pParse->rc = SQLITE_NOMEM;
 1.99798 +  }
 1.99799 +  if( pzTail ){
 1.99800 +    *pzTail = pParse->zTail;
 1.99801 +  }
 1.99802 +  rc = pParse->rc;
 1.99803 +
 1.99804 +#ifndef SQLITE_OMIT_EXPLAIN
 1.99805 +  if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
 1.99806 +    static const char * const azColName[] = {
 1.99807 +       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
 1.99808 +       "selectid", "order", "from", "detail"
 1.99809 +    };
 1.99810 +    int iFirst, mx;
 1.99811 +    if( pParse->explain==2 ){
 1.99812 +      sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
 1.99813 +      iFirst = 8;
 1.99814 +      mx = 12;
 1.99815 +    }else{
 1.99816 +      sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
 1.99817 +      iFirst = 0;
 1.99818 +      mx = 8;
 1.99819 +    }
 1.99820 +    for(i=iFirst; i<mx; i++){
 1.99821 +      sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
 1.99822 +                            azColName[i], SQLITE_STATIC);
 1.99823 +    }
 1.99824 +  }
 1.99825 +#endif
 1.99826 +
 1.99827 +  if( db->init.busy==0 ){
 1.99828 +    Vdbe *pVdbe = pParse->pVdbe;
 1.99829 +    sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
 1.99830 +  }
 1.99831 +  if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
 1.99832 +    sqlite3VdbeFinalize(pParse->pVdbe);
 1.99833 +    assert(!(*ppStmt));
 1.99834 +  }else{
 1.99835 +    *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
 1.99836 +  }
 1.99837 +
 1.99838 +  if( zErrMsg ){
 1.99839 +    sqlite3Error(db, rc, "%s", zErrMsg);
 1.99840 +    sqlite3DbFree(db, zErrMsg);
 1.99841 +  }else{
 1.99842 +    sqlite3Error(db, rc, 0);
 1.99843 +  }
 1.99844 +
 1.99845 +  /* Delete any TriggerPrg structures allocated while parsing this statement. */
 1.99846 +  while( pParse->pTriggerPrg ){
 1.99847 +    TriggerPrg *pT = pParse->pTriggerPrg;
 1.99848 +    pParse->pTriggerPrg = pT->pNext;
 1.99849 +    sqlite3DbFree(db, pT);
 1.99850 +  }
 1.99851 +
 1.99852 +end_prepare:
 1.99853 +
 1.99854 +  sqlite3ParserReset(pParse);
 1.99855 +  sqlite3StackFree(db, pParse);
 1.99856 +  rc = sqlite3ApiExit(db, rc);
 1.99857 +  assert( (rc&db->errMask)==rc );
 1.99858 +  return rc;
 1.99859 +}
 1.99860 +static int sqlite3LockAndPrepare(
 1.99861 +  sqlite3 *db,              /* Database handle. */
 1.99862 +  const char *zSql,         /* UTF-8 encoded SQL statement. */
 1.99863 +  int nBytes,               /* Length of zSql in bytes. */
 1.99864 +  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
 1.99865 +  Vdbe *pOld,               /* VM being reprepared */
 1.99866 +  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
 1.99867 +  const char **pzTail       /* OUT: End of parsed string */
 1.99868 +){
 1.99869 +  int rc;
 1.99870 +  assert( ppStmt!=0 );
 1.99871 +  *ppStmt = 0;
 1.99872 +  if( !sqlite3SafetyCheckOk(db) ){
 1.99873 +    return SQLITE_MISUSE_BKPT;
 1.99874 +  }
 1.99875 +  sqlite3_mutex_enter(db->mutex);
 1.99876 +  sqlite3BtreeEnterAll(db);
 1.99877 +  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
 1.99878 +  if( rc==SQLITE_SCHEMA ){
 1.99879 +    sqlite3_finalize(*ppStmt);
 1.99880 +    rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
 1.99881 +  }
 1.99882 +  sqlite3BtreeLeaveAll(db);
 1.99883 +  sqlite3_mutex_leave(db->mutex);
 1.99884 +  assert( rc==SQLITE_OK || *ppStmt==0 );
 1.99885 +  return rc;
 1.99886 +}
 1.99887 +
 1.99888 +/*
 1.99889 +** Rerun the compilation of a statement after a schema change.
 1.99890 +**
 1.99891 +** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
 1.99892 +** if the statement cannot be recompiled because another connection has
 1.99893 +** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
 1.99894 +** occurs, return SQLITE_SCHEMA.
 1.99895 +*/
 1.99896 +SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
 1.99897 +  int rc;
 1.99898 +  sqlite3_stmt *pNew;
 1.99899 +  const char *zSql;
 1.99900 +  sqlite3 *db;
 1.99901 +
 1.99902 +  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
 1.99903 +  zSql = sqlite3_sql((sqlite3_stmt *)p);
 1.99904 +  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
 1.99905 +  db = sqlite3VdbeDb(p);
 1.99906 +  assert( sqlite3_mutex_held(db->mutex) );
 1.99907 +  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
 1.99908 +  if( rc ){
 1.99909 +    if( rc==SQLITE_NOMEM ){
 1.99910 +      db->mallocFailed = 1;
 1.99911 +    }
 1.99912 +    assert( pNew==0 );
 1.99913 +    return rc;
 1.99914 +  }else{
 1.99915 +    assert( pNew!=0 );
 1.99916 +  }
 1.99917 +  sqlite3VdbeSwap((Vdbe*)pNew, p);
 1.99918 +  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
 1.99919 +  sqlite3VdbeResetStepResult((Vdbe*)pNew);
 1.99920 +  sqlite3VdbeFinalize((Vdbe*)pNew);
 1.99921 +  return SQLITE_OK;
 1.99922 +}
 1.99923 +
 1.99924 +
 1.99925 +/*
 1.99926 +** Two versions of the official API.  Legacy and new use.  In the legacy
 1.99927 +** version, the original SQL text is not saved in the prepared statement
 1.99928 +** and so if a schema change occurs, SQLITE_SCHEMA is returned by
 1.99929 +** sqlite3_step().  In the new version, the original SQL text is retained
 1.99930 +** and the statement is automatically recompiled if an schema change
 1.99931 +** occurs.
 1.99932 +*/
 1.99933 +SQLITE_API int sqlite3_prepare(
 1.99934 +  sqlite3 *db,              /* Database handle. */
 1.99935 +  const char *zSql,         /* UTF-8 encoded SQL statement. */
 1.99936 +  int nBytes,               /* Length of zSql in bytes. */
 1.99937 +  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
 1.99938 +  const char **pzTail       /* OUT: End of parsed string */
 1.99939 +){
 1.99940 +  int rc;
 1.99941 +  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
 1.99942 +  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
 1.99943 +  return rc;
 1.99944 +}
 1.99945 +SQLITE_API int sqlite3_prepare_v2(
 1.99946 +  sqlite3 *db,              /* Database handle. */
 1.99947 +  const char *zSql,         /* UTF-8 encoded SQL statement. */
 1.99948 +  int nBytes,               /* Length of zSql in bytes. */
 1.99949 +  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
 1.99950 +  const char **pzTail       /* OUT: End of parsed string */
 1.99951 +){
 1.99952 +  int rc;
 1.99953 +  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
 1.99954 +  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
 1.99955 +  return rc;
 1.99956 +}
 1.99957 +
 1.99958 +
 1.99959 +#ifndef SQLITE_OMIT_UTF16
 1.99960 +/*
 1.99961 +** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
 1.99962 +*/
 1.99963 +static int sqlite3Prepare16(
 1.99964 +  sqlite3 *db,              /* Database handle. */ 
 1.99965 +  const void *zSql,         /* UTF-16 encoded SQL statement. */
 1.99966 +  int nBytes,               /* Length of zSql in bytes. */
 1.99967 +  int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
 1.99968 +  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
 1.99969 +  const void **pzTail       /* OUT: End of parsed string */
 1.99970 +){
 1.99971 +  /* This function currently works by first transforming the UTF-16
 1.99972 +  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
 1.99973 +  ** tricky bit is figuring out the pointer to return in *pzTail.
 1.99974 +  */
 1.99975 +  char *zSql8;
 1.99976 +  const char *zTail8 = 0;
 1.99977 +  int rc = SQLITE_OK;
 1.99978 +
 1.99979 +  assert( ppStmt );
 1.99980 +  *ppStmt = 0;
 1.99981 +  if( !sqlite3SafetyCheckOk(db) ){
 1.99982 +    return SQLITE_MISUSE_BKPT;
 1.99983 +  }
 1.99984 +  if( nBytes>=0 ){
 1.99985 +    int sz;
 1.99986 +    const char *z = (const char*)zSql;
 1.99987 +    for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
 1.99988 +    nBytes = sz;
 1.99989 +  }
 1.99990 +  sqlite3_mutex_enter(db->mutex);
 1.99991 +  zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
 1.99992 +  if( zSql8 ){
 1.99993 +    rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
 1.99994 +  }
 1.99995 +
 1.99996 +  if( zTail8 && pzTail ){
 1.99997 +    /* If sqlite3_prepare returns a tail pointer, we calculate the
 1.99998 +    ** equivalent pointer into the UTF-16 string by counting the unicode
 1.99999 +    ** characters between zSql8 and zTail8, and then returning a pointer
1.100000 +    ** the same number of characters into the UTF-16 string.
1.100001 +    */
1.100002 +    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
1.100003 +    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
1.100004 +  }
1.100005 +  sqlite3DbFree(db, zSql8); 
1.100006 +  rc = sqlite3ApiExit(db, rc);
1.100007 +  sqlite3_mutex_leave(db->mutex);
1.100008 +  return rc;
1.100009 +}
1.100010 +
1.100011 +/*
1.100012 +** Two versions of the official API.  Legacy and new use.  In the legacy
1.100013 +** version, the original SQL text is not saved in the prepared statement
1.100014 +** and so if a schema change occurs, SQLITE_SCHEMA is returned by
1.100015 +** sqlite3_step().  In the new version, the original SQL text is retained
1.100016 +** and the statement is automatically recompiled if an schema change
1.100017 +** occurs.
1.100018 +*/
1.100019 +SQLITE_API int sqlite3_prepare16(
1.100020 +  sqlite3 *db,              /* Database handle. */ 
1.100021 +  const void *zSql,         /* UTF-16 encoded SQL statement. */
1.100022 +  int nBytes,               /* Length of zSql in bytes. */
1.100023 +  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
1.100024 +  const void **pzTail       /* OUT: End of parsed string */
1.100025 +){
1.100026 +  int rc;
1.100027 +  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
1.100028 +  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
1.100029 +  return rc;
1.100030 +}
1.100031 +SQLITE_API int sqlite3_prepare16_v2(
1.100032 +  sqlite3 *db,              /* Database handle. */ 
1.100033 +  const void *zSql,         /* UTF-16 encoded SQL statement. */
1.100034 +  int nBytes,               /* Length of zSql in bytes. */
1.100035 +  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
1.100036 +  const void **pzTail       /* OUT: End of parsed string */
1.100037 +){
1.100038 +  int rc;
1.100039 +  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
1.100040 +  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
1.100041 +  return rc;
1.100042 +}
1.100043 +
1.100044 +#endif /* SQLITE_OMIT_UTF16 */
1.100045 +
1.100046 +/************** End of prepare.c *********************************************/
1.100047 +/************** Begin file select.c ******************************************/
1.100048 +/*
1.100049 +** 2001 September 15
1.100050 +**
1.100051 +** The author disclaims copyright to this source code.  In place of
1.100052 +** a legal notice, here is a blessing:
1.100053 +**
1.100054 +**    May you do good and not evil.
1.100055 +**    May you find forgiveness for yourself and forgive others.
1.100056 +**    May you share freely, never taking more than you give.
1.100057 +**
1.100058 +*************************************************************************
1.100059 +** This file contains C code routines that are called by the parser
1.100060 +** to handle SELECT statements in SQLite.
1.100061 +*/
1.100062 +
1.100063 +
1.100064 +/*
1.100065 +** Delete all the content of a Select structure but do not deallocate
1.100066 +** the select structure itself.
1.100067 +*/
1.100068 +static void clearSelect(sqlite3 *db, Select *p){
1.100069 +  sqlite3ExprListDelete(db, p->pEList);
1.100070 +  sqlite3SrcListDelete(db, p->pSrc);
1.100071 +  sqlite3ExprDelete(db, p->pWhere);
1.100072 +  sqlite3ExprListDelete(db, p->pGroupBy);
1.100073 +  sqlite3ExprDelete(db, p->pHaving);
1.100074 +  sqlite3ExprListDelete(db, p->pOrderBy);
1.100075 +  sqlite3SelectDelete(db, p->pPrior);
1.100076 +  sqlite3ExprDelete(db, p->pLimit);
1.100077 +  sqlite3ExprDelete(db, p->pOffset);
1.100078 +  sqlite3WithDelete(db, p->pWith);
1.100079 +}
1.100080 +
1.100081 +/*
1.100082 +** Initialize a SelectDest structure.
1.100083 +*/
1.100084 +SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
1.100085 +  pDest->eDest = (u8)eDest;
1.100086 +  pDest->iSDParm = iParm;
1.100087 +  pDest->affSdst = 0;
1.100088 +  pDest->iSdst = 0;
1.100089 +  pDest->nSdst = 0;
1.100090 +}
1.100091 +
1.100092 +
1.100093 +/*
1.100094 +** Allocate a new Select structure and return a pointer to that
1.100095 +** structure.
1.100096 +*/
1.100097 +SQLITE_PRIVATE Select *sqlite3SelectNew(
1.100098 +  Parse *pParse,        /* Parsing context */
1.100099 +  ExprList *pEList,     /* which columns to include in the result */
1.100100 +  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
1.100101 +  Expr *pWhere,         /* the WHERE clause */
1.100102 +  ExprList *pGroupBy,   /* the GROUP BY clause */
1.100103 +  Expr *pHaving,        /* the HAVING clause */
1.100104 +  ExprList *pOrderBy,   /* the ORDER BY clause */
1.100105 +  u16 selFlags,         /* Flag parameters, such as SF_Distinct */
1.100106 +  Expr *pLimit,         /* LIMIT value.  NULL means not used */
1.100107 +  Expr *pOffset         /* OFFSET value.  NULL means no offset */
1.100108 +){
1.100109 +  Select *pNew;
1.100110 +  Select standin;
1.100111 +  sqlite3 *db = pParse->db;
1.100112 +  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
1.100113 +  assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
1.100114 +  if( pNew==0 ){
1.100115 +    assert( db->mallocFailed );
1.100116 +    pNew = &standin;
1.100117 +    memset(pNew, 0, sizeof(*pNew));
1.100118 +  }
1.100119 +  if( pEList==0 ){
1.100120 +    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
1.100121 +  }
1.100122 +  pNew->pEList = pEList;
1.100123 +  if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
1.100124 +  pNew->pSrc = pSrc;
1.100125 +  pNew->pWhere = pWhere;
1.100126 +  pNew->pGroupBy = pGroupBy;
1.100127 +  pNew->pHaving = pHaving;
1.100128 +  pNew->pOrderBy = pOrderBy;
1.100129 +  pNew->selFlags = selFlags;
1.100130 +  pNew->op = TK_SELECT;
1.100131 +  pNew->pLimit = pLimit;
1.100132 +  pNew->pOffset = pOffset;
1.100133 +  assert( pOffset==0 || pLimit!=0 );
1.100134 +  pNew->addrOpenEphm[0] = -1;
1.100135 +  pNew->addrOpenEphm[1] = -1;
1.100136 +  pNew->addrOpenEphm[2] = -1;
1.100137 +  if( db->mallocFailed ) {
1.100138 +    clearSelect(db, pNew);
1.100139 +    if( pNew!=&standin ) sqlite3DbFree(db, pNew);
1.100140 +    pNew = 0;
1.100141 +  }else{
1.100142 +    assert( pNew->pSrc!=0 || pParse->nErr>0 );
1.100143 +  }
1.100144 +  assert( pNew!=&standin );
1.100145 +  return pNew;
1.100146 +}
1.100147 +
1.100148 +/*
1.100149 +** Delete the given Select structure and all of its substructures.
1.100150 +*/
1.100151 +SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
1.100152 +  if( p ){
1.100153 +    clearSelect(db, p);
1.100154 +    sqlite3DbFree(db, p);
1.100155 +  }
1.100156 +}
1.100157 +
1.100158 +/*
1.100159 +** Return a pointer to the right-most SELECT statement in a compound.
1.100160 +*/
1.100161 +static Select *findRightmost(Select *p){
1.100162 +  while( p->pNext ) p = p->pNext;
1.100163 +  return p;
1.100164 +}
1.100165 +
1.100166 +/*
1.100167 +** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
1.100168 +** type of join.  Return an integer constant that expresses that type
1.100169 +** in terms of the following bit values:
1.100170 +**
1.100171 +**     JT_INNER
1.100172 +**     JT_CROSS
1.100173 +**     JT_OUTER
1.100174 +**     JT_NATURAL
1.100175 +**     JT_LEFT
1.100176 +**     JT_RIGHT
1.100177 +**
1.100178 +** A full outer join is the combination of JT_LEFT and JT_RIGHT.
1.100179 +**
1.100180 +** If an illegal or unsupported join type is seen, then still return
1.100181 +** a join type, but put an error in the pParse structure.
1.100182 +*/
1.100183 +SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
1.100184 +  int jointype = 0;
1.100185 +  Token *apAll[3];
1.100186 +  Token *p;
1.100187 +                             /*   0123456789 123456789 123456789 123 */
1.100188 +  static const char zKeyText[] = "naturaleftouterightfullinnercross";
1.100189 +  static const struct {
1.100190 +    u8 i;        /* Beginning of keyword text in zKeyText[] */
1.100191 +    u8 nChar;    /* Length of the keyword in characters */
1.100192 +    u8 code;     /* Join type mask */
1.100193 +  } aKeyword[] = {
1.100194 +    /* natural */ { 0,  7, JT_NATURAL                },
1.100195 +    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
1.100196 +    /* outer   */ { 10, 5, JT_OUTER                  },
1.100197 +    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
1.100198 +    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
1.100199 +    /* inner   */ { 23, 5, JT_INNER                  },
1.100200 +    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
1.100201 +  };
1.100202 +  int i, j;
1.100203 +  apAll[0] = pA;
1.100204 +  apAll[1] = pB;
1.100205 +  apAll[2] = pC;
1.100206 +  for(i=0; i<3 && apAll[i]; i++){
1.100207 +    p = apAll[i];
1.100208 +    for(j=0; j<ArraySize(aKeyword); j++){
1.100209 +      if( p->n==aKeyword[j].nChar 
1.100210 +          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
1.100211 +        jointype |= aKeyword[j].code;
1.100212 +        break;
1.100213 +      }
1.100214 +    }
1.100215 +    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
1.100216 +    if( j>=ArraySize(aKeyword) ){
1.100217 +      jointype |= JT_ERROR;
1.100218 +      break;
1.100219 +    }
1.100220 +  }
1.100221 +  if(
1.100222 +     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
1.100223 +     (jointype & JT_ERROR)!=0
1.100224 +  ){
1.100225 +    const char *zSp = " ";
1.100226 +    assert( pB!=0 );
1.100227 +    if( pC==0 ){ zSp++; }
1.100228 +    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
1.100229 +       "%T %T%s%T", pA, pB, zSp, pC);
1.100230 +    jointype = JT_INNER;
1.100231 +  }else if( (jointype & JT_OUTER)!=0 
1.100232 +         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
1.100233 +    sqlite3ErrorMsg(pParse, 
1.100234 +      "RIGHT and FULL OUTER JOINs are not currently supported");
1.100235 +    jointype = JT_INNER;
1.100236 +  }
1.100237 +  return jointype;
1.100238 +}
1.100239 +
1.100240 +/*
1.100241 +** Return the index of a column in a table.  Return -1 if the column
1.100242 +** is not contained in the table.
1.100243 +*/
1.100244 +static int columnIndex(Table *pTab, const char *zCol){
1.100245 +  int i;
1.100246 +  for(i=0; i<pTab->nCol; i++){
1.100247 +    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
1.100248 +  }
1.100249 +  return -1;
1.100250 +}
1.100251 +
1.100252 +/*
1.100253 +** Search the first N tables in pSrc, from left to right, looking for a
1.100254 +** table that has a column named zCol.  
1.100255 +**
1.100256 +** When found, set *piTab and *piCol to the table index and column index
1.100257 +** of the matching column and return TRUE.
1.100258 +**
1.100259 +** If not found, return FALSE.
1.100260 +*/
1.100261 +static int tableAndColumnIndex(
1.100262 +  SrcList *pSrc,       /* Array of tables to search */
1.100263 +  int N,               /* Number of tables in pSrc->a[] to search */
1.100264 +  const char *zCol,    /* Name of the column we are looking for */
1.100265 +  int *piTab,          /* Write index of pSrc->a[] here */
1.100266 +  int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
1.100267 +){
1.100268 +  int i;               /* For looping over tables in pSrc */
1.100269 +  int iCol;            /* Index of column matching zCol */
1.100270 +
1.100271 +  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
1.100272 +  for(i=0; i<N; i++){
1.100273 +    iCol = columnIndex(pSrc->a[i].pTab, zCol);
1.100274 +    if( iCol>=0 ){
1.100275 +      if( piTab ){
1.100276 +        *piTab = i;
1.100277 +        *piCol = iCol;
1.100278 +      }
1.100279 +      return 1;
1.100280 +    }
1.100281 +  }
1.100282 +  return 0;
1.100283 +}
1.100284 +
1.100285 +/*
1.100286 +** This function is used to add terms implied by JOIN syntax to the
1.100287 +** WHERE clause expression of a SELECT statement. The new term, which
1.100288 +** is ANDed with the existing WHERE clause, is of the form:
1.100289 +**
1.100290 +**    (tab1.col1 = tab2.col2)
1.100291 +**
1.100292 +** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
1.100293 +** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
1.100294 +** column iColRight of tab2.
1.100295 +*/
1.100296 +static void addWhereTerm(
1.100297 +  Parse *pParse,                  /* Parsing context */
1.100298 +  SrcList *pSrc,                  /* List of tables in FROM clause */
1.100299 +  int iLeft,                      /* Index of first table to join in pSrc */
1.100300 +  int iColLeft,                   /* Index of column in first table */
1.100301 +  int iRight,                     /* Index of second table in pSrc */
1.100302 +  int iColRight,                  /* Index of column in second table */
1.100303 +  int isOuterJoin,                /* True if this is an OUTER join */
1.100304 +  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
1.100305 +){
1.100306 +  sqlite3 *db = pParse->db;
1.100307 +  Expr *pE1;
1.100308 +  Expr *pE2;
1.100309 +  Expr *pEq;
1.100310 +
1.100311 +  assert( iLeft<iRight );
1.100312 +  assert( pSrc->nSrc>iRight );
1.100313 +  assert( pSrc->a[iLeft].pTab );
1.100314 +  assert( pSrc->a[iRight].pTab );
1.100315 +
1.100316 +  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
1.100317 +  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
1.100318 +
1.100319 +  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
1.100320 +  if( pEq && isOuterJoin ){
1.100321 +    ExprSetProperty(pEq, EP_FromJoin);
1.100322 +    assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
1.100323 +    ExprSetVVAProperty(pEq, EP_NoReduce);
1.100324 +    pEq->iRightJoinTable = (i16)pE2->iTable;
1.100325 +  }
1.100326 +  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
1.100327 +}
1.100328 +
1.100329 +/*
1.100330 +** Set the EP_FromJoin property on all terms of the given expression.
1.100331 +** And set the Expr.iRightJoinTable to iTable for every term in the
1.100332 +** expression.
1.100333 +**
1.100334 +** The EP_FromJoin property is used on terms of an expression to tell
1.100335 +** the LEFT OUTER JOIN processing logic that this term is part of the
1.100336 +** join restriction specified in the ON or USING clause and not a part
1.100337 +** of the more general WHERE clause.  These terms are moved over to the
1.100338 +** WHERE clause during join processing but we need to remember that they
1.100339 +** originated in the ON or USING clause.
1.100340 +**
1.100341 +** The Expr.iRightJoinTable tells the WHERE clause processing that the
1.100342 +** expression depends on table iRightJoinTable even if that table is not
1.100343 +** explicitly mentioned in the expression.  That information is needed
1.100344 +** for cases like this:
1.100345 +**
1.100346 +**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
1.100347 +**
1.100348 +** The where clause needs to defer the handling of the t1.x=5
1.100349 +** term until after the t2 loop of the join.  In that way, a
1.100350 +** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
1.100351 +** defer the handling of t1.x=5, it will be processed immediately
1.100352 +** after the t1 loop and rows with t1.x!=5 will never appear in
1.100353 +** the output, which is incorrect.
1.100354 +*/
1.100355 +static void setJoinExpr(Expr *p, int iTable){
1.100356 +  while( p ){
1.100357 +    ExprSetProperty(p, EP_FromJoin);
1.100358 +    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
1.100359 +    ExprSetVVAProperty(p, EP_NoReduce);
1.100360 +    p->iRightJoinTable = (i16)iTable;
1.100361 +    setJoinExpr(p->pLeft, iTable);
1.100362 +    p = p->pRight;
1.100363 +  } 
1.100364 +}
1.100365 +
1.100366 +/*
1.100367 +** This routine processes the join information for a SELECT statement.
1.100368 +** ON and USING clauses are converted into extra terms of the WHERE clause.
1.100369 +** NATURAL joins also create extra WHERE clause terms.
1.100370 +**
1.100371 +** The terms of a FROM clause are contained in the Select.pSrc structure.
1.100372 +** The left most table is the first entry in Select.pSrc.  The right-most
1.100373 +** table is the last entry.  The join operator is held in the entry to
1.100374 +** the left.  Thus entry 0 contains the join operator for the join between
1.100375 +** entries 0 and 1.  Any ON or USING clauses associated with the join are
1.100376 +** also attached to the left entry.
1.100377 +**
1.100378 +** This routine returns the number of errors encountered.
1.100379 +*/
1.100380 +static int sqliteProcessJoin(Parse *pParse, Select *p){
1.100381 +  SrcList *pSrc;                  /* All tables in the FROM clause */
1.100382 +  int i, j;                       /* Loop counters */
1.100383 +  struct SrcList_item *pLeft;     /* Left table being joined */
1.100384 +  struct SrcList_item *pRight;    /* Right table being joined */
1.100385 +
1.100386 +  pSrc = p->pSrc;
1.100387 +  pLeft = &pSrc->a[0];
1.100388 +  pRight = &pLeft[1];
1.100389 +  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
1.100390 +    Table *pLeftTab = pLeft->pTab;
1.100391 +    Table *pRightTab = pRight->pTab;
1.100392 +    int isOuter;
1.100393 +
1.100394 +    if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
1.100395 +    isOuter = (pRight->jointype & JT_OUTER)!=0;
1.100396 +
1.100397 +    /* When the NATURAL keyword is present, add WHERE clause terms for
1.100398 +    ** every column that the two tables have in common.
1.100399 +    */
1.100400 +    if( pRight->jointype & JT_NATURAL ){
1.100401 +      if( pRight->pOn || pRight->pUsing ){
1.100402 +        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
1.100403 +           "an ON or USING clause", 0);
1.100404 +        return 1;
1.100405 +      }
1.100406 +      for(j=0; j<pRightTab->nCol; j++){
1.100407 +        char *zName;   /* Name of column in the right table */
1.100408 +        int iLeft;     /* Matching left table */
1.100409 +        int iLeftCol;  /* Matching column in the left table */
1.100410 +
1.100411 +        zName = pRightTab->aCol[j].zName;
1.100412 +        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
1.100413 +          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
1.100414 +                       isOuter, &p->pWhere);
1.100415 +        }
1.100416 +      }
1.100417 +    }
1.100418 +
1.100419 +    /* Disallow both ON and USING clauses in the same join
1.100420 +    */
1.100421 +    if( pRight->pOn && pRight->pUsing ){
1.100422 +      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
1.100423 +        "clauses in the same join");
1.100424 +      return 1;
1.100425 +    }
1.100426 +
1.100427 +    /* Add the ON clause to the end of the WHERE clause, connected by
1.100428 +    ** an AND operator.
1.100429 +    */
1.100430 +    if( pRight->pOn ){
1.100431 +      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
1.100432 +      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
1.100433 +      pRight->pOn = 0;
1.100434 +    }
1.100435 +
1.100436 +    /* Create extra terms on the WHERE clause for each column named
1.100437 +    ** in the USING clause.  Example: If the two tables to be joined are 
1.100438 +    ** A and B and the USING clause names X, Y, and Z, then add this
1.100439 +    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
1.100440 +    ** Report an error if any column mentioned in the USING clause is
1.100441 +    ** not contained in both tables to be joined.
1.100442 +    */
1.100443 +    if( pRight->pUsing ){
1.100444 +      IdList *pList = pRight->pUsing;
1.100445 +      for(j=0; j<pList->nId; j++){
1.100446 +        char *zName;     /* Name of the term in the USING clause */
1.100447 +        int iLeft;       /* Table on the left with matching column name */
1.100448 +        int iLeftCol;    /* Column number of matching column on the left */
1.100449 +        int iRightCol;   /* Column number of matching column on the right */
1.100450 +
1.100451 +        zName = pList->a[j].zName;
1.100452 +        iRightCol = columnIndex(pRightTab, zName);
1.100453 +        if( iRightCol<0
1.100454 +         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
1.100455 +        ){
1.100456 +          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
1.100457 +            "not present in both tables", zName);
1.100458 +          return 1;
1.100459 +        }
1.100460 +        addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
1.100461 +                     isOuter, &p->pWhere);
1.100462 +      }
1.100463 +    }
1.100464 +  }
1.100465 +  return 0;
1.100466 +}
1.100467 +
1.100468 +/*
1.100469 +** Insert code into "v" that will push the record on the top of the
1.100470 +** stack into the sorter.
1.100471 +*/
1.100472 +static void pushOntoSorter(
1.100473 +  Parse *pParse,         /* Parser context */
1.100474 +  ExprList *pOrderBy,    /* The ORDER BY clause */
1.100475 +  Select *pSelect,       /* The whole SELECT statement */
1.100476 +  int regData            /* Register holding data to be sorted */
1.100477 +){
1.100478 +  Vdbe *v = pParse->pVdbe;
1.100479 +  int nExpr = pOrderBy->nExpr;
1.100480 +  int regBase = sqlite3GetTempRange(pParse, nExpr+2);
1.100481 +  int regRecord = sqlite3GetTempReg(pParse);
1.100482 +  int op;
1.100483 +  sqlite3ExprCacheClear(pParse);
1.100484 +  sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
1.100485 +  sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
1.100486 +  sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
1.100487 +  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
1.100488 +  if( pSelect->selFlags & SF_UseSorter ){
1.100489 +    op = OP_SorterInsert;
1.100490 +  }else{
1.100491 +    op = OP_IdxInsert;
1.100492 +  }
1.100493 +  sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
1.100494 +  sqlite3ReleaseTempReg(pParse, regRecord);
1.100495 +  sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
1.100496 +  if( pSelect->iLimit ){
1.100497 +    int addr1, addr2;
1.100498 +    int iLimit;
1.100499 +    if( pSelect->iOffset ){
1.100500 +      iLimit = pSelect->iOffset+1;
1.100501 +    }else{
1.100502 +      iLimit = pSelect->iLimit;
1.100503 +    }
1.100504 +    addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit); VdbeCoverage(v);
1.100505 +    sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
1.100506 +    addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
1.100507 +    sqlite3VdbeJumpHere(v, addr1);
1.100508 +    sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
1.100509 +    sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
1.100510 +    sqlite3VdbeJumpHere(v, addr2);
1.100511 +  }
1.100512 +}
1.100513 +
1.100514 +/*
1.100515 +** Add code to implement the OFFSET
1.100516 +*/
1.100517 +static void codeOffset(
1.100518 +  Vdbe *v,          /* Generate code into this VM */
1.100519 +  int iOffset,      /* Register holding the offset counter */
1.100520 +  int iContinue     /* Jump here to skip the current record */
1.100521 +){
1.100522 +  if( iOffset>0 && iContinue!=0 ){
1.100523 +    int addr;
1.100524 +    sqlite3VdbeAddOp2(v, OP_AddImm, iOffset, -1);
1.100525 +    addr = sqlite3VdbeAddOp1(v, OP_IfNeg, iOffset); VdbeCoverage(v);
1.100526 +    sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
1.100527 +    VdbeComment((v, "skip OFFSET records"));
1.100528 +    sqlite3VdbeJumpHere(v, addr);
1.100529 +  }
1.100530 +}
1.100531 +
1.100532 +/*
1.100533 +** Add code that will check to make sure the N registers starting at iMem
1.100534 +** form a distinct entry.  iTab is a sorting index that holds previously
1.100535 +** seen combinations of the N values.  A new entry is made in iTab
1.100536 +** if the current N values are new.
1.100537 +**
1.100538 +** A jump to addrRepeat is made and the N+1 values are popped from the
1.100539 +** stack if the top N elements are not distinct.
1.100540 +*/
1.100541 +static void codeDistinct(
1.100542 +  Parse *pParse,     /* Parsing and code generating context */
1.100543 +  int iTab,          /* A sorting index used to test for distinctness */
1.100544 +  int addrRepeat,    /* Jump to here if not distinct */
1.100545 +  int N,             /* Number of elements */
1.100546 +  int iMem           /* First element */
1.100547 +){
1.100548 +  Vdbe *v;
1.100549 +  int r1;
1.100550 +
1.100551 +  v = pParse->pVdbe;
1.100552 +  r1 = sqlite3GetTempReg(pParse);
1.100553 +  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
1.100554 +  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
1.100555 +  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
1.100556 +  sqlite3ReleaseTempReg(pParse, r1);
1.100557 +}
1.100558 +
1.100559 +#ifndef SQLITE_OMIT_SUBQUERY
1.100560 +/*
1.100561 +** Generate an error message when a SELECT is used within a subexpression
1.100562 +** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
1.100563 +** column.  We do this in a subroutine because the error used to occur
1.100564 +** in multiple places.  (The error only occurs in one place now, but we
1.100565 +** retain the subroutine to minimize code disruption.)
1.100566 +*/
1.100567 +static int checkForMultiColumnSelectError(
1.100568 +  Parse *pParse,       /* Parse context. */
1.100569 +  SelectDest *pDest,   /* Destination of SELECT results */
1.100570 +  int nExpr            /* Number of result columns returned by SELECT */
1.100571 +){
1.100572 +  int eDest = pDest->eDest;
1.100573 +  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
1.100574 +    sqlite3ErrorMsg(pParse, "only a single result allowed for "
1.100575 +       "a SELECT that is part of an expression");
1.100576 +    return 1;
1.100577 +  }else{
1.100578 +    return 0;
1.100579 +  }
1.100580 +}
1.100581 +#endif
1.100582 +
1.100583 +/*
1.100584 +** An instance of the following object is used to record information about
1.100585 +** how to process the DISTINCT keyword, to simplify passing that information
1.100586 +** into the selectInnerLoop() routine.
1.100587 +*/
1.100588 +typedef struct DistinctCtx DistinctCtx;
1.100589 +struct DistinctCtx {
1.100590 +  u8 isTnct;      /* True if the DISTINCT keyword is present */
1.100591 +  u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
1.100592 +  int tabTnct;    /* Ephemeral table used for DISTINCT processing */
1.100593 +  int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
1.100594 +};
1.100595 +
1.100596 +/*
1.100597 +** This routine generates the code for the inside of the inner loop
1.100598 +** of a SELECT.
1.100599 +**
1.100600 +** If srcTab is negative, then the pEList expressions
1.100601 +** are evaluated in order to get the data for this row.  If srcTab is
1.100602 +** zero or more, then data is pulled from srcTab and pEList is used only 
1.100603 +** to get number columns and the datatype for each column.
1.100604 +*/
1.100605 +static void selectInnerLoop(
1.100606 +  Parse *pParse,          /* The parser context */
1.100607 +  Select *p,              /* The complete select statement being coded */
1.100608 +  ExprList *pEList,       /* List of values being extracted */
1.100609 +  int srcTab,             /* Pull data from this table */
1.100610 +  ExprList *pOrderBy,     /* If not NULL, sort results using this key */
1.100611 +  DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
1.100612 +  SelectDest *pDest,      /* How to dispose of the results */
1.100613 +  int iContinue,          /* Jump here to continue with next row */
1.100614 +  int iBreak              /* Jump here to break out of the inner loop */
1.100615 +){
1.100616 +  Vdbe *v = pParse->pVdbe;
1.100617 +  int i;
1.100618 +  int hasDistinct;        /* True if the DISTINCT keyword is present */
1.100619 +  int regResult;              /* Start of memory holding result set */
1.100620 +  int eDest = pDest->eDest;   /* How to dispose of results */
1.100621 +  int iParm = pDest->iSDParm; /* First argument to disposal method */
1.100622 +  int nResultCol;             /* Number of result columns */
1.100623 +
1.100624 +  assert( v );
1.100625 +  assert( pEList!=0 );
1.100626 +  hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
1.100627 +  if( pOrderBy==0 && !hasDistinct ){
1.100628 +    codeOffset(v, p->iOffset, iContinue);
1.100629 +  }
1.100630 +
1.100631 +  /* Pull the requested columns.
1.100632 +  */
1.100633 +  nResultCol = pEList->nExpr;
1.100634 +
1.100635 +  if( pDest->iSdst==0 ){
1.100636 +    pDest->iSdst = pParse->nMem+1;
1.100637 +    pParse->nMem += nResultCol;
1.100638 +  }else if( pDest->iSdst+nResultCol > pParse->nMem ){
1.100639 +    /* This is an error condition that can result, for example, when a SELECT
1.100640 +    ** on the right-hand side of an INSERT contains more result columns than
1.100641 +    ** there are columns in the table on the left.  The error will be caught
1.100642 +    ** and reported later.  But we need to make sure enough memory is allocated
1.100643 +    ** to avoid other spurious errors in the meantime. */
1.100644 +    pParse->nMem += nResultCol;
1.100645 +  }
1.100646 +  pDest->nSdst = nResultCol;
1.100647 +  regResult = pDest->iSdst;
1.100648 +  if( srcTab>=0 ){
1.100649 +    for(i=0; i<nResultCol; i++){
1.100650 +      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
1.100651 +      VdbeComment((v, "%s", pEList->a[i].zName));
1.100652 +    }
1.100653 +  }else if( eDest!=SRT_Exists ){
1.100654 +    /* If the destination is an EXISTS(...) expression, the actual
1.100655 +    ** values returned by the SELECT are not required.
1.100656 +    */
1.100657 +    sqlite3ExprCodeExprList(pParse, pEList, regResult,
1.100658 +                  (eDest==SRT_Output||eDest==SRT_Coroutine)?SQLITE_ECEL_DUP:0);
1.100659 +  }
1.100660 +
1.100661 +  /* If the DISTINCT keyword was present on the SELECT statement
1.100662 +  ** and this row has been seen before, then do not make this row
1.100663 +  ** part of the result.
1.100664 +  */
1.100665 +  if( hasDistinct ){
1.100666 +    switch( pDistinct->eTnctType ){
1.100667 +      case WHERE_DISTINCT_ORDERED: {
1.100668 +        VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
1.100669 +        int iJump;              /* Jump destination */
1.100670 +        int regPrev;            /* Previous row content */
1.100671 +
1.100672 +        /* Allocate space for the previous row */
1.100673 +        regPrev = pParse->nMem+1;
1.100674 +        pParse->nMem += nResultCol;
1.100675 +
1.100676 +        /* Change the OP_OpenEphemeral coded earlier to an OP_Null
1.100677 +        ** sets the MEM_Cleared bit on the first register of the
1.100678 +        ** previous value.  This will cause the OP_Ne below to always
1.100679 +        ** fail on the first iteration of the loop even if the first
1.100680 +        ** row is all NULLs.
1.100681 +        */
1.100682 +        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
1.100683 +        pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
1.100684 +        pOp->opcode = OP_Null;
1.100685 +        pOp->p1 = 1;
1.100686 +        pOp->p2 = regPrev;
1.100687 +
1.100688 +        iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
1.100689 +        for(i=0; i<nResultCol; i++){
1.100690 +          CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
1.100691 +          if( i<nResultCol-1 ){
1.100692 +            sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
1.100693 +            VdbeCoverage(v);
1.100694 +          }else{
1.100695 +            sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
1.100696 +            VdbeCoverage(v);
1.100697 +           }
1.100698 +          sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
1.100699 +          sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
1.100700 +        }
1.100701 +        assert( sqlite3VdbeCurrentAddr(v)==iJump );
1.100702 +        sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
1.100703 +        break;
1.100704 +      }
1.100705 +
1.100706 +      case WHERE_DISTINCT_UNIQUE: {
1.100707 +        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
1.100708 +        break;
1.100709 +      }
1.100710 +
1.100711 +      default: {
1.100712 +        assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
1.100713 +        codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, regResult);
1.100714 +        break;
1.100715 +      }
1.100716 +    }
1.100717 +    if( pOrderBy==0 ){
1.100718 +      codeOffset(v, p->iOffset, iContinue);
1.100719 +    }
1.100720 +  }
1.100721 +
1.100722 +  switch( eDest ){
1.100723 +    /* In this mode, write each query result to the key of the temporary
1.100724 +    ** table iParm.
1.100725 +    */
1.100726 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
1.100727 +    case SRT_Union: {
1.100728 +      int r1;
1.100729 +      r1 = sqlite3GetTempReg(pParse);
1.100730 +      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
1.100731 +      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
1.100732 +      sqlite3ReleaseTempReg(pParse, r1);
1.100733 +      break;
1.100734 +    }
1.100735 +
1.100736 +    /* Construct a record from the query result, but instead of
1.100737 +    ** saving that record, use it as a key to delete elements from
1.100738 +    ** the temporary table iParm.
1.100739 +    */
1.100740 +    case SRT_Except: {
1.100741 +      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
1.100742 +      break;
1.100743 +    }
1.100744 +#endif /* SQLITE_OMIT_COMPOUND_SELECT */
1.100745 +
1.100746 +    /* Store the result as data using a unique key.
1.100747 +    */
1.100748 +    case SRT_DistTable:
1.100749 +    case SRT_Table:
1.100750 +    case SRT_EphemTab: {
1.100751 +      int r1 = sqlite3GetTempReg(pParse);
1.100752 +      testcase( eDest==SRT_Table );
1.100753 +      testcase( eDest==SRT_EphemTab );
1.100754 +      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
1.100755 +#ifndef SQLITE_OMIT_CTE
1.100756 +      if( eDest==SRT_DistTable ){
1.100757 +        /* If the destination is DistTable, then cursor (iParm+1) is open
1.100758 +        ** on an ephemeral index. If the current row is already present
1.100759 +        ** in the index, do not write it to the output. If not, add the
1.100760 +        ** current row to the index and proceed with writing it to the
1.100761 +        ** output table as well.  */
1.100762 +        int addr = sqlite3VdbeCurrentAddr(v) + 4;
1.100763 +        sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); VdbeCoverage(v);
1.100764 +        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
1.100765 +        assert( pOrderBy==0 );
1.100766 +      }
1.100767 +#endif
1.100768 +      if( pOrderBy ){
1.100769 +        pushOntoSorter(pParse, pOrderBy, p, r1);
1.100770 +      }else{
1.100771 +        int r2 = sqlite3GetTempReg(pParse);
1.100772 +        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
1.100773 +        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
1.100774 +        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1.100775 +        sqlite3ReleaseTempReg(pParse, r2);
1.100776 +      }
1.100777 +      sqlite3ReleaseTempReg(pParse, r1);
1.100778 +      break;
1.100779 +    }
1.100780 +
1.100781 +#ifndef SQLITE_OMIT_SUBQUERY
1.100782 +    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
1.100783 +    ** then there should be a single item on the stack.  Write this
1.100784 +    ** item into the set table with bogus data.
1.100785 +    */
1.100786 +    case SRT_Set: {
1.100787 +      assert( nResultCol==1 );
1.100788 +      pDest->affSdst =
1.100789 +                  sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
1.100790 +      if( pOrderBy ){
1.100791 +        /* At first glance you would think we could optimize out the
1.100792 +        ** ORDER BY in this case since the order of entries in the set
1.100793 +        ** does not matter.  But there might be a LIMIT clause, in which
1.100794 +        ** case the order does matter */
1.100795 +        pushOntoSorter(pParse, pOrderBy, p, regResult);
1.100796 +      }else{
1.100797 +        int r1 = sqlite3GetTempReg(pParse);
1.100798 +        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
1.100799 +        sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
1.100800 +        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
1.100801 +        sqlite3ReleaseTempReg(pParse, r1);
1.100802 +      }
1.100803 +      break;
1.100804 +    }
1.100805 +
1.100806 +    /* If any row exist in the result set, record that fact and abort.
1.100807 +    */
1.100808 +    case SRT_Exists: {
1.100809 +      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
1.100810 +      /* The LIMIT clause will terminate the loop for us */
1.100811 +      break;
1.100812 +    }
1.100813 +
1.100814 +    /* If this is a scalar select that is part of an expression, then
1.100815 +    ** store the results in the appropriate memory cell and break out
1.100816 +    ** of the scan loop.
1.100817 +    */
1.100818 +    case SRT_Mem: {
1.100819 +      assert( nResultCol==1 );
1.100820 +      if( pOrderBy ){
1.100821 +        pushOntoSorter(pParse, pOrderBy, p, regResult);
1.100822 +      }else{
1.100823 +        sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
1.100824 +        /* The LIMIT clause will jump out of the loop for us */
1.100825 +      }
1.100826 +      break;
1.100827 +    }
1.100828 +#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
1.100829 +
1.100830 +    case SRT_Coroutine:       /* Send data to a co-routine */
1.100831 +    case SRT_Output: {        /* Return the results */
1.100832 +      testcase( eDest==SRT_Coroutine );
1.100833 +      testcase( eDest==SRT_Output );
1.100834 +      if( pOrderBy ){
1.100835 +        int r1 = sqlite3GetTempReg(pParse);
1.100836 +        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
1.100837 +        pushOntoSorter(pParse, pOrderBy, p, r1);
1.100838 +        sqlite3ReleaseTempReg(pParse, r1);
1.100839 +      }else if( eDest==SRT_Coroutine ){
1.100840 +        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
1.100841 +      }else{
1.100842 +        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
1.100843 +        sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
1.100844 +      }
1.100845 +      break;
1.100846 +    }
1.100847 +
1.100848 +#ifndef SQLITE_OMIT_CTE
1.100849 +    /* Write the results into a priority queue that is order according to
1.100850 +    ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
1.100851 +    ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
1.100852 +    ** pSO->nExpr columns, then make sure all keys are unique by adding a
1.100853 +    ** final OP_Sequence column.  The last column is the record as a blob.
1.100854 +    */
1.100855 +    case SRT_DistQueue:
1.100856 +    case SRT_Queue: {
1.100857 +      int nKey;
1.100858 +      int r1, r2, r3;
1.100859 +      int addrTest = 0;
1.100860 +      ExprList *pSO;
1.100861 +      pSO = pDest->pOrderBy;
1.100862 +      assert( pSO );
1.100863 +      nKey = pSO->nExpr;
1.100864 +      r1 = sqlite3GetTempReg(pParse);
1.100865 +      r2 = sqlite3GetTempRange(pParse, nKey+2);
1.100866 +      r3 = r2+nKey+1;
1.100867 +      if( eDest==SRT_DistQueue ){
1.100868 +        /* If the destination is DistQueue, then cursor (iParm+1) is open
1.100869 +        ** on a second ephemeral index that holds all values every previously
1.100870 +        ** added to the queue. */
1.100871 +        addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, 
1.100872 +                                        regResult, nResultCol);
1.100873 +        VdbeCoverage(v);
1.100874 +      }
1.100875 +      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
1.100876 +      if( eDest==SRT_DistQueue ){
1.100877 +        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
1.100878 +        sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1.100879 +      }
1.100880 +      for(i=0; i<nKey; i++){
1.100881 +        sqlite3VdbeAddOp2(v, OP_SCopy,
1.100882 +                          regResult + pSO->a[i].u.x.iOrderByCol - 1,
1.100883 +                          r2+i);
1.100884 +      }
1.100885 +      sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
1.100886 +      sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
1.100887 +      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
1.100888 +      if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
1.100889 +      sqlite3ReleaseTempReg(pParse, r1);
1.100890 +      sqlite3ReleaseTempRange(pParse, r2, nKey+2);
1.100891 +      break;
1.100892 +    }
1.100893 +#endif /* SQLITE_OMIT_CTE */
1.100894 +
1.100895 +
1.100896 +
1.100897 +#if !defined(SQLITE_OMIT_TRIGGER)
1.100898 +    /* Discard the results.  This is used for SELECT statements inside
1.100899 +    ** the body of a TRIGGER.  The purpose of such selects is to call
1.100900 +    ** user-defined functions that have side effects.  We do not care
1.100901 +    ** about the actual results of the select.
1.100902 +    */
1.100903 +    default: {
1.100904 +      assert( eDest==SRT_Discard );
1.100905 +      break;
1.100906 +    }
1.100907 +#endif
1.100908 +  }
1.100909 +
1.100910 +  /* Jump to the end of the loop if the LIMIT is reached.  Except, if
1.100911 +  ** there is a sorter, in which case the sorter has already limited
1.100912 +  ** the output for us.
1.100913 +  */
1.100914 +  if( pOrderBy==0 && p->iLimit ){
1.100915 +    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v);
1.100916 +  }
1.100917 +}
1.100918 +
1.100919 +/*
1.100920 +** Allocate a KeyInfo object sufficient for an index of N key columns and
1.100921 +** X extra columns.
1.100922 +*/
1.100923 +SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
1.100924 +  KeyInfo *p = sqlite3DbMallocZero(0, 
1.100925 +                   sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
1.100926 +  if( p ){
1.100927 +    p->aSortOrder = (u8*)&p->aColl[N+X];
1.100928 +    p->nField = (u16)N;
1.100929 +    p->nXField = (u16)X;
1.100930 +    p->enc = ENC(db);
1.100931 +    p->db = db;
1.100932 +    p->nRef = 1;
1.100933 +  }else{
1.100934 +    db->mallocFailed = 1;
1.100935 +  }
1.100936 +  return p;
1.100937 +}
1.100938 +
1.100939 +/*
1.100940 +** Deallocate a KeyInfo object
1.100941 +*/
1.100942 +SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
1.100943 +  if( p ){
1.100944 +    assert( p->nRef>0 );
1.100945 +    p->nRef--;
1.100946 +    if( p->nRef==0 ) sqlite3DbFree(0, p);
1.100947 +  }
1.100948 +}
1.100949 +
1.100950 +/*
1.100951 +** Make a new pointer to a KeyInfo object
1.100952 +*/
1.100953 +SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
1.100954 +  if( p ){
1.100955 +    assert( p->nRef>0 );
1.100956 +    p->nRef++;
1.100957 +  }
1.100958 +  return p;
1.100959 +}
1.100960 +
1.100961 +#ifdef SQLITE_DEBUG
1.100962 +/*
1.100963 +** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
1.100964 +** can only be changed if this is just a single reference to the object.
1.100965 +**
1.100966 +** This routine is used only inside of assert() statements.
1.100967 +*/
1.100968 +SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
1.100969 +#endif /* SQLITE_DEBUG */
1.100970 +
1.100971 +/*
1.100972 +** Given an expression list, generate a KeyInfo structure that records
1.100973 +** the collating sequence for each expression in that expression list.
1.100974 +**
1.100975 +** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
1.100976 +** KeyInfo structure is appropriate for initializing a virtual index to
1.100977 +** implement that clause.  If the ExprList is the result set of a SELECT
1.100978 +** then the KeyInfo structure is appropriate for initializing a virtual
1.100979 +** index to implement a DISTINCT test.
1.100980 +**
1.100981 +** Space to hold the KeyInfo structure is obtain from malloc.  The calling
1.100982 +** function is responsible for seeing that this structure is eventually
1.100983 +** freed.
1.100984 +*/
1.100985 +static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList, int nExtra){
1.100986 +  int nExpr;
1.100987 +  KeyInfo *pInfo;
1.100988 +  struct ExprList_item *pItem;
1.100989 +  sqlite3 *db = pParse->db;
1.100990 +  int i;
1.100991 +
1.100992 +  nExpr = pList->nExpr;
1.100993 +  pInfo = sqlite3KeyInfoAlloc(db, nExpr+nExtra, 1);
1.100994 +  if( pInfo ){
1.100995 +    assert( sqlite3KeyInfoIsWriteable(pInfo) );
1.100996 +    for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
1.100997 +      CollSeq *pColl;
1.100998 +      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
1.100999 +      if( !pColl ) pColl = db->pDfltColl;
1.101000 +      pInfo->aColl[i] = pColl;
1.101001 +      pInfo->aSortOrder[i] = pItem->sortOrder;
1.101002 +    }
1.101003 +  }
1.101004 +  return pInfo;
1.101005 +}
1.101006 +
1.101007 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
1.101008 +/*
1.101009 +** Name of the connection operator, used for error messages.
1.101010 +*/
1.101011 +static const char *selectOpName(int id){
1.101012 +  char *z;
1.101013 +  switch( id ){
1.101014 +    case TK_ALL:       z = "UNION ALL";   break;
1.101015 +    case TK_INTERSECT: z = "INTERSECT";   break;
1.101016 +    case TK_EXCEPT:    z = "EXCEPT";      break;
1.101017 +    default:           z = "UNION";       break;
1.101018 +  }
1.101019 +  return z;
1.101020 +}
1.101021 +#endif /* SQLITE_OMIT_COMPOUND_SELECT */
1.101022 +
1.101023 +#ifndef SQLITE_OMIT_EXPLAIN
1.101024 +/*
1.101025 +** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
1.101026 +** is a no-op. Otherwise, it adds a single row of output to the EQP result,
1.101027 +** where the caption is of the form:
1.101028 +**
1.101029 +**   "USE TEMP B-TREE FOR xxx"
1.101030 +**
1.101031 +** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
1.101032 +** is determined by the zUsage argument.
1.101033 +*/
1.101034 +static void explainTempTable(Parse *pParse, const char *zUsage){
1.101035 +  if( pParse->explain==2 ){
1.101036 +    Vdbe *v = pParse->pVdbe;
1.101037 +    char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
1.101038 +    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
1.101039 +  }
1.101040 +}
1.101041 +
1.101042 +/*
1.101043 +** Assign expression b to lvalue a. A second, no-op, version of this macro
1.101044 +** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
1.101045 +** in sqlite3Select() to assign values to structure member variables that
1.101046 +** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
1.101047 +** code with #ifndef directives.
1.101048 +*/
1.101049 +# define explainSetInteger(a, b) a = b
1.101050 +
1.101051 +#else
1.101052 +/* No-op versions of the explainXXX() functions and macros. */
1.101053 +# define explainTempTable(y,z)
1.101054 +# define explainSetInteger(y,z)
1.101055 +#endif
1.101056 +
1.101057 +#if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
1.101058 +/*
1.101059 +** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
1.101060 +** is a no-op. Otherwise, it adds a single row of output to the EQP result,
1.101061 +** where the caption is of one of the two forms:
1.101062 +**
1.101063 +**   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
1.101064 +**   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
1.101065 +**
1.101066 +** where iSub1 and iSub2 are the integers passed as the corresponding
1.101067 +** function parameters, and op is the text representation of the parameter
1.101068 +** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
1.101069 +** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 
1.101070 +** false, or the second form if it is true.
1.101071 +*/
1.101072 +static void explainComposite(
1.101073 +  Parse *pParse,                  /* Parse context */
1.101074 +  int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
1.101075 +  int iSub1,                      /* Subquery id 1 */
1.101076 +  int iSub2,                      /* Subquery id 2 */
1.101077 +  int bUseTmp                     /* True if a temp table was used */
1.101078 +){
1.101079 +  assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
1.101080 +  if( pParse->explain==2 ){
1.101081 +    Vdbe *v = pParse->pVdbe;
1.101082 +    char *zMsg = sqlite3MPrintf(
1.101083 +        pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
1.101084 +        bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
1.101085 +    );
1.101086 +    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
1.101087 +  }
1.101088 +}
1.101089 +#else
1.101090 +/* No-op versions of the explainXXX() functions and macros. */
1.101091 +# define explainComposite(v,w,x,y,z)
1.101092 +#endif
1.101093 +
1.101094 +/*
1.101095 +** If the inner loop was generated using a non-null pOrderBy argument,
1.101096 +** then the results were placed in a sorter.  After the loop is terminated
1.101097 +** we need to run the sorter and output the results.  The following
1.101098 +** routine generates the code needed to do that.
1.101099 +*/
1.101100 +static void generateSortTail(
1.101101 +  Parse *pParse,    /* Parsing context */
1.101102 +  Select *p,        /* The SELECT statement */
1.101103 +  Vdbe *v,          /* Generate code into this VDBE */
1.101104 +  int nColumn,      /* Number of columns of data */
1.101105 +  SelectDest *pDest /* Write the sorted results here */
1.101106 +){
1.101107 +  int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
1.101108 +  int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
1.101109 +  int addr;
1.101110 +  int iTab;
1.101111 +  int pseudoTab = 0;
1.101112 +  ExprList *pOrderBy = p->pOrderBy;
1.101113 +
1.101114 +  int eDest = pDest->eDest;
1.101115 +  int iParm = pDest->iSDParm;
1.101116 +
1.101117 +  int regRow;
1.101118 +  int regRowid;
1.101119 +
1.101120 +  iTab = pOrderBy->iECursor;
1.101121 +  regRow = sqlite3GetTempReg(pParse);
1.101122 +  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
1.101123 +    pseudoTab = pParse->nTab++;
1.101124 +    sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
1.101125 +    regRowid = 0;
1.101126 +  }else{
1.101127 +    regRowid = sqlite3GetTempReg(pParse);
1.101128 +  }
1.101129 +  if( p->selFlags & SF_UseSorter ){
1.101130 +    int regSortOut = ++pParse->nMem;
1.101131 +    int ptab2 = pParse->nTab++;
1.101132 +    sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
1.101133 +    addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
1.101134 +    VdbeCoverage(v);
1.101135 +    codeOffset(v, p->iOffset, addrContinue);
1.101136 +    sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
1.101137 +    sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
1.101138 +    sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
1.101139 +  }else{
1.101140 +    addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
1.101141 +    codeOffset(v, p->iOffset, addrContinue);
1.101142 +    sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
1.101143 +  }
1.101144 +  switch( eDest ){
1.101145 +    case SRT_Table:
1.101146 +    case SRT_EphemTab: {
1.101147 +      testcase( eDest==SRT_Table );
1.101148 +      testcase( eDest==SRT_EphemTab );
1.101149 +      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
1.101150 +      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
1.101151 +      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1.101152 +      break;
1.101153 +    }
1.101154 +#ifndef SQLITE_OMIT_SUBQUERY
1.101155 +    case SRT_Set: {
1.101156 +      assert( nColumn==1 );
1.101157 +      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
1.101158 +                        &pDest->affSdst, 1);
1.101159 +      sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
1.101160 +      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
1.101161 +      break;
1.101162 +    }
1.101163 +    case SRT_Mem: {
1.101164 +      assert( nColumn==1 );
1.101165 +      sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
1.101166 +      /* The LIMIT clause will terminate the loop for us */
1.101167 +      break;
1.101168 +    }
1.101169 +#endif
1.101170 +    default: {
1.101171 +      int i;
1.101172 +      assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
1.101173 +      testcase( eDest==SRT_Output );
1.101174 +      testcase( eDest==SRT_Coroutine );
1.101175 +      for(i=0; i<nColumn; i++){
1.101176 +        assert( regRow!=pDest->iSdst+i );
1.101177 +        sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
1.101178 +        if( i==0 ){
1.101179 +          sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
1.101180 +        }
1.101181 +      }
1.101182 +      if( eDest==SRT_Output ){
1.101183 +        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
1.101184 +        sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
1.101185 +      }else{
1.101186 +        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
1.101187 +      }
1.101188 +      break;
1.101189 +    }
1.101190 +  }
1.101191 +  sqlite3ReleaseTempReg(pParse, regRow);
1.101192 +  sqlite3ReleaseTempReg(pParse, regRowid);
1.101193 +
1.101194 +  /* The bottom of the loop
1.101195 +  */
1.101196 +  sqlite3VdbeResolveLabel(v, addrContinue);
1.101197 +  if( p->selFlags & SF_UseSorter ){
1.101198 +    sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
1.101199 +  }else{
1.101200 +    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
1.101201 +  }
1.101202 +  sqlite3VdbeResolveLabel(v, addrBreak);
1.101203 +  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
1.101204 +    sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
1.101205 +  }
1.101206 +}
1.101207 +
1.101208 +/*
1.101209 +** Return a pointer to a string containing the 'declaration type' of the
1.101210 +** expression pExpr. The string may be treated as static by the caller.
1.101211 +**
1.101212 +** Also try to estimate the size of the returned value and return that
1.101213 +** result in *pEstWidth.
1.101214 +**
1.101215 +** The declaration type is the exact datatype definition extracted from the
1.101216 +** original CREATE TABLE statement if the expression is a column. The
1.101217 +** declaration type for a ROWID field is INTEGER. Exactly when an expression
1.101218 +** is considered a column can be complex in the presence of subqueries. The
1.101219 +** result-set expression in all of the following SELECT statements is 
1.101220 +** considered a column by this function.
1.101221 +**
1.101222 +**   SELECT col FROM tbl;
1.101223 +**   SELECT (SELECT col FROM tbl;
1.101224 +**   SELECT (SELECT col FROM tbl);
1.101225 +**   SELECT abc FROM (SELECT col AS abc FROM tbl);
1.101226 +** 
1.101227 +** The declaration type for any expression other than a column is NULL.
1.101228 +**
1.101229 +** This routine has either 3 or 6 parameters depending on whether or not
1.101230 +** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
1.101231 +*/
1.101232 +#ifdef SQLITE_ENABLE_COLUMN_METADATA
1.101233 +# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
1.101234 +static const char *columnTypeImpl(
1.101235 +  NameContext *pNC, 
1.101236 +  Expr *pExpr,
1.101237 +  const char **pzOrigDb,
1.101238 +  const char **pzOrigTab,
1.101239 +  const char **pzOrigCol,
1.101240 +  u8 *pEstWidth
1.101241 +){
1.101242 +  char const *zOrigDb = 0;
1.101243 +  char const *zOrigTab = 0;
1.101244 +  char const *zOrigCol = 0;
1.101245 +#else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
1.101246 +# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
1.101247 +static const char *columnTypeImpl(
1.101248 +  NameContext *pNC, 
1.101249 +  Expr *pExpr,
1.101250 +  u8 *pEstWidth
1.101251 +){
1.101252 +#endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
1.101253 +  char const *zType = 0;
1.101254 +  int j;
1.101255 +  u8 estWidth = 1;
1.101256 +
1.101257 +  if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
1.101258 +  switch( pExpr->op ){
1.101259 +    case TK_AGG_COLUMN:
1.101260 +    case TK_COLUMN: {
1.101261 +      /* The expression is a column. Locate the table the column is being
1.101262 +      ** extracted from in NameContext.pSrcList. This table may be real
1.101263 +      ** database table or a subquery.
1.101264 +      */
1.101265 +      Table *pTab = 0;            /* Table structure column is extracted from */
1.101266 +      Select *pS = 0;             /* Select the column is extracted from */
1.101267 +      int iCol = pExpr->iColumn;  /* Index of column in pTab */
1.101268 +      testcase( pExpr->op==TK_AGG_COLUMN );
1.101269 +      testcase( pExpr->op==TK_COLUMN );
1.101270 +      while( pNC && !pTab ){
1.101271 +        SrcList *pTabList = pNC->pSrcList;
1.101272 +        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
1.101273 +        if( j<pTabList->nSrc ){
1.101274 +          pTab = pTabList->a[j].pTab;
1.101275 +          pS = pTabList->a[j].pSelect;
1.101276 +        }else{
1.101277 +          pNC = pNC->pNext;
1.101278 +        }
1.101279 +      }
1.101280 +
1.101281 +      if( pTab==0 ){
1.101282 +        /* At one time, code such as "SELECT new.x" within a trigger would
1.101283 +        ** cause this condition to run.  Since then, we have restructured how
1.101284 +        ** trigger code is generated and so this condition is no longer 
1.101285 +        ** possible. However, it can still be true for statements like
1.101286 +        ** the following:
1.101287 +        **
1.101288 +        **   CREATE TABLE t1(col INTEGER);
1.101289 +        **   SELECT (SELECT t1.col) FROM FROM t1;
1.101290 +        **
1.101291 +        ** when columnType() is called on the expression "t1.col" in the 
1.101292 +        ** sub-select. In this case, set the column type to NULL, even
1.101293 +        ** though it should really be "INTEGER".
1.101294 +        **
1.101295 +        ** This is not a problem, as the column type of "t1.col" is never
1.101296 +        ** used. When columnType() is called on the expression 
1.101297 +        ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
1.101298 +        ** branch below.  */
1.101299 +        break;
1.101300 +      }
1.101301 +
1.101302 +      assert( pTab && pExpr->pTab==pTab );
1.101303 +      if( pS ){
1.101304 +        /* The "table" is actually a sub-select or a view in the FROM clause
1.101305 +        ** of the SELECT statement. Return the declaration type and origin
1.101306 +        ** data for the result-set column of the sub-select.
1.101307 +        */
1.101308 +        if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
1.101309 +          /* If iCol is less than zero, then the expression requests the
1.101310 +          ** rowid of the sub-select or view. This expression is legal (see 
1.101311 +          ** test case misc2.2.2) - it always evaluates to NULL.
1.101312 +          */
1.101313 +          NameContext sNC;
1.101314 +          Expr *p = pS->pEList->a[iCol].pExpr;
1.101315 +          sNC.pSrcList = pS->pSrc;
1.101316 +          sNC.pNext = pNC;
1.101317 +          sNC.pParse = pNC->pParse;
1.101318 +          zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth); 
1.101319 +        }
1.101320 +      }else if( pTab->pSchema ){
1.101321 +        /* A real table */
1.101322 +        assert( !pS );
1.101323 +        if( iCol<0 ) iCol = pTab->iPKey;
1.101324 +        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1.101325 +#ifdef SQLITE_ENABLE_COLUMN_METADATA
1.101326 +        if( iCol<0 ){
1.101327 +          zType = "INTEGER";
1.101328 +          zOrigCol = "rowid";
1.101329 +        }else{
1.101330 +          zType = pTab->aCol[iCol].zType;
1.101331 +          zOrigCol = pTab->aCol[iCol].zName;
1.101332 +          estWidth = pTab->aCol[iCol].szEst;
1.101333 +        }
1.101334 +        zOrigTab = pTab->zName;
1.101335 +        if( pNC->pParse ){
1.101336 +          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
1.101337 +          zOrigDb = pNC->pParse->db->aDb[iDb].zName;
1.101338 +        }
1.101339 +#else
1.101340 +        if( iCol<0 ){
1.101341 +          zType = "INTEGER";
1.101342 +        }else{
1.101343 +          zType = pTab->aCol[iCol].zType;
1.101344 +          estWidth = pTab->aCol[iCol].szEst;
1.101345 +        }
1.101346 +#endif
1.101347 +      }
1.101348 +      break;
1.101349 +    }
1.101350 +#ifndef SQLITE_OMIT_SUBQUERY
1.101351 +    case TK_SELECT: {
1.101352 +      /* The expression is a sub-select. Return the declaration type and
1.101353 +      ** origin info for the single column in the result set of the SELECT
1.101354 +      ** statement.
1.101355 +      */
1.101356 +      NameContext sNC;
1.101357 +      Select *pS = pExpr->x.pSelect;
1.101358 +      Expr *p = pS->pEList->a[0].pExpr;
1.101359 +      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
1.101360 +      sNC.pSrcList = pS->pSrc;
1.101361 +      sNC.pNext = pNC;
1.101362 +      sNC.pParse = pNC->pParse;
1.101363 +      zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth); 
1.101364 +      break;
1.101365 +    }
1.101366 +#endif
1.101367 +  }
1.101368 +
1.101369 +#ifdef SQLITE_ENABLE_COLUMN_METADATA  
1.101370 +  if( pzOrigDb ){
1.101371 +    assert( pzOrigTab && pzOrigCol );
1.101372 +    *pzOrigDb = zOrigDb;
1.101373 +    *pzOrigTab = zOrigTab;
1.101374 +    *pzOrigCol = zOrigCol;
1.101375 +  }
1.101376 +#endif
1.101377 +  if( pEstWidth ) *pEstWidth = estWidth;
1.101378 +  return zType;
1.101379 +}
1.101380 +
1.101381 +/*
1.101382 +** Generate code that will tell the VDBE the declaration types of columns
1.101383 +** in the result set.
1.101384 +*/
1.101385 +static void generateColumnTypes(
1.101386 +  Parse *pParse,      /* Parser context */
1.101387 +  SrcList *pTabList,  /* List of tables */
1.101388 +  ExprList *pEList    /* Expressions defining the result set */
1.101389 +){
1.101390 +#ifndef SQLITE_OMIT_DECLTYPE
1.101391 +  Vdbe *v = pParse->pVdbe;
1.101392 +  int i;
1.101393 +  NameContext sNC;
1.101394 +  sNC.pSrcList = pTabList;
1.101395 +  sNC.pParse = pParse;
1.101396 +  for(i=0; i<pEList->nExpr; i++){
1.101397 +    Expr *p = pEList->a[i].pExpr;
1.101398 +    const char *zType;
1.101399 +#ifdef SQLITE_ENABLE_COLUMN_METADATA
1.101400 +    const char *zOrigDb = 0;
1.101401 +    const char *zOrigTab = 0;
1.101402 +    const char *zOrigCol = 0;
1.101403 +    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
1.101404 +
1.101405 +    /* The vdbe must make its own copy of the column-type and other 
1.101406 +    ** column specific strings, in case the schema is reset before this
1.101407 +    ** virtual machine is deleted.
1.101408 +    */
1.101409 +    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
1.101410 +    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
1.101411 +    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
1.101412 +#else
1.101413 +    zType = columnType(&sNC, p, 0, 0, 0, 0);
1.101414 +#endif
1.101415 +    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
1.101416 +  }
1.101417 +#endif /* !defined(SQLITE_OMIT_DECLTYPE) */
1.101418 +}
1.101419 +
1.101420 +/*
1.101421 +** Generate code that will tell the VDBE the names of columns
1.101422 +** in the result set.  This information is used to provide the
1.101423 +** azCol[] values in the callback.
1.101424 +*/
1.101425 +static void generateColumnNames(
1.101426 +  Parse *pParse,      /* Parser context */
1.101427 +  SrcList *pTabList,  /* List of tables */
1.101428 +  ExprList *pEList    /* Expressions defining the result set */
1.101429 +){
1.101430 +  Vdbe *v = pParse->pVdbe;
1.101431 +  int i, j;
1.101432 +  sqlite3 *db = pParse->db;
1.101433 +  int fullNames, shortNames;
1.101434 +
1.101435 +#ifndef SQLITE_OMIT_EXPLAIN
1.101436 +  /* If this is an EXPLAIN, skip this step */
1.101437 +  if( pParse->explain ){
1.101438 +    return;
1.101439 +  }
1.101440 +#endif
1.101441 +
1.101442 +  if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
1.101443 +  pParse->colNamesSet = 1;
1.101444 +  fullNames = (db->flags & SQLITE_FullColNames)!=0;
1.101445 +  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
1.101446 +  sqlite3VdbeSetNumCols(v, pEList->nExpr);
1.101447 +  for(i=0; i<pEList->nExpr; i++){
1.101448 +    Expr *p;
1.101449 +    p = pEList->a[i].pExpr;
1.101450 +    if( NEVER(p==0) ) continue;
1.101451 +    if( pEList->a[i].zName ){
1.101452 +      char *zName = pEList->a[i].zName;
1.101453 +      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
1.101454 +    }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
1.101455 +      Table *pTab;
1.101456 +      char *zCol;
1.101457 +      int iCol = p->iColumn;
1.101458 +      for(j=0; ALWAYS(j<pTabList->nSrc); j++){
1.101459 +        if( pTabList->a[j].iCursor==p->iTable ) break;
1.101460 +      }
1.101461 +      assert( j<pTabList->nSrc );
1.101462 +      pTab = pTabList->a[j].pTab;
1.101463 +      if( iCol<0 ) iCol = pTab->iPKey;
1.101464 +      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1.101465 +      if( iCol<0 ){
1.101466 +        zCol = "rowid";
1.101467 +      }else{
1.101468 +        zCol = pTab->aCol[iCol].zName;
1.101469 +      }
1.101470 +      if( !shortNames && !fullNames ){
1.101471 +        sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
1.101472 +            sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
1.101473 +      }else if( fullNames ){
1.101474 +        char *zName = 0;
1.101475 +        zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
1.101476 +        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
1.101477 +      }else{
1.101478 +        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
1.101479 +      }
1.101480 +    }else{
1.101481 +      const char *z = pEList->a[i].zSpan;
1.101482 +      z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
1.101483 +      sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
1.101484 +    }
1.101485 +  }
1.101486 +  generateColumnTypes(pParse, pTabList, pEList);
1.101487 +}
1.101488 +
1.101489 +/*
1.101490 +** Given a an expression list (which is really the list of expressions
1.101491 +** that form the result set of a SELECT statement) compute appropriate
1.101492 +** column names for a table that would hold the expression list.
1.101493 +**
1.101494 +** All column names will be unique.
1.101495 +**
1.101496 +** Only the column names are computed.  Column.zType, Column.zColl,
1.101497 +** and other fields of Column are zeroed.
1.101498 +**
1.101499 +** Return SQLITE_OK on success.  If a memory allocation error occurs,
1.101500 +** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
1.101501 +*/
1.101502 +static int selectColumnsFromExprList(
1.101503 +  Parse *pParse,          /* Parsing context */
1.101504 +  ExprList *pEList,       /* Expr list from which to derive column names */
1.101505 +  i16 *pnCol,             /* Write the number of columns here */
1.101506 +  Column **paCol          /* Write the new column list here */
1.101507 +){
1.101508 +  sqlite3 *db = pParse->db;   /* Database connection */
1.101509 +  int i, j;                   /* Loop counters */
1.101510 +  int cnt;                    /* Index added to make the name unique */
1.101511 +  Column *aCol, *pCol;        /* For looping over result columns */
1.101512 +  int nCol;                   /* Number of columns in the result set */
1.101513 +  Expr *p;                    /* Expression for a single result column */
1.101514 +  char *zName;                /* Column name */
1.101515 +  int nName;                  /* Size of name in zName[] */
1.101516 +
1.101517 +  if( pEList ){
1.101518 +    nCol = pEList->nExpr;
1.101519 +    aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
1.101520 +    testcase( aCol==0 );
1.101521 +  }else{
1.101522 +    nCol = 0;
1.101523 +    aCol = 0;
1.101524 +  }
1.101525 +  *pnCol = nCol;
1.101526 +  *paCol = aCol;
1.101527 +
1.101528 +  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
1.101529 +    /* Get an appropriate name for the column
1.101530 +    */
1.101531 +    p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
1.101532 +    if( (zName = pEList->a[i].zName)!=0 ){
1.101533 +      /* If the column contains an "AS <name>" phrase, use <name> as the name */
1.101534 +      zName = sqlite3DbStrDup(db, zName);
1.101535 +    }else{
1.101536 +      Expr *pColExpr = p;  /* The expression that is the result column name */
1.101537 +      Table *pTab;         /* Table associated with this expression */
1.101538 +      while( pColExpr->op==TK_DOT ){
1.101539 +        pColExpr = pColExpr->pRight;
1.101540 +        assert( pColExpr!=0 );
1.101541 +      }
1.101542 +      if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
1.101543 +        /* For columns use the column name name */
1.101544 +        int iCol = pColExpr->iColumn;
1.101545 +        pTab = pColExpr->pTab;
1.101546 +        if( iCol<0 ) iCol = pTab->iPKey;
1.101547 +        zName = sqlite3MPrintf(db, "%s",
1.101548 +                 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
1.101549 +      }else if( pColExpr->op==TK_ID ){
1.101550 +        assert( !ExprHasProperty(pColExpr, EP_IntValue) );
1.101551 +        zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
1.101552 +      }else{
1.101553 +        /* Use the original text of the column expression as its name */
1.101554 +        zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
1.101555 +      }
1.101556 +    }
1.101557 +    if( db->mallocFailed ){
1.101558 +      sqlite3DbFree(db, zName);
1.101559 +      break;
1.101560 +    }
1.101561 +
1.101562 +    /* Make sure the column name is unique.  If the name is not unique,
1.101563 +    ** append a integer to the name so that it becomes unique.
1.101564 +    */
1.101565 +    nName = sqlite3Strlen30(zName);
1.101566 +    for(j=cnt=0; j<i; j++){
1.101567 +      if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
1.101568 +        char *zNewName;
1.101569 +        int k;
1.101570 +        for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
1.101571 +        if( k>=0 && zName[k]==':' ) nName = k;
1.101572 +        zName[nName] = 0;
1.101573 +        zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
1.101574 +        sqlite3DbFree(db, zName);
1.101575 +        zName = zNewName;
1.101576 +        j = -1;
1.101577 +        if( zName==0 ) break;
1.101578 +      }
1.101579 +    }
1.101580 +    pCol->zName = zName;
1.101581 +  }
1.101582 +  if( db->mallocFailed ){
1.101583 +    for(j=0; j<i; j++){
1.101584 +      sqlite3DbFree(db, aCol[j].zName);
1.101585 +    }
1.101586 +    sqlite3DbFree(db, aCol);
1.101587 +    *paCol = 0;
1.101588 +    *pnCol = 0;
1.101589 +    return SQLITE_NOMEM;
1.101590 +  }
1.101591 +  return SQLITE_OK;
1.101592 +}
1.101593 +
1.101594 +/*
1.101595 +** Add type and collation information to a column list based on
1.101596 +** a SELECT statement.
1.101597 +** 
1.101598 +** The column list presumably came from selectColumnNamesFromExprList().
1.101599 +** The column list has only names, not types or collations.  This
1.101600 +** routine goes through and adds the types and collations.
1.101601 +**
1.101602 +** This routine requires that all identifiers in the SELECT
1.101603 +** statement be resolved.
1.101604 +*/
1.101605 +static void selectAddColumnTypeAndCollation(
1.101606 +  Parse *pParse,        /* Parsing contexts */
1.101607 +  Table *pTab,          /* Add column type information to this table */
1.101608 +  Select *pSelect       /* SELECT used to determine types and collations */
1.101609 +){
1.101610 +  sqlite3 *db = pParse->db;
1.101611 +  NameContext sNC;
1.101612 +  Column *pCol;
1.101613 +  CollSeq *pColl;
1.101614 +  int i;
1.101615 +  Expr *p;
1.101616 +  struct ExprList_item *a;
1.101617 +  u64 szAll = 0;
1.101618 +
1.101619 +  assert( pSelect!=0 );
1.101620 +  assert( (pSelect->selFlags & SF_Resolved)!=0 );
1.101621 +  assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
1.101622 +  if( db->mallocFailed ) return;
1.101623 +  memset(&sNC, 0, sizeof(sNC));
1.101624 +  sNC.pSrcList = pSelect->pSrc;
1.101625 +  a = pSelect->pEList->a;
1.101626 +  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
1.101627 +    p = a[i].pExpr;
1.101628 +    pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
1.101629 +    szAll += pCol->szEst;
1.101630 +    pCol->affinity = sqlite3ExprAffinity(p);
1.101631 +    if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
1.101632 +    pColl = sqlite3ExprCollSeq(pParse, p);
1.101633 +    if( pColl ){
1.101634 +      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
1.101635 +    }
1.101636 +  }
1.101637 +  pTab->szTabRow = sqlite3LogEst(szAll*4);
1.101638 +}
1.101639 +
1.101640 +/*
1.101641 +** Given a SELECT statement, generate a Table structure that describes
1.101642 +** the result set of that SELECT.
1.101643 +*/
1.101644 +SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
1.101645 +  Table *pTab;
1.101646 +  sqlite3 *db = pParse->db;
1.101647 +  int savedFlags;
1.101648 +
1.101649 +  savedFlags = db->flags;
1.101650 +  db->flags &= ~SQLITE_FullColNames;
1.101651 +  db->flags |= SQLITE_ShortColNames;
1.101652 +  sqlite3SelectPrep(pParse, pSelect, 0);
1.101653 +  if( pParse->nErr ) return 0;
1.101654 +  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
1.101655 +  db->flags = savedFlags;
1.101656 +  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
1.101657 +  if( pTab==0 ){
1.101658 +    return 0;
1.101659 +  }
1.101660 +  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
1.101661 +  ** is disabled */
1.101662 +  assert( db->lookaside.bEnabled==0 );
1.101663 +  pTab->nRef = 1;
1.101664 +  pTab->zName = 0;
1.101665 +  pTab->nRowEst = 1048576;
1.101666 +  selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
1.101667 +  selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
1.101668 +  pTab->iPKey = -1;
1.101669 +  if( db->mallocFailed ){
1.101670 +    sqlite3DeleteTable(db, pTab);
1.101671 +    return 0;
1.101672 +  }
1.101673 +  return pTab;
1.101674 +}
1.101675 +
1.101676 +/*
1.101677 +** Get a VDBE for the given parser context.  Create a new one if necessary.
1.101678 +** If an error occurs, return NULL and leave a message in pParse.
1.101679 +*/
1.101680 +SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
1.101681 +  Vdbe *v = pParse->pVdbe;
1.101682 +  if( v==0 ){
1.101683 +    v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
1.101684 +    if( v ) sqlite3VdbeAddOp0(v, OP_Init);
1.101685 +    if( pParse->pToplevel==0
1.101686 +     && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
1.101687 +    ){
1.101688 +      pParse->okConstFactor = 1;
1.101689 +    }
1.101690 +
1.101691 +  }
1.101692 +  return v;
1.101693 +}
1.101694 +
1.101695 +
1.101696 +/*
1.101697 +** Compute the iLimit and iOffset fields of the SELECT based on the
1.101698 +** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
1.101699 +** that appear in the original SQL statement after the LIMIT and OFFSET
1.101700 +** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
1.101701 +** are the integer memory register numbers for counters used to compute 
1.101702 +** the limit and offset.  If there is no limit and/or offset, then 
1.101703 +** iLimit and iOffset are negative.
1.101704 +**
1.101705 +** This routine changes the values of iLimit and iOffset only if
1.101706 +** a limit or offset is defined by pLimit and pOffset.  iLimit and
1.101707 +** iOffset should have been preset to appropriate default values (zero)
1.101708 +** prior to calling this routine.
1.101709 +**
1.101710 +** The iOffset register (if it exists) is initialized to the value
1.101711 +** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
1.101712 +** iOffset+1 is initialized to LIMIT+OFFSET.
1.101713 +**
1.101714 +** Only if pLimit!=0 or pOffset!=0 do the limit registers get
1.101715 +** redefined.  The UNION ALL operator uses this property to force
1.101716 +** the reuse of the same limit and offset registers across multiple
1.101717 +** SELECT statements.
1.101718 +*/
1.101719 +static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
1.101720 +  Vdbe *v = 0;
1.101721 +  int iLimit = 0;
1.101722 +  int iOffset;
1.101723 +  int addr1, n;
1.101724 +  if( p->iLimit ) return;
1.101725 +
1.101726 +  /* 
1.101727 +  ** "LIMIT -1" always shows all rows.  There is some
1.101728 +  ** controversy about what the correct behavior should be.
1.101729 +  ** The current implementation interprets "LIMIT 0" to mean
1.101730 +  ** no rows.
1.101731 +  */
1.101732 +  sqlite3ExprCacheClear(pParse);
1.101733 +  assert( p->pOffset==0 || p->pLimit!=0 );
1.101734 +  if( p->pLimit ){
1.101735 +    p->iLimit = iLimit = ++pParse->nMem;
1.101736 +    v = sqlite3GetVdbe(pParse);
1.101737 +    assert( v!=0 );
1.101738 +    if( sqlite3ExprIsInteger(p->pLimit, &n) ){
1.101739 +      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
1.101740 +      VdbeComment((v, "LIMIT counter"));
1.101741 +      if( n==0 ){
1.101742 +        sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
1.101743 +      }else if( n>=0 && p->nSelectRow>(u64)n ){
1.101744 +        p->nSelectRow = n;
1.101745 +      }
1.101746 +    }else{
1.101747 +      sqlite3ExprCode(pParse, p->pLimit, iLimit);
1.101748 +      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
1.101749 +      VdbeComment((v, "LIMIT counter"));
1.101750 +      sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); VdbeCoverage(v);
1.101751 +    }
1.101752 +    if( p->pOffset ){
1.101753 +      p->iOffset = iOffset = ++pParse->nMem;
1.101754 +      pParse->nMem++;   /* Allocate an extra register for limit+offset */
1.101755 +      sqlite3ExprCode(pParse, p->pOffset, iOffset);
1.101756 +      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
1.101757 +      VdbeComment((v, "OFFSET counter"));
1.101758 +      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); VdbeCoverage(v);
1.101759 +      sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
1.101760 +      sqlite3VdbeJumpHere(v, addr1);
1.101761 +      sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
1.101762 +      VdbeComment((v, "LIMIT+OFFSET"));
1.101763 +      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); VdbeCoverage(v);
1.101764 +      sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
1.101765 +      sqlite3VdbeJumpHere(v, addr1);
1.101766 +    }
1.101767 +  }
1.101768 +}
1.101769 +
1.101770 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
1.101771 +/*
1.101772 +** Return the appropriate collating sequence for the iCol-th column of
1.101773 +** the result set for the compound-select statement "p".  Return NULL if
1.101774 +** the column has no default collating sequence.
1.101775 +**
1.101776 +** The collating sequence for the compound select is taken from the
1.101777 +** left-most term of the select that has a collating sequence.
1.101778 +*/
1.101779 +static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1.101780 +  CollSeq *pRet;
1.101781 +  if( p->pPrior ){
1.101782 +    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1.101783 +  }else{
1.101784 +    pRet = 0;
1.101785 +  }
1.101786 +  assert( iCol>=0 );
1.101787 +  if( pRet==0 && iCol<p->pEList->nExpr ){
1.101788 +    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1.101789 +  }
1.101790 +  return pRet;
1.101791 +}
1.101792 +
1.101793 +/*
1.101794 +** The select statement passed as the second parameter is a compound SELECT
1.101795 +** with an ORDER BY clause. This function allocates and returns a KeyInfo
1.101796 +** structure suitable for implementing the ORDER BY.
1.101797 +**
1.101798 +** Space to hold the KeyInfo structure is obtained from malloc. The calling
1.101799 +** function is responsible for ensuring that this structure is eventually
1.101800 +** freed.
1.101801 +*/
1.101802 +static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
1.101803 +  ExprList *pOrderBy = p->pOrderBy;
1.101804 +  int nOrderBy = p->pOrderBy->nExpr;
1.101805 +  sqlite3 *db = pParse->db;
1.101806 +  KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
1.101807 +  if( pRet ){
1.101808 +    int i;
1.101809 +    for(i=0; i<nOrderBy; i++){
1.101810 +      struct ExprList_item *pItem = &pOrderBy->a[i];
1.101811 +      Expr *pTerm = pItem->pExpr;
1.101812 +      CollSeq *pColl;
1.101813 +
1.101814 +      if( pTerm->flags & EP_Collate ){
1.101815 +        pColl = sqlite3ExprCollSeq(pParse, pTerm);
1.101816 +      }else{
1.101817 +        pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
1.101818 +        if( pColl==0 ) pColl = db->pDfltColl;
1.101819 +        pOrderBy->a[i].pExpr =
1.101820 +          sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
1.101821 +      }
1.101822 +      assert( sqlite3KeyInfoIsWriteable(pRet) );
1.101823 +      pRet->aColl[i] = pColl;
1.101824 +      pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
1.101825 +    }
1.101826 +  }
1.101827 +
1.101828 +  return pRet;
1.101829 +}
1.101830 +
1.101831 +#ifndef SQLITE_OMIT_CTE
1.101832 +/*
1.101833 +** This routine generates VDBE code to compute the content of a WITH RECURSIVE
1.101834 +** query of the form:
1.101835 +**
1.101836 +**   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
1.101837 +**                         \___________/             \_______________/
1.101838 +**                           p->pPrior                      p
1.101839 +**
1.101840 +**
1.101841 +** There is exactly one reference to the recursive-table in the FROM clause
1.101842 +** of recursive-query, marked with the SrcList->a[].isRecursive flag.
1.101843 +**
1.101844 +** The setup-query runs once to generate an initial set of rows that go
1.101845 +** into a Queue table.  Rows are extracted from the Queue table one by
1.101846 +** one.  Each row extracted from Queue is output to pDest.  Then the single
1.101847 +** extracted row (now in the iCurrent table) becomes the content of the
1.101848 +** recursive-table for a recursive-query run.  The output of the recursive-query
1.101849 +** is added back into the Queue table.  Then another row is extracted from Queue
1.101850 +** and the iteration continues until the Queue table is empty.
1.101851 +**
1.101852 +** If the compound query operator is UNION then no duplicate rows are ever
1.101853 +** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
1.101854 +** that have ever been inserted into Queue and causes duplicates to be
1.101855 +** discarded.  If the operator is UNION ALL, then duplicates are allowed.
1.101856 +** 
1.101857 +** If the query has an ORDER BY, then entries in the Queue table are kept in
1.101858 +** ORDER BY order and the first entry is extracted for each cycle.  Without
1.101859 +** an ORDER BY, the Queue table is just a FIFO.
1.101860 +**
1.101861 +** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
1.101862 +** have been output to pDest.  A LIMIT of zero means to output no rows and a
1.101863 +** negative LIMIT means to output all rows.  If there is also an OFFSET clause
1.101864 +** with a positive value, then the first OFFSET outputs are discarded rather
1.101865 +** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
1.101866 +** rows have been skipped.
1.101867 +*/
1.101868 +static void generateWithRecursiveQuery(
1.101869 +  Parse *pParse,        /* Parsing context */
1.101870 +  Select *p,            /* The recursive SELECT to be coded */
1.101871 +  SelectDest *pDest     /* What to do with query results */
1.101872 +){
1.101873 +  SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
1.101874 +  int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
1.101875 +  Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
1.101876 +  Select *pSetup = p->pPrior;   /* The setup query */
1.101877 +  int addrTop;                  /* Top of the loop */
1.101878 +  int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
1.101879 +  int iCurrent = 0;             /* The Current table */
1.101880 +  int regCurrent;               /* Register holding Current table */
1.101881 +  int iQueue;                   /* The Queue table */
1.101882 +  int iDistinct = 0;            /* To ensure unique results if UNION */
1.101883 +  int eDest = SRT_Table;        /* How to write to Queue */
1.101884 +  SelectDest destQueue;         /* SelectDest targetting the Queue table */
1.101885 +  int i;                        /* Loop counter */
1.101886 +  int rc;                       /* Result code */
1.101887 +  ExprList *pOrderBy;           /* The ORDER BY clause */
1.101888 +  Expr *pLimit, *pOffset;       /* Saved LIMIT and OFFSET */
1.101889 +  int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
1.101890 +
1.101891 +  /* Obtain authorization to do a recursive query */
1.101892 +  if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
1.101893 +
1.101894 +  /* Process the LIMIT and OFFSET clauses, if they exist */
1.101895 +  addrBreak = sqlite3VdbeMakeLabel(v);
1.101896 +  computeLimitRegisters(pParse, p, addrBreak);
1.101897 +  pLimit = p->pLimit;
1.101898 +  pOffset = p->pOffset;
1.101899 +  regLimit = p->iLimit;
1.101900 +  regOffset = p->iOffset;
1.101901 +  p->pLimit = p->pOffset = 0;
1.101902 +  p->iLimit = p->iOffset = 0;
1.101903 +  pOrderBy = p->pOrderBy;
1.101904 +
1.101905 +  /* Locate the cursor number of the Current table */
1.101906 +  for(i=0; ALWAYS(i<pSrc->nSrc); i++){
1.101907 +    if( pSrc->a[i].isRecursive ){
1.101908 +      iCurrent = pSrc->a[i].iCursor;
1.101909 +      break;
1.101910 +    }
1.101911 +  }
1.101912 +
1.101913 +  /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
1.101914 +  ** the Distinct table must be exactly one greater than Queue in order
1.101915 +  ** for the SRT_DistTable and SRT_DistQueue destinations to work. */
1.101916 +  iQueue = pParse->nTab++;
1.101917 +  if( p->op==TK_UNION ){
1.101918 +    eDest = pOrderBy ? SRT_DistQueue : SRT_DistTable;
1.101919 +    iDistinct = pParse->nTab++;
1.101920 +  }else{
1.101921 +    eDest = pOrderBy ? SRT_Queue : SRT_Table;
1.101922 +  }
1.101923 +  sqlite3SelectDestInit(&destQueue, eDest, iQueue);
1.101924 +
1.101925 +  /* Allocate cursors for Current, Queue, and Distinct. */
1.101926 +  regCurrent = ++pParse->nMem;
1.101927 +  sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
1.101928 +  if( pOrderBy ){
1.101929 +    KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
1.101930 +    sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
1.101931 +                      (char*)pKeyInfo, P4_KEYINFO);
1.101932 +    destQueue.pOrderBy = pOrderBy;
1.101933 +  }else{
1.101934 +    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
1.101935 +  }
1.101936 +  VdbeComment((v, "Queue table"));
1.101937 +  if( iDistinct ){
1.101938 +    p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
1.101939 +    p->selFlags |= SF_UsesEphemeral;
1.101940 +  }
1.101941 +
1.101942 +  /* Detach the ORDER BY clause from the compound SELECT */
1.101943 +  p->pOrderBy = 0;
1.101944 +
1.101945 +  /* Store the results of the setup-query in Queue. */
1.101946 +  pSetup->pNext = 0;
1.101947 +  rc = sqlite3Select(pParse, pSetup, &destQueue);
1.101948 +  pSetup->pNext = p;
1.101949 +  if( rc ) goto end_of_recursive_query;
1.101950 +
1.101951 +  /* Find the next row in the Queue and output that row */
1.101952 +  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
1.101953 +
1.101954 +  /* Transfer the next row in Queue over to Current */
1.101955 +  sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
1.101956 +  if( pOrderBy ){
1.101957 +    sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
1.101958 +  }else{
1.101959 +    sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
1.101960 +  }
1.101961 +  sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
1.101962 +
1.101963 +  /* Output the single row in Current */
1.101964 +  addrCont = sqlite3VdbeMakeLabel(v);
1.101965 +  codeOffset(v, regOffset, addrCont);
1.101966 +  selectInnerLoop(pParse, p, p->pEList, iCurrent,
1.101967 +      0, 0, pDest, addrCont, addrBreak);
1.101968 +  if( regLimit ){
1.101969 +    sqlite3VdbeAddOp3(v, OP_IfZero, regLimit, addrBreak, -1);
1.101970 +    VdbeCoverage(v);
1.101971 +  }
1.101972 +  sqlite3VdbeResolveLabel(v, addrCont);
1.101973 +
1.101974 +  /* Execute the recursive SELECT taking the single row in Current as
1.101975 +  ** the value for the recursive-table. Store the results in the Queue.
1.101976 +  */
1.101977 +  p->pPrior = 0;
1.101978 +  sqlite3Select(pParse, p, &destQueue);
1.101979 +  assert( p->pPrior==0 );
1.101980 +  p->pPrior = pSetup;
1.101981 +
1.101982 +  /* Keep running the loop until the Queue is empty */
1.101983 +  sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
1.101984 +  sqlite3VdbeResolveLabel(v, addrBreak);
1.101985 +
1.101986 +end_of_recursive_query:
1.101987 +  p->pOrderBy = pOrderBy;
1.101988 +  p->pLimit = pLimit;
1.101989 +  p->pOffset = pOffset;
1.101990 +  return;
1.101991 +}
1.101992 +#endif /* SQLITE_OMIT_CTE */
1.101993 +
1.101994 +/* Forward references */
1.101995 +static int multiSelectOrderBy(
1.101996 +  Parse *pParse,        /* Parsing context */
1.101997 +  Select *p,            /* The right-most of SELECTs to be coded */
1.101998 +  SelectDest *pDest     /* What to do with query results */
1.101999 +);
1.102000 +
1.102001 +
1.102002 +/*
1.102003 +** This routine is called to process a compound query form from
1.102004 +** two or more separate queries using UNION, UNION ALL, EXCEPT, or
1.102005 +** INTERSECT
1.102006 +**
1.102007 +** "p" points to the right-most of the two queries.  the query on the
1.102008 +** left is p->pPrior.  The left query could also be a compound query
1.102009 +** in which case this routine will be called recursively. 
1.102010 +**
1.102011 +** The results of the total query are to be written into a destination
1.102012 +** of type eDest with parameter iParm.
1.102013 +**
1.102014 +** Example 1:  Consider a three-way compound SQL statement.
1.102015 +**
1.102016 +**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1.102017 +**
1.102018 +** This statement is parsed up as follows:
1.102019 +**
1.102020 +**     SELECT c FROM t3
1.102021 +**      |
1.102022 +**      `----->  SELECT b FROM t2
1.102023 +**                |
1.102024 +**                `------>  SELECT a FROM t1
1.102025 +**
1.102026 +** The arrows in the diagram above represent the Select.pPrior pointer.
1.102027 +** So if this routine is called with p equal to the t3 query, then
1.102028 +** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1.102029 +**
1.102030 +** Notice that because of the way SQLite parses compound SELECTs, the
1.102031 +** individual selects always group from left to right.
1.102032 +*/
1.102033 +static int multiSelect(
1.102034 +  Parse *pParse,        /* Parsing context */
1.102035 +  Select *p,            /* The right-most of SELECTs to be coded */
1.102036 +  SelectDest *pDest     /* What to do with query results */
1.102037 +){
1.102038 +  int rc = SQLITE_OK;   /* Success code from a subroutine */
1.102039 +  Select *pPrior;       /* Another SELECT immediately to our left */
1.102040 +  Vdbe *v;              /* Generate code to this VDBE */
1.102041 +  SelectDest dest;      /* Alternative data destination */
1.102042 +  Select *pDelete = 0;  /* Chain of simple selects to delete */
1.102043 +  sqlite3 *db;          /* Database connection */
1.102044 +#ifndef SQLITE_OMIT_EXPLAIN
1.102045 +  int iSub1 = 0;        /* EQP id of left-hand query */
1.102046 +  int iSub2 = 0;        /* EQP id of right-hand query */
1.102047 +#endif
1.102048 +
1.102049 +  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
1.102050 +  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
1.102051 +  */
1.102052 +  assert( p && p->pPrior );  /* Calling function guarantees this much */
1.102053 +  assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
1.102054 +  db = pParse->db;
1.102055 +  pPrior = p->pPrior;
1.102056 +  dest = *pDest;
1.102057 +  if( pPrior->pOrderBy ){
1.102058 +    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1.102059 +      selectOpName(p->op));
1.102060 +    rc = 1;
1.102061 +    goto multi_select_end;
1.102062 +  }
1.102063 +  if( pPrior->pLimit ){
1.102064 +    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
1.102065 +      selectOpName(p->op));
1.102066 +    rc = 1;
1.102067 +    goto multi_select_end;
1.102068 +  }
1.102069 +
1.102070 +  v = sqlite3GetVdbe(pParse);
1.102071 +  assert( v!=0 );  /* The VDBE already created by calling function */
1.102072 +
1.102073 +  /* Create the destination temporary table if necessary
1.102074 +  */
1.102075 +  if( dest.eDest==SRT_EphemTab ){
1.102076 +    assert( p->pEList );
1.102077 +    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
1.102078 +    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
1.102079 +    dest.eDest = SRT_Table;
1.102080 +  }
1.102081 +
1.102082 +  /* Make sure all SELECTs in the statement have the same number of elements
1.102083 +  ** in their result sets.
1.102084 +  */
1.102085 +  assert( p->pEList && pPrior->pEList );
1.102086 +  if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
1.102087 +    if( p->selFlags & SF_Values ){
1.102088 +      sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
1.102089 +    }else{
1.102090 +      sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
1.102091 +        " do not have the same number of result columns", selectOpName(p->op));
1.102092 +    }
1.102093 +    rc = 1;
1.102094 +    goto multi_select_end;
1.102095 +  }
1.102096 +
1.102097 +#ifndef SQLITE_OMIT_CTE
1.102098 +  if( p->selFlags & SF_Recursive ){
1.102099 +    generateWithRecursiveQuery(pParse, p, &dest);
1.102100 +  }else
1.102101 +#endif
1.102102 +
1.102103 +  /* Compound SELECTs that have an ORDER BY clause are handled separately.
1.102104 +  */
1.102105 +  if( p->pOrderBy ){
1.102106 +    return multiSelectOrderBy(pParse, p, pDest);
1.102107 +  }else
1.102108 +
1.102109 +  /* Generate code for the left and right SELECT statements.
1.102110 +  */
1.102111 +  switch( p->op ){
1.102112 +    case TK_ALL: {
1.102113 +      int addr = 0;
1.102114 +      int nLimit;
1.102115 +      assert( !pPrior->pLimit );
1.102116 +      pPrior->iLimit = p->iLimit;
1.102117 +      pPrior->iOffset = p->iOffset;
1.102118 +      pPrior->pLimit = p->pLimit;
1.102119 +      pPrior->pOffset = p->pOffset;
1.102120 +      explainSetInteger(iSub1, pParse->iNextSelectId);
1.102121 +      rc = sqlite3Select(pParse, pPrior, &dest);
1.102122 +      p->pLimit = 0;
1.102123 +      p->pOffset = 0;
1.102124 +      if( rc ){
1.102125 +        goto multi_select_end;
1.102126 +      }
1.102127 +      p->pPrior = 0;
1.102128 +      p->iLimit = pPrior->iLimit;
1.102129 +      p->iOffset = pPrior->iOffset;
1.102130 +      if( p->iLimit ){
1.102131 +        addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); VdbeCoverage(v);
1.102132 +        VdbeComment((v, "Jump ahead if LIMIT reached"));
1.102133 +      }
1.102134 +      explainSetInteger(iSub2, pParse->iNextSelectId);
1.102135 +      rc = sqlite3Select(pParse, p, &dest);
1.102136 +      testcase( rc!=SQLITE_OK );
1.102137 +      pDelete = p->pPrior;
1.102138 +      p->pPrior = pPrior;
1.102139 +      p->nSelectRow += pPrior->nSelectRow;
1.102140 +      if( pPrior->pLimit
1.102141 +       && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
1.102142 +       && nLimit>0 && p->nSelectRow > (u64)nLimit 
1.102143 +      ){
1.102144 +        p->nSelectRow = nLimit;
1.102145 +      }
1.102146 +      if( addr ){
1.102147 +        sqlite3VdbeJumpHere(v, addr);
1.102148 +      }
1.102149 +      break;
1.102150 +    }
1.102151 +    case TK_EXCEPT:
1.102152 +    case TK_UNION: {
1.102153 +      int unionTab;    /* Cursor number of the temporary table holding result */
1.102154 +      u8 op = 0;       /* One of the SRT_ operations to apply to self */
1.102155 +      int priorOp;     /* The SRT_ operation to apply to prior selects */
1.102156 +      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
1.102157 +      int addr;
1.102158 +      SelectDest uniondest;
1.102159 +
1.102160 +      testcase( p->op==TK_EXCEPT );
1.102161 +      testcase( p->op==TK_UNION );
1.102162 +      priorOp = SRT_Union;
1.102163 +      if( dest.eDest==priorOp ){
1.102164 +        /* We can reuse a temporary table generated by a SELECT to our
1.102165 +        ** right.
1.102166 +        */
1.102167 +        assert( p->pLimit==0 );      /* Not allowed on leftward elements */
1.102168 +        assert( p->pOffset==0 );     /* Not allowed on leftward elements */
1.102169 +        unionTab = dest.iSDParm;
1.102170 +      }else{
1.102171 +        /* We will need to create our own temporary table to hold the
1.102172 +        ** intermediate results.
1.102173 +        */
1.102174 +        unionTab = pParse->nTab++;
1.102175 +        assert( p->pOrderBy==0 );
1.102176 +        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
1.102177 +        assert( p->addrOpenEphm[0] == -1 );
1.102178 +        p->addrOpenEphm[0] = addr;
1.102179 +        findRightmost(p)->selFlags |= SF_UsesEphemeral;
1.102180 +        assert( p->pEList );
1.102181 +      }
1.102182 +
1.102183 +      /* Code the SELECT statements to our left
1.102184 +      */
1.102185 +      assert( !pPrior->pOrderBy );
1.102186 +      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
1.102187 +      explainSetInteger(iSub1, pParse->iNextSelectId);
1.102188 +      rc = sqlite3Select(pParse, pPrior, &uniondest);
1.102189 +      if( rc ){
1.102190 +        goto multi_select_end;
1.102191 +      }
1.102192 +
1.102193 +      /* Code the current SELECT statement
1.102194 +      */
1.102195 +      if( p->op==TK_EXCEPT ){
1.102196 +        op = SRT_Except;
1.102197 +      }else{
1.102198 +        assert( p->op==TK_UNION );
1.102199 +        op = SRT_Union;
1.102200 +      }
1.102201 +      p->pPrior = 0;
1.102202 +      pLimit = p->pLimit;
1.102203 +      p->pLimit = 0;
1.102204 +      pOffset = p->pOffset;
1.102205 +      p->pOffset = 0;
1.102206 +      uniondest.eDest = op;
1.102207 +      explainSetInteger(iSub2, pParse->iNextSelectId);
1.102208 +      rc = sqlite3Select(pParse, p, &uniondest);
1.102209 +      testcase( rc!=SQLITE_OK );
1.102210 +      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
1.102211 +      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
1.102212 +      sqlite3ExprListDelete(db, p->pOrderBy);
1.102213 +      pDelete = p->pPrior;
1.102214 +      p->pPrior = pPrior;
1.102215 +      p->pOrderBy = 0;
1.102216 +      if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
1.102217 +      sqlite3ExprDelete(db, p->pLimit);
1.102218 +      p->pLimit = pLimit;
1.102219 +      p->pOffset = pOffset;
1.102220 +      p->iLimit = 0;
1.102221 +      p->iOffset = 0;
1.102222 +
1.102223 +      /* Convert the data in the temporary table into whatever form
1.102224 +      ** it is that we currently need.
1.102225 +      */
1.102226 +      assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
1.102227 +      if( dest.eDest!=priorOp ){
1.102228 +        int iCont, iBreak, iStart;
1.102229 +        assert( p->pEList );
1.102230 +        if( dest.eDest==SRT_Output ){
1.102231 +          Select *pFirst = p;
1.102232 +          while( pFirst->pPrior ) pFirst = pFirst->pPrior;
1.102233 +          generateColumnNames(pParse, 0, pFirst->pEList);
1.102234 +        }
1.102235 +        iBreak = sqlite3VdbeMakeLabel(v);
1.102236 +        iCont = sqlite3VdbeMakeLabel(v);
1.102237 +        computeLimitRegisters(pParse, p, iBreak);
1.102238 +        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
1.102239 +        iStart = sqlite3VdbeCurrentAddr(v);
1.102240 +        selectInnerLoop(pParse, p, p->pEList, unionTab,
1.102241 +                        0, 0, &dest, iCont, iBreak);
1.102242 +        sqlite3VdbeResolveLabel(v, iCont);
1.102243 +        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
1.102244 +        sqlite3VdbeResolveLabel(v, iBreak);
1.102245 +        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
1.102246 +      }
1.102247 +      break;
1.102248 +    }
1.102249 +    default: assert( p->op==TK_INTERSECT ); {
1.102250 +      int tab1, tab2;
1.102251 +      int iCont, iBreak, iStart;
1.102252 +      Expr *pLimit, *pOffset;
1.102253 +      int addr;
1.102254 +      SelectDest intersectdest;
1.102255 +      int r1;
1.102256 +
1.102257 +      /* INTERSECT is different from the others since it requires
1.102258 +      ** two temporary tables.  Hence it has its own case.  Begin
1.102259 +      ** by allocating the tables we will need.
1.102260 +      */
1.102261 +      tab1 = pParse->nTab++;
1.102262 +      tab2 = pParse->nTab++;
1.102263 +      assert( p->pOrderBy==0 );
1.102264 +
1.102265 +      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
1.102266 +      assert( p->addrOpenEphm[0] == -1 );
1.102267 +      p->addrOpenEphm[0] = addr;
1.102268 +      findRightmost(p)->selFlags |= SF_UsesEphemeral;
1.102269 +      assert( p->pEList );
1.102270 +
1.102271 +      /* Code the SELECTs to our left into temporary table "tab1".
1.102272 +      */
1.102273 +      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
1.102274 +      explainSetInteger(iSub1, pParse->iNextSelectId);
1.102275 +      rc = sqlite3Select(pParse, pPrior, &intersectdest);
1.102276 +      if( rc ){
1.102277 +        goto multi_select_end;
1.102278 +      }
1.102279 +
1.102280 +      /* Code the current SELECT into temporary table "tab2"
1.102281 +      */
1.102282 +      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
1.102283 +      assert( p->addrOpenEphm[1] == -1 );
1.102284 +      p->addrOpenEphm[1] = addr;
1.102285 +      p->pPrior = 0;
1.102286 +      pLimit = p->pLimit;
1.102287 +      p->pLimit = 0;
1.102288 +      pOffset = p->pOffset;
1.102289 +      p->pOffset = 0;
1.102290 +      intersectdest.iSDParm = tab2;
1.102291 +      explainSetInteger(iSub2, pParse->iNextSelectId);
1.102292 +      rc = sqlite3Select(pParse, p, &intersectdest);
1.102293 +      testcase( rc!=SQLITE_OK );
1.102294 +      pDelete = p->pPrior;
1.102295 +      p->pPrior = pPrior;
1.102296 +      if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
1.102297 +      sqlite3ExprDelete(db, p->pLimit);
1.102298 +      p->pLimit = pLimit;
1.102299 +      p->pOffset = pOffset;
1.102300 +
1.102301 +      /* Generate code to take the intersection of the two temporary
1.102302 +      ** tables.
1.102303 +      */
1.102304 +      assert( p->pEList );
1.102305 +      if( dest.eDest==SRT_Output ){
1.102306 +        Select *pFirst = p;
1.102307 +        while( pFirst->pPrior ) pFirst = pFirst->pPrior;
1.102308 +        generateColumnNames(pParse, 0, pFirst->pEList);
1.102309 +      }
1.102310 +      iBreak = sqlite3VdbeMakeLabel(v);
1.102311 +      iCont = sqlite3VdbeMakeLabel(v);
1.102312 +      computeLimitRegisters(pParse, p, iBreak);
1.102313 +      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
1.102314 +      r1 = sqlite3GetTempReg(pParse);
1.102315 +      iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
1.102316 +      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
1.102317 +      sqlite3ReleaseTempReg(pParse, r1);
1.102318 +      selectInnerLoop(pParse, p, p->pEList, tab1,
1.102319 +                      0, 0, &dest, iCont, iBreak);
1.102320 +      sqlite3VdbeResolveLabel(v, iCont);
1.102321 +      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
1.102322 +      sqlite3VdbeResolveLabel(v, iBreak);
1.102323 +      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
1.102324 +      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
1.102325 +      break;
1.102326 +    }
1.102327 +  }
1.102328 +
1.102329 +  explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
1.102330 +
1.102331 +  /* Compute collating sequences used by 
1.102332 +  ** temporary tables needed to implement the compound select.
1.102333 +  ** Attach the KeyInfo structure to all temporary tables.
1.102334 +  **
1.102335 +  ** This section is run by the right-most SELECT statement only.
1.102336 +  ** SELECT statements to the left always skip this part.  The right-most
1.102337 +  ** SELECT might also skip this part if it has no ORDER BY clause and
1.102338 +  ** no temp tables are required.
1.102339 +  */
1.102340 +  if( p->selFlags & SF_UsesEphemeral ){
1.102341 +    int i;                        /* Loop counter */
1.102342 +    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
1.102343 +    Select *pLoop;                /* For looping through SELECT statements */
1.102344 +    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
1.102345 +    int nCol;                     /* Number of columns in result set */
1.102346 +
1.102347 +    assert( p->pNext==0 );
1.102348 +    nCol = p->pEList->nExpr;
1.102349 +    pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
1.102350 +    if( !pKeyInfo ){
1.102351 +      rc = SQLITE_NOMEM;
1.102352 +      goto multi_select_end;
1.102353 +    }
1.102354 +    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
1.102355 +      *apColl = multiSelectCollSeq(pParse, p, i);
1.102356 +      if( 0==*apColl ){
1.102357 +        *apColl = db->pDfltColl;
1.102358 +      }
1.102359 +    }
1.102360 +
1.102361 +    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
1.102362 +      for(i=0; i<2; i++){
1.102363 +        int addr = pLoop->addrOpenEphm[i];
1.102364 +        if( addr<0 ){
1.102365 +          /* If [0] is unused then [1] is also unused.  So we can
1.102366 +          ** always safely abort as soon as the first unused slot is found */
1.102367 +          assert( pLoop->addrOpenEphm[1]<0 );
1.102368 +          break;
1.102369 +        }
1.102370 +        sqlite3VdbeChangeP2(v, addr, nCol);
1.102371 +        sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
1.102372 +                            P4_KEYINFO);
1.102373 +        pLoop->addrOpenEphm[i] = -1;
1.102374 +      }
1.102375 +    }
1.102376 +    sqlite3KeyInfoUnref(pKeyInfo);
1.102377 +  }
1.102378 +
1.102379 +multi_select_end:
1.102380 +  pDest->iSdst = dest.iSdst;
1.102381 +  pDest->nSdst = dest.nSdst;
1.102382 +  sqlite3SelectDelete(db, pDelete);
1.102383 +  return rc;
1.102384 +}
1.102385 +#endif /* SQLITE_OMIT_COMPOUND_SELECT */
1.102386 +
1.102387 +/*
1.102388 +** Code an output subroutine for a coroutine implementation of a
1.102389 +** SELECT statment.
1.102390 +**
1.102391 +** The data to be output is contained in pIn->iSdst.  There are
1.102392 +** pIn->nSdst columns to be output.  pDest is where the output should
1.102393 +** be sent.
1.102394 +**
1.102395 +** regReturn is the number of the register holding the subroutine
1.102396 +** return address.
1.102397 +**
1.102398 +** If regPrev>0 then it is the first register in a vector that
1.102399 +** records the previous output.  mem[regPrev] is a flag that is false
1.102400 +** if there has been no previous output.  If regPrev>0 then code is
1.102401 +** generated to suppress duplicates.  pKeyInfo is used for comparing
1.102402 +** keys.
1.102403 +**
1.102404 +** If the LIMIT found in p->iLimit is reached, jump immediately to
1.102405 +** iBreak.
1.102406 +*/
1.102407 +static int generateOutputSubroutine(
1.102408 +  Parse *pParse,          /* Parsing context */
1.102409 +  Select *p,              /* The SELECT statement */
1.102410 +  SelectDest *pIn,        /* Coroutine supplying data */
1.102411 +  SelectDest *pDest,      /* Where to send the data */
1.102412 +  int regReturn,          /* The return address register */
1.102413 +  int regPrev,            /* Previous result register.  No uniqueness if 0 */
1.102414 +  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
1.102415 +  int iBreak              /* Jump here if we hit the LIMIT */
1.102416 +){
1.102417 +  Vdbe *v = pParse->pVdbe;
1.102418 +  int iContinue;
1.102419 +  int addr;
1.102420 +
1.102421 +  addr = sqlite3VdbeCurrentAddr(v);
1.102422 +  iContinue = sqlite3VdbeMakeLabel(v);
1.102423 +
1.102424 +  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
1.102425 +  */
1.102426 +  if( regPrev ){
1.102427 +    int j1, j2;
1.102428 +    j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
1.102429 +    j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
1.102430 +                              (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
1.102431 +    sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); VdbeCoverage(v);
1.102432 +    sqlite3VdbeJumpHere(v, j1);
1.102433 +    sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
1.102434 +    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
1.102435 +  }
1.102436 +  if( pParse->db->mallocFailed ) return 0;
1.102437 +
1.102438 +  /* Suppress the first OFFSET entries if there is an OFFSET clause
1.102439 +  */
1.102440 +  codeOffset(v, p->iOffset, iContinue);
1.102441 +
1.102442 +  switch( pDest->eDest ){
1.102443 +    /* Store the result as data using a unique key.
1.102444 +    */
1.102445 +    case SRT_Table:
1.102446 +    case SRT_EphemTab: {
1.102447 +      int r1 = sqlite3GetTempReg(pParse);
1.102448 +      int r2 = sqlite3GetTempReg(pParse);
1.102449 +      testcase( pDest->eDest==SRT_Table );
1.102450 +      testcase( pDest->eDest==SRT_EphemTab );
1.102451 +      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
1.102452 +      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
1.102453 +      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
1.102454 +      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1.102455 +      sqlite3ReleaseTempReg(pParse, r2);
1.102456 +      sqlite3ReleaseTempReg(pParse, r1);
1.102457 +      break;
1.102458 +    }
1.102459 +
1.102460 +#ifndef SQLITE_OMIT_SUBQUERY
1.102461 +    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
1.102462 +    ** then there should be a single item on the stack.  Write this
1.102463 +    ** item into the set table with bogus data.
1.102464 +    */
1.102465 +    case SRT_Set: {
1.102466 +      int r1;
1.102467 +      assert( pIn->nSdst==1 );
1.102468 +      pDest->affSdst = 
1.102469 +         sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
1.102470 +      r1 = sqlite3GetTempReg(pParse);
1.102471 +      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
1.102472 +      sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
1.102473 +      sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
1.102474 +      sqlite3ReleaseTempReg(pParse, r1);
1.102475 +      break;
1.102476 +    }
1.102477 +
1.102478 +#if 0  /* Never occurs on an ORDER BY query */
1.102479 +    /* If any row exist in the result set, record that fact and abort.
1.102480 +    */
1.102481 +    case SRT_Exists: {
1.102482 +      sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
1.102483 +      /* The LIMIT clause will terminate the loop for us */
1.102484 +      break;
1.102485 +    }
1.102486 +#endif
1.102487 +
1.102488 +    /* If this is a scalar select that is part of an expression, then
1.102489 +    ** store the results in the appropriate memory cell and break out
1.102490 +    ** of the scan loop.
1.102491 +    */
1.102492 +    case SRT_Mem: {
1.102493 +      assert( pIn->nSdst==1 );
1.102494 +      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
1.102495 +      /* The LIMIT clause will jump out of the loop for us */
1.102496 +      break;
1.102497 +    }
1.102498 +#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
1.102499 +
1.102500 +    /* The results are stored in a sequence of registers
1.102501 +    ** starting at pDest->iSdst.  Then the co-routine yields.
1.102502 +    */
1.102503 +    case SRT_Coroutine: {
1.102504 +      if( pDest->iSdst==0 ){
1.102505 +        pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
1.102506 +        pDest->nSdst = pIn->nSdst;
1.102507 +      }
1.102508 +      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
1.102509 +      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
1.102510 +      break;
1.102511 +    }
1.102512 +
1.102513 +    /* If none of the above, then the result destination must be
1.102514 +    ** SRT_Output.  This routine is never called with any other
1.102515 +    ** destination other than the ones handled above or SRT_Output.
1.102516 +    **
1.102517 +    ** For SRT_Output, results are stored in a sequence of registers.  
1.102518 +    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
1.102519 +    ** return the next row of result.
1.102520 +    */
1.102521 +    default: {
1.102522 +      assert( pDest->eDest==SRT_Output );
1.102523 +      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
1.102524 +      sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
1.102525 +      break;
1.102526 +    }
1.102527 +  }
1.102528 +
1.102529 +  /* Jump to the end of the loop if the LIMIT is reached.
1.102530 +  */
1.102531 +  if( p->iLimit ){
1.102532 +    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v);
1.102533 +  }
1.102534 +
1.102535 +  /* Generate the subroutine return
1.102536 +  */
1.102537 +  sqlite3VdbeResolveLabel(v, iContinue);
1.102538 +  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
1.102539 +
1.102540 +  return addr;
1.102541 +}
1.102542 +
1.102543 +/*
1.102544 +** Alternative compound select code generator for cases when there
1.102545 +** is an ORDER BY clause.
1.102546 +**
1.102547 +** We assume a query of the following form:
1.102548 +**
1.102549 +**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
1.102550 +**
1.102551 +** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
1.102552 +** is to code both <selectA> and <selectB> with the ORDER BY clause as
1.102553 +** co-routines.  Then run the co-routines in parallel and merge the results
1.102554 +** into the output.  In addition to the two coroutines (called selectA and
1.102555 +** selectB) there are 7 subroutines:
1.102556 +**
1.102557 +**    outA:    Move the output of the selectA coroutine into the output
1.102558 +**             of the compound query.
1.102559 +**
1.102560 +**    outB:    Move the output of the selectB coroutine into the output
1.102561 +**             of the compound query.  (Only generated for UNION and
1.102562 +**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
1.102563 +**             appears only in B.)
1.102564 +**
1.102565 +**    AltB:    Called when there is data from both coroutines and A<B.
1.102566 +**
1.102567 +**    AeqB:    Called when there is data from both coroutines and A==B.
1.102568 +**
1.102569 +**    AgtB:    Called when there is data from both coroutines and A>B.
1.102570 +**
1.102571 +**    EofA:    Called when data is exhausted from selectA.
1.102572 +**
1.102573 +**    EofB:    Called when data is exhausted from selectB.
1.102574 +**
1.102575 +** The implementation of the latter five subroutines depend on which 
1.102576 +** <operator> is used:
1.102577 +**
1.102578 +**
1.102579 +**             UNION ALL         UNION            EXCEPT          INTERSECT
1.102580 +**          -------------  -----------------  --------------  -----------------
1.102581 +**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
1.102582 +**
1.102583 +**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
1.102584 +**
1.102585 +**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
1.102586 +**
1.102587 +**   EofA:   outB, nextB      outB, nextB          halt             halt
1.102588 +**
1.102589 +**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
1.102590 +**
1.102591 +** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
1.102592 +** causes an immediate jump to EofA and an EOF on B following nextB causes
1.102593 +** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
1.102594 +** following nextX causes a jump to the end of the select processing.
1.102595 +**
1.102596 +** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
1.102597 +** within the output subroutine.  The regPrev register set holds the previously
1.102598 +** output value.  A comparison is made against this value and the output
1.102599 +** is skipped if the next results would be the same as the previous.
1.102600 +**
1.102601 +** The implementation plan is to implement the two coroutines and seven
1.102602 +** subroutines first, then put the control logic at the bottom.  Like this:
1.102603 +**
1.102604 +**          goto Init
1.102605 +**     coA: coroutine for left query (A)
1.102606 +**     coB: coroutine for right query (B)
1.102607 +**    outA: output one row of A
1.102608 +**    outB: output one row of B (UNION and UNION ALL only)
1.102609 +**    EofA: ...
1.102610 +**    EofB: ...
1.102611 +**    AltB: ...
1.102612 +**    AeqB: ...
1.102613 +**    AgtB: ...
1.102614 +**    Init: initialize coroutine registers
1.102615 +**          yield coA
1.102616 +**          if eof(A) goto EofA
1.102617 +**          yield coB
1.102618 +**          if eof(B) goto EofB
1.102619 +**    Cmpr: Compare A, B
1.102620 +**          Jump AltB, AeqB, AgtB
1.102621 +**     End: ...
1.102622 +**
1.102623 +** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
1.102624 +** actually called using Gosub and they do not Return.  EofA and EofB loop
1.102625 +** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
1.102626 +** and AgtB jump to either L2 or to one of EofA or EofB.
1.102627 +*/
1.102628 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
1.102629 +static int multiSelectOrderBy(
1.102630 +  Parse *pParse,        /* Parsing context */
1.102631 +  Select *p,            /* The right-most of SELECTs to be coded */
1.102632 +  SelectDest *pDest     /* What to do with query results */
1.102633 +){
1.102634 +  int i, j;             /* Loop counters */
1.102635 +  Select *pPrior;       /* Another SELECT immediately to our left */
1.102636 +  Vdbe *v;              /* Generate code to this VDBE */
1.102637 +  SelectDest destA;     /* Destination for coroutine A */
1.102638 +  SelectDest destB;     /* Destination for coroutine B */
1.102639 +  int regAddrA;         /* Address register for select-A coroutine */
1.102640 +  int regAddrB;         /* Address register for select-B coroutine */
1.102641 +  int addrSelectA;      /* Address of the select-A coroutine */
1.102642 +  int addrSelectB;      /* Address of the select-B coroutine */
1.102643 +  int regOutA;          /* Address register for the output-A subroutine */
1.102644 +  int regOutB;          /* Address register for the output-B subroutine */
1.102645 +  int addrOutA;         /* Address of the output-A subroutine */
1.102646 +  int addrOutB = 0;     /* Address of the output-B subroutine */
1.102647 +  int addrEofA;         /* Address of the select-A-exhausted subroutine */
1.102648 +  int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
1.102649 +  int addrEofB;         /* Address of the select-B-exhausted subroutine */
1.102650 +  int addrAltB;         /* Address of the A<B subroutine */
1.102651 +  int addrAeqB;         /* Address of the A==B subroutine */
1.102652 +  int addrAgtB;         /* Address of the A>B subroutine */
1.102653 +  int regLimitA;        /* Limit register for select-A */
1.102654 +  int regLimitB;        /* Limit register for select-A */
1.102655 +  int regPrev;          /* A range of registers to hold previous output */
1.102656 +  int savedLimit;       /* Saved value of p->iLimit */
1.102657 +  int savedOffset;      /* Saved value of p->iOffset */
1.102658 +  int labelCmpr;        /* Label for the start of the merge algorithm */
1.102659 +  int labelEnd;         /* Label for the end of the overall SELECT stmt */
1.102660 +  int j1;               /* Jump instructions that get retargetted */
1.102661 +  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
1.102662 +  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
1.102663 +  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
1.102664 +  sqlite3 *db;          /* Database connection */
1.102665 +  ExprList *pOrderBy;   /* The ORDER BY clause */
1.102666 +  int nOrderBy;         /* Number of terms in the ORDER BY clause */
1.102667 +  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
1.102668 +#ifndef SQLITE_OMIT_EXPLAIN
1.102669 +  int iSub1;            /* EQP id of left-hand query */
1.102670 +  int iSub2;            /* EQP id of right-hand query */
1.102671 +#endif
1.102672 +
1.102673 +  assert( p->pOrderBy!=0 );
1.102674 +  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
1.102675 +  db = pParse->db;
1.102676 +  v = pParse->pVdbe;
1.102677 +  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
1.102678 +  labelEnd = sqlite3VdbeMakeLabel(v);
1.102679 +  labelCmpr = sqlite3VdbeMakeLabel(v);
1.102680 +
1.102681 +
1.102682 +  /* Patch up the ORDER BY clause
1.102683 +  */
1.102684 +  op = p->op;  
1.102685 +  pPrior = p->pPrior;
1.102686 +  assert( pPrior->pOrderBy==0 );
1.102687 +  pOrderBy = p->pOrderBy;
1.102688 +  assert( pOrderBy );
1.102689 +  nOrderBy = pOrderBy->nExpr;
1.102690 +
1.102691 +  /* For operators other than UNION ALL we have to make sure that
1.102692 +  ** the ORDER BY clause covers every term of the result set.  Add
1.102693 +  ** terms to the ORDER BY clause as necessary.
1.102694 +  */
1.102695 +  if( op!=TK_ALL ){
1.102696 +    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
1.102697 +      struct ExprList_item *pItem;
1.102698 +      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
1.102699 +        assert( pItem->u.x.iOrderByCol>0 );
1.102700 +        if( pItem->u.x.iOrderByCol==i ) break;
1.102701 +      }
1.102702 +      if( j==nOrderBy ){
1.102703 +        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
1.102704 +        if( pNew==0 ) return SQLITE_NOMEM;
1.102705 +        pNew->flags |= EP_IntValue;
1.102706 +        pNew->u.iValue = i;
1.102707 +        pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
1.102708 +        if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
1.102709 +      }
1.102710 +    }
1.102711 +  }
1.102712 +
1.102713 +  /* Compute the comparison permutation and keyinfo that is used with
1.102714 +  ** the permutation used to determine if the next
1.102715 +  ** row of results comes from selectA or selectB.  Also add explicit
1.102716 +  ** collations to the ORDER BY clause terms so that when the subqueries
1.102717 +  ** to the right and the left are evaluated, they use the correct
1.102718 +  ** collation.
1.102719 +  */
1.102720 +  aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
1.102721 +  if( aPermute ){
1.102722 +    struct ExprList_item *pItem;
1.102723 +    for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
1.102724 +      assert( pItem->u.x.iOrderByCol>0
1.102725 +          && pItem->u.x.iOrderByCol<=p->pEList->nExpr );
1.102726 +      aPermute[i] = pItem->u.x.iOrderByCol - 1;
1.102727 +    }
1.102728 +    pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
1.102729 +  }else{
1.102730 +    pKeyMerge = 0;
1.102731 +  }
1.102732 +
1.102733 +  /* Reattach the ORDER BY clause to the query.
1.102734 +  */
1.102735 +  p->pOrderBy = pOrderBy;
1.102736 +  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
1.102737 +
1.102738 +  /* Allocate a range of temporary registers and the KeyInfo needed
1.102739 +  ** for the logic that removes duplicate result rows when the
1.102740 +  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
1.102741 +  */
1.102742 +  if( op==TK_ALL ){
1.102743 +    regPrev = 0;
1.102744 +  }else{
1.102745 +    int nExpr = p->pEList->nExpr;
1.102746 +    assert( nOrderBy>=nExpr || db->mallocFailed );
1.102747 +    regPrev = pParse->nMem+1;
1.102748 +    pParse->nMem += nExpr+1;
1.102749 +    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
1.102750 +    pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
1.102751 +    if( pKeyDup ){
1.102752 +      assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
1.102753 +      for(i=0; i<nExpr; i++){
1.102754 +        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
1.102755 +        pKeyDup->aSortOrder[i] = 0;
1.102756 +      }
1.102757 +    }
1.102758 +  }
1.102759 + 
1.102760 +  /* Separate the left and the right query from one another
1.102761 +  */
1.102762 +  p->pPrior = 0;
1.102763 +  pPrior->pNext = 0;
1.102764 +  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
1.102765 +  if( pPrior->pPrior==0 ){
1.102766 +    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
1.102767 +  }
1.102768 +
1.102769 +  /* Compute the limit registers */
1.102770 +  computeLimitRegisters(pParse, p, labelEnd);
1.102771 +  if( p->iLimit && op==TK_ALL ){
1.102772 +    regLimitA = ++pParse->nMem;
1.102773 +    regLimitB = ++pParse->nMem;
1.102774 +    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
1.102775 +                                  regLimitA);
1.102776 +    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
1.102777 +  }else{
1.102778 +    regLimitA = regLimitB = 0;
1.102779 +  }
1.102780 +  sqlite3ExprDelete(db, p->pLimit);
1.102781 +  p->pLimit = 0;
1.102782 +  sqlite3ExprDelete(db, p->pOffset);
1.102783 +  p->pOffset = 0;
1.102784 +
1.102785 +  regAddrA = ++pParse->nMem;
1.102786 +  regAddrB = ++pParse->nMem;
1.102787 +  regOutA = ++pParse->nMem;
1.102788 +  regOutB = ++pParse->nMem;
1.102789 +  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
1.102790 +  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
1.102791 +
1.102792 +  /* Generate a coroutine to evaluate the SELECT statement to the
1.102793 +  ** left of the compound operator - the "A" select.
1.102794 +  */
1.102795 +  addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
1.102796 +  j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
1.102797 +  VdbeComment((v, "left SELECT"));
1.102798 +  pPrior->iLimit = regLimitA;
1.102799 +  explainSetInteger(iSub1, pParse->iNextSelectId);
1.102800 +  sqlite3Select(pParse, pPrior, &destA);
1.102801 +  sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA);
1.102802 +  sqlite3VdbeJumpHere(v, j1);
1.102803 +
1.102804 +  /* Generate a coroutine to evaluate the SELECT statement on 
1.102805 +  ** the right - the "B" select
1.102806 +  */
1.102807 +  addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
1.102808 +  j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
1.102809 +  VdbeComment((v, "right SELECT"));
1.102810 +  savedLimit = p->iLimit;
1.102811 +  savedOffset = p->iOffset;
1.102812 +  p->iLimit = regLimitB;
1.102813 +  p->iOffset = 0;  
1.102814 +  explainSetInteger(iSub2, pParse->iNextSelectId);
1.102815 +  sqlite3Select(pParse, p, &destB);
1.102816 +  p->iLimit = savedLimit;
1.102817 +  p->iOffset = savedOffset;
1.102818 +  sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB);
1.102819 +
1.102820 +  /* Generate a subroutine that outputs the current row of the A
1.102821 +  ** select as the next output row of the compound select.
1.102822 +  */
1.102823 +  VdbeNoopComment((v, "Output routine for A"));
1.102824 +  addrOutA = generateOutputSubroutine(pParse,
1.102825 +                 p, &destA, pDest, regOutA,
1.102826 +                 regPrev, pKeyDup, labelEnd);
1.102827 +  
1.102828 +  /* Generate a subroutine that outputs the current row of the B
1.102829 +  ** select as the next output row of the compound select.
1.102830 +  */
1.102831 +  if( op==TK_ALL || op==TK_UNION ){
1.102832 +    VdbeNoopComment((v, "Output routine for B"));
1.102833 +    addrOutB = generateOutputSubroutine(pParse,
1.102834 +                 p, &destB, pDest, regOutB,
1.102835 +                 regPrev, pKeyDup, labelEnd);
1.102836 +  }
1.102837 +  sqlite3KeyInfoUnref(pKeyDup);
1.102838 +
1.102839 +  /* Generate a subroutine to run when the results from select A
1.102840 +  ** are exhausted and only data in select B remains.
1.102841 +  */
1.102842 +  if( op==TK_EXCEPT || op==TK_INTERSECT ){
1.102843 +    addrEofA_noB = addrEofA = labelEnd;
1.102844 +  }else{  
1.102845 +    VdbeNoopComment((v, "eof-A subroutine"));
1.102846 +    addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
1.102847 +    addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
1.102848 +                                     VdbeCoverage(v);
1.102849 +    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
1.102850 +    p->nSelectRow += pPrior->nSelectRow;
1.102851 +  }
1.102852 +
1.102853 +  /* Generate a subroutine to run when the results from select B
1.102854 +  ** are exhausted and only data in select A remains.
1.102855 +  */
1.102856 +  if( op==TK_INTERSECT ){
1.102857 +    addrEofB = addrEofA;
1.102858 +    if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
1.102859 +  }else{  
1.102860 +    VdbeNoopComment((v, "eof-B subroutine"));
1.102861 +    addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
1.102862 +    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
1.102863 +    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
1.102864 +  }
1.102865 +
1.102866 +  /* Generate code to handle the case of A<B
1.102867 +  */
1.102868 +  VdbeNoopComment((v, "A-lt-B subroutine"));
1.102869 +  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
1.102870 +  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
1.102871 +  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
1.102872 +
1.102873 +  /* Generate code to handle the case of A==B
1.102874 +  */
1.102875 +  if( op==TK_ALL ){
1.102876 +    addrAeqB = addrAltB;
1.102877 +  }else if( op==TK_INTERSECT ){
1.102878 +    addrAeqB = addrAltB;
1.102879 +    addrAltB++;
1.102880 +  }else{
1.102881 +    VdbeNoopComment((v, "A-eq-B subroutine"));
1.102882 +    addrAeqB =
1.102883 +    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
1.102884 +    sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
1.102885 +  }
1.102886 +
1.102887 +  /* Generate code to handle the case of A>B
1.102888 +  */
1.102889 +  VdbeNoopComment((v, "A-gt-B subroutine"));
1.102890 +  addrAgtB = sqlite3VdbeCurrentAddr(v);
1.102891 +  if( op==TK_ALL || op==TK_UNION ){
1.102892 +    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
1.102893 +  }
1.102894 +  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
1.102895 +  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
1.102896 +
1.102897 +  /* This code runs once to initialize everything.
1.102898 +  */
1.102899 +  sqlite3VdbeJumpHere(v, j1);
1.102900 +  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
1.102901 +  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
1.102902 +
1.102903 +  /* Implement the main merge loop
1.102904 +  */
1.102905 +  sqlite3VdbeResolveLabel(v, labelCmpr);
1.102906 +  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
1.102907 +  sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
1.102908 +                         (char*)pKeyMerge, P4_KEYINFO);
1.102909 +  sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
1.102910 +  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
1.102911 +
1.102912 +  /* Jump to the this point in order to terminate the query.
1.102913 +  */
1.102914 +  sqlite3VdbeResolveLabel(v, labelEnd);
1.102915 +
1.102916 +  /* Set the number of output columns
1.102917 +  */
1.102918 +  if( pDest->eDest==SRT_Output ){
1.102919 +    Select *pFirst = pPrior;
1.102920 +    while( pFirst->pPrior ) pFirst = pFirst->pPrior;
1.102921 +    generateColumnNames(pParse, 0, pFirst->pEList);
1.102922 +  }
1.102923 +
1.102924 +  /* Reassembly the compound query so that it will be freed correctly
1.102925 +  ** by the calling function */
1.102926 +  if( p->pPrior ){
1.102927 +    sqlite3SelectDelete(db, p->pPrior);
1.102928 +  }
1.102929 +  p->pPrior = pPrior;
1.102930 +  pPrior->pNext = p;
1.102931 +
1.102932 +  /*** TBD:  Insert subroutine calls to close cursors on incomplete
1.102933 +  **** subqueries ****/
1.102934 +  explainComposite(pParse, p->op, iSub1, iSub2, 0);
1.102935 +  return SQLITE_OK;
1.102936 +}
1.102937 +#endif
1.102938 +
1.102939 +#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
1.102940 +/* Forward Declarations */
1.102941 +static void substExprList(sqlite3*, ExprList*, int, ExprList*);
1.102942 +static void substSelect(sqlite3*, Select *, int, ExprList *);
1.102943 +
1.102944 +/*
1.102945 +** Scan through the expression pExpr.  Replace every reference to
1.102946 +** a column in table number iTable with a copy of the iColumn-th
1.102947 +** entry in pEList.  (But leave references to the ROWID column 
1.102948 +** unchanged.)
1.102949 +**
1.102950 +** This routine is part of the flattening procedure.  A subquery
1.102951 +** whose result set is defined by pEList appears as entry in the
1.102952 +** FROM clause of a SELECT such that the VDBE cursor assigned to that
1.102953 +** FORM clause entry is iTable.  This routine make the necessary 
1.102954 +** changes to pExpr so that it refers directly to the source table
1.102955 +** of the subquery rather the result set of the subquery.
1.102956 +*/
1.102957 +static Expr *substExpr(
1.102958 +  sqlite3 *db,        /* Report malloc errors to this connection */
1.102959 +  Expr *pExpr,        /* Expr in which substitution occurs */
1.102960 +  int iTable,         /* Table to be substituted */
1.102961 +  ExprList *pEList    /* Substitute expressions */
1.102962 +){
1.102963 +  if( pExpr==0 ) return 0;
1.102964 +  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
1.102965 +    if( pExpr->iColumn<0 ){
1.102966 +      pExpr->op = TK_NULL;
1.102967 +    }else{
1.102968 +      Expr *pNew;
1.102969 +      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1.102970 +      assert( pExpr->pLeft==0 && pExpr->pRight==0 );
1.102971 +      pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
1.102972 +      sqlite3ExprDelete(db, pExpr);
1.102973 +      pExpr = pNew;
1.102974 +    }
1.102975 +  }else{
1.102976 +    pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
1.102977 +    pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
1.102978 +    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1.102979 +      substSelect(db, pExpr->x.pSelect, iTable, pEList);
1.102980 +    }else{
1.102981 +      substExprList(db, pExpr->x.pList, iTable, pEList);
1.102982 +    }
1.102983 +  }
1.102984 +  return pExpr;
1.102985 +}
1.102986 +static void substExprList(
1.102987 +  sqlite3 *db,         /* Report malloc errors here */
1.102988 +  ExprList *pList,     /* List to scan and in which to make substitutes */
1.102989 +  int iTable,          /* Table to be substituted */
1.102990 +  ExprList *pEList     /* Substitute values */
1.102991 +){
1.102992 +  int i;
1.102993 +  if( pList==0 ) return;
1.102994 +  for(i=0; i<pList->nExpr; i++){
1.102995 +    pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
1.102996 +  }
1.102997 +}
1.102998 +static void substSelect(
1.102999 +  sqlite3 *db,         /* Report malloc errors here */
1.103000 +  Select *p,           /* SELECT statement in which to make substitutions */
1.103001 +  int iTable,          /* Table to be replaced */
1.103002 +  ExprList *pEList     /* Substitute values */
1.103003 +){
1.103004 +  SrcList *pSrc;
1.103005 +  struct SrcList_item *pItem;
1.103006 +  int i;
1.103007 +  if( !p ) return;
1.103008 +  substExprList(db, p->pEList, iTable, pEList);
1.103009 +  substExprList(db, p->pGroupBy, iTable, pEList);
1.103010 +  substExprList(db, p->pOrderBy, iTable, pEList);
1.103011 +  p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
1.103012 +  p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
1.103013 +  substSelect(db, p->pPrior, iTable, pEList);
1.103014 +  pSrc = p->pSrc;
1.103015 +  assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
1.103016 +  if( ALWAYS(pSrc) ){
1.103017 +    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
1.103018 +      substSelect(db, pItem->pSelect, iTable, pEList);
1.103019 +    }
1.103020 +  }
1.103021 +}
1.103022 +#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
1.103023 +
1.103024 +#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
1.103025 +/*
1.103026 +** This routine attempts to flatten subqueries as a performance optimization.
1.103027 +** This routine returns 1 if it makes changes and 0 if no flattening occurs.
1.103028 +**
1.103029 +** To understand the concept of flattening, consider the following
1.103030 +** query:
1.103031 +**
1.103032 +**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
1.103033 +**
1.103034 +** The default way of implementing this query is to execute the
1.103035 +** subquery first and store the results in a temporary table, then
1.103036 +** run the outer query on that temporary table.  This requires two
1.103037 +** passes over the data.  Furthermore, because the temporary table
1.103038 +** has no indices, the WHERE clause on the outer query cannot be
1.103039 +** optimized.
1.103040 +**
1.103041 +** This routine attempts to rewrite queries such as the above into
1.103042 +** a single flat select, like this:
1.103043 +**
1.103044 +**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
1.103045 +**
1.103046 +** The code generated for this simpification gives the same result
1.103047 +** but only has to scan the data once.  And because indices might 
1.103048 +** exist on the table t1, a complete scan of the data might be
1.103049 +** avoided.
1.103050 +**
1.103051 +** Flattening is only attempted if all of the following are true:
1.103052 +**
1.103053 +**   (1)  The subquery and the outer query do not both use aggregates.
1.103054 +**
1.103055 +**   (2)  The subquery is not an aggregate or the outer query is not a join.
1.103056 +**
1.103057 +**   (3)  The subquery is not the right operand of a left outer join
1.103058 +**        (Originally ticket #306.  Strengthened by ticket #3300)
1.103059 +**
1.103060 +**   (4)  The subquery is not DISTINCT.
1.103061 +**
1.103062 +**  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
1.103063 +**        sub-queries that were excluded from this optimization. Restriction 
1.103064 +**        (4) has since been expanded to exclude all DISTINCT subqueries.
1.103065 +**
1.103066 +**   (6)  The subquery does not use aggregates or the outer query is not
1.103067 +**        DISTINCT.
1.103068 +**
1.103069 +**   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
1.103070 +**        A FROM clause, consider adding a FROM close with the special
1.103071 +**        table sqlite_once that consists of a single row containing a
1.103072 +**        single NULL.
1.103073 +**
1.103074 +**   (8)  The subquery does not use LIMIT or the outer query is not a join.
1.103075 +**
1.103076 +**   (9)  The subquery does not use LIMIT or the outer query does not use
1.103077 +**        aggregates.
1.103078 +**
1.103079 +**  (10)  The subquery does not use aggregates or the outer query does not
1.103080 +**        use LIMIT.
1.103081 +**
1.103082 +**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
1.103083 +**
1.103084 +**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
1.103085 +**        a separate restriction deriving from ticket #350.
1.103086 +**
1.103087 +**  (13)  The subquery and outer query do not both use LIMIT.
1.103088 +**
1.103089 +**  (14)  The subquery does not use OFFSET.
1.103090 +**
1.103091 +**  (15)  The outer query is not part of a compound select or the
1.103092 +**        subquery does not have a LIMIT clause.
1.103093 +**        (See ticket #2339 and ticket [02a8e81d44]).
1.103094 +**
1.103095 +**  (16)  The outer query is not an aggregate or the subquery does
1.103096 +**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
1.103097 +**        until we introduced the group_concat() function.  
1.103098 +**
1.103099 +**  (17)  The sub-query is not a compound select, or it is a UNION ALL 
1.103100 +**        compound clause made up entirely of non-aggregate queries, and 
1.103101 +**        the parent query:
1.103102 +**
1.103103 +**          * is not itself part of a compound select,
1.103104 +**          * is not an aggregate or DISTINCT query, and
1.103105 +**          * is not a join
1.103106 +**
1.103107 +**        The parent and sub-query may contain WHERE clauses. Subject to
1.103108 +**        rules (11), (13) and (14), they may also contain ORDER BY,
1.103109 +**        LIMIT and OFFSET clauses.  The subquery cannot use any compound
1.103110 +**        operator other than UNION ALL because all the other compound
1.103111 +**        operators have an implied DISTINCT which is disallowed by
1.103112 +**        restriction (4).
1.103113 +**
1.103114 +**        Also, each component of the sub-query must return the same number
1.103115 +**        of result columns. This is actually a requirement for any compound
1.103116 +**        SELECT statement, but all the code here does is make sure that no
1.103117 +**        such (illegal) sub-query is flattened. The caller will detect the
1.103118 +**        syntax error and return a detailed message.
1.103119 +**
1.103120 +**  (18)  If the sub-query is a compound select, then all terms of the
1.103121 +**        ORDER by clause of the parent must be simple references to 
1.103122 +**        columns of the sub-query.
1.103123 +**
1.103124 +**  (19)  The subquery does not use LIMIT or the outer query does not
1.103125 +**        have a WHERE clause.
1.103126 +**
1.103127 +**  (20)  If the sub-query is a compound select, then it must not use
1.103128 +**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
1.103129 +**        somewhat by saying that the terms of the ORDER BY clause must
1.103130 +**        appear as unmodified result columns in the outer query.  But we
1.103131 +**        have other optimizations in mind to deal with that case.
1.103132 +**
1.103133 +**  (21)  The subquery does not use LIMIT or the outer query is not
1.103134 +**        DISTINCT.  (See ticket [752e1646fc]).
1.103135 +**
1.103136 +**  (22)  The subquery is not a recursive CTE.
1.103137 +**
1.103138 +**  (23)  The parent is not a recursive CTE, or the sub-query is not a
1.103139 +**        compound query. This restriction is because transforming the
1.103140 +**        parent to a compound query confuses the code that handles
1.103141 +**        recursive queries in multiSelect().
1.103142 +**
1.103143 +**
1.103144 +** In this routine, the "p" parameter is a pointer to the outer query.
1.103145 +** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
1.103146 +** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1.103147 +**
1.103148 +** If flattening is not attempted, this routine is a no-op and returns 0.
1.103149 +** If flattening is attempted this routine returns 1.
1.103150 +**
1.103151 +** All of the expression analysis must occur on both the outer query and
1.103152 +** the subquery before this routine runs.
1.103153 +*/
1.103154 +static int flattenSubquery(
1.103155 +  Parse *pParse,       /* Parsing context */
1.103156 +  Select *p,           /* The parent or outer SELECT statement */
1.103157 +  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
1.103158 +  int isAgg,           /* True if outer SELECT uses aggregate functions */
1.103159 +  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
1.103160 +){
1.103161 +  const char *zSavedAuthContext = pParse->zAuthContext;
1.103162 +  Select *pParent;
1.103163 +  Select *pSub;       /* The inner query or "subquery" */
1.103164 +  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
1.103165 +  SrcList *pSrc;      /* The FROM clause of the outer query */
1.103166 +  SrcList *pSubSrc;   /* The FROM clause of the subquery */
1.103167 +  ExprList *pList;    /* The result set of the outer query */
1.103168 +  int iParent;        /* VDBE cursor number of the pSub result set temp table */
1.103169 +  int i;              /* Loop counter */
1.103170 +  Expr *pWhere;                    /* The WHERE clause */
1.103171 +  struct SrcList_item *pSubitem;   /* The subquery */
1.103172 +  sqlite3 *db = pParse->db;
1.103173 +
1.103174 +  /* Check to see if flattening is permitted.  Return 0 if not.
1.103175 +  */
1.103176 +  assert( p!=0 );
1.103177 +  assert( p->pPrior==0 );  /* Unable to flatten compound queries */
1.103178 +  if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
1.103179 +  pSrc = p->pSrc;
1.103180 +  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
1.103181 +  pSubitem = &pSrc->a[iFrom];
1.103182 +  iParent = pSubitem->iCursor;
1.103183 +  pSub = pSubitem->pSelect;
1.103184 +  assert( pSub!=0 );
1.103185 +  if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
1.103186 +  if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
1.103187 +  pSubSrc = pSub->pSrc;
1.103188 +  assert( pSubSrc );
1.103189 +  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
1.103190 +  ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
1.103191 +  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
1.103192 +  ** became arbitrary expressions, we were forced to add restrictions (13)
1.103193 +  ** and (14). */
1.103194 +  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
1.103195 +  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
1.103196 +  if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
1.103197 +    return 0;                                            /* Restriction (15) */
1.103198 +  }
1.103199 +  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
1.103200 +  if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
1.103201 +  if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
1.103202 +     return 0;         /* Restrictions (8)(9) */
1.103203 +  }
1.103204 +  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
1.103205 +     return 0;         /* Restriction (6)  */
1.103206 +  }
1.103207 +  if( p->pOrderBy && pSub->pOrderBy ){
1.103208 +     return 0;                                           /* Restriction (11) */
1.103209 +  }
1.103210 +  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
1.103211 +  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
1.103212 +  if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
1.103213 +     return 0;         /* Restriction (21) */
1.103214 +  }
1.103215 +  if( pSub->selFlags & SF_Recursive ) return 0;          /* Restriction (22)  */
1.103216 +  if( (p->selFlags & SF_Recursive) && pSub->pPrior ) return 0;       /* (23)  */
1.103217 +
1.103218 +  /* OBSOLETE COMMENT 1:
1.103219 +  ** Restriction 3:  If the subquery is a join, make sure the subquery is 
1.103220 +  ** not used as the right operand of an outer join.  Examples of why this
1.103221 +  ** is not allowed:
1.103222 +  **
1.103223 +  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
1.103224 +  **
1.103225 +  ** If we flatten the above, we would get
1.103226 +  **
1.103227 +  **         (t1 LEFT OUTER JOIN t2) JOIN t3
1.103228 +  **
1.103229 +  ** which is not at all the same thing.
1.103230 +  **
1.103231 +  ** OBSOLETE COMMENT 2:
1.103232 +  ** Restriction 12:  If the subquery is the right operand of a left outer
1.103233 +  ** join, make sure the subquery has no WHERE clause.
1.103234 +  ** An examples of why this is not allowed:
1.103235 +  **
1.103236 +  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
1.103237 +  **
1.103238 +  ** If we flatten the above, we would get
1.103239 +  **
1.103240 +  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
1.103241 +  **
1.103242 +  ** But the t2.x>0 test will always fail on a NULL row of t2, which
1.103243 +  ** effectively converts the OUTER JOIN into an INNER JOIN.
1.103244 +  **
1.103245 +  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
1.103246 +  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
1.103247 +  ** is fraught with danger.  Best to avoid the whole thing.  If the
1.103248 +  ** subquery is the right term of a LEFT JOIN, then do not flatten.
1.103249 +  */
1.103250 +  if( (pSubitem->jointype & JT_OUTER)!=0 ){
1.103251 +    return 0;
1.103252 +  }
1.103253 +
1.103254 +  /* Restriction 17: If the sub-query is a compound SELECT, then it must
1.103255 +  ** use only the UNION ALL operator. And none of the simple select queries
1.103256 +  ** that make up the compound SELECT are allowed to be aggregate or distinct
1.103257 +  ** queries.
1.103258 +  */
1.103259 +  if( pSub->pPrior ){
1.103260 +    if( pSub->pOrderBy ){
1.103261 +      return 0;  /* Restriction 20 */
1.103262 +    }
1.103263 +    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
1.103264 +      return 0;
1.103265 +    }
1.103266 +    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
1.103267 +      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
1.103268 +      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
1.103269 +      assert( pSub->pSrc!=0 );
1.103270 +      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
1.103271 +       || (pSub1->pPrior && pSub1->op!=TK_ALL) 
1.103272 +       || pSub1->pSrc->nSrc<1
1.103273 +       || pSub->pEList->nExpr!=pSub1->pEList->nExpr
1.103274 +      ){
1.103275 +        return 0;
1.103276 +      }
1.103277 +      testcase( pSub1->pSrc->nSrc>1 );
1.103278 +    }
1.103279 +
1.103280 +    /* Restriction 18. */
1.103281 +    if( p->pOrderBy ){
1.103282 +      int ii;
1.103283 +      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
1.103284 +        if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
1.103285 +      }
1.103286 +    }
1.103287 +  }
1.103288 +
1.103289 +  /***** If we reach this point, flattening is permitted. *****/
1.103290 +
1.103291 +  /* Authorize the subquery */
1.103292 +  pParse->zAuthContext = pSubitem->zName;
1.103293 +  TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
1.103294 +  testcase( i==SQLITE_DENY );
1.103295 +  pParse->zAuthContext = zSavedAuthContext;
1.103296 +
1.103297 +  /* If the sub-query is a compound SELECT statement, then (by restrictions
1.103298 +  ** 17 and 18 above) it must be a UNION ALL and the parent query must 
1.103299 +  ** be of the form:
1.103300 +  **
1.103301 +  **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
1.103302 +  **
1.103303 +  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
1.103304 +  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
1.103305 +  ** OFFSET clauses and joins them to the left-hand-side of the original
1.103306 +  ** using UNION ALL operators. In this case N is the number of simple
1.103307 +  ** select statements in the compound sub-query.
1.103308 +  **
1.103309 +  ** Example:
1.103310 +  **
1.103311 +  **     SELECT a+1 FROM (
1.103312 +  **        SELECT x FROM tab
1.103313 +  **        UNION ALL
1.103314 +  **        SELECT y FROM tab
1.103315 +  **        UNION ALL
1.103316 +  **        SELECT abs(z*2) FROM tab2
1.103317 +  **     ) WHERE a!=5 ORDER BY 1
1.103318 +  **
1.103319 +  ** Transformed into:
1.103320 +  **
1.103321 +  **     SELECT x+1 FROM tab WHERE x+1!=5
1.103322 +  **     UNION ALL
1.103323 +  **     SELECT y+1 FROM tab WHERE y+1!=5
1.103324 +  **     UNION ALL
1.103325 +  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
1.103326 +  **     ORDER BY 1
1.103327 +  **
1.103328 +  ** We call this the "compound-subquery flattening".
1.103329 +  */
1.103330 +  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
1.103331 +    Select *pNew;
1.103332 +    ExprList *pOrderBy = p->pOrderBy;
1.103333 +    Expr *pLimit = p->pLimit;
1.103334 +    Expr *pOffset = p->pOffset;
1.103335 +    Select *pPrior = p->pPrior;
1.103336 +    p->pOrderBy = 0;
1.103337 +    p->pSrc = 0;
1.103338 +    p->pPrior = 0;
1.103339 +    p->pLimit = 0;
1.103340 +    p->pOffset = 0;
1.103341 +    pNew = sqlite3SelectDup(db, p, 0);
1.103342 +    p->pOffset = pOffset;
1.103343 +    p->pLimit = pLimit;
1.103344 +    p->pOrderBy = pOrderBy;
1.103345 +    p->pSrc = pSrc;
1.103346 +    p->op = TK_ALL;
1.103347 +    if( pNew==0 ){
1.103348 +      p->pPrior = pPrior;
1.103349 +    }else{
1.103350 +      pNew->pPrior = pPrior;
1.103351 +      if( pPrior ) pPrior->pNext = pNew;
1.103352 +      pNew->pNext = p;
1.103353 +      p->pPrior = pNew;
1.103354 +    }
1.103355 +    if( db->mallocFailed ) return 1;
1.103356 +  }
1.103357 +
1.103358 +  /* Begin flattening the iFrom-th entry of the FROM clause 
1.103359 +  ** in the outer query.
1.103360 +  */
1.103361 +  pSub = pSub1 = pSubitem->pSelect;
1.103362 +
1.103363 +  /* Delete the transient table structure associated with the
1.103364 +  ** subquery
1.103365 +  */
1.103366 +  sqlite3DbFree(db, pSubitem->zDatabase);
1.103367 +  sqlite3DbFree(db, pSubitem->zName);
1.103368 +  sqlite3DbFree(db, pSubitem->zAlias);
1.103369 +  pSubitem->zDatabase = 0;
1.103370 +  pSubitem->zName = 0;
1.103371 +  pSubitem->zAlias = 0;
1.103372 +  pSubitem->pSelect = 0;
1.103373 +
1.103374 +  /* Defer deleting the Table object associated with the
1.103375 +  ** subquery until code generation is
1.103376 +  ** complete, since there may still exist Expr.pTab entries that
1.103377 +  ** refer to the subquery even after flattening.  Ticket #3346.
1.103378 +  **
1.103379 +  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
1.103380 +  */
1.103381 +  if( ALWAYS(pSubitem->pTab!=0) ){
1.103382 +    Table *pTabToDel = pSubitem->pTab;
1.103383 +    if( pTabToDel->nRef==1 ){
1.103384 +      Parse *pToplevel = sqlite3ParseToplevel(pParse);
1.103385 +      pTabToDel->pNextZombie = pToplevel->pZombieTab;
1.103386 +      pToplevel->pZombieTab = pTabToDel;
1.103387 +    }else{
1.103388 +      pTabToDel->nRef--;
1.103389 +    }
1.103390 +    pSubitem->pTab = 0;
1.103391 +  }
1.103392 +
1.103393 +  /* The following loop runs once for each term in a compound-subquery
1.103394 +  ** flattening (as described above).  If we are doing a different kind
1.103395 +  ** of flattening - a flattening other than a compound-subquery flattening -
1.103396 +  ** then this loop only runs once.
1.103397 +  **
1.103398 +  ** This loop moves all of the FROM elements of the subquery into the
1.103399 +  ** the FROM clause of the outer query.  Before doing this, remember
1.103400 +  ** the cursor number for the original outer query FROM element in
1.103401 +  ** iParent.  The iParent cursor will never be used.  Subsequent code
1.103402 +  ** will scan expressions looking for iParent references and replace
1.103403 +  ** those references with expressions that resolve to the subquery FROM
1.103404 +  ** elements we are now copying in.
1.103405 +  */
1.103406 +  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
1.103407 +    int nSubSrc;
1.103408 +    u8 jointype = 0;
1.103409 +    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
1.103410 +    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
1.103411 +    pSrc = pParent->pSrc;     /* FROM clause of the outer query */
1.103412 +
1.103413 +    if( pSrc ){
1.103414 +      assert( pParent==p );  /* First time through the loop */
1.103415 +      jointype = pSubitem->jointype;
1.103416 +    }else{
1.103417 +      assert( pParent!=p );  /* 2nd and subsequent times through the loop */
1.103418 +      pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
1.103419 +      if( pSrc==0 ){
1.103420 +        assert( db->mallocFailed );
1.103421 +        break;
1.103422 +      }
1.103423 +    }
1.103424 +
1.103425 +    /* The subquery uses a single slot of the FROM clause of the outer
1.103426 +    ** query.  If the subquery has more than one element in its FROM clause,
1.103427 +    ** then expand the outer query to make space for it to hold all elements
1.103428 +    ** of the subquery.
1.103429 +    **
1.103430 +    ** Example:
1.103431 +    **
1.103432 +    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
1.103433 +    **
1.103434 +    ** The outer query has 3 slots in its FROM clause.  One slot of the
1.103435 +    ** outer query (the middle slot) is used by the subquery.  The next
1.103436 +    ** block of code will expand the out query to 4 slots.  The middle
1.103437 +    ** slot is expanded to two slots in order to make space for the
1.103438 +    ** two elements in the FROM clause of the subquery.
1.103439 +    */
1.103440 +    if( nSubSrc>1 ){
1.103441 +      pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
1.103442 +      if( db->mallocFailed ){
1.103443 +        break;
1.103444 +      }
1.103445 +    }
1.103446 +
1.103447 +    /* Transfer the FROM clause terms from the subquery into the
1.103448 +    ** outer query.
1.103449 +    */
1.103450 +    for(i=0; i<nSubSrc; i++){
1.103451 +      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
1.103452 +      pSrc->a[i+iFrom] = pSubSrc->a[i];
1.103453 +      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1.103454 +    }
1.103455 +    pSrc->a[iFrom].jointype = jointype;
1.103456 +  
1.103457 +    /* Now begin substituting subquery result set expressions for 
1.103458 +    ** references to the iParent in the outer query.
1.103459 +    ** 
1.103460 +    ** Example:
1.103461 +    **
1.103462 +    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1.103463 +    **   \                     \_____________ subquery __________/          /
1.103464 +    **    \_____________________ outer query ______________________________/
1.103465 +    **
1.103466 +    ** We look at every expression in the outer query and every place we see
1.103467 +    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1.103468 +    */
1.103469 +    pList = pParent->pEList;
1.103470 +    for(i=0; i<pList->nExpr; i++){
1.103471 +      if( pList->a[i].zName==0 ){
1.103472 +        char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
1.103473 +        sqlite3Dequote(zName);
1.103474 +        pList->a[i].zName = zName;
1.103475 +      }
1.103476 +    }
1.103477 +    substExprList(db, pParent->pEList, iParent, pSub->pEList);
1.103478 +    if( isAgg ){
1.103479 +      substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
1.103480 +      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
1.103481 +    }
1.103482 +    if( pSub->pOrderBy ){
1.103483 +      assert( pParent->pOrderBy==0 );
1.103484 +      pParent->pOrderBy = pSub->pOrderBy;
1.103485 +      pSub->pOrderBy = 0;
1.103486 +    }else if( pParent->pOrderBy ){
1.103487 +      substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
1.103488 +    }
1.103489 +    if( pSub->pWhere ){
1.103490 +      pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
1.103491 +    }else{
1.103492 +      pWhere = 0;
1.103493 +    }
1.103494 +    if( subqueryIsAgg ){
1.103495 +      assert( pParent->pHaving==0 );
1.103496 +      pParent->pHaving = pParent->pWhere;
1.103497 +      pParent->pWhere = pWhere;
1.103498 +      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
1.103499 +      pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
1.103500 +                                  sqlite3ExprDup(db, pSub->pHaving, 0));
1.103501 +      assert( pParent->pGroupBy==0 );
1.103502 +      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
1.103503 +    }else{
1.103504 +      pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
1.103505 +      pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
1.103506 +    }
1.103507 +  
1.103508 +    /* The flattened query is distinct if either the inner or the
1.103509 +    ** outer query is distinct. 
1.103510 +    */
1.103511 +    pParent->selFlags |= pSub->selFlags & SF_Distinct;
1.103512 +  
1.103513 +    /*
1.103514 +    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
1.103515 +    **
1.103516 +    ** One is tempted to try to add a and b to combine the limits.  But this
1.103517 +    ** does not work if either limit is negative.
1.103518 +    */
1.103519 +    if( pSub->pLimit ){
1.103520 +      pParent->pLimit = pSub->pLimit;
1.103521 +      pSub->pLimit = 0;
1.103522 +    }
1.103523 +  }
1.103524 +
1.103525 +  /* Finially, delete what is left of the subquery and return
1.103526 +  ** success.
1.103527 +  */
1.103528 +  sqlite3SelectDelete(db, pSub1);
1.103529 +
1.103530 +  return 1;
1.103531 +}
1.103532 +#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
1.103533 +
1.103534 +/*
1.103535 +** Based on the contents of the AggInfo structure indicated by the first
1.103536 +** argument, this function checks if the following are true:
1.103537 +**
1.103538 +**    * the query contains just a single aggregate function,
1.103539 +**    * the aggregate function is either min() or max(), and
1.103540 +**    * the argument to the aggregate function is a column value.
1.103541 +**
1.103542 +** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
1.103543 +** is returned as appropriate. Also, *ppMinMax is set to point to the 
1.103544 +** list of arguments passed to the aggregate before returning.
1.103545 +**
1.103546 +** Or, if the conditions above are not met, *ppMinMax is set to 0 and
1.103547 +** WHERE_ORDERBY_NORMAL is returned.
1.103548 +*/
1.103549 +static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
1.103550 +  int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
1.103551 +
1.103552 +  *ppMinMax = 0;
1.103553 +  if( pAggInfo->nFunc==1 ){
1.103554 +    Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
1.103555 +    ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
1.103556 +
1.103557 +    assert( pExpr->op==TK_AGG_FUNCTION );
1.103558 +    if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
1.103559 +      const char *zFunc = pExpr->u.zToken;
1.103560 +      if( sqlite3StrICmp(zFunc, "min")==0 ){
1.103561 +        eRet = WHERE_ORDERBY_MIN;
1.103562 +        *ppMinMax = pEList;
1.103563 +      }else if( sqlite3StrICmp(zFunc, "max")==0 ){
1.103564 +        eRet = WHERE_ORDERBY_MAX;
1.103565 +        *ppMinMax = pEList;
1.103566 +      }
1.103567 +    }
1.103568 +  }
1.103569 +
1.103570 +  assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
1.103571 +  return eRet;
1.103572 +}
1.103573 +
1.103574 +/*
1.103575 +** The select statement passed as the first argument is an aggregate query.
1.103576 +** The second argment is the associated aggregate-info object. This 
1.103577 +** function tests if the SELECT is of the form:
1.103578 +**
1.103579 +**   SELECT count(*) FROM <tbl>
1.103580 +**
1.103581 +** where table is a database table, not a sub-select or view. If the query
1.103582 +** does match this pattern, then a pointer to the Table object representing
1.103583 +** <tbl> is returned. Otherwise, 0 is returned.
1.103584 +*/
1.103585 +static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
1.103586 +  Table *pTab;
1.103587 +  Expr *pExpr;
1.103588 +
1.103589 +  assert( !p->pGroupBy );
1.103590 +
1.103591 +  if( p->pWhere || p->pEList->nExpr!=1 
1.103592 +   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
1.103593 +  ){
1.103594 +    return 0;
1.103595 +  }
1.103596 +  pTab = p->pSrc->a[0].pTab;
1.103597 +  pExpr = p->pEList->a[0].pExpr;
1.103598 +  assert( pTab && !pTab->pSelect && pExpr );
1.103599 +
1.103600 +  if( IsVirtual(pTab) ) return 0;
1.103601 +  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
1.103602 +  if( NEVER(pAggInfo->nFunc==0) ) return 0;
1.103603 +  if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
1.103604 +  if( pExpr->flags&EP_Distinct ) return 0;
1.103605 +
1.103606 +  return pTab;
1.103607 +}
1.103608 +
1.103609 +/*
1.103610 +** If the source-list item passed as an argument was augmented with an
1.103611 +** INDEXED BY clause, then try to locate the specified index. If there
1.103612 +** was such a clause and the named index cannot be found, return 
1.103613 +** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
1.103614 +** pFrom->pIndex and return SQLITE_OK.
1.103615 +*/
1.103616 +SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
1.103617 +  if( pFrom->pTab && pFrom->zIndex ){
1.103618 +    Table *pTab = pFrom->pTab;
1.103619 +    char *zIndex = pFrom->zIndex;
1.103620 +    Index *pIdx;
1.103621 +    for(pIdx=pTab->pIndex; 
1.103622 +        pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
1.103623 +        pIdx=pIdx->pNext
1.103624 +    );
1.103625 +    if( !pIdx ){
1.103626 +      sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
1.103627 +      pParse->checkSchema = 1;
1.103628 +      return SQLITE_ERROR;
1.103629 +    }
1.103630 +    pFrom->pIndex = pIdx;
1.103631 +  }
1.103632 +  return SQLITE_OK;
1.103633 +}
1.103634 +/*
1.103635 +** Detect compound SELECT statements that use an ORDER BY clause with 
1.103636 +** an alternative collating sequence.
1.103637 +**
1.103638 +**    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
1.103639 +**
1.103640 +** These are rewritten as a subquery:
1.103641 +**
1.103642 +**    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
1.103643 +**     ORDER BY ... COLLATE ...
1.103644 +**
1.103645 +** This transformation is necessary because the multiSelectOrderBy() routine
1.103646 +** above that generates the code for a compound SELECT with an ORDER BY clause
1.103647 +** uses a merge algorithm that requires the same collating sequence on the
1.103648 +** result columns as on the ORDER BY clause.  See ticket
1.103649 +** http://www.sqlite.org/src/info/6709574d2a
1.103650 +**
1.103651 +** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
1.103652 +** The UNION ALL operator works fine with multiSelectOrderBy() even when
1.103653 +** there are COLLATE terms in the ORDER BY.
1.103654 +*/
1.103655 +static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
1.103656 +  int i;
1.103657 +  Select *pNew;
1.103658 +  Select *pX;
1.103659 +  sqlite3 *db;
1.103660 +  struct ExprList_item *a;
1.103661 +  SrcList *pNewSrc;
1.103662 +  Parse *pParse;
1.103663 +  Token dummy;
1.103664 +
1.103665 +  if( p->pPrior==0 ) return WRC_Continue;
1.103666 +  if( p->pOrderBy==0 ) return WRC_Continue;
1.103667 +  for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
1.103668 +  if( pX==0 ) return WRC_Continue;
1.103669 +  a = p->pOrderBy->a;
1.103670 +  for(i=p->pOrderBy->nExpr-1; i>=0; i--){
1.103671 +    if( a[i].pExpr->flags & EP_Collate ) break;
1.103672 +  }
1.103673 +  if( i<0 ) return WRC_Continue;
1.103674 +
1.103675 +  /* If we reach this point, that means the transformation is required. */
1.103676 +
1.103677 +  pParse = pWalker->pParse;
1.103678 +  db = pParse->db;
1.103679 +  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
1.103680 +  if( pNew==0 ) return WRC_Abort;
1.103681 +  memset(&dummy, 0, sizeof(dummy));
1.103682 +  pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
1.103683 +  if( pNewSrc==0 ) return WRC_Abort;
1.103684 +  *pNew = *p;
1.103685 +  p->pSrc = pNewSrc;
1.103686 +  p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
1.103687 +  p->op = TK_SELECT;
1.103688 +  p->pWhere = 0;
1.103689 +  pNew->pGroupBy = 0;
1.103690 +  pNew->pHaving = 0;
1.103691 +  pNew->pOrderBy = 0;
1.103692 +  p->pPrior = 0;
1.103693 +  p->pNext = 0;
1.103694 +  p->selFlags &= ~SF_Compound;
1.103695 +  assert( pNew->pPrior!=0 );
1.103696 +  pNew->pPrior->pNext = pNew;
1.103697 +  pNew->pLimit = 0;
1.103698 +  pNew->pOffset = 0;
1.103699 +  return WRC_Continue;
1.103700 +}
1.103701 +
1.103702 +#ifndef SQLITE_OMIT_CTE
1.103703 +/*
1.103704 +** Argument pWith (which may be NULL) points to a linked list of nested 
1.103705 +** WITH contexts, from inner to outermost. If the table identified by 
1.103706 +** FROM clause element pItem is really a common-table-expression (CTE) 
1.103707 +** then return a pointer to the CTE definition for that table. Otherwise
1.103708 +** return NULL.
1.103709 +**
1.103710 +** If a non-NULL value is returned, set *ppContext to point to the With
1.103711 +** object that the returned CTE belongs to.
1.103712 +*/
1.103713 +static struct Cte *searchWith(
1.103714 +  With *pWith,                    /* Current outermost WITH clause */
1.103715 +  struct SrcList_item *pItem,     /* FROM clause element to resolve */
1.103716 +  With **ppContext                /* OUT: WITH clause return value belongs to */
1.103717 +){
1.103718 +  const char *zName;
1.103719 +  if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
1.103720 +    With *p;
1.103721 +    for(p=pWith; p; p=p->pOuter){
1.103722 +      int i;
1.103723 +      for(i=0; i<p->nCte; i++){
1.103724 +        if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
1.103725 +          *ppContext = p;
1.103726 +          return &p->a[i];
1.103727 +        }
1.103728 +      }
1.103729 +    }
1.103730 +  }
1.103731 +  return 0;
1.103732 +}
1.103733 +
1.103734 +/* The code generator maintains a stack of active WITH clauses
1.103735 +** with the inner-most WITH clause being at the top of the stack.
1.103736 +**
1.103737 +** This routine pushes the WITH clause passed as the second argument
1.103738 +** onto the top of the stack. If argument bFree is true, then this
1.103739 +** WITH clause will never be popped from the stack. In this case it
1.103740 +** should be freed along with the Parse object. In other cases, when
1.103741 +** bFree==0, the With object will be freed along with the SELECT 
1.103742 +** statement with which it is associated.
1.103743 +*/
1.103744 +SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
1.103745 +  assert( bFree==0 || pParse->pWith==0 );
1.103746 +  if( pWith ){
1.103747 +    pWith->pOuter = pParse->pWith;
1.103748 +    pParse->pWith = pWith;
1.103749 +    pParse->bFreeWith = bFree;
1.103750 +  }
1.103751 +}
1.103752 +
1.103753 +/*
1.103754 +** This function checks if argument pFrom refers to a CTE declared by 
1.103755 +** a WITH clause on the stack currently maintained by the parser. And,
1.103756 +** if currently processing a CTE expression, if it is a recursive
1.103757 +** reference to the current CTE.
1.103758 +**
1.103759 +** If pFrom falls into either of the two categories above, pFrom->pTab
1.103760 +** and other fields are populated accordingly. The caller should check
1.103761 +** (pFrom->pTab!=0) to determine whether or not a successful match
1.103762 +** was found.
1.103763 +**
1.103764 +** Whether or not a match is found, SQLITE_OK is returned if no error
1.103765 +** occurs. If an error does occur, an error message is stored in the
1.103766 +** parser and some error code other than SQLITE_OK returned.
1.103767 +*/
1.103768 +static int withExpand(
1.103769 +  Walker *pWalker, 
1.103770 +  struct SrcList_item *pFrom
1.103771 +){
1.103772 +  Parse *pParse = pWalker->pParse;
1.103773 +  sqlite3 *db = pParse->db;
1.103774 +  struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
1.103775 +  With *pWith;                    /* WITH clause that pCte belongs to */
1.103776 +
1.103777 +  assert( pFrom->pTab==0 );
1.103778 +
1.103779 +  pCte = searchWith(pParse->pWith, pFrom, &pWith);
1.103780 +  if( pCte ){
1.103781 +    Table *pTab;
1.103782 +    ExprList *pEList;
1.103783 +    Select *pSel;
1.103784 +    Select *pLeft;                /* Left-most SELECT statement */
1.103785 +    int bMayRecursive;            /* True if compound joined by UNION [ALL] */
1.103786 +    With *pSavedWith;             /* Initial value of pParse->pWith */
1.103787 +
1.103788 +    /* If pCte->zErr is non-NULL at this point, then this is an illegal
1.103789 +    ** recursive reference to CTE pCte. Leave an error in pParse and return
1.103790 +    ** early. If pCte->zErr is NULL, then this is not a recursive reference.
1.103791 +    ** In this case, proceed.  */
1.103792 +    if( pCte->zErr ){
1.103793 +      sqlite3ErrorMsg(pParse, pCte->zErr, pCte->zName);
1.103794 +      return SQLITE_ERROR;
1.103795 +    }
1.103796 +
1.103797 +    assert( pFrom->pTab==0 );
1.103798 +    pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
1.103799 +    if( pTab==0 ) return WRC_Abort;
1.103800 +    pTab->nRef = 1;
1.103801 +    pTab->zName = sqlite3DbStrDup(db, pCte->zName);
1.103802 +    pTab->iPKey = -1;
1.103803 +    pTab->nRowEst = 1048576;
1.103804 +    pTab->tabFlags |= TF_Ephemeral;
1.103805 +    pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
1.103806 +    if( db->mallocFailed ) return SQLITE_NOMEM;
1.103807 +    assert( pFrom->pSelect );
1.103808 +
1.103809 +    /* Check if this is a recursive CTE. */
1.103810 +    pSel = pFrom->pSelect;
1.103811 +    bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
1.103812 +    if( bMayRecursive ){
1.103813 +      int i;
1.103814 +      SrcList *pSrc = pFrom->pSelect->pSrc;
1.103815 +      for(i=0; i<pSrc->nSrc; i++){
1.103816 +        struct SrcList_item *pItem = &pSrc->a[i];
1.103817 +        if( pItem->zDatabase==0 
1.103818 +         && pItem->zName!=0 
1.103819 +         && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
1.103820 +          ){
1.103821 +          pItem->pTab = pTab;
1.103822 +          pItem->isRecursive = 1;
1.103823 +          pTab->nRef++;
1.103824 +          pSel->selFlags |= SF_Recursive;
1.103825 +        }
1.103826 +      }
1.103827 +    }
1.103828 +
1.103829 +    /* Only one recursive reference is permitted. */ 
1.103830 +    if( pTab->nRef>2 ){
1.103831 +      sqlite3ErrorMsg(
1.103832 +          pParse, "multiple references to recursive table: %s", pCte->zName
1.103833 +      );
1.103834 +      return SQLITE_ERROR;
1.103835 +    }
1.103836 +    assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
1.103837 +
1.103838 +    pCte->zErr = "circular reference: %s";
1.103839 +    pSavedWith = pParse->pWith;
1.103840 +    pParse->pWith = pWith;
1.103841 +    sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
1.103842 +
1.103843 +    for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
1.103844 +    pEList = pLeft->pEList;
1.103845 +    if( pCte->pCols ){
1.103846 +      if( pEList->nExpr!=pCte->pCols->nExpr ){
1.103847 +        sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
1.103848 +            pCte->zName, pEList->nExpr, pCte->pCols->nExpr
1.103849 +        );
1.103850 +        pParse->pWith = pSavedWith;
1.103851 +        return SQLITE_ERROR;
1.103852 +      }
1.103853 +      pEList = pCte->pCols;
1.103854 +    }
1.103855 +
1.103856 +    selectColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
1.103857 +    if( bMayRecursive ){
1.103858 +      if( pSel->selFlags & SF_Recursive ){
1.103859 +        pCte->zErr = "multiple recursive references: %s";
1.103860 +      }else{
1.103861 +        pCte->zErr = "recursive reference in a subquery: %s";
1.103862 +      }
1.103863 +      sqlite3WalkSelect(pWalker, pSel);
1.103864 +    }
1.103865 +    pCte->zErr = 0;
1.103866 +    pParse->pWith = pSavedWith;
1.103867 +  }
1.103868 +
1.103869 +  return SQLITE_OK;
1.103870 +}
1.103871 +#endif
1.103872 +
1.103873 +#ifndef SQLITE_OMIT_CTE
1.103874 +/*
1.103875 +** If the SELECT passed as the second argument has an associated WITH 
1.103876 +** clause, pop it from the stack stored as part of the Parse object.
1.103877 +**
1.103878 +** This function is used as the xSelectCallback2() callback by
1.103879 +** sqlite3SelectExpand() when walking a SELECT tree to resolve table
1.103880 +** names and other FROM clause elements. 
1.103881 +*/
1.103882 +static void selectPopWith(Walker *pWalker, Select *p){
1.103883 +  Parse *pParse = pWalker->pParse;
1.103884 +  With *pWith = findRightmost(p)->pWith;
1.103885 +  if( pWith!=0 ){
1.103886 +    assert( pParse->pWith==pWith );
1.103887 +    pParse->pWith = pWith->pOuter;
1.103888 +  }
1.103889 +}
1.103890 +#else
1.103891 +#define selectPopWith 0
1.103892 +#endif
1.103893 +
1.103894 +/*
1.103895 +** This routine is a Walker callback for "expanding" a SELECT statement.
1.103896 +** "Expanding" means to do the following:
1.103897 +**
1.103898 +**    (1)  Make sure VDBE cursor numbers have been assigned to every
1.103899 +**         element of the FROM clause.
1.103900 +**
1.103901 +**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
1.103902 +**         defines FROM clause.  When views appear in the FROM clause,
1.103903 +**         fill pTabList->a[].pSelect with a copy of the SELECT statement
1.103904 +**         that implements the view.  A copy is made of the view's SELECT
1.103905 +**         statement so that we can freely modify or delete that statement
1.103906 +**         without worrying about messing up the presistent representation
1.103907 +**         of the view.
1.103908 +**
1.103909 +**    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
1.103910 +**         on joins and the ON and USING clause of joins.
1.103911 +**
1.103912 +**    (4)  Scan the list of columns in the result set (pEList) looking
1.103913 +**         for instances of the "*" operator or the TABLE.* operator.
1.103914 +**         If found, expand each "*" to be every column in every table
1.103915 +**         and TABLE.* to be every column in TABLE.
1.103916 +**
1.103917 +*/
1.103918 +static int selectExpander(Walker *pWalker, Select *p){
1.103919 +  Parse *pParse = pWalker->pParse;
1.103920 +  int i, j, k;
1.103921 +  SrcList *pTabList;
1.103922 +  ExprList *pEList;
1.103923 +  struct SrcList_item *pFrom;
1.103924 +  sqlite3 *db = pParse->db;
1.103925 +  Expr *pE, *pRight, *pExpr;
1.103926 +  u16 selFlags = p->selFlags;
1.103927 +
1.103928 +  p->selFlags |= SF_Expanded;
1.103929 +  if( db->mallocFailed  ){
1.103930 +    return WRC_Abort;
1.103931 +  }
1.103932 +  if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
1.103933 +    return WRC_Prune;
1.103934 +  }
1.103935 +  pTabList = p->pSrc;
1.103936 +  pEList = p->pEList;
1.103937 +  sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
1.103938 +
1.103939 +  /* Make sure cursor numbers have been assigned to all entries in
1.103940 +  ** the FROM clause of the SELECT statement.
1.103941 +  */
1.103942 +  sqlite3SrcListAssignCursors(pParse, pTabList);
1.103943 +
1.103944 +  /* Look up every table named in the FROM clause of the select.  If
1.103945 +  ** an entry of the FROM clause is a subquery instead of a table or view,
1.103946 +  ** then create a transient table structure to describe the subquery.
1.103947 +  */
1.103948 +  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1.103949 +    Table *pTab;
1.103950 +    assert( pFrom->isRecursive==0 || pFrom->pTab );
1.103951 +    if( pFrom->isRecursive ) continue;
1.103952 +    if( pFrom->pTab!=0 ){
1.103953 +      /* This statement has already been prepared.  There is no need
1.103954 +      ** to go further. */
1.103955 +      assert( i==0 );
1.103956 +#ifndef SQLITE_OMIT_CTE
1.103957 +      selectPopWith(pWalker, p);
1.103958 +#endif
1.103959 +      return WRC_Prune;
1.103960 +    }
1.103961 +#ifndef SQLITE_OMIT_CTE
1.103962 +    if( withExpand(pWalker, pFrom) ) return WRC_Abort;
1.103963 +    if( pFrom->pTab ) {} else
1.103964 +#endif
1.103965 +    if( pFrom->zName==0 ){
1.103966 +#ifndef SQLITE_OMIT_SUBQUERY
1.103967 +      Select *pSel = pFrom->pSelect;
1.103968 +      /* A sub-query in the FROM clause of a SELECT */
1.103969 +      assert( pSel!=0 );
1.103970 +      assert( pFrom->pTab==0 );
1.103971 +      sqlite3WalkSelect(pWalker, pSel);
1.103972 +      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
1.103973 +      if( pTab==0 ) return WRC_Abort;
1.103974 +      pTab->nRef = 1;
1.103975 +      pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
1.103976 +      while( pSel->pPrior ){ pSel = pSel->pPrior; }
1.103977 +      selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
1.103978 +      pTab->iPKey = -1;
1.103979 +      pTab->nRowEst = 1048576;
1.103980 +      pTab->tabFlags |= TF_Ephemeral;
1.103981 +#endif
1.103982 +    }else{
1.103983 +      /* An ordinary table or view name in the FROM clause */
1.103984 +      assert( pFrom->pTab==0 );
1.103985 +      pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
1.103986 +      if( pTab==0 ) return WRC_Abort;
1.103987 +      if( pTab->nRef==0xffff ){
1.103988 +        sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
1.103989 +           pTab->zName);
1.103990 +        pFrom->pTab = 0;
1.103991 +        return WRC_Abort;
1.103992 +      }
1.103993 +      pTab->nRef++;
1.103994 +#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
1.103995 +      if( pTab->pSelect || IsVirtual(pTab) ){
1.103996 +        /* We reach here if the named table is a really a view */
1.103997 +        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
1.103998 +        assert( pFrom->pSelect==0 );
1.103999 +        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
1.104000 +        sqlite3WalkSelect(pWalker, pFrom->pSelect);
1.104001 +      }
1.104002 +#endif
1.104003 +    }
1.104004 +
1.104005 +    /* Locate the index named by the INDEXED BY clause, if any. */
1.104006 +    if( sqlite3IndexedByLookup(pParse, pFrom) ){
1.104007 +      return WRC_Abort;
1.104008 +    }
1.104009 +  }
1.104010 +
1.104011 +  /* Process NATURAL keywords, and ON and USING clauses of joins.
1.104012 +  */
1.104013 +  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
1.104014 +    return WRC_Abort;
1.104015 +  }
1.104016 +
1.104017 +  /* For every "*" that occurs in the column list, insert the names of
1.104018 +  ** all columns in all tables.  And for every TABLE.* insert the names
1.104019 +  ** of all columns in TABLE.  The parser inserted a special expression
1.104020 +  ** with the TK_ALL operator for each "*" that it found in the column list.
1.104021 +  ** The following code just has to locate the TK_ALL expressions and expand
1.104022 +  ** each one to the list of all columns in all tables.
1.104023 +  **
1.104024 +  ** The first loop just checks to see if there are any "*" operators
1.104025 +  ** that need expanding.
1.104026 +  */
1.104027 +  for(k=0; k<pEList->nExpr; k++){
1.104028 +    pE = pEList->a[k].pExpr;
1.104029 +    if( pE->op==TK_ALL ) break;
1.104030 +    assert( pE->op!=TK_DOT || pE->pRight!=0 );
1.104031 +    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
1.104032 +    if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
1.104033 +  }
1.104034 +  if( k<pEList->nExpr ){
1.104035 +    /*
1.104036 +    ** If we get here it means the result set contains one or more "*"
1.104037 +    ** operators that need to be expanded.  Loop through each expression
1.104038 +    ** in the result set and expand them one by one.
1.104039 +    */
1.104040 +    struct ExprList_item *a = pEList->a;
1.104041 +    ExprList *pNew = 0;
1.104042 +    int flags = pParse->db->flags;
1.104043 +    int longNames = (flags & SQLITE_FullColNames)!=0
1.104044 +                      && (flags & SQLITE_ShortColNames)==0;
1.104045 +
1.104046 +    /* When processing FROM-clause subqueries, it is always the case
1.104047 +    ** that full_column_names=OFF and short_column_names=ON.  The
1.104048 +    ** sqlite3ResultSetOfSelect() routine makes it so. */
1.104049 +    assert( (p->selFlags & SF_NestedFrom)==0
1.104050 +          || ((flags & SQLITE_FullColNames)==0 &&
1.104051 +              (flags & SQLITE_ShortColNames)!=0) );
1.104052 +
1.104053 +    for(k=0; k<pEList->nExpr; k++){
1.104054 +      pE = a[k].pExpr;
1.104055 +      pRight = pE->pRight;
1.104056 +      assert( pE->op!=TK_DOT || pRight!=0 );
1.104057 +      if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
1.104058 +        /* This particular expression does not need to be expanded.
1.104059 +        */
1.104060 +        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
1.104061 +        if( pNew ){
1.104062 +          pNew->a[pNew->nExpr-1].zName = a[k].zName;
1.104063 +          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
1.104064 +          a[k].zName = 0;
1.104065 +          a[k].zSpan = 0;
1.104066 +        }
1.104067 +        a[k].pExpr = 0;
1.104068 +      }else{
1.104069 +        /* This expression is a "*" or a "TABLE.*" and needs to be
1.104070 +        ** expanded. */
1.104071 +        int tableSeen = 0;      /* Set to 1 when TABLE matches */
1.104072 +        char *zTName = 0;       /* text of name of TABLE */
1.104073 +        if( pE->op==TK_DOT ){
1.104074 +          assert( pE->pLeft!=0 );
1.104075 +          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
1.104076 +          zTName = pE->pLeft->u.zToken;
1.104077 +        }
1.104078 +        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1.104079 +          Table *pTab = pFrom->pTab;
1.104080 +          Select *pSub = pFrom->pSelect;
1.104081 +          char *zTabName = pFrom->zAlias;
1.104082 +          const char *zSchemaName = 0;
1.104083 +          int iDb;
1.104084 +          if( zTabName==0 ){
1.104085 +            zTabName = pTab->zName;
1.104086 +          }
1.104087 +          if( db->mallocFailed ) break;
1.104088 +          if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
1.104089 +            pSub = 0;
1.104090 +            if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
1.104091 +              continue;
1.104092 +            }
1.104093 +            iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1.104094 +            zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
1.104095 +          }
1.104096 +          for(j=0; j<pTab->nCol; j++){
1.104097 +            char *zName = pTab->aCol[j].zName;
1.104098 +            char *zColname;  /* The computed column name */
1.104099 +            char *zToFree;   /* Malloced string that needs to be freed */
1.104100 +            Token sColname;  /* Computed column name as a token */
1.104101 +
1.104102 +            assert( zName );
1.104103 +            if( zTName && pSub
1.104104 +             && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
1.104105 +            ){
1.104106 +              continue;
1.104107 +            }
1.104108 +
1.104109 +            /* If a column is marked as 'hidden' (currently only possible
1.104110 +            ** for virtual tables), do not include it in the expanded
1.104111 +            ** result-set list.
1.104112 +            */
1.104113 +            if( IsHiddenColumn(&pTab->aCol[j]) ){
1.104114 +              assert(IsVirtual(pTab));
1.104115 +              continue;
1.104116 +            }
1.104117 +            tableSeen = 1;
1.104118 +
1.104119 +            if( i>0 && zTName==0 ){
1.104120 +              if( (pFrom->jointype & JT_NATURAL)!=0
1.104121 +                && tableAndColumnIndex(pTabList, i, zName, 0, 0)
1.104122 +              ){
1.104123 +                /* In a NATURAL join, omit the join columns from the 
1.104124 +                ** table to the right of the join */
1.104125 +                continue;
1.104126 +              }
1.104127 +              if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
1.104128 +                /* In a join with a USING clause, omit columns in the
1.104129 +                ** using clause from the table on the right. */
1.104130 +                continue;
1.104131 +              }
1.104132 +            }
1.104133 +            pRight = sqlite3Expr(db, TK_ID, zName);
1.104134 +            zColname = zName;
1.104135 +            zToFree = 0;
1.104136 +            if( longNames || pTabList->nSrc>1 ){
1.104137 +              Expr *pLeft;
1.104138 +              pLeft = sqlite3Expr(db, TK_ID, zTabName);
1.104139 +              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
1.104140 +              if( zSchemaName ){
1.104141 +                pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
1.104142 +                pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
1.104143 +              }
1.104144 +              if( longNames ){
1.104145 +                zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
1.104146 +                zToFree = zColname;
1.104147 +              }
1.104148 +            }else{
1.104149 +              pExpr = pRight;
1.104150 +            }
1.104151 +            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
1.104152 +            sColname.z = zColname;
1.104153 +            sColname.n = sqlite3Strlen30(zColname);
1.104154 +            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
1.104155 +            if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
1.104156 +              struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
1.104157 +              if( pSub ){
1.104158 +                pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
1.104159 +                testcase( pX->zSpan==0 );
1.104160 +              }else{
1.104161 +                pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
1.104162 +                                           zSchemaName, zTabName, zColname);
1.104163 +                testcase( pX->zSpan==0 );
1.104164 +              }
1.104165 +              pX->bSpanIsTab = 1;
1.104166 +            }
1.104167 +            sqlite3DbFree(db, zToFree);
1.104168 +          }
1.104169 +        }
1.104170 +        if( !tableSeen ){
1.104171 +          if( zTName ){
1.104172 +            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
1.104173 +          }else{
1.104174 +            sqlite3ErrorMsg(pParse, "no tables specified");
1.104175 +          }
1.104176 +        }
1.104177 +      }
1.104178 +    }
1.104179 +    sqlite3ExprListDelete(db, pEList);
1.104180 +    p->pEList = pNew;
1.104181 +  }
1.104182 +#if SQLITE_MAX_COLUMN
1.104183 +  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1.104184 +    sqlite3ErrorMsg(pParse, "too many columns in result set");
1.104185 +  }
1.104186 +#endif
1.104187 +  return WRC_Continue;
1.104188 +}
1.104189 +
1.104190 +/*
1.104191 +** No-op routine for the parse-tree walker.
1.104192 +**
1.104193 +** When this routine is the Walker.xExprCallback then expression trees
1.104194 +** are walked without any actions being taken at each node.  Presumably,
1.104195 +** when this routine is used for Walker.xExprCallback then 
1.104196 +** Walker.xSelectCallback is set to do something useful for every 
1.104197 +** subquery in the parser tree.
1.104198 +*/
1.104199 +static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
1.104200 +  UNUSED_PARAMETER2(NotUsed, NotUsed2);
1.104201 +  return WRC_Continue;
1.104202 +}
1.104203 +
1.104204 +/*
1.104205 +** This routine "expands" a SELECT statement and all of its subqueries.
1.104206 +** For additional information on what it means to "expand" a SELECT
1.104207 +** statement, see the comment on the selectExpand worker callback above.
1.104208 +**
1.104209 +** Expanding a SELECT statement is the first step in processing a
1.104210 +** SELECT statement.  The SELECT statement must be expanded before
1.104211 +** name resolution is performed.
1.104212 +**
1.104213 +** If anything goes wrong, an error message is written into pParse.
1.104214 +** The calling function can detect the problem by looking at pParse->nErr
1.104215 +** and/or pParse->db->mallocFailed.
1.104216 +*/
1.104217 +static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
1.104218 +  Walker w;
1.104219 +  memset(&w, 0, sizeof(w));
1.104220 +  w.xExprCallback = exprWalkNoop;
1.104221 +  w.pParse = pParse;
1.104222 +  if( pParse->hasCompound ){
1.104223 +    w.xSelectCallback = convertCompoundSelectToSubquery;
1.104224 +    sqlite3WalkSelect(&w, pSelect);
1.104225 +  }
1.104226 +  w.xSelectCallback = selectExpander;
1.104227 +  w.xSelectCallback2 = selectPopWith;
1.104228 +  sqlite3WalkSelect(&w, pSelect);
1.104229 +}
1.104230 +
1.104231 +
1.104232 +#ifndef SQLITE_OMIT_SUBQUERY
1.104233 +/*
1.104234 +** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
1.104235 +** interface.
1.104236 +**
1.104237 +** For each FROM-clause subquery, add Column.zType and Column.zColl
1.104238 +** information to the Table structure that represents the result set
1.104239 +** of that subquery.
1.104240 +**
1.104241 +** The Table structure that represents the result set was constructed
1.104242 +** by selectExpander() but the type and collation information was omitted
1.104243 +** at that point because identifiers had not yet been resolved.  This
1.104244 +** routine is called after identifier resolution.
1.104245 +*/
1.104246 +static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
1.104247 +  Parse *pParse;
1.104248 +  int i;
1.104249 +  SrcList *pTabList;
1.104250 +  struct SrcList_item *pFrom;
1.104251 +
1.104252 +  assert( p->selFlags & SF_Resolved );
1.104253 +  if( (p->selFlags & SF_HasTypeInfo)==0 ){
1.104254 +    p->selFlags |= SF_HasTypeInfo;
1.104255 +    pParse = pWalker->pParse;
1.104256 +    pTabList = p->pSrc;
1.104257 +    for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1.104258 +      Table *pTab = pFrom->pTab;
1.104259 +      if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
1.104260 +        /* A sub-query in the FROM clause of a SELECT */
1.104261 +        Select *pSel = pFrom->pSelect;
1.104262 +        if( pSel ){
1.104263 +          while( pSel->pPrior ) pSel = pSel->pPrior;
1.104264 +          selectAddColumnTypeAndCollation(pParse, pTab, pSel);
1.104265 +        }
1.104266 +      }
1.104267 +    }
1.104268 +  }
1.104269 +}
1.104270 +#endif
1.104271 +
1.104272 +
1.104273 +/*
1.104274 +** This routine adds datatype and collating sequence information to
1.104275 +** the Table structures of all FROM-clause subqueries in a
1.104276 +** SELECT statement.
1.104277 +**
1.104278 +** Use this routine after name resolution.
1.104279 +*/
1.104280 +static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
1.104281 +#ifndef SQLITE_OMIT_SUBQUERY
1.104282 +  Walker w;
1.104283 +  memset(&w, 0, sizeof(w));
1.104284 +  w.xSelectCallback2 = selectAddSubqueryTypeInfo;
1.104285 +  w.xExprCallback = exprWalkNoop;
1.104286 +  w.pParse = pParse;
1.104287 +  sqlite3WalkSelect(&w, pSelect);
1.104288 +#endif
1.104289 +}
1.104290 +
1.104291 +
1.104292 +/*
1.104293 +** This routine sets up a SELECT statement for processing.  The
1.104294 +** following is accomplished:
1.104295 +**
1.104296 +**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
1.104297 +**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
1.104298 +**     *  ON and USING clauses are shifted into WHERE statements
1.104299 +**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
1.104300 +**     *  Identifiers in expression are matched to tables.
1.104301 +**
1.104302 +** This routine acts recursively on all subqueries within the SELECT.
1.104303 +*/
1.104304 +SQLITE_PRIVATE void sqlite3SelectPrep(
1.104305 +  Parse *pParse,         /* The parser context */
1.104306 +  Select *p,             /* The SELECT statement being coded. */
1.104307 +  NameContext *pOuterNC  /* Name context for container */
1.104308 +){
1.104309 +  sqlite3 *db;
1.104310 +  if( NEVER(p==0) ) return;
1.104311 +  db = pParse->db;
1.104312 +  if( db->mallocFailed ) return;
1.104313 +  if( p->selFlags & SF_HasTypeInfo ) return;
1.104314 +  sqlite3SelectExpand(pParse, p);
1.104315 +  if( pParse->nErr || db->mallocFailed ) return;
1.104316 +  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
1.104317 +  if( pParse->nErr || db->mallocFailed ) return;
1.104318 +  sqlite3SelectAddTypeInfo(pParse, p);
1.104319 +}
1.104320 +
1.104321 +/*
1.104322 +** Reset the aggregate accumulator.
1.104323 +**
1.104324 +** The aggregate accumulator is a set of memory cells that hold
1.104325 +** intermediate results while calculating an aggregate.  This
1.104326 +** routine generates code that stores NULLs in all of those memory
1.104327 +** cells.
1.104328 +*/
1.104329 +static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
1.104330 +  Vdbe *v = pParse->pVdbe;
1.104331 +  int i;
1.104332 +  struct AggInfo_func *pFunc;
1.104333 +  int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
1.104334 +  if( nReg==0 ) return;
1.104335 +#ifdef SQLITE_DEBUG
1.104336 +  /* Verify that all AggInfo registers are within the range specified by
1.104337 +  ** AggInfo.mnReg..AggInfo.mxReg */
1.104338 +  assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
1.104339 +  for(i=0; i<pAggInfo->nColumn; i++){
1.104340 +    assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
1.104341 +         && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
1.104342 +  }
1.104343 +  for(i=0; i<pAggInfo->nFunc; i++){
1.104344 +    assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
1.104345 +         && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
1.104346 +  }
1.104347 +#endif
1.104348 +  sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
1.104349 +  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
1.104350 +    if( pFunc->iDistinct>=0 ){
1.104351 +      Expr *pE = pFunc->pExpr;
1.104352 +      assert( !ExprHasProperty(pE, EP_xIsSelect) );
1.104353 +      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
1.104354 +        sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
1.104355 +           "argument");
1.104356 +        pFunc->iDistinct = -1;
1.104357 +      }else{
1.104358 +        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0);
1.104359 +        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
1.104360 +                          (char*)pKeyInfo, P4_KEYINFO);
1.104361 +      }
1.104362 +    }
1.104363 +  }
1.104364 +}
1.104365 +
1.104366 +/*
1.104367 +** Invoke the OP_AggFinalize opcode for every aggregate function
1.104368 +** in the AggInfo structure.
1.104369 +*/
1.104370 +static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
1.104371 +  Vdbe *v = pParse->pVdbe;
1.104372 +  int i;
1.104373 +  struct AggInfo_func *pF;
1.104374 +  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
1.104375 +    ExprList *pList = pF->pExpr->x.pList;
1.104376 +    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
1.104377 +    sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
1.104378 +                      (void*)pF->pFunc, P4_FUNCDEF);
1.104379 +  }
1.104380 +}
1.104381 +
1.104382 +/*
1.104383 +** Update the accumulator memory cells for an aggregate based on
1.104384 +** the current cursor position.
1.104385 +*/
1.104386 +static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
1.104387 +  Vdbe *v = pParse->pVdbe;
1.104388 +  int i;
1.104389 +  int regHit = 0;
1.104390 +  int addrHitTest = 0;
1.104391 +  struct AggInfo_func *pF;
1.104392 +  struct AggInfo_col *pC;
1.104393 +
1.104394 +  pAggInfo->directMode = 1;
1.104395 +  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
1.104396 +    int nArg;
1.104397 +    int addrNext = 0;
1.104398 +    int regAgg;
1.104399 +    ExprList *pList = pF->pExpr->x.pList;
1.104400 +    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
1.104401 +    if( pList ){
1.104402 +      nArg = pList->nExpr;
1.104403 +      regAgg = sqlite3GetTempRange(pParse, nArg);
1.104404 +      sqlite3ExprCodeExprList(pParse, pList, regAgg, SQLITE_ECEL_DUP);
1.104405 +    }else{
1.104406 +      nArg = 0;
1.104407 +      regAgg = 0;
1.104408 +    }
1.104409 +    if( pF->iDistinct>=0 ){
1.104410 +      addrNext = sqlite3VdbeMakeLabel(v);
1.104411 +      assert( nArg==1 );
1.104412 +      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
1.104413 +    }
1.104414 +    if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
1.104415 +      CollSeq *pColl = 0;
1.104416 +      struct ExprList_item *pItem;
1.104417 +      int j;
1.104418 +      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
1.104419 +      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
1.104420 +        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
1.104421 +      }
1.104422 +      if( !pColl ){
1.104423 +        pColl = pParse->db->pDfltColl;
1.104424 +      }
1.104425 +      if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
1.104426 +      sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
1.104427 +    }
1.104428 +    sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
1.104429 +                      (void*)pF->pFunc, P4_FUNCDEF);
1.104430 +    sqlite3VdbeChangeP5(v, (u8)nArg);
1.104431 +    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
1.104432 +    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
1.104433 +    if( addrNext ){
1.104434 +      sqlite3VdbeResolveLabel(v, addrNext);
1.104435 +      sqlite3ExprCacheClear(pParse);
1.104436 +    }
1.104437 +  }
1.104438 +
1.104439 +  /* Before populating the accumulator registers, clear the column cache.
1.104440 +  ** Otherwise, if any of the required column values are already present 
1.104441 +  ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
1.104442 +  ** to pC->iMem. But by the time the value is used, the original register
1.104443 +  ** may have been used, invalidating the underlying buffer holding the
1.104444 +  ** text or blob value. See ticket [883034dcb5].
1.104445 +  **
1.104446 +  ** Another solution would be to change the OP_SCopy used to copy cached
1.104447 +  ** values to an OP_Copy.
1.104448 +  */
1.104449 +  if( regHit ){
1.104450 +    addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
1.104451 +  }
1.104452 +  sqlite3ExprCacheClear(pParse);
1.104453 +  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
1.104454 +    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
1.104455 +  }
1.104456 +  pAggInfo->directMode = 0;
1.104457 +  sqlite3ExprCacheClear(pParse);
1.104458 +  if( addrHitTest ){
1.104459 +    sqlite3VdbeJumpHere(v, addrHitTest);
1.104460 +  }
1.104461 +}
1.104462 +
1.104463 +/*
1.104464 +** Add a single OP_Explain instruction to the VDBE to explain a simple
1.104465 +** count(*) query ("SELECT count(*) FROM pTab").
1.104466 +*/
1.104467 +#ifndef SQLITE_OMIT_EXPLAIN
1.104468 +static void explainSimpleCount(
1.104469 +  Parse *pParse,                  /* Parse context */
1.104470 +  Table *pTab,                    /* Table being queried */
1.104471 +  Index *pIdx                     /* Index used to optimize scan, or NULL */
1.104472 +){
1.104473 +  if( pParse->explain==2 ){
1.104474 +    char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
1.104475 +        pTab->zName, 
1.104476 +        pIdx ? " USING COVERING INDEX " : "",
1.104477 +        pIdx ? pIdx->zName : ""
1.104478 +    );
1.104479 +    sqlite3VdbeAddOp4(
1.104480 +        pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
1.104481 +    );
1.104482 +  }
1.104483 +}
1.104484 +#else
1.104485 +# define explainSimpleCount(a,b,c)
1.104486 +#endif
1.104487 +
1.104488 +/*
1.104489 +** Generate code for the SELECT statement given in the p argument.  
1.104490 +**
1.104491 +** The results are returned according to the SelectDest structure.
1.104492 +** See comments in sqliteInt.h for further information.
1.104493 +**
1.104494 +** This routine returns the number of errors.  If any errors are
1.104495 +** encountered, then an appropriate error message is left in
1.104496 +** pParse->zErrMsg.
1.104497 +**
1.104498 +** This routine does NOT free the Select structure passed in.  The
1.104499 +** calling function needs to do that.
1.104500 +*/
1.104501 +SQLITE_PRIVATE int sqlite3Select(
1.104502 +  Parse *pParse,         /* The parser context */
1.104503 +  Select *p,             /* The SELECT statement being coded. */
1.104504 +  SelectDest *pDest      /* What to do with the query results */
1.104505 +){
1.104506 +  int i, j;              /* Loop counters */
1.104507 +  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
1.104508 +  Vdbe *v;               /* The virtual machine under construction */
1.104509 +  int isAgg;             /* True for select lists like "count(*)" */
1.104510 +  ExprList *pEList;      /* List of columns to extract. */
1.104511 +  SrcList *pTabList;     /* List of tables to select from */
1.104512 +  Expr *pWhere;          /* The WHERE clause.  May be NULL */
1.104513 +  ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
1.104514 +  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
1.104515 +  Expr *pHaving;         /* The HAVING clause.  May be NULL */
1.104516 +  int rc = 1;            /* Value to return from this function */
1.104517 +  int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
1.104518 +  DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
1.104519 +  AggInfo sAggInfo;      /* Information used by aggregate queries */
1.104520 +  int iEnd;              /* Address of the end of the query */
1.104521 +  sqlite3 *db;           /* The database connection */
1.104522 +
1.104523 +#ifndef SQLITE_OMIT_EXPLAIN
1.104524 +  int iRestoreSelectId = pParse->iSelectId;
1.104525 +  pParse->iSelectId = pParse->iNextSelectId++;
1.104526 +#endif
1.104527 +
1.104528 +  db = pParse->db;
1.104529 +  if( p==0 || db->mallocFailed || pParse->nErr ){
1.104530 +    return 1;
1.104531 +  }
1.104532 +  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
1.104533 +  memset(&sAggInfo, 0, sizeof(sAggInfo));
1.104534 +
1.104535 +  if( IgnorableOrderby(pDest) ){
1.104536 +    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
1.104537 +           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
1.104538 +    /* If ORDER BY makes no difference in the output then neither does
1.104539 +    ** DISTINCT so it can be removed too. */
1.104540 +    sqlite3ExprListDelete(db, p->pOrderBy);
1.104541 +    p->pOrderBy = 0;
1.104542 +    p->selFlags &= ~SF_Distinct;
1.104543 +  }
1.104544 +  sqlite3SelectPrep(pParse, p, 0);
1.104545 +  pOrderBy = p->pOrderBy;
1.104546 +  pTabList = p->pSrc;
1.104547 +  pEList = p->pEList;
1.104548 +  if( pParse->nErr || db->mallocFailed ){
1.104549 +    goto select_end;
1.104550 +  }
1.104551 +  isAgg = (p->selFlags & SF_Aggregate)!=0;
1.104552 +  assert( pEList!=0 );
1.104553 +
1.104554 +  /* Begin generating code.
1.104555 +  */
1.104556 +  v = sqlite3GetVdbe(pParse);
1.104557 +  if( v==0 ) goto select_end;
1.104558 +
1.104559 +  /* If writing to memory or generating a set
1.104560 +  ** only a single column may be output.
1.104561 +  */
1.104562 +#ifndef SQLITE_OMIT_SUBQUERY
1.104563 +  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
1.104564 +    goto select_end;
1.104565 +  }
1.104566 +#endif
1.104567 +
1.104568 +  /* Generate code for all sub-queries in the FROM clause
1.104569 +  */
1.104570 +#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
1.104571 +  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
1.104572 +    struct SrcList_item *pItem = &pTabList->a[i];
1.104573 +    SelectDest dest;
1.104574 +    Select *pSub = pItem->pSelect;
1.104575 +    int isAggSub;
1.104576 +
1.104577 +    if( pSub==0 ) continue;
1.104578 +
1.104579 +    /* Sometimes the code for a subquery will be generated more than
1.104580 +    ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
1.104581 +    ** for example.  In that case, do not regenerate the code to manifest
1.104582 +    ** a view or the co-routine to implement a view.  The first instance
1.104583 +    ** is sufficient, though the subroutine to manifest the view does need
1.104584 +    ** to be invoked again. */
1.104585 +    if( pItem->addrFillSub ){
1.104586 +      if( pItem->viaCoroutine==0 ){
1.104587 +        sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
1.104588 +      }
1.104589 +      continue;
1.104590 +    }
1.104591 +
1.104592 +    /* Increment Parse.nHeight by the height of the largest expression
1.104593 +    ** tree referred to by this, the parent select. The child select
1.104594 +    ** may contain expression trees of at most
1.104595 +    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
1.104596 +    ** more conservative than necessary, but much easier than enforcing
1.104597 +    ** an exact limit.
1.104598 +    */
1.104599 +    pParse->nHeight += sqlite3SelectExprHeight(p);
1.104600 +
1.104601 +    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
1.104602 +    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
1.104603 +      /* This subquery can be absorbed into its parent. */
1.104604 +      if( isAggSub ){
1.104605 +        isAgg = 1;
1.104606 +        p->selFlags |= SF_Aggregate;
1.104607 +      }
1.104608 +      i = -1;
1.104609 +    }else if( pTabList->nSrc==1
1.104610 +           && OptimizationEnabled(db, SQLITE_SubqCoroutine)
1.104611 +    ){
1.104612 +      /* Implement a co-routine that will return a single row of the result
1.104613 +      ** set on each invocation.
1.104614 +      */
1.104615 +      int addrTop = sqlite3VdbeCurrentAddr(v)+1;
1.104616 +      pItem->regReturn = ++pParse->nMem;
1.104617 +      sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
1.104618 +      VdbeComment((v, "%s", pItem->pTab->zName));
1.104619 +      pItem->addrFillSub = addrTop;
1.104620 +      sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
1.104621 +      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
1.104622 +      sqlite3Select(pParse, pSub, &dest);
1.104623 +      pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
1.104624 +      pItem->viaCoroutine = 1;
1.104625 +      pItem->regResult = dest.iSdst;
1.104626 +      sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn);
1.104627 +      sqlite3VdbeJumpHere(v, addrTop-1);
1.104628 +      sqlite3ClearTempRegCache(pParse);
1.104629 +    }else{
1.104630 +      /* Generate a subroutine that will fill an ephemeral table with
1.104631 +      ** the content of this subquery.  pItem->addrFillSub will point
1.104632 +      ** to the address of the generated subroutine.  pItem->regReturn
1.104633 +      ** is a register allocated to hold the subroutine return address
1.104634 +      */
1.104635 +      int topAddr;
1.104636 +      int onceAddr = 0;
1.104637 +      int retAddr;
1.104638 +      assert( pItem->addrFillSub==0 );
1.104639 +      pItem->regReturn = ++pParse->nMem;
1.104640 +      topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
1.104641 +      pItem->addrFillSub = topAddr+1;
1.104642 +      if( pItem->isCorrelated==0 ){
1.104643 +        /* If the subquery is not correlated and if we are not inside of
1.104644 +        ** a trigger, then we only need to compute the value of the subquery
1.104645 +        ** once. */
1.104646 +        onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
1.104647 +        VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
1.104648 +      }else{
1.104649 +        VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
1.104650 +      }
1.104651 +      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
1.104652 +      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
1.104653 +      sqlite3Select(pParse, pSub, &dest);
1.104654 +      pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
1.104655 +      if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
1.104656 +      retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
1.104657 +      VdbeComment((v, "end %s", pItem->pTab->zName));
1.104658 +      sqlite3VdbeChangeP1(v, topAddr, retAddr);
1.104659 +      sqlite3ClearTempRegCache(pParse);
1.104660 +    }
1.104661 +    if( /*pParse->nErr ||*/ db->mallocFailed ){
1.104662 +      goto select_end;
1.104663 +    }
1.104664 +    pParse->nHeight -= sqlite3SelectExprHeight(p);
1.104665 +    pTabList = p->pSrc;
1.104666 +    if( !IgnorableOrderby(pDest) ){
1.104667 +      pOrderBy = p->pOrderBy;
1.104668 +    }
1.104669 +  }
1.104670 +  pEList = p->pEList;
1.104671 +#endif
1.104672 +  pWhere = p->pWhere;
1.104673 +  pGroupBy = p->pGroupBy;
1.104674 +  pHaving = p->pHaving;
1.104675 +  sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
1.104676 +
1.104677 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
1.104678 +  /* If there is are a sequence of queries, do the earlier ones first.
1.104679 +  */
1.104680 +  if( p->pPrior ){
1.104681 +    rc = multiSelect(pParse, p, pDest);
1.104682 +    explainSetInteger(pParse->iSelectId, iRestoreSelectId);
1.104683 +    return rc;
1.104684 +  }
1.104685 +#endif
1.104686 +
1.104687 +  /* If there is both a GROUP BY and an ORDER BY clause and they are
1.104688 +  ** identical, then disable the ORDER BY clause since the GROUP BY
1.104689 +  ** will cause elements to come out in the correct order.  This is
1.104690 +  ** an optimization - the correct answer should result regardless.
1.104691 +  ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
1.104692 +  ** to disable this optimization for testing purposes.
1.104693 +  */
1.104694 +  if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy, -1)==0
1.104695 +         && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
1.104696 +    pOrderBy = 0;
1.104697 +  }
1.104698 +
1.104699 +  /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 
1.104700 +  ** if the select-list is the same as the ORDER BY list, then this query
1.104701 +  ** can be rewritten as a GROUP BY. In other words, this:
1.104702 +  **
1.104703 +  **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
1.104704 +  **
1.104705 +  ** is transformed to:
1.104706 +  **
1.104707 +  **     SELECT xyz FROM ... GROUP BY xyz
1.104708 +  **
1.104709 +  ** The second form is preferred as a single index (or temp-table) may be 
1.104710 +  ** used for both the ORDER BY and DISTINCT processing. As originally 
1.104711 +  ** written the query must use a temp-table for at least one of the ORDER 
1.104712 +  ** BY and DISTINCT, and an index or separate temp-table for the other.
1.104713 +  */
1.104714 +  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 
1.104715 +   && sqlite3ExprListCompare(pOrderBy, p->pEList, -1)==0
1.104716 +  ){
1.104717 +    p->selFlags &= ~SF_Distinct;
1.104718 +    p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
1.104719 +    pGroupBy = p->pGroupBy;
1.104720 +    pOrderBy = 0;
1.104721 +    /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
1.104722 +    ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
1.104723 +    ** original setting of the SF_Distinct flag, not the current setting */
1.104724 +    assert( sDistinct.isTnct );
1.104725 +  }
1.104726 +
1.104727 +  /* If there is an ORDER BY clause, then this sorting
1.104728 +  ** index might end up being unused if the data can be 
1.104729 +  ** extracted in pre-sorted order.  If that is the case, then the
1.104730 +  ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
1.104731 +  ** we figure out that the sorting index is not needed.  The addrSortIndex
1.104732 +  ** variable is used to facilitate that change.
1.104733 +  */
1.104734 +  if( pOrderBy ){
1.104735 +    KeyInfo *pKeyInfo;
1.104736 +    pKeyInfo = keyInfoFromExprList(pParse, pOrderBy, 0);
1.104737 +    pOrderBy->iECursor = pParse->nTab++;
1.104738 +    p->addrOpenEphm[2] = addrSortIndex =
1.104739 +      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
1.104740 +                           pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
1.104741 +                           (char*)pKeyInfo, P4_KEYINFO);
1.104742 +  }else{
1.104743 +    addrSortIndex = -1;
1.104744 +  }
1.104745 +
1.104746 +  /* If the output is destined for a temporary table, open that table.
1.104747 +  */
1.104748 +  if( pDest->eDest==SRT_EphemTab ){
1.104749 +    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
1.104750 +  }
1.104751 +
1.104752 +  /* Set the limiter.
1.104753 +  */
1.104754 +  iEnd = sqlite3VdbeMakeLabel(v);
1.104755 +  p->nSelectRow = LARGEST_INT64;
1.104756 +  computeLimitRegisters(pParse, p, iEnd);
1.104757 +  if( p->iLimit==0 && addrSortIndex>=0 ){
1.104758 +    sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
1.104759 +    p->selFlags |= SF_UseSorter;
1.104760 +  }
1.104761 +
1.104762 +  /* Open a virtual index to use for the distinct set.
1.104763 +  */
1.104764 +  if( p->selFlags & SF_Distinct ){
1.104765 +    sDistinct.tabTnct = pParse->nTab++;
1.104766 +    sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
1.104767 +                                sDistinct.tabTnct, 0, 0,
1.104768 +                                (char*)keyInfoFromExprList(pParse, p->pEList, 0),
1.104769 +                                P4_KEYINFO);
1.104770 +    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
1.104771 +    sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
1.104772 +  }else{
1.104773 +    sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
1.104774 +  }
1.104775 +
1.104776 +  if( !isAgg && pGroupBy==0 ){
1.104777 +    /* No aggregate functions and no GROUP BY clause */
1.104778 +    u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
1.104779 +
1.104780 +    /* Begin the database scan. */
1.104781 +    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, p->pEList,
1.104782 +                               wctrlFlags, 0);
1.104783 +    if( pWInfo==0 ) goto select_end;
1.104784 +    if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
1.104785 +      p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
1.104786 +    }
1.104787 +    if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
1.104788 +      sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
1.104789 +    }
1.104790 +    if( pOrderBy && sqlite3WhereIsOrdered(pWInfo) ) pOrderBy = 0;
1.104791 +
1.104792 +    /* If sorting index that was created by a prior OP_OpenEphemeral 
1.104793 +    ** instruction ended up not being needed, then change the OP_OpenEphemeral
1.104794 +    ** into an OP_Noop.
1.104795 +    */
1.104796 +    if( addrSortIndex>=0 && pOrderBy==0 ){
1.104797 +      sqlite3VdbeChangeToNoop(v, addrSortIndex);
1.104798 +      p->addrOpenEphm[2] = -1;
1.104799 +    }
1.104800 +
1.104801 +    /* Use the standard inner loop. */
1.104802 +    selectInnerLoop(pParse, p, pEList, -1, pOrderBy, &sDistinct, pDest,
1.104803 +                    sqlite3WhereContinueLabel(pWInfo),
1.104804 +                    sqlite3WhereBreakLabel(pWInfo));
1.104805 +
1.104806 +    /* End the database scan loop.
1.104807 +    */
1.104808 +    sqlite3WhereEnd(pWInfo);
1.104809 +  }else{
1.104810 +    /* This case when there exist aggregate functions or a GROUP BY clause
1.104811 +    ** or both */
1.104812 +    NameContext sNC;    /* Name context for processing aggregate information */
1.104813 +    int iAMem;          /* First Mem address for storing current GROUP BY */
1.104814 +    int iBMem;          /* First Mem address for previous GROUP BY */
1.104815 +    int iUseFlag;       /* Mem address holding flag indicating that at least
1.104816 +                        ** one row of the input to the aggregator has been
1.104817 +                        ** processed */
1.104818 +    int iAbortFlag;     /* Mem address which causes query abort if positive */
1.104819 +    int groupBySort;    /* Rows come from source in GROUP BY order */
1.104820 +    int addrEnd;        /* End of processing for this SELECT */
1.104821 +    int sortPTab = 0;   /* Pseudotable used to decode sorting results */
1.104822 +    int sortOut = 0;    /* Output register from the sorter */
1.104823 +
1.104824 +    /* Remove any and all aliases between the result set and the
1.104825 +    ** GROUP BY clause.
1.104826 +    */
1.104827 +    if( pGroupBy ){
1.104828 +      int k;                        /* Loop counter */
1.104829 +      struct ExprList_item *pItem;  /* For looping over expression in a list */
1.104830 +
1.104831 +      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
1.104832 +        pItem->u.x.iAlias = 0;
1.104833 +      }
1.104834 +      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
1.104835 +        pItem->u.x.iAlias = 0;
1.104836 +      }
1.104837 +      if( p->nSelectRow>100 ) p->nSelectRow = 100;
1.104838 +    }else{
1.104839 +      p->nSelectRow = 1;
1.104840 +    }
1.104841 +
1.104842 + 
1.104843 +    /* Create a label to jump to when we want to abort the query */
1.104844 +    addrEnd = sqlite3VdbeMakeLabel(v);
1.104845 +
1.104846 +    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
1.104847 +    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
1.104848 +    ** SELECT statement.
1.104849 +    */
1.104850 +    memset(&sNC, 0, sizeof(sNC));
1.104851 +    sNC.pParse = pParse;
1.104852 +    sNC.pSrcList = pTabList;
1.104853 +    sNC.pAggInfo = &sAggInfo;
1.104854 +    sAggInfo.mnReg = pParse->nMem+1;
1.104855 +    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
1.104856 +    sAggInfo.pGroupBy = pGroupBy;
1.104857 +    sqlite3ExprAnalyzeAggList(&sNC, pEList);
1.104858 +    sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
1.104859 +    if( pHaving ){
1.104860 +      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
1.104861 +    }
1.104862 +    sAggInfo.nAccumulator = sAggInfo.nColumn;
1.104863 +    for(i=0; i<sAggInfo.nFunc; i++){
1.104864 +      assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
1.104865 +      sNC.ncFlags |= NC_InAggFunc;
1.104866 +      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
1.104867 +      sNC.ncFlags &= ~NC_InAggFunc;
1.104868 +    }
1.104869 +    sAggInfo.mxReg = pParse->nMem;
1.104870 +    if( db->mallocFailed ) goto select_end;
1.104871 +
1.104872 +    /* Processing for aggregates with GROUP BY is very different and
1.104873 +    ** much more complex than aggregates without a GROUP BY.
1.104874 +    */
1.104875 +    if( pGroupBy ){
1.104876 +      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
1.104877 +      int j1;             /* A-vs-B comparision jump */
1.104878 +      int addrOutputRow;  /* Start of subroutine that outputs a result row */
1.104879 +      int regOutputRow;   /* Return address register for output subroutine */
1.104880 +      int addrSetAbort;   /* Set the abort flag and return */
1.104881 +      int addrTopOfLoop;  /* Top of the input loop */
1.104882 +      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
1.104883 +      int addrReset;      /* Subroutine for resetting the accumulator */
1.104884 +      int regReset;       /* Return address register for reset subroutine */
1.104885 +
1.104886 +      /* If there is a GROUP BY clause we might need a sorting index to
1.104887 +      ** implement it.  Allocate that sorting index now.  If it turns out
1.104888 +      ** that we do not need it after all, the OP_SorterOpen instruction
1.104889 +      ** will be converted into a Noop.  
1.104890 +      */
1.104891 +      sAggInfo.sortingIdx = pParse->nTab++;
1.104892 +      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0);
1.104893 +      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 
1.104894 +          sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
1.104895 +          0, (char*)pKeyInfo, P4_KEYINFO);
1.104896 +
1.104897 +      /* Initialize memory locations used by GROUP BY aggregate processing
1.104898 +      */
1.104899 +      iUseFlag = ++pParse->nMem;
1.104900 +      iAbortFlag = ++pParse->nMem;
1.104901 +      regOutputRow = ++pParse->nMem;
1.104902 +      addrOutputRow = sqlite3VdbeMakeLabel(v);
1.104903 +      regReset = ++pParse->nMem;
1.104904 +      addrReset = sqlite3VdbeMakeLabel(v);
1.104905 +      iAMem = pParse->nMem + 1;
1.104906 +      pParse->nMem += pGroupBy->nExpr;
1.104907 +      iBMem = pParse->nMem + 1;
1.104908 +      pParse->nMem += pGroupBy->nExpr;
1.104909 +      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
1.104910 +      VdbeComment((v, "clear abort flag"));
1.104911 +      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
1.104912 +      VdbeComment((v, "indicate accumulator empty"));
1.104913 +      sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
1.104914 +
1.104915 +      /* Begin a loop that will extract all source rows in GROUP BY order.
1.104916 +      ** This might involve two separate loops with an OP_Sort in between, or
1.104917 +      ** it might be a single loop that uses an index to extract information
1.104918 +      ** in the right order to begin with.
1.104919 +      */
1.104920 +      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
1.104921 +      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 
1.104922 +                                 WHERE_GROUPBY, 0);
1.104923 +      if( pWInfo==0 ) goto select_end;
1.104924 +      if( sqlite3WhereIsOrdered(pWInfo) ){
1.104925 +        /* The optimizer is able to deliver rows in group by order so
1.104926 +        ** we do not have to sort.  The OP_OpenEphemeral table will be
1.104927 +        ** cancelled later because we still need to use the pKeyInfo
1.104928 +        */
1.104929 +        groupBySort = 0;
1.104930 +      }else{
1.104931 +        /* Rows are coming out in undetermined order.  We have to push
1.104932 +        ** each row into a sorting index, terminate the first loop,
1.104933 +        ** then loop over the sorting index in order to get the output
1.104934 +        ** in sorted order
1.104935 +        */
1.104936 +        int regBase;
1.104937 +        int regRecord;
1.104938 +        int nCol;
1.104939 +        int nGroupBy;
1.104940 +
1.104941 +        explainTempTable(pParse, 
1.104942 +            (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
1.104943 +                    "DISTINCT" : "GROUP BY");
1.104944 +
1.104945 +        groupBySort = 1;
1.104946 +        nGroupBy = pGroupBy->nExpr;
1.104947 +        nCol = nGroupBy + 1;
1.104948 +        j = nGroupBy+1;
1.104949 +        for(i=0; i<sAggInfo.nColumn; i++){
1.104950 +          if( sAggInfo.aCol[i].iSorterColumn>=j ){
1.104951 +            nCol++;
1.104952 +            j++;
1.104953 +          }
1.104954 +        }
1.104955 +        regBase = sqlite3GetTempRange(pParse, nCol);
1.104956 +        sqlite3ExprCacheClear(pParse);
1.104957 +        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
1.104958 +        sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
1.104959 +        j = nGroupBy+1;
1.104960 +        for(i=0; i<sAggInfo.nColumn; i++){
1.104961 +          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
1.104962 +          if( pCol->iSorterColumn>=j ){
1.104963 +            int r1 = j + regBase;
1.104964 +            int r2;
1.104965 +
1.104966 +            r2 = sqlite3ExprCodeGetColumn(pParse, 
1.104967 +                               pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
1.104968 +            if( r1!=r2 ){
1.104969 +              sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
1.104970 +            }
1.104971 +            j++;
1.104972 +          }
1.104973 +        }
1.104974 +        regRecord = sqlite3GetTempReg(pParse);
1.104975 +        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
1.104976 +        sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
1.104977 +        sqlite3ReleaseTempReg(pParse, regRecord);
1.104978 +        sqlite3ReleaseTempRange(pParse, regBase, nCol);
1.104979 +        sqlite3WhereEnd(pWInfo);
1.104980 +        sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
1.104981 +        sortOut = sqlite3GetTempReg(pParse);
1.104982 +        sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
1.104983 +        sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
1.104984 +        VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
1.104985 +        sAggInfo.useSortingIdx = 1;
1.104986 +        sqlite3ExprCacheClear(pParse);
1.104987 +      }
1.104988 +
1.104989 +      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
1.104990 +      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
1.104991 +      ** Then compare the current GROUP BY terms against the GROUP BY terms
1.104992 +      ** from the previous row currently stored in a0, a1, a2...
1.104993 +      */
1.104994 +      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
1.104995 +      sqlite3ExprCacheClear(pParse);
1.104996 +      if( groupBySort ){
1.104997 +        sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
1.104998 +      }
1.104999 +      for(j=0; j<pGroupBy->nExpr; j++){
1.105000 +        if( groupBySort ){
1.105001 +          sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
1.105002 +          if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
1.105003 +        }else{
1.105004 +          sAggInfo.directMode = 1;
1.105005 +          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
1.105006 +        }
1.105007 +      }
1.105008 +      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
1.105009 +                          (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
1.105010 +      j1 = sqlite3VdbeCurrentAddr(v);
1.105011 +      sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); VdbeCoverage(v);
1.105012 +
1.105013 +      /* Generate code that runs whenever the GROUP BY changes.
1.105014 +      ** Changes in the GROUP BY are detected by the previous code
1.105015 +      ** block.  If there were no changes, this block is skipped.
1.105016 +      **
1.105017 +      ** This code copies current group by terms in b0,b1,b2,...
1.105018 +      ** over to a0,a1,a2.  It then calls the output subroutine
1.105019 +      ** and resets the aggregate accumulator registers in preparation
1.105020 +      ** for the next GROUP BY batch.
1.105021 +      */
1.105022 +      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
1.105023 +      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
1.105024 +      VdbeComment((v, "output one row"));
1.105025 +      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
1.105026 +      VdbeComment((v, "check abort flag"));
1.105027 +      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
1.105028 +      VdbeComment((v, "reset accumulator"));
1.105029 +
1.105030 +      /* Update the aggregate accumulators based on the content of
1.105031 +      ** the current row
1.105032 +      */
1.105033 +      sqlite3VdbeJumpHere(v, j1);
1.105034 +      updateAccumulator(pParse, &sAggInfo);
1.105035 +      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
1.105036 +      VdbeComment((v, "indicate data in accumulator"));
1.105037 +
1.105038 +      /* End of the loop
1.105039 +      */
1.105040 +      if( groupBySort ){
1.105041 +        sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
1.105042 +        VdbeCoverage(v);
1.105043 +      }else{
1.105044 +        sqlite3WhereEnd(pWInfo);
1.105045 +        sqlite3VdbeChangeToNoop(v, addrSortingIdx);
1.105046 +      }
1.105047 +
1.105048 +      /* Output the final row of result
1.105049 +      */
1.105050 +      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
1.105051 +      VdbeComment((v, "output final row"));
1.105052 +
1.105053 +      /* Jump over the subroutines
1.105054 +      */
1.105055 +      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
1.105056 +
1.105057 +      /* Generate a subroutine that outputs a single row of the result
1.105058 +      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
1.105059 +      ** is less than or equal to zero, the subroutine is a no-op.  If
1.105060 +      ** the processing calls for the query to abort, this subroutine
1.105061 +      ** increments the iAbortFlag memory location before returning in
1.105062 +      ** order to signal the caller to abort.
1.105063 +      */
1.105064 +      addrSetAbort = sqlite3VdbeCurrentAddr(v);
1.105065 +      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
1.105066 +      VdbeComment((v, "set abort flag"));
1.105067 +      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
1.105068 +      sqlite3VdbeResolveLabel(v, addrOutputRow);
1.105069 +      addrOutputRow = sqlite3VdbeCurrentAddr(v);
1.105070 +      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); VdbeCoverage(v);
1.105071 +      VdbeComment((v, "Groupby result generator entry point"));
1.105072 +      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
1.105073 +      finalizeAggFunctions(pParse, &sAggInfo);
1.105074 +      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
1.105075 +      selectInnerLoop(pParse, p, p->pEList, -1, pOrderBy,
1.105076 +                      &sDistinct, pDest,
1.105077 +                      addrOutputRow+1, addrSetAbort);
1.105078 +      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
1.105079 +      VdbeComment((v, "end groupby result generator"));
1.105080 +
1.105081 +      /* Generate a subroutine that will reset the group-by accumulator
1.105082 +      */
1.105083 +      sqlite3VdbeResolveLabel(v, addrReset);
1.105084 +      resetAccumulator(pParse, &sAggInfo);
1.105085 +      sqlite3VdbeAddOp1(v, OP_Return, regReset);
1.105086 +     
1.105087 +    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
1.105088 +    else {
1.105089 +      ExprList *pDel = 0;
1.105090 +#ifndef SQLITE_OMIT_BTREECOUNT
1.105091 +      Table *pTab;
1.105092 +      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
1.105093 +        /* If isSimpleCount() returns a pointer to a Table structure, then
1.105094 +        ** the SQL statement is of the form:
1.105095 +        **
1.105096 +        **   SELECT count(*) FROM <tbl>
1.105097 +        **
1.105098 +        ** where the Table structure returned represents table <tbl>.
1.105099 +        **
1.105100 +        ** This statement is so common that it is optimized specially. The
1.105101 +        ** OP_Count instruction is executed either on the intkey table that
1.105102 +        ** contains the data for table <tbl> or on one of its indexes. It
1.105103 +        ** is better to execute the op on an index, as indexes are almost
1.105104 +        ** always spread across less pages than their corresponding tables.
1.105105 +        */
1.105106 +        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1.105107 +        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
1.105108 +        Index *pIdx;                         /* Iterator variable */
1.105109 +        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
1.105110 +        Index *pBest = 0;                    /* Best index found so far */
1.105111 +        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
1.105112 +
1.105113 +        sqlite3CodeVerifySchema(pParse, iDb);
1.105114 +        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
1.105115 +
1.105116 +        /* Search for the index that has the lowest scan cost.
1.105117 +        **
1.105118 +        ** (2011-04-15) Do not do a full scan of an unordered index.
1.105119 +        **
1.105120 +        ** (2013-10-03) Do not count the entries in a partial index.
1.105121 +        **
1.105122 +        ** In practice the KeyInfo structure will not be used. It is only 
1.105123 +        ** passed to keep OP_OpenRead happy.
1.105124 +        */
1.105125 +        if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
1.105126 +        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1.105127 +          if( pIdx->bUnordered==0
1.105128 +           && pIdx->szIdxRow<pTab->szTabRow
1.105129 +           && pIdx->pPartIdxWhere==0
1.105130 +           && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
1.105131 +          ){
1.105132 +            pBest = pIdx;
1.105133 +          }
1.105134 +        }
1.105135 +        if( pBest ){
1.105136 +          iRoot = pBest->tnum;
1.105137 +          pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
1.105138 +        }
1.105139 +
1.105140 +        /* Open a read-only cursor, execute the OP_Count, close the cursor. */
1.105141 +        sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
1.105142 +        if( pKeyInfo ){
1.105143 +          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
1.105144 +        }
1.105145 +        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
1.105146 +        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
1.105147 +        explainSimpleCount(pParse, pTab, pBest);
1.105148 +      }else
1.105149 +#endif /* SQLITE_OMIT_BTREECOUNT */
1.105150 +      {
1.105151 +        /* Check if the query is of one of the following forms:
1.105152 +        **
1.105153 +        **   SELECT min(x) FROM ...
1.105154 +        **   SELECT max(x) FROM ...
1.105155 +        **
1.105156 +        ** If it is, then ask the code in where.c to attempt to sort results
1.105157 +        ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
1.105158 +        ** If where.c is able to produce results sorted in this order, then
1.105159 +        ** add vdbe code to break out of the processing loop after the 
1.105160 +        ** first iteration (since the first iteration of the loop is 
1.105161 +        ** guaranteed to operate on the row with the minimum or maximum 
1.105162 +        ** value of x, the only row required).
1.105163 +        **
1.105164 +        ** A special flag must be passed to sqlite3WhereBegin() to slightly
1.105165 +        ** modify behavior as follows:
1.105166 +        **
1.105167 +        **   + If the query is a "SELECT min(x)", then the loop coded by
1.105168 +        **     where.c should not iterate over any values with a NULL value
1.105169 +        **     for x.
1.105170 +        **
1.105171 +        **   + The optimizer code in where.c (the thing that decides which
1.105172 +        **     index or indices to use) should place a different priority on 
1.105173 +        **     satisfying the 'ORDER BY' clause than it does in other cases.
1.105174 +        **     Refer to code and comments in where.c for details.
1.105175 +        */
1.105176 +        ExprList *pMinMax = 0;
1.105177 +        u8 flag = WHERE_ORDERBY_NORMAL;
1.105178 +        
1.105179 +        assert( p->pGroupBy==0 );
1.105180 +        assert( flag==0 );
1.105181 +        if( p->pHaving==0 ){
1.105182 +          flag = minMaxQuery(&sAggInfo, &pMinMax);
1.105183 +        }
1.105184 +        assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
1.105185 +
1.105186 +        if( flag ){
1.105187 +          pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
1.105188 +          pDel = pMinMax;
1.105189 +          if( pMinMax && !db->mallocFailed ){
1.105190 +            pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
1.105191 +            pMinMax->a[0].pExpr->op = TK_COLUMN;
1.105192 +          }
1.105193 +        }
1.105194 +  
1.105195 +        /* This case runs if the aggregate has no GROUP BY clause.  The
1.105196 +        ** processing is much simpler since there is only a single row
1.105197 +        ** of output.
1.105198 +        */
1.105199 +        resetAccumulator(pParse, &sAggInfo);
1.105200 +        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
1.105201 +        if( pWInfo==0 ){
1.105202 +          sqlite3ExprListDelete(db, pDel);
1.105203 +          goto select_end;
1.105204 +        }
1.105205 +        updateAccumulator(pParse, &sAggInfo);
1.105206 +        assert( pMinMax==0 || pMinMax->nExpr==1 );
1.105207 +        if( sqlite3WhereIsOrdered(pWInfo) ){
1.105208 +          sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
1.105209 +          VdbeComment((v, "%s() by index",
1.105210 +                (flag==WHERE_ORDERBY_MIN?"min":"max")));
1.105211 +        }
1.105212 +        sqlite3WhereEnd(pWInfo);
1.105213 +        finalizeAggFunctions(pParse, &sAggInfo);
1.105214 +      }
1.105215 +
1.105216 +      pOrderBy = 0;
1.105217 +      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
1.105218 +      selectInnerLoop(pParse, p, p->pEList, -1, 0, 0, 
1.105219 +                      pDest, addrEnd, addrEnd);
1.105220 +      sqlite3ExprListDelete(db, pDel);
1.105221 +    }
1.105222 +    sqlite3VdbeResolveLabel(v, addrEnd);
1.105223 +    
1.105224 +  } /* endif aggregate query */
1.105225 +
1.105226 +  if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
1.105227 +    explainTempTable(pParse, "DISTINCT");
1.105228 +  }
1.105229 +
1.105230 +  /* If there is an ORDER BY clause, then we need to sort the results
1.105231 +  ** and send them to the callback one by one.
1.105232 +  */
1.105233 +  if( pOrderBy ){
1.105234 +    explainTempTable(pParse, "ORDER BY");
1.105235 +    generateSortTail(pParse, p, v, pEList->nExpr, pDest);
1.105236 +  }
1.105237 +
1.105238 +  /* Jump here to skip this query
1.105239 +  */
1.105240 +  sqlite3VdbeResolveLabel(v, iEnd);
1.105241 +
1.105242 +  /* The SELECT was successfully coded.   Set the return code to 0
1.105243 +  ** to indicate no errors.
1.105244 +  */
1.105245 +  rc = 0;
1.105246 +
1.105247 +  /* Control jumps to here if an error is encountered above, or upon
1.105248 +  ** successful coding of the SELECT.
1.105249 +  */
1.105250 +select_end:
1.105251 +  explainSetInteger(pParse->iSelectId, iRestoreSelectId);
1.105252 +
1.105253 +  /* Identify column names if results of the SELECT are to be output.
1.105254 +  */
1.105255 +  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
1.105256 +    generateColumnNames(pParse, pTabList, pEList);
1.105257 +  }
1.105258 +
1.105259 +  sqlite3DbFree(db, sAggInfo.aCol);
1.105260 +  sqlite3DbFree(db, sAggInfo.aFunc);
1.105261 +  return rc;
1.105262 +}
1.105263 +
1.105264 +#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
1.105265 +/*
1.105266 +** Generate a human-readable description of a the Select object.
1.105267 +*/
1.105268 +static void explainOneSelect(Vdbe *pVdbe, Select *p){
1.105269 +  sqlite3ExplainPrintf(pVdbe, "SELECT ");
1.105270 +  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
1.105271 +    if( p->selFlags & SF_Distinct ){
1.105272 +      sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
1.105273 +    }
1.105274 +    if( p->selFlags & SF_Aggregate ){
1.105275 +      sqlite3ExplainPrintf(pVdbe, "agg_flag ");
1.105276 +    }
1.105277 +    sqlite3ExplainNL(pVdbe);
1.105278 +    sqlite3ExplainPrintf(pVdbe, "   ");
1.105279 +  }
1.105280 +  sqlite3ExplainExprList(pVdbe, p->pEList);
1.105281 +  sqlite3ExplainNL(pVdbe);
1.105282 +  if( p->pSrc && p->pSrc->nSrc ){
1.105283 +    int i;
1.105284 +    sqlite3ExplainPrintf(pVdbe, "FROM ");
1.105285 +    sqlite3ExplainPush(pVdbe);
1.105286 +    for(i=0; i<p->pSrc->nSrc; i++){
1.105287 +      struct SrcList_item *pItem = &p->pSrc->a[i];
1.105288 +      sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
1.105289 +      if( pItem->pSelect ){
1.105290 +        sqlite3ExplainSelect(pVdbe, pItem->pSelect);
1.105291 +        if( pItem->pTab ){
1.105292 +          sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
1.105293 +        }
1.105294 +      }else if( pItem->zName ){
1.105295 +        sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
1.105296 +      }
1.105297 +      if( pItem->zAlias ){
1.105298 +        sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
1.105299 +      }
1.105300 +      if( pItem->jointype & JT_LEFT ){
1.105301 +        sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
1.105302 +      }
1.105303 +      sqlite3ExplainNL(pVdbe);
1.105304 +    }
1.105305 +    sqlite3ExplainPop(pVdbe);
1.105306 +  }
1.105307 +  if( p->pWhere ){
1.105308 +    sqlite3ExplainPrintf(pVdbe, "WHERE ");
1.105309 +    sqlite3ExplainExpr(pVdbe, p->pWhere);
1.105310 +    sqlite3ExplainNL(pVdbe);
1.105311 +  }
1.105312 +  if( p->pGroupBy ){
1.105313 +    sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
1.105314 +    sqlite3ExplainExprList(pVdbe, p->pGroupBy);
1.105315 +    sqlite3ExplainNL(pVdbe);
1.105316 +  }
1.105317 +  if( p->pHaving ){
1.105318 +    sqlite3ExplainPrintf(pVdbe, "HAVING ");
1.105319 +    sqlite3ExplainExpr(pVdbe, p->pHaving);
1.105320 +    sqlite3ExplainNL(pVdbe);
1.105321 +  }
1.105322 +  if( p->pOrderBy ){
1.105323 +    sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
1.105324 +    sqlite3ExplainExprList(pVdbe, p->pOrderBy);
1.105325 +    sqlite3ExplainNL(pVdbe);
1.105326 +  }
1.105327 +  if( p->pLimit ){
1.105328 +    sqlite3ExplainPrintf(pVdbe, "LIMIT ");
1.105329 +    sqlite3ExplainExpr(pVdbe, p->pLimit);
1.105330 +    sqlite3ExplainNL(pVdbe);
1.105331 +  }
1.105332 +  if( p->pOffset ){
1.105333 +    sqlite3ExplainPrintf(pVdbe, "OFFSET ");
1.105334 +    sqlite3ExplainExpr(pVdbe, p->pOffset);
1.105335 +    sqlite3ExplainNL(pVdbe);
1.105336 +  }
1.105337 +}
1.105338 +SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
1.105339 +  if( p==0 ){
1.105340 +    sqlite3ExplainPrintf(pVdbe, "(null-select)");
1.105341 +    return;
1.105342 +  }
1.105343 +  sqlite3ExplainPush(pVdbe);
1.105344 +  while( p ){
1.105345 +    explainOneSelect(pVdbe, p);
1.105346 +    p = p->pNext;
1.105347 +    if( p==0 ) break;
1.105348 +    sqlite3ExplainNL(pVdbe);
1.105349 +    sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
1.105350 +  }
1.105351 +  sqlite3ExplainPrintf(pVdbe, "END");
1.105352 +  sqlite3ExplainPop(pVdbe);
1.105353 +}
1.105354 +
1.105355 +/* End of the structure debug printing code
1.105356 +*****************************************************************************/
1.105357 +#endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
1.105358 +
1.105359 +/************** End of select.c **********************************************/
1.105360 +/************** Begin file table.c *******************************************/
1.105361 +/*
1.105362 +** 2001 September 15
1.105363 +**
1.105364 +** The author disclaims copyright to this source code.  In place of
1.105365 +** a legal notice, here is a blessing:
1.105366 +**
1.105367 +**    May you do good and not evil.
1.105368 +**    May you find forgiveness for yourself and forgive others.
1.105369 +**    May you share freely, never taking more than you give.
1.105370 +**
1.105371 +*************************************************************************
1.105372 +** This file contains the sqlite3_get_table() and sqlite3_free_table()
1.105373 +** interface routines.  These are just wrappers around the main
1.105374 +** interface routine of sqlite3_exec().
1.105375 +**
1.105376 +** These routines are in a separate files so that they will not be linked
1.105377 +** if they are not used.
1.105378 +*/
1.105379 +/* #include <stdlib.h> */
1.105380 +/* #include <string.h> */
1.105381 +
1.105382 +#ifndef SQLITE_OMIT_GET_TABLE
1.105383 +
1.105384 +/*
1.105385 +** This structure is used to pass data from sqlite3_get_table() through
1.105386 +** to the callback function is uses to build the result.
1.105387 +*/
1.105388 +typedef struct TabResult {
1.105389 +  char **azResult;   /* Accumulated output */
1.105390 +  char *zErrMsg;     /* Error message text, if an error occurs */
1.105391 +  int nAlloc;        /* Slots allocated for azResult[] */
1.105392 +  int nRow;          /* Number of rows in the result */
1.105393 +  int nColumn;       /* Number of columns in the result */
1.105394 +  int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
1.105395 +  int rc;            /* Return code from sqlite3_exec() */
1.105396 +} TabResult;
1.105397 +
1.105398 +/*
1.105399 +** This routine is called once for each row in the result table.  Its job
1.105400 +** is to fill in the TabResult structure appropriately, allocating new
1.105401 +** memory as necessary.
1.105402 +*/
1.105403 +static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
1.105404 +  TabResult *p = (TabResult*)pArg;  /* Result accumulator */
1.105405 +  int need;                         /* Slots needed in p->azResult[] */
1.105406 +  int i;                            /* Loop counter */
1.105407 +  char *z;                          /* A single column of result */
1.105408 +
1.105409 +  /* Make sure there is enough space in p->azResult to hold everything
1.105410 +  ** we need to remember from this invocation of the callback.
1.105411 +  */
1.105412 +  if( p->nRow==0 && argv!=0 ){
1.105413 +    need = nCol*2;
1.105414 +  }else{
1.105415 +    need = nCol;
1.105416 +  }
1.105417 +  if( p->nData + need > p->nAlloc ){
1.105418 +    char **azNew;
1.105419 +    p->nAlloc = p->nAlloc*2 + need;
1.105420 +    azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
1.105421 +    if( azNew==0 ) goto malloc_failed;
1.105422 +    p->azResult = azNew;
1.105423 +  }
1.105424 +
1.105425 +  /* If this is the first row, then generate an extra row containing
1.105426 +  ** the names of all columns.
1.105427 +  */
1.105428 +  if( p->nRow==0 ){
1.105429 +    p->nColumn = nCol;
1.105430 +    for(i=0; i<nCol; i++){
1.105431 +      z = sqlite3_mprintf("%s", colv[i]);
1.105432 +      if( z==0 ) goto malloc_failed;
1.105433 +      p->azResult[p->nData++] = z;
1.105434 +    }
1.105435 +  }else if( p->nColumn!=nCol ){
1.105436 +    sqlite3_free(p->zErrMsg);
1.105437 +    p->zErrMsg = sqlite3_mprintf(
1.105438 +       "sqlite3_get_table() called with two or more incompatible queries"
1.105439 +    );
1.105440 +    p->rc = SQLITE_ERROR;
1.105441 +    return 1;
1.105442 +  }
1.105443 +
1.105444 +  /* Copy over the row data
1.105445 +  */
1.105446 +  if( argv!=0 ){
1.105447 +    for(i=0; i<nCol; i++){
1.105448 +      if( argv[i]==0 ){
1.105449 +        z = 0;
1.105450 +      }else{
1.105451 +        int n = sqlite3Strlen30(argv[i])+1;
1.105452 +        z = sqlite3_malloc( n );
1.105453 +        if( z==0 ) goto malloc_failed;
1.105454 +        memcpy(z, argv[i], n);
1.105455 +      }
1.105456 +      p->azResult[p->nData++] = z;
1.105457 +    }
1.105458 +    p->nRow++;
1.105459 +  }
1.105460 +  return 0;
1.105461 +
1.105462 +malloc_failed:
1.105463 +  p->rc = SQLITE_NOMEM;
1.105464 +  return 1;
1.105465 +}
1.105466 +
1.105467 +/*
1.105468 +** Query the database.  But instead of invoking a callback for each row,
1.105469 +** malloc() for space to hold the result and return the entire results
1.105470 +** at the conclusion of the call.
1.105471 +**
1.105472 +** The result that is written to ***pazResult is held in memory obtained
1.105473 +** from malloc().  But the caller cannot free this memory directly.  
1.105474 +** Instead, the entire table should be passed to sqlite3_free_table() when
1.105475 +** the calling procedure is finished using it.
1.105476 +*/
1.105477 +SQLITE_API int sqlite3_get_table(
1.105478 +  sqlite3 *db,                /* The database on which the SQL executes */
1.105479 +  const char *zSql,           /* The SQL to be executed */
1.105480 +  char ***pazResult,          /* Write the result table here */
1.105481 +  int *pnRow,                 /* Write the number of rows in the result here */
1.105482 +  int *pnColumn,              /* Write the number of columns of result here */
1.105483 +  char **pzErrMsg             /* Write error messages here */
1.105484 +){
1.105485 +  int rc;
1.105486 +  TabResult res;
1.105487 +
1.105488 +  *pazResult = 0;
1.105489 +  if( pnColumn ) *pnColumn = 0;
1.105490 +  if( pnRow ) *pnRow = 0;
1.105491 +  if( pzErrMsg ) *pzErrMsg = 0;
1.105492 +  res.zErrMsg = 0;
1.105493 +  res.nRow = 0;
1.105494 +  res.nColumn = 0;
1.105495 +  res.nData = 1;
1.105496 +  res.nAlloc = 20;
1.105497 +  res.rc = SQLITE_OK;
1.105498 +  res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
1.105499 +  if( res.azResult==0 ){
1.105500 +     db->errCode = SQLITE_NOMEM;
1.105501 +     return SQLITE_NOMEM;
1.105502 +  }
1.105503 +  res.azResult[0] = 0;
1.105504 +  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
1.105505 +  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
1.105506 +  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
1.105507 +  if( (rc&0xff)==SQLITE_ABORT ){
1.105508 +    sqlite3_free_table(&res.azResult[1]);
1.105509 +    if( res.zErrMsg ){
1.105510 +      if( pzErrMsg ){
1.105511 +        sqlite3_free(*pzErrMsg);
1.105512 +        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
1.105513 +      }
1.105514 +      sqlite3_free(res.zErrMsg);
1.105515 +    }
1.105516 +    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
1.105517 +    return res.rc;
1.105518 +  }
1.105519 +  sqlite3_free(res.zErrMsg);
1.105520 +  if( rc!=SQLITE_OK ){
1.105521 +    sqlite3_free_table(&res.azResult[1]);
1.105522 +    return rc;
1.105523 +  }
1.105524 +  if( res.nAlloc>res.nData ){
1.105525 +    char **azNew;
1.105526 +    azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
1.105527 +    if( azNew==0 ){
1.105528 +      sqlite3_free_table(&res.azResult[1]);
1.105529 +      db->errCode = SQLITE_NOMEM;
1.105530 +      return SQLITE_NOMEM;
1.105531 +    }
1.105532 +    res.azResult = azNew;
1.105533 +  }
1.105534 +  *pazResult = &res.azResult[1];
1.105535 +  if( pnColumn ) *pnColumn = res.nColumn;
1.105536 +  if( pnRow ) *pnRow = res.nRow;
1.105537 +  return rc;
1.105538 +}
1.105539 +
1.105540 +/*
1.105541 +** This routine frees the space the sqlite3_get_table() malloced.
1.105542 +*/
1.105543 +SQLITE_API void sqlite3_free_table(
1.105544 +  char **azResult            /* Result returned from from sqlite3_get_table() */
1.105545 +){
1.105546 +  if( azResult ){
1.105547 +    int i, n;
1.105548 +    azResult--;
1.105549 +    assert( azResult!=0 );
1.105550 +    n = SQLITE_PTR_TO_INT(azResult[0]);
1.105551 +    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
1.105552 +    sqlite3_free(azResult);
1.105553 +  }
1.105554 +}
1.105555 +
1.105556 +#endif /* SQLITE_OMIT_GET_TABLE */
1.105557 +
1.105558 +/************** End of table.c ***********************************************/
1.105559 +/************** Begin file trigger.c *****************************************/
1.105560 +/*
1.105561 +**
1.105562 +** The author disclaims copyright to this source code.  In place of
1.105563 +** a legal notice, here is a blessing:
1.105564 +**
1.105565 +**    May you do good and not evil.
1.105566 +**    May you find forgiveness for yourself and forgive others.
1.105567 +**    May you share freely, never taking more than you give.
1.105568 +**
1.105569 +*************************************************************************
1.105570 +** This file contains the implementation for TRIGGERs
1.105571 +*/
1.105572 +
1.105573 +#ifndef SQLITE_OMIT_TRIGGER
1.105574 +/*
1.105575 +** Delete a linked list of TriggerStep structures.
1.105576 +*/
1.105577 +SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
1.105578 +  while( pTriggerStep ){
1.105579 +    TriggerStep * pTmp = pTriggerStep;
1.105580 +    pTriggerStep = pTriggerStep->pNext;
1.105581 +
1.105582 +    sqlite3ExprDelete(db, pTmp->pWhere);
1.105583 +    sqlite3ExprListDelete(db, pTmp->pExprList);
1.105584 +    sqlite3SelectDelete(db, pTmp->pSelect);
1.105585 +    sqlite3IdListDelete(db, pTmp->pIdList);
1.105586 +
1.105587 +    sqlite3DbFree(db, pTmp);
1.105588 +  }
1.105589 +}
1.105590 +
1.105591 +/*
1.105592 +** Given table pTab, return a list of all the triggers attached to 
1.105593 +** the table. The list is connected by Trigger.pNext pointers.
1.105594 +**
1.105595 +** All of the triggers on pTab that are in the same database as pTab
1.105596 +** are already attached to pTab->pTrigger.  But there might be additional
1.105597 +** triggers on pTab in the TEMP schema.  This routine prepends all
1.105598 +** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
1.105599 +** and returns the combined list.
1.105600 +**
1.105601 +** To state it another way:  This routine returns a list of all triggers
1.105602 +** that fire off of pTab.  The list will include any TEMP triggers on
1.105603 +** pTab as well as the triggers lised in pTab->pTrigger.
1.105604 +*/
1.105605 +SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
1.105606 +  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
1.105607 +  Trigger *pList = 0;                  /* List of triggers to return */
1.105608 +
1.105609 +  if( pParse->disableTriggers ){
1.105610 +    return 0;
1.105611 +  }
1.105612 +
1.105613 +  if( pTmpSchema!=pTab->pSchema ){
1.105614 +    HashElem *p;
1.105615 +    assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
1.105616 +    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
1.105617 +      Trigger *pTrig = (Trigger *)sqliteHashData(p);
1.105618 +      if( pTrig->pTabSchema==pTab->pSchema
1.105619 +       && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
1.105620 +      ){
1.105621 +        pTrig->pNext = (pList ? pList : pTab->pTrigger);
1.105622 +        pList = pTrig;
1.105623 +      }
1.105624 +    }
1.105625 +  }
1.105626 +
1.105627 +  return (pList ? pList : pTab->pTrigger);
1.105628 +}
1.105629 +
1.105630 +/*
1.105631 +** This is called by the parser when it sees a CREATE TRIGGER statement
1.105632 +** up to the point of the BEGIN before the trigger actions.  A Trigger
1.105633 +** structure is generated based on the information available and stored
1.105634 +** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
1.105635 +** sqlite3FinishTrigger() function is called to complete the trigger
1.105636 +** construction process.
1.105637 +*/
1.105638 +SQLITE_PRIVATE void sqlite3BeginTrigger(
1.105639 +  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
1.105640 +  Token *pName1,      /* The name of the trigger */
1.105641 +  Token *pName2,      /* The name of the trigger */
1.105642 +  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
1.105643 +  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
1.105644 +  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
1.105645 +  SrcList *pTableName,/* The name of the table/view the trigger applies to */
1.105646 +  Expr *pWhen,        /* WHEN clause */
1.105647 +  int isTemp,         /* True if the TEMPORARY keyword is present */
1.105648 +  int noErr           /* Suppress errors if the trigger already exists */
1.105649 +){
1.105650 +  Trigger *pTrigger = 0;  /* The new trigger */
1.105651 +  Table *pTab;            /* Table that the trigger fires off of */
1.105652 +  char *zName = 0;        /* Name of the trigger */
1.105653 +  sqlite3 *db = pParse->db;  /* The database connection */
1.105654 +  int iDb;                /* The database to store the trigger in */
1.105655 +  Token *pName;           /* The unqualified db name */
1.105656 +  DbFixer sFix;           /* State vector for the DB fixer */
1.105657 +  int iTabDb;             /* Index of the database holding pTab */
1.105658 +
1.105659 +  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
1.105660 +  assert( pName2!=0 );
1.105661 +  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
1.105662 +  assert( op>0 && op<0xff );
1.105663 +  if( isTemp ){
1.105664 +    /* If TEMP was specified, then the trigger name may not be qualified. */
1.105665 +    if( pName2->n>0 ){
1.105666 +      sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
1.105667 +      goto trigger_cleanup;
1.105668 +    }
1.105669 +    iDb = 1;
1.105670 +    pName = pName1;
1.105671 +  }else{
1.105672 +    /* Figure out the db that the trigger will be created in */
1.105673 +    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
1.105674 +    if( iDb<0 ){
1.105675 +      goto trigger_cleanup;
1.105676 +    }
1.105677 +  }
1.105678 +  if( !pTableName || db->mallocFailed ){
1.105679 +    goto trigger_cleanup;
1.105680 +  }
1.105681 +
1.105682 +  /* A long-standing parser bug is that this syntax was allowed:
1.105683 +  **
1.105684 +  **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
1.105685 +  **                                                 ^^^^^^^^
1.105686 +  **
1.105687 +  ** To maintain backwards compatibility, ignore the database
1.105688 +  ** name on pTableName if we are reparsing our of SQLITE_MASTER.
1.105689 +  */
1.105690 +  if( db->init.busy && iDb!=1 ){
1.105691 +    sqlite3DbFree(db, pTableName->a[0].zDatabase);
1.105692 +    pTableName->a[0].zDatabase = 0;
1.105693 +  }
1.105694 +
1.105695 +  /* If the trigger name was unqualified, and the table is a temp table,
1.105696 +  ** then set iDb to 1 to create the trigger in the temporary database.
1.105697 +  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
1.105698 +  ** exist, the error is caught by the block below.
1.105699 +  */
1.105700 +  pTab = sqlite3SrcListLookup(pParse, pTableName);
1.105701 +  if( db->init.busy==0 && pName2->n==0 && pTab
1.105702 +        && pTab->pSchema==db->aDb[1].pSchema ){
1.105703 +    iDb = 1;
1.105704 +  }
1.105705 +
1.105706 +  /* Ensure the table name matches database name and that the table exists */
1.105707 +  if( db->mallocFailed ) goto trigger_cleanup;
1.105708 +  assert( pTableName->nSrc==1 );
1.105709 +  sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
1.105710 +  if( sqlite3FixSrcList(&sFix, pTableName) ){
1.105711 +    goto trigger_cleanup;
1.105712 +  }
1.105713 +  pTab = sqlite3SrcListLookup(pParse, pTableName);
1.105714 +  if( !pTab ){
1.105715 +    /* The table does not exist. */
1.105716 +    if( db->init.iDb==1 ){
1.105717 +      /* Ticket #3810.
1.105718 +      ** Normally, whenever a table is dropped, all associated triggers are
1.105719 +      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
1.105720 +      ** and the table is dropped by a different database connection, the
1.105721 +      ** trigger is not visible to the database connection that does the
1.105722 +      ** drop so the trigger cannot be dropped.  This results in an
1.105723 +      ** "orphaned trigger" - a trigger whose associated table is missing.
1.105724 +      */
1.105725 +      db->init.orphanTrigger = 1;
1.105726 +    }
1.105727 +    goto trigger_cleanup;
1.105728 +  }
1.105729 +  if( IsVirtual(pTab) ){
1.105730 +    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
1.105731 +    goto trigger_cleanup;
1.105732 +  }
1.105733 +
1.105734 +  /* Check that the trigger name is not reserved and that no trigger of the
1.105735 +  ** specified name exists */
1.105736 +  zName = sqlite3NameFromToken(db, pName);
1.105737 +  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
1.105738 +    goto trigger_cleanup;
1.105739 +  }
1.105740 +  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1.105741 +  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
1.105742 +                      zName, sqlite3Strlen30(zName)) ){
1.105743 +    if( !noErr ){
1.105744 +      sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
1.105745 +    }else{
1.105746 +      assert( !db->init.busy );
1.105747 +      sqlite3CodeVerifySchema(pParse, iDb);
1.105748 +    }
1.105749 +    goto trigger_cleanup;
1.105750 +  }
1.105751 +
1.105752 +  /* Do not create a trigger on a system table */
1.105753 +  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
1.105754 +    sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
1.105755 +    pParse->nErr++;
1.105756 +    goto trigger_cleanup;
1.105757 +  }
1.105758 +
1.105759 +  /* INSTEAD of triggers are only for views and views only support INSTEAD
1.105760 +  ** of triggers.
1.105761 +  */
1.105762 +  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
1.105763 +    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
1.105764 +        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
1.105765 +    goto trigger_cleanup;
1.105766 +  }
1.105767 +  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
1.105768 +    sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
1.105769 +        " trigger on table: %S", pTableName, 0);
1.105770 +    goto trigger_cleanup;
1.105771 +  }
1.105772 +  iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1.105773 +
1.105774 +#ifndef SQLITE_OMIT_AUTHORIZATION
1.105775 +  {
1.105776 +    int code = SQLITE_CREATE_TRIGGER;
1.105777 +    const char *zDb = db->aDb[iTabDb].zName;
1.105778 +    const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
1.105779 +    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
1.105780 +    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
1.105781 +      goto trigger_cleanup;
1.105782 +    }
1.105783 +    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
1.105784 +      goto trigger_cleanup;
1.105785 +    }
1.105786 +  }
1.105787 +#endif
1.105788 +
1.105789 +  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
1.105790 +  ** cannot appear on views.  So we might as well translate every
1.105791 +  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
1.105792 +  ** elsewhere.
1.105793 +  */
1.105794 +  if (tr_tm == TK_INSTEAD){
1.105795 +    tr_tm = TK_BEFORE;
1.105796 +  }
1.105797 +
1.105798 +  /* Build the Trigger object */
1.105799 +  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
1.105800 +  if( pTrigger==0 ) goto trigger_cleanup;
1.105801 +  pTrigger->zName = zName;
1.105802 +  zName = 0;
1.105803 +  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
1.105804 +  pTrigger->pSchema = db->aDb[iDb].pSchema;
1.105805 +  pTrigger->pTabSchema = pTab->pSchema;
1.105806 +  pTrigger->op = (u8)op;
1.105807 +  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
1.105808 +  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
1.105809 +  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
1.105810 +  assert( pParse->pNewTrigger==0 );
1.105811 +  pParse->pNewTrigger = pTrigger;
1.105812 +
1.105813 +trigger_cleanup:
1.105814 +  sqlite3DbFree(db, zName);
1.105815 +  sqlite3SrcListDelete(db, pTableName);
1.105816 +  sqlite3IdListDelete(db, pColumns);
1.105817 +  sqlite3ExprDelete(db, pWhen);
1.105818 +  if( !pParse->pNewTrigger ){
1.105819 +    sqlite3DeleteTrigger(db, pTrigger);
1.105820 +  }else{
1.105821 +    assert( pParse->pNewTrigger==pTrigger );
1.105822 +  }
1.105823 +}
1.105824 +
1.105825 +/*
1.105826 +** This routine is called after all of the trigger actions have been parsed
1.105827 +** in order to complete the process of building the trigger.
1.105828 +*/
1.105829 +SQLITE_PRIVATE void sqlite3FinishTrigger(
1.105830 +  Parse *pParse,          /* Parser context */
1.105831 +  TriggerStep *pStepList, /* The triggered program */
1.105832 +  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
1.105833 +){
1.105834 +  Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
1.105835 +  char *zName;                            /* Name of trigger */
1.105836 +  sqlite3 *db = pParse->db;               /* The database */
1.105837 +  DbFixer sFix;                           /* Fixer object */
1.105838 +  int iDb;                                /* Database containing the trigger */
1.105839 +  Token nameToken;                        /* Trigger name for error reporting */
1.105840 +
1.105841 +  pParse->pNewTrigger = 0;
1.105842 +  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
1.105843 +  zName = pTrig->zName;
1.105844 +  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
1.105845 +  pTrig->step_list = pStepList;
1.105846 +  while( pStepList ){
1.105847 +    pStepList->pTrig = pTrig;
1.105848 +    pStepList = pStepList->pNext;
1.105849 +  }
1.105850 +  nameToken.z = pTrig->zName;
1.105851 +  nameToken.n = sqlite3Strlen30(nameToken.z);
1.105852 +  sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
1.105853 +  if( sqlite3FixTriggerStep(&sFix, pTrig->step_list) 
1.105854 +   || sqlite3FixExpr(&sFix, pTrig->pWhen) 
1.105855 +  ){
1.105856 +    goto triggerfinish_cleanup;
1.105857 +  }
1.105858 +
1.105859 +  /* if we are not initializing,
1.105860 +  ** build the sqlite_master entry
1.105861 +  */
1.105862 +  if( !db->init.busy ){
1.105863 +    Vdbe *v;
1.105864 +    char *z;
1.105865 +
1.105866 +    /* Make an entry in the sqlite_master table */
1.105867 +    v = sqlite3GetVdbe(pParse);
1.105868 +    if( v==0 ) goto triggerfinish_cleanup;
1.105869 +    sqlite3BeginWriteOperation(pParse, 0, iDb);
1.105870 +    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
1.105871 +    sqlite3NestedParse(pParse,
1.105872 +       "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
1.105873 +       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
1.105874 +       pTrig->table, z);
1.105875 +    sqlite3DbFree(db, z);
1.105876 +    sqlite3ChangeCookie(pParse, iDb);
1.105877 +    sqlite3VdbeAddParseSchemaOp(v, iDb,
1.105878 +        sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
1.105879 +  }
1.105880 +
1.105881 +  if( db->init.busy ){
1.105882 +    Trigger *pLink = pTrig;
1.105883 +    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
1.105884 +    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1.105885 +    pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
1.105886 +    if( pTrig ){
1.105887 +      db->mallocFailed = 1;
1.105888 +    }else if( pLink->pSchema==pLink->pTabSchema ){
1.105889 +      Table *pTab;
1.105890 +      int n = sqlite3Strlen30(pLink->table);
1.105891 +      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
1.105892 +      assert( pTab!=0 );
1.105893 +      pLink->pNext = pTab->pTrigger;
1.105894 +      pTab->pTrigger = pLink;
1.105895 +    }
1.105896 +  }
1.105897 +
1.105898 +triggerfinish_cleanup:
1.105899 +  sqlite3DeleteTrigger(db, pTrig);
1.105900 +  assert( !pParse->pNewTrigger );
1.105901 +  sqlite3DeleteTriggerStep(db, pStepList);
1.105902 +}
1.105903 +
1.105904 +/*
1.105905 +** Turn a SELECT statement (that the pSelect parameter points to) into
1.105906 +** a trigger step.  Return a pointer to a TriggerStep structure.
1.105907 +**
1.105908 +** The parser calls this routine when it finds a SELECT statement in
1.105909 +** body of a TRIGGER.  
1.105910 +*/
1.105911 +SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
1.105912 +  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
1.105913 +  if( pTriggerStep==0 ) {
1.105914 +    sqlite3SelectDelete(db, pSelect);
1.105915 +    return 0;
1.105916 +  }
1.105917 +  pTriggerStep->op = TK_SELECT;
1.105918 +  pTriggerStep->pSelect = pSelect;
1.105919 +  pTriggerStep->orconf = OE_Default;
1.105920 +  return pTriggerStep;
1.105921 +}
1.105922 +
1.105923 +/*
1.105924 +** Allocate space to hold a new trigger step.  The allocated space
1.105925 +** holds both the TriggerStep object and the TriggerStep.target.z string.
1.105926 +**
1.105927 +** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
1.105928 +*/
1.105929 +static TriggerStep *triggerStepAllocate(
1.105930 +  sqlite3 *db,                /* Database connection */
1.105931 +  u8 op,                      /* Trigger opcode */
1.105932 +  Token *pName                /* The target name */
1.105933 +){
1.105934 +  TriggerStep *pTriggerStep;
1.105935 +
1.105936 +  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
1.105937 +  if( pTriggerStep ){
1.105938 +    char *z = (char*)&pTriggerStep[1];
1.105939 +    memcpy(z, pName->z, pName->n);
1.105940 +    pTriggerStep->target.z = z;
1.105941 +    pTriggerStep->target.n = pName->n;
1.105942 +    pTriggerStep->op = op;
1.105943 +  }
1.105944 +  return pTriggerStep;
1.105945 +}
1.105946 +
1.105947 +/*
1.105948 +** Build a trigger step out of an INSERT statement.  Return a pointer
1.105949 +** to the new trigger step.
1.105950 +**
1.105951 +** The parser calls this routine when it sees an INSERT inside the
1.105952 +** body of a trigger.
1.105953 +*/
1.105954 +SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
1.105955 +  sqlite3 *db,        /* The database connection */
1.105956 +  Token *pTableName,  /* Name of the table into which we insert */
1.105957 +  IdList *pColumn,    /* List of columns in pTableName to insert into */
1.105958 +  Select *pSelect,    /* A SELECT statement that supplies values */
1.105959 +  u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
1.105960 +){
1.105961 +  TriggerStep *pTriggerStep;
1.105962 +
1.105963 +  assert(pSelect != 0 || db->mallocFailed);
1.105964 +
1.105965 +  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
1.105966 +  if( pTriggerStep ){
1.105967 +    pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
1.105968 +    pTriggerStep->pIdList = pColumn;
1.105969 +    pTriggerStep->orconf = orconf;
1.105970 +  }else{
1.105971 +    sqlite3IdListDelete(db, pColumn);
1.105972 +  }
1.105973 +  sqlite3SelectDelete(db, pSelect);
1.105974 +
1.105975 +  return pTriggerStep;
1.105976 +}
1.105977 +
1.105978 +/*
1.105979 +** Construct a trigger step that implements an UPDATE statement and return
1.105980 +** a pointer to that trigger step.  The parser calls this routine when it
1.105981 +** sees an UPDATE statement inside the body of a CREATE TRIGGER.
1.105982 +*/
1.105983 +SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
1.105984 +  sqlite3 *db,         /* The database connection */
1.105985 +  Token *pTableName,   /* Name of the table to be updated */
1.105986 +  ExprList *pEList,    /* The SET clause: list of column and new values */
1.105987 +  Expr *pWhere,        /* The WHERE clause */
1.105988 +  u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
1.105989 +){
1.105990 +  TriggerStep *pTriggerStep;
1.105991 +
1.105992 +  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
1.105993 +  if( pTriggerStep ){
1.105994 +    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
1.105995 +    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
1.105996 +    pTriggerStep->orconf = orconf;
1.105997 +  }
1.105998 +  sqlite3ExprListDelete(db, pEList);
1.105999 +  sqlite3ExprDelete(db, pWhere);
1.106000 +  return pTriggerStep;
1.106001 +}
1.106002 +
1.106003 +/*
1.106004 +** Construct a trigger step that implements a DELETE statement and return
1.106005 +** a pointer to that trigger step.  The parser calls this routine when it
1.106006 +** sees a DELETE statement inside the body of a CREATE TRIGGER.
1.106007 +*/
1.106008 +SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
1.106009 +  sqlite3 *db,            /* Database connection */
1.106010 +  Token *pTableName,      /* The table from which rows are deleted */
1.106011 +  Expr *pWhere            /* The WHERE clause */
1.106012 +){
1.106013 +  TriggerStep *pTriggerStep;
1.106014 +
1.106015 +  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
1.106016 +  if( pTriggerStep ){
1.106017 +    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
1.106018 +    pTriggerStep->orconf = OE_Default;
1.106019 +  }
1.106020 +  sqlite3ExprDelete(db, pWhere);
1.106021 +  return pTriggerStep;
1.106022 +}
1.106023 +
1.106024 +/* 
1.106025 +** Recursively delete a Trigger structure
1.106026 +*/
1.106027 +SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
1.106028 +  if( pTrigger==0 ) return;
1.106029 +  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
1.106030 +  sqlite3DbFree(db, pTrigger->zName);
1.106031 +  sqlite3DbFree(db, pTrigger->table);
1.106032 +  sqlite3ExprDelete(db, pTrigger->pWhen);
1.106033 +  sqlite3IdListDelete(db, pTrigger->pColumns);
1.106034 +  sqlite3DbFree(db, pTrigger);
1.106035 +}
1.106036 +
1.106037 +/*
1.106038 +** This function is called to drop a trigger from the database schema. 
1.106039 +**
1.106040 +** This may be called directly from the parser and therefore identifies
1.106041 +** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
1.106042 +** same job as this routine except it takes a pointer to the trigger
1.106043 +** instead of the trigger name.
1.106044 +**/
1.106045 +SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
1.106046 +  Trigger *pTrigger = 0;
1.106047 +  int i;
1.106048 +  const char *zDb;
1.106049 +  const char *zName;
1.106050 +  int nName;
1.106051 +  sqlite3 *db = pParse->db;
1.106052 +
1.106053 +  if( db->mallocFailed ) goto drop_trigger_cleanup;
1.106054 +  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
1.106055 +    goto drop_trigger_cleanup;
1.106056 +  }
1.106057 +
1.106058 +  assert( pName->nSrc==1 );
1.106059 +  zDb = pName->a[0].zDatabase;
1.106060 +  zName = pName->a[0].zName;
1.106061 +  nName = sqlite3Strlen30(zName);
1.106062 +  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
1.106063 +  for(i=OMIT_TEMPDB; i<db->nDb; i++){
1.106064 +    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
1.106065 +    if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
1.106066 +    assert( sqlite3SchemaMutexHeld(db, j, 0) );
1.106067 +    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
1.106068 +    if( pTrigger ) break;
1.106069 +  }
1.106070 +  if( !pTrigger ){
1.106071 +    if( !noErr ){
1.106072 +      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
1.106073 +    }else{
1.106074 +      sqlite3CodeVerifyNamedSchema(pParse, zDb);
1.106075 +    }
1.106076 +    pParse->checkSchema = 1;
1.106077 +    goto drop_trigger_cleanup;
1.106078 +  }
1.106079 +  sqlite3DropTriggerPtr(pParse, pTrigger);
1.106080 +
1.106081 +drop_trigger_cleanup:
1.106082 +  sqlite3SrcListDelete(db, pName);
1.106083 +}
1.106084 +
1.106085 +/*
1.106086 +** Return a pointer to the Table structure for the table that a trigger
1.106087 +** is set on.
1.106088 +*/
1.106089 +static Table *tableOfTrigger(Trigger *pTrigger){
1.106090 +  int n = sqlite3Strlen30(pTrigger->table);
1.106091 +  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
1.106092 +}
1.106093 +
1.106094 +
1.106095 +/*
1.106096 +** Drop a trigger given a pointer to that trigger. 
1.106097 +*/
1.106098 +SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
1.106099 +  Table   *pTable;
1.106100 +  Vdbe *v;
1.106101 +  sqlite3 *db = pParse->db;
1.106102 +  int iDb;
1.106103 +
1.106104 +  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
1.106105 +  assert( iDb>=0 && iDb<db->nDb );
1.106106 +  pTable = tableOfTrigger(pTrigger);
1.106107 +  assert( pTable );
1.106108 +  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
1.106109 +#ifndef SQLITE_OMIT_AUTHORIZATION
1.106110 +  {
1.106111 +    int code = SQLITE_DROP_TRIGGER;
1.106112 +    const char *zDb = db->aDb[iDb].zName;
1.106113 +    const char *zTab = SCHEMA_TABLE(iDb);
1.106114 +    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
1.106115 +    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
1.106116 +      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
1.106117 +      return;
1.106118 +    }
1.106119 +  }
1.106120 +#endif
1.106121 +
1.106122 +  /* Generate code to destroy the database record of the trigger.
1.106123 +  */
1.106124 +  assert( pTable!=0 );
1.106125 +  if( (v = sqlite3GetVdbe(pParse))!=0 ){
1.106126 +    int base;
1.106127 +    static const int iLn = VDBE_OFFSET_LINENO(2);
1.106128 +    static const VdbeOpList dropTrigger[] = {
1.106129 +      { OP_Rewind,     0, ADDR(9),  0},
1.106130 +      { OP_String8,    0, 1,        0}, /* 1 */
1.106131 +      { OP_Column,     0, 1,        2},
1.106132 +      { OP_Ne,         2, ADDR(8),  1},
1.106133 +      { OP_String8,    0, 1,        0}, /* 4: "trigger" */
1.106134 +      { OP_Column,     0, 0,        2},
1.106135 +      { OP_Ne,         2, ADDR(8),  1},
1.106136 +      { OP_Delete,     0, 0,        0},
1.106137 +      { OP_Next,       0, ADDR(1),  0}, /* 8 */
1.106138 +    };
1.106139 +
1.106140 +    sqlite3BeginWriteOperation(pParse, 0, iDb);
1.106141 +    sqlite3OpenMasterTable(pParse, iDb);
1.106142 +    base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger, iLn);
1.106143 +    sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
1.106144 +    sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
1.106145 +    sqlite3ChangeCookie(pParse, iDb);
1.106146 +    sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
1.106147 +    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
1.106148 +    if( pParse->nMem<3 ){
1.106149 +      pParse->nMem = 3;
1.106150 +    }
1.106151 +  }
1.106152 +}
1.106153 +
1.106154 +/*
1.106155 +** Remove a trigger from the hash tables of the sqlite* pointer.
1.106156 +*/
1.106157 +SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
1.106158 +  Trigger *pTrigger;
1.106159 +  Hash *pHash;
1.106160 +
1.106161 +  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1.106162 +  pHash = &(db->aDb[iDb].pSchema->trigHash);
1.106163 +  pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
1.106164 +  if( ALWAYS(pTrigger) ){
1.106165 +    if( pTrigger->pSchema==pTrigger->pTabSchema ){
1.106166 +      Table *pTab = tableOfTrigger(pTrigger);
1.106167 +      Trigger **pp;
1.106168 +      for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
1.106169 +      *pp = (*pp)->pNext;
1.106170 +    }
1.106171 +    sqlite3DeleteTrigger(db, pTrigger);
1.106172 +    db->flags |= SQLITE_InternChanges;
1.106173 +  }
1.106174 +}
1.106175 +
1.106176 +/*
1.106177 +** pEList is the SET clause of an UPDATE statement.  Each entry
1.106178 +** in pEList is of the format <id>=<expr>.  If any of the entries
1.106179 +** in pEList have an <id> which matches an identifier in pIdList,
1.106180 +** then return TRUE.  If pIdList==NULL, then it is considered a
1.106181 +** wildcard that matches anything.  Likewise if pEList==NULL then
1.106182 +** it matches anything so always return true.  Return false only
1.106183 +** if there is no match.
1.106184 +*/
1.106185 +static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
1.106186 +  int e;
1.106187 +  if( pIdList==0 || NEVER(pEList==0) ) return 1;
1.106188 +  for(e=0; e<pEList->nExpr; e++){
1.106189 +    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
1.106190 +  }
1.106191 +  return 0; 
1.106192 +}
1.106193 +
1.106194 +/*
1.106195 +** Return a list of all triggers on table pTab if there exists at least
1.106196 +** one trigger that must be fired when an operation of type 'op' is 
1.106197 +** performed on the table, and, if that operation is an UPDATE, if at
1.106198 +** least one of the columns in pChanges is being modified.
1.106199 +*/
1.106200 +SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
1.106201 +  Parse *pParse,          /* Parse context */
1.106202 +  Table *pTab,            /* The table the contains the triggers */
1.106203 +  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
1.106204 +  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
1.106205 +  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
1.106206 +){
1.106207 +  int mask = 0;
1.106208 +  Trigger *pList = 0;
1.106209 +  Trigger *p;
1.106210 +
1.106211 +  if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
1.106212 +    pList = sqlite3TriggerList(pParse, pTab);
1.106213 +  }
1.106214 +  assert( pList==0 || IsVirtual(pTab)==0 );
1.106215 +  for(p=pList; p; p=p->pNext){
1.106216 +    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
1.106217 +      mask |= p->tr_tm;
1.106218 +    }
1.106219 +  }
1.106220 +  if( pMask ){
1.106221 +    *pMask = mask;
1.106222 +  }
1.106223 +  return (mask ? pList : 0);
1.106224 +}
1.106225 +
1.106226 +/*
1.106227 +** Convert the pStep->target token into a SrcList and return a pointer
1.106228 +** to that SrcList.
1.106229 +**
1.106230 +** This routine adds a specific database name, if needed, to the target when
1.106231 +** forming the SrcList.  This prevents a trigger in one database from
1.106232 +** referring to a target in another database.  An exception is when the
1.106233 +** trigger is in TEMP in which case it can refer to any other database it
1.106234 +** wants.
1.106235 +*/
1.106236 +static SrcList *targetSrcList(
1.106237 +  Parse *pParse,       /* The parsing context */
1.106238 +  TriggerStep *pStep   /* The trigger containing the target token */
1.106239 +){
1.106240 +  int iDb;             /* Index of the database to use */
1.106241 +  SrcList *pSrc;       /* SrcList to be returned */
1.106242 +
1.106243 +  pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
1.106244 +  if( pSrc ){
1.106245 +    assert( pSrc->nSrc>0 );
1.106246 +    assert( pSrc->a!=0 );
1.106247 +    iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
1.106248 +    if( iDb==0 || iDb>=2 ){
1.106249 +      sqlite3 *db = pParse->db;
1.106250 +      assert( iDb<pParse->db->nDb );
1.106251 +      pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
1.106252 +    }
1.106253 +  }
1.106254 +  return pSrc;
1.106255 +}
1.106256 +
1.106257 +/*
1.106258 +** Generate VDBE code for the statements inside the body of a single 
1.106259 +** trigger.
1.106260 +*/
1.106261 +static int codeTriggerProgram(
1.106262 +  Parse *pParse,            /* The parser context */
1.106263 +  TriggerStep *pStepList,   /* List of statements inside the trigger body */
1.106264 +  int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
1.106265 +){
1.106266 +  TriggerStep *pStep;
1.106267 +  Vdbe *v = pParse->pVdbe;
1.106268 +  sqlite3 *db = pParse->db;
1.106269 +
1.106270 +  assert( pParse->pTriggerTab && pParse->pToplevel );
1.106271 +  assert( pStepList );
1.106272 +  assert( v!=0 );
1.106273 +  for(pStep=pStepList; pStep; pStep=pStep->pNext){
1.106274 +    /* Figure out the ON CONFLICT policy that will be used for this step
1.106275 +    ** of the trigger program. If the statement that caused this trigger
1.106276 +    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
1.106277 +    ** the ON CONFLICT policy that was specified as part of the trigger
1.106278 +    ** step statement. Example:
1.106279 +    **
1.106280 +    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
1.106281 +    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
1.106282 +    **   END;
1.106283 +    **
1.106284 +    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
1.106285 +    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
1.106286 +    */
1.106287 +    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
1.106288 +    assert( pParse->okConstFactor==0 );
1.106289 +
1.106290 +    switch( pStep->op ){
1.106291 +      case TK_UPDATE: {
1.106292 +        sqlite3Update(pParse, 
1.106293 +          targetSrcList(pParse, pStep),
1.106294 +          sqlite3ExprListDup(db, pStep->pExprList, 0), 
1.106295 +          sqlite3ExprDup(db, pStep->pWhere, 0), 
1.106296 +          pParse->eOrconf
1.106297 +        );
1.106298 +        break;
1.106299 +      }
1.106300 +      case TK_INSERT: {
1.106301 +        sqlite3Insert(pParse, 
1.106302 +          targetSrcList(pParse, pStep),
1.106303 +          sqlite3SelectDup(db, pStep->pSelect, 0), 
1.106304 +          sqlite3IdListDup(db, pStep->pIdList), 
1.106305 +          pParse->eOrconf
1.106306 +        );
1.106307 +        break;
1.106308 +      }
1.106309 +      case TK_DELETE: {
1.106310 +        sqlite3DeleteFrom(pParse, 
1.106311 +          targetSrcList(pParse, pStep),
1.106312 +          sqlite3ExprDup(db, pStep->pWhere, 0)
1.106313 +        );
1.106314 +        break;
1.106315 +      }
1.106316 +      default: assert( pStep->op==TK_SELECT ); {
1.106317 +        SelectDest sDest;
1.106318 +        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
1.106319 +        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
1.106320 +        sqlite3Select(pParse, pSelect, &sDest);
1.106321 +        sqlite3SelectDelete(db, pSelect);
1.106322 +        break;
1.106323 +      }
1.106324 +    } 
1.106325 +    if( pStep->op!=TK_SELECT ){
1.106326 +      sqlite3VdbeAddOp0(v, OP_ResetCount);
1.106327 +    }
1.106328 +  }
1.106329 +
1.106330 +  return 0;
1.106331 +}
1.106332 +
1.106333 +#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
1.106334 +/*
1.106335 +** This function is used to add VdbeComment() annotations to a VDBE
1.106336 +** program. It is not used in production code, only for debugging.
1.106337 +*/
1.106338 +static const char *onErrorText(int onError){
1.106339 +  switch( onError ){
1.106340 +    case OE_Abort:    return "abort";
1.106341 +    case OE_Rollback: return "rollback";
1.106342 +    case OE_Fail:     return "fail";
1.106343 +    case OE_Replace:  return "replace";
1.106344 +    case OE_Ignore:   return "ignore";
1.106345 +    case OE_Default:  return "default";
1.106346 +  }
1.106347 +  return "n/a";
1.106348 +}
1.106349 +#endif
1.106350 +
1.106351 +/*
1.106352 +** Parse context structure pFrom has just been used to create a sub-vdbe
1.106353 +** (trigger program). If an error has occurred, transfer error information
1.106354 +** from pFrom to pTo.
1.106355 +*/
1.106356 +static void transferParseError(Parse *pTo, Parse *pFrom){
1.106357 +  assert( pFrom->zErrMsg==0 || pFrom->nErr );
1.106358 +  assert( pTo->zErrMsg==0 || pTo->nErr );
1.106359 +  if( pTo->nErr==0 ){
1.106360 +    pTo->zErrMsg = pFrom->zErrMsg;
1.106361 +    pTo->nErr = pFrom->nErr;
1.106362 +  }else{
1.106363 +    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
1.106364 +  }
1.106365 +}
1.106366 +
1.106367 +/*
1.106368 +** Create and populate a new TriggerPrg object with a sub-program 
1.106369 +** implementing trigger pTrigger with ON CONFLICT policy orconf.
1.106370 +*/
1.106371 +static TriggerPrg *codeRowTrigger(
1.106372 +  Parse *pParse,       /* Current parse context */
1.106373 +  Trigger *pTrigger,   /* Trigger to code */
1.106374 +  Table *pTab,         /* The table pTrigger is attached to */
1.106375 +  int orconf           /* ON CONFLICT policy to code trigger program with */
1.106376 +){
1.106377 +  Parse *pTop = sqlite3ParseToplevel(pParse);
1.106378 +  sqlite3 *db = pParse->db;   /* Database handle */
1.106379 +  TriggerPrg *pPrg;           /* Value to return */
1.106380 +  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
1.106381 +  Vdbe *v;                    /* Temporary VM */
1.106382 +  NameContext sNC;            /* Name context for sub-vdbe */
1.106383 +  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
1.106384 +  Parse *pSubParse;           /* Parse context for sub-vdbe */
1.106385 +  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
1.106386 +
1.106387 +  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
1.106388 +  assert( pTop->pVdbe );
1.106389 +
1.106390 +  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
1.106391 +  ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
1.106392 +  ** list of the top-level Parse object sooner rather than later.  */
1.106393 +  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
1.106394 +  if( !pPrg ) return 0;
1.106395 +  pPrg->pNext = pTop->pTriggerPrg;
1.106396 +  pTop->pTriggerPrg = pPrg;
1.106397 +  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
1.106398 +  if( !pProgram ) return 0;
1.106399 +  sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
1.106400 +  pPrg->pTrigger = pTrigger;
1.106401 +  pPrg->orconf = orconf;
1.106402 +  pPrg->aColmask[0] = 0xffffffff;
1.106403 +  pPrg->aColmask[1] = 0xffffffff;
1.106404 +
1.106405 +  /* Allocate and populate a new Parse context to use for coding the 
1.106406 +  ** trigger sub-program.  */
1.106407 +  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
1.106408 +  if( !pSubParse ) return 0;
1.106409 +  memset(&sNC, 0, sizeof(sNC));
1.106410 +  sNC.pParse = pSubParse;
1.106411 +  pSubParse->db = db;
1.106412 +  pSubParse->pTriggerTab = pTab;
1.106413 +  pSubParse->pToplevel = pTop;
1.106414 +  pSubParse->zAuthContext = pTrigger->zName;
1.106415 +  pSubParse->eTriggerOp = pTrigger->op;
1.106416 +  pSubParse->nQueryLoop = pParse->nQueryLoop;
1.106417 +
1.106418 +  v = sqlite3GetVdbe(pSubParse);
1.106419 +  if( v ){
1.106420 +    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
1.106421 +      pTrigger->zName, onErrorText(orconf),
1.106422 +      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
1.106423 +        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
1.106424 +        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
1.106425 +        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
1.106426 +      pTab->zName
1.106427 +    ));
1.106428 +#ifndef SQLITE_OMIT_TRACE
1.106429 +    sqlite3VdbeChangeP4(v, -1, 
1.106430 +      sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
1.106431 +    );
1.106432 +#endif
1.106433 +
1.106434 +    /* If one was specified, code the WHEN clause. If it evaluates to false
1.106435 +    ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
1.106436 +    ** OP_Halt inserted at the end of the program.  */
1.106437 +    if( pTrigger->pWhen ){
1.106438 +      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
1.106439 +      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
1.106440 +       && db->mallocFailed==0 
1.106441 +      ){
1.106442 +        iEndTrigger = sqlite3VdbeMakeLabel(v);
1.106443 +        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
1.106444 +      }
1.106445 +      sqlite3ExprDelete(db, pWhen);
1.106446 +    }
1.106447 +
1.106448 +    /* Code the trigger program into the sub-vdbe. */
1.106449 +    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
1.106450 +
1.106451 +    /* Insert an OP_Halt at the end of the sub-program. */
1.106452 +    if( iEndTrigger ){
1.106453 +      sqlite3VdbeResolveLabel(v, iEndTrigger);
1.106454 +    }
1.106455 +    sqlite3VdbeAddOp0(v, OP_Halt);
1.106456 +    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
1.106457 +
1.106458 +    transferParseError(pParse, pSubParse);
1.106459 +    if( db->mallocFailed==0 ){
1.106460 +      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
1.106461 +    }
1.106462 +    pProgram->nMem = pSubParse->nMem;
1.106463 +    pProgram->nCsr = pSubParse->nTab;
1.106464 +    pProgram->nOnce = pSubParse->nOnce;
1.106465 +    pProgram->token = (void *)pTrigger;
1.106466 +    pPrg->aColmask[0] = pSubParse->oldmask;
1.106467 +    pPrg->aColmask[1] = pSubParse->newmask;
1.106468 +    sqlite3VdbeDelete(v);
1.106469 +  }
1.106470 +
1.106471 +  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
1.106472 +  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
1.106473 +  sqlite3ParserReset(pSubParse);
1.106474 +  sqlite3StackFree(db, pSubParse);
1.106475 +
1.106476 +  return pPrg;
1.106477 +}
1.106478 +    
1.106479 +/*
1.106480 +** Return a pointer to a TriggerPrg object containing the sub-program for
1.106481 +** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
1.106482 +** TriggerPrg object exists, a new object is allocated and populated before
1.106483 +** being returned.
1.106484 +*/
1.106485 +static TriggerPrg *getRowTrigger(
1.106486 +  Parse *pParse,       /* Current parse context */
1.106487 +  Trigger *pTrigger,   /* Trigger to code */
1.106488 +  Table *pTab,         /* The table trigger pTrigger is attached to */
1.106489 +  int orconf           /* ON CONFLICT algorithm. */
1.106490 +){
1.106491 +  Parse *pRoot = sqlite3ParseToplevel(pParse);
1.106492 +  TriggerPrg *pPrg;
1.106493 +
1.106494 +  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
1.106495 +
1.106496 +  /* It may be that this trigger has already been coded (or is in the
1.106497 +  ** process of being coded). If this is the case, then an entry with
1.106498 +  ** a matching TriggerPrg.pTrigger field will be present somewhere
1.106499 +  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
1.106500 +  for(pPrg=pRoot->pTriggerPrg; 
1.106501 +      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
1.106502 +      pPrg=pPrg->pNext
1.106503 +  );
1.106504 +
1.106505 +  /* If an existing TriggerPrg could not be located, create a new one. */
1.106506 +  if( !pPrg ){
1.106507 +    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
1.106508 +  }
1.106509 +
1.106510 +  return pPrg;
1.106511 +}
1.106512 +
1.106513 +/*
1.106514 +** Generate code for the trigger program associated with trigger p on 
1.106515 +** table pTab. The reg, orconf and ignoreJump parameters passed to this
1.106516 +** function are the same as those described in the header function for
1.106517 +** sqlite3CodeRowTrigger()
1.106518 +*/
1.106519 +SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
1.106520 +  Parse *pParse,       /* Parse context */
1.106521 +  Trigger *p,          /* Trigger to code */
1.106522 +  Table *pTab,         /* The table to code triggers from */
1.106523 +  int reg,             /* Reg array containing OLD.* and NEW.* values */
1.106524 +  int orconf,          /* ON CONFLICT policy */
1.106525 +  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
1.106526 +){
1.106527 +  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
1.106528 +  TriggerPrg *pPrg;
1.106529 +  pPrg = getRowTrigger(pParse, p, pTab, orconf);
1.106530 +  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
1.106531 +
1.106532 +  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
1.106533 +  ** is a pointer to the sub-vdbe containing the trigger program.  */
1.106534 +  if( pPrg ){
1.106535 +    int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
1.106536 +
1.106537 +    sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
1.106538 +    sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
1.106539 +    VdbeComment(
1.106540 +        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
1.106541 +
1.106542 +    /* Set the P5 operand of the OP_Program instruction to non-zero if
1.106543 +    ** recursive invocation of this trigger program is disallowed. Recursive
1.106544 +    ** invocation is disallowed if (a) the sub-program is really a trigger,
1.106545 +    ** not a foreign key action, and (b) the flag to enable recursive triggers
1.106546 +    ** is clear.  */
1.106547 +    sqlite3VdbeChangeP5(v, (u8)bRecursive);
1.106548 +  }
1.106549 +}
1.106550 +
1.106551 +/*
1.106552 +** This is called to code the required FOR EACH ROW triggers for an operation
1.106553 +** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
1.106554 +** is given by the op parameter. The tr_tm parameter determines whether the
1.106555 +** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
1.106556 +** parameter pChanges is passed the list of columns being modified.
1.106557 +**
1.106558 +** If there are no triggers that fire at the specified time for the specified
1.106559 +** operation on pTab, this function is a no-op.
1.106560 +**
1.106561 +** The reg argument is the address of the first in an array of registers 
1.106562 +** that contain the values substituted for the new.* and old.* references
1.106563 +** in the trigger program. If N is the number of columns in table pTab
1.106564 +** (a copy of pTab->nCol), then registers are populated as follows:
1.106565 +**
1.106566 +**   Register       Contains
1.106567 +**   ------------------------------------------------------
1.106568 +**   reg+0          OLD.rowid
1.106569 +**   reg+1          OLD.* value of left-most column of pTab
1.106570 +**   ...            ...
1.106571 +**   reg+N          OLD.* value of right-most column of pTab
1.106572 +**   reg+N+1        NEW.rowid
1.106573 +**   reg+N+2        OLD.* value of left-most column of pTab
1.106574 +**   ...            ...
1.106575 +**   reg+N+N+1      NEW.* value of right-most column of pTab
1.106576 +**
1.106577 +** For ON DELETE triggers, the registers containing the NEW.* values will
1.106578 +** never be accessed by the trigger program, so they are not allocated or 
1.106579 +** populated by the caller (there is no data to populate them with anyway). 
1.106580 +** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
1.106581 +** are never accessed, and so are not allocated by the caller. So, for an
1.106582 +** ON INSERT trigger, the value passed to this function as parameter reg
1.106583 +** is not a readable register, although registers (reg+N) through 
1.106584 +** (reg+N+N+1) are.
1.106585 +**
1.106586 +** Parameter orconf is the default conflict resolution algorithm for the
1.106587 +** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
1.106588 +** is the instruction that control should jump to if a trigger program
1.106589 +** raises an IGNORE exception.
1.106590 +*/
1.106591 +SQLITE_PRIVATE void sqlite3CodeRowTrigger(
1.106592 +  Parse *pParse,       /* Parse context */
1.106593 +  Trigger *pTrigger,   /* List of triggers on table pTab */
1.106594 +  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
1.106595 +  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
1.106596 +  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
1.106597 +  Table *pTab,         /* The table to code triggers from */
1.106598 +  int reg,             /* The first in an array of registers (see above) */
1.106599 +  int orconf,          /* ON CONFLICT policy */
1.106600 +  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
1.106601 +){
1.106602 +  Trigger *p;          /* Used to iterate through pTrigger list */
1.106603 +
1.106604 +  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
1.106605 +  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
1.106606 +  assert( (op==TK_UPDATE)==(pChanges!=0) );
1.106607 +
1.106608 +  for(p=pTrigger; p; p=p->pNext){
1.106609 +
1.106610 +    /* Sanity checking:  The schema for the trigger and for the table are
1.106611 +    ** always defined.  The trigger must be in the same schema as the table
1.106612 +    ** or else it must be a TEMP trigger. */
1.106613 +    assert( p->pSchema!=0 );
1.106614 +    assert( p->pTabSchema!=0 );
1.106615 +    assert( p->pSchema==p->pTabSchema 
1.106616 +         || p->pSchema==pParse->db->aDb[1].pSchema );
1.106617 +
1.106618 +    /* Determine whether we should code this trigger */
1.106619 +    if( p->op==op 
1.106620 +     && p->tr_tm==tr_tm 
1.106621 +     && checkColumnOverlap(p->pColumns, pChanges)
1.106622 +    ){
1.106623 +      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
1.106624 +    }
1.106625 +  }
1.106626 +}
1.106627 +
1.106628 +/*
1.106629 +** Triggers may access values stored in the old.* or new.* pseudo-table. 
1.106630 +** This function returns a 32-bit bitmask indicating which columns of the 
1.106631 +** old.* or new.* tables actually are used by triggers. This information 
1.106632 +** may be used by the caller, for example, to avoid having to load the entire
1.106633 +** old.* record into memory when executing an UPDATE or DELETE command.
1.106634 +**
1.106635 +** Bit 0 of the returned mask is set if the left-most column of the
1.106636 +** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
1.106637 +** the second leftmost column value is required, and so on. If there
1.106638 +** are more than 32 columns in the table, and at least one of the columns
1.106639 +** with an index greater than 32 may be accessed, 0xffffffff is returned.
1.106640 +**
1.106641 +** It is not possible to determine if the old.rowid or new.rowid column is 
1.106642 +** accessed by triggers. The caller must always assume that it is.
1.106643 +**
1.106644 +** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
1.106645 +** applies to the old.* table. If 1, the new.* table.
1.106646 +**
1.106647 +** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
1.106648 +** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
1.106649 +** included in the returned mask if the TRIGGER_BEFORE bit is set in the
1.106650 +** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
1.106651 +** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
1.106652 +*/
1.106653 +SQLITE_PRIVATE u32 sqlite3TriggerColmask(
1.106654 +  Parse *pParse,       /* Parse context */
1.106655 +  Trigger *pTrigger,   /* List of triggers on table pTab */
1.106656 +  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
1.106657 +  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
1.106658 +  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
1.106659 +  Table *pTab,         /* The table to code triggers from */
1.106660 +  int orconf           /* Default ON CONFLICT policy for trigger steps */
1.106661 +){
1.106662 +  const int op = pChanges ? TK_UPDATE : TK_DELETE;
1.106663 +  u32 mask = 0;
1.106664 +  Trigger *p;
1.106665 +
1.106666 +  assert( isNew==1 || isNew==0 );
1.106667 +  for(p=pTrigger; p; p=p->pNext){
1.106668 +    if( p->op==op && (tr_tm&p->tr_tm)
1.106669 +     && checkColumnOverlap(p->pColumns,pChanges)
1.106670 +    ){
1.106671 +      TriggerPrg *pPrg;
1.106672 +      pPrg = getRowTrigger(pParse, p, pTab, orconf);
1.106673 +      if( pPrg ){
1.106674 +        mask |= pPrg->aColmask[isNew];
1.106675 +      }
1.106676 +    }
1.106677 +  }
1.106678 +
1.106679 +  return mask;
1.106680 +}
1.106681 +
1.106682 +#endif /* !defined(SQLITE_OMIT_TRIGGER) */
1.106683 +
1.106684 +/************** End of trigger.c *********************************************/
1.106685 +/************** Begin file update.c ******************************************/
1.106686 +/*
1.106687 +** 2001 September 15
1.106688 +**
1.106689 +** The author disclaims copyright to this source code.  In place of
1.106690 +** a legal notice, here is a blessing:
1.106691 +**
1.106692 +**    May you do good and not evil.
1.106693 +**    May you find forgiveness for yourself and forgive others.
1.106694 +**    May you share freely, never taking more than you give.
1.106695 +**
1.106696 +*************************************************************************
1.106697 +** This file contains C code routines that are called by the parser
1.106698 +** to handle UPDATE statements.
1.106699 +*/
1.106700 +
1.106701 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.106702 +/* Forward declaration */
1.106703 +static void updateVirtualTable(
1.106704 +  Parse *pParse,       /* The parsing context */
1.106705 +  SrcList *pSrc,       /* The virtual table to be modified */
1.106706 +  Table *pTab,         /* The virtual table */
1.106707 +  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
1.106708 +  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
1.106709 +  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
1.106710 +  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
1.106711 +  int onError          /* ON CONFLICT strategy */
1.106712 +);
1.106713 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
1.106714 +
1.106715 +/*
1.106716 +** The most recently coded instruction was an OP_Column to retrieve the
1.106717 +** i-th column of table pTab. This routine sets the P4 parameter of the 
1.106718 +** OP_Column to the default value, if any.
1.106719 +**
1.106720 +** The default value of a column is specified by a DEFAULT clause in the 
1.106721 +** column definition. This was either supplied by the user when the table
1.106722 +** was created, or added later to the table definition by an ALTER TABLE
1.106723 +** command. If the latter, then the row-records in the table btree on disk
1.106724 +** may not contain a value for the column and the default value, taken
1.106725 +** from the P4 parameter of the OP_Column instruction, is returned instead.
1.106726 +** If the former, then all row-records are guaranteed to include a value
1.106727 +** for the column and the P4 value is not required.
1.106728 +**
1.106729 +** Column definitions created by an ALTER TABLE command may only have 
1.106730 +** literal default values specified: a number, null or a string. (If a more
1.106731 +** complicated default expression value was provided, it is evaluated 
1.106732 +** when the ALTER TABLE is executed and one of the literal values written
1.106733 +** into the sqlite_master table.)
1.106734 +**
1.106735 +** Therefore, the P4 parameter is only required if the default value for
1.106736 +** the column is a literal number, string or null. The sqlite3ValueFromExpr()
1.106737 +** function is capable of transforming these types of expressions into
1.106738 +** sqlite3_value objects.
1.106739 +**
1.106740 +** If parameter iReg is not negative, code an OP_RealAffinity instruction
1.106741 +** on register iReg. This is used when an equivalent integer value is 
1.106742 +** stored in place of an 8-byte floating point value in order to save 
1.106743 +** space.
1.106744 +*/
1.106745 +SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
1.106746 +  assert( pTab!=0 );
1.106747 +  if( !pTab->pSelect ){
1.106748 +    sqlite3_value *pValue = 0;
1.106749 +    u8 enc = ENC(sqlite3VdbeDb(v));
1.106750 +    Column *pCol = &pTab->aCol[i];
1.106751 +    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
1.106752 +    assert( i<pTab->nCol );
1.106753 +    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
1.106754 +                         pCol->affinity, &pValue);
1.106755 +    if( pValue ){
1.106756 +      sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
1.106757 +    }
1.106758 +#ifndef SQLITE_OMIT_FLOATING_POINT
1.106759 +    if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
1.106760 +      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
1.106761 +    }
1.106762 +#endif
1.106763 +  }
1.106764 +}
1.106765 +
1.106766 +/*
1.106767 +** Process an UPDATE statement.
1.106768 +**
1.106769 +**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
1.106770 +**          \_______/ \________/     \______/       \________________/
1.106771 +*            onError   pTabList      pChanges             pWhere
1.106772 +*/
1.106773 +SQLITE_PRIVATE void sqlite3Update(
1.106774 +  Parse *pParse,         /* The parser context */
1.106775 +  SrcList *pTabList,     /* The table in which we should change things */
1.106776 +  ExprList *pChanges,    /* Things to be changed */
1.106777 +  Expr *pWhere,          /* The WHERE clause.  May be null */
1.106778 +  int onError            /* How to handle constraint errors */
1.106779 +){
1.106780 +  int i, j;              /* Loop counters */
1.106781 +  Table *pTab;           /* The table to be updated */
1.106782 +  int addrTop = 0;       /* VDBE instruction address of the start of the loop */
1.106783 +  WhereInfo *pWInfo;     /* Information about the WHERE clause */
1.106784 +  Vdbe *v;               /* The virtual database engine */
1.106785 +  Index *pIdx;           /* For looping over indices */
1.106786 +  Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
1.106787 +  int nIdx;              /* Number of indices that need updating */
1.106788 +  int iBaseCur;          /* Base cursor number */
1.106789 +  int iDataCur;          /* Cursor for the canonical data btree */
1.106790 +  int iIdxCur;           /* Cursor for the first index */
1.106791 +  sqlite3 *db;           /* The database structure */
1.106792 +  int *aRegIdx = 0;      /* One register assigned to each index to be updated */
1.106793 +  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
1.106794 +                         ** an expression for the i-th column of the table.
1.106795 +                         ** aXRef[i]==-1 if the i-th column is not changed. */
1.106796 +  u8 *aToOpen;           /* 1 for tables and indices to be opened */
1.106797 +  u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
1.106798 +  u8 chngRowid;          /* Rowid changed in a normal table */
1.106799 +  u8 chngKey;            /* Either chngPk or chngRowid */
1.106800 +  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
1.106801 +  AuthContext sContext;  /* The authorization context */
1.106802 +  NameContext sNC;       /* The name-context to resolve expressions in */
1.106803 +  int iDb;               /* Database containing the table being updated */
1.106804 +  int okOnePass;         /* True for one-pass algorithm without the FIFO */
1.106805 +  int hasFK;             /* True if foreign key processing is required */
1.106806 +  int labelBreak;        /* Jump here to break out of UPDATE loop */
1.106807 +  int labelContinue;     /* Jump here to continue next step of UPDATE loop */
1.106808 +
1.106809 +#ifndef SQLITE_OMIT_TRIGGER
1.106810 +  int isView;            /* True when updating a view (INSTEAD OF trigger) */
1.106811 +  Trigger *pTrigger;     /* List of triggers on pTab, if required */
1.106812 +  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
1.106813 +#endif
1.106814 +  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
1.106815 +  int iEph = 0;          /* Ephemeral table holding all primary key values */
1.106816 +  int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
1.106817 +  int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
1.106818 +
1.106819 +  /* Register Allocations */
1.106820 +  int regRowCount = 0;   /* A count of rows changed */
1.106821 +  int regOldRowid;       /* The old rowid */
1.106822 +  int regNewRowid;       /* The new rowid */
1.106823 +  int regNew;            /* Content of the NEW.* table in triggers */
1.106824 +  int regOld = 0;        /* Content of OLD.* table in triggers */
1.106825 +  int regRowSet = 0;     /* Rowset of rows to be updated */
1.106826 +  int regKey = 0;        /* composite PRIMARY KEY value */
1.106827 +
1.106828 +  memset(&sContext, 0, sizeof(sContext));
1.106829 +  db = pParse->db;
1.106830 +  if( pParse->nErr || db->mallocFailed ){
1.106831 +    goto update_cleanup;
1.106832 +  }
1.106833 +  assert( pTabList->nSrc==1 );
1.106834 +
1.106835 +  /* Locate the table which we want to update. 
1.106836 +  */
1.106837 +  pTab = sqlite3SrcListLookup(pParse, pTabList);
1.106838 +  if( pTab==0 ) goto update_cleanup;
1.106839 +  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1.106840 +
1.106841 +  /* Figure out if we have any triggers and if the table being
1.106842 +  ** updated is a view.
1.106843 +  */
1.106844 +#ifndef SQLITE_OMIT_TRIGGER
1.106845 +  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
1.106846 +  isView = pTab->pSelect!=0;
1.106847 +  assert( pTrigger || tmask==0 );
1.106848 +#else
1.106849 +# define pTrigger 0
1.106850 +# define isView 0
1.106851 +# define tmask 0
1.106852 +#endif
1.106853 +#ifdef SQLITE_OMIT_VIEW
1.106854 +# undef isView
1.106855 +# define isView 0
1.106856 +#endif
1.106857 +
1.106858 +  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
1.106859 +    goto update_cleanup;
1.106860 +  }
1.106861 +  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
1.106862 +    goto update_cleanup;
1.106863 +  }
1.106864 +
1.106865 +  /* Allocate a cursors for the main database table and for all indices.
1.106866 +  ** The index cursors might not be used, but if they are used they
1.106867 +  ** need to occur right after the database cursor.  So go ahead and
1.106868 +  ** allocate enough space, just in case.
1.106869 +  */
1.106870 +  pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
1.106871 +  iIdxCur = iDataCur+1;
1.106872 +  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
1.106873 +  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
1.106874 +    if( pIdx->autoIndex==2 && pPk!=0 ){
1.106875 +      iDataCur = pParse->nTab;
1.106876 +      pTabList->a[0].iCursor = iDataCur;
1.106877 +    }
1.106878 +    pParse->nTab++;
1.106879 +  }
1.106880 +
1.106881 +  /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].  
1.106882 +  ** Initialize aXRef[] and aToOpen[] to their default values.
1.106883 +  */
1.106884 +  aXRef = sqlite3DbMallocRaw(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
1.106885 +  if( aXRef==0 ) goto update_cleanup;
1.106886 +  aRegIdx = aXRef+pTab->nCol;
1.106887 +  aToOpen = (u8*)(aRegIdx+nIdx);
1.106888 +  memset(aToOpen, 1, nIdx+1);
1.106889 +  aToOpen[nIdx+1] = 0;
1.106890 +  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
1.106891 +
1.106892 +  /* Initialize the name-context */
1.106893 +  memset(&sNC, 0, sizeof(sNC));
1.106894 +  sNC.pParse = pParse;
1.106895 +  sNC.pSrcList = pTabList;
1.106896 +
1.106897 +  /* Resolve the column names in all the expressions of the
1.106898 +  ** of the UPDATE statement.  Also find the column index
1.106899 +  ** for each column to be updated in the pChanges array.  For each
1.106900 +  ** column to be updated, make sure we have authorization to change
1.106901 +  ** that column.
1.106902 +  */
1.106903 +  chngRowid = chngPk = 0;
1.106904 +  for(i=0; i<pChanges->nExpr; i++){
1.106905 +    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
1.106906 +      goto update_cleanup;
1.106907 +    }
1.106908 +    for(j=0; j<pTab->nCol; j++){
1.106909 +      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
1.106910 +        if( j==pTab->iPKey ){
1.106911 +          chngRowid = 1;
1.106912 +          pRowidExpr = pChanges->a[i].pExpr;
1.106913 +        }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
1.106914 +          chngPk = 1;
1.106915 +        }
1.106916 +        aXRef[j] = i;
1.106917 +        break;
1.106918 +      }
1.106919 +    }
1.106920 +    if( j>=pTab->nCol ){
1.106921 +      if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
1.106922 +        j = -1;
1.106923 +        chngRowid = 1;
1.106924 +        pRowidExpr = pChanges->a[i].pExpr;
1.106925 +      }else{
1.106926 +        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
1.106927 +        pParse->checkSchema = 1;
1.106928 +        goto update_cleanup;
1.106929 +      }
1.106930 +    }
1.106931 +#ifndef SQLITE_OMIT_AUTHORIZATION
1.106932 +    {
1.106933 +      int rc;
1.106934 +      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
1.106935 +                            j<0 ? "ROWID" : pTab->aCol[j].zName,
1.106936 +                            db->aDb[iDb].zName);
1.106937 +      if( rc==SQLITE_DENY ){
1.106938 +        goto update_cleanup;
1.106939 +      }else if( rc==SQLITE_IGNORE ){
1.106940 +        aXRef[j] = -1;
1.106941 +      }
1.106942 +    }
1.106943 +#endif
1.106944 +  }
1.106945 +  assert( (chngRowid & chngPk)==0 );
1.106946 +  assert( chngRowid==0 || chngRowid==1 );
1.106947 +  assert( chngPk==0 || chngPk==1 );
1.106948 +  chngKey = chngRowid + chngPk;
1.106949 +
1.106950 +  /* The SET expressions are not actually used inside the WHERE loop.
1.106951 +  ** So reset the colUsed mask
1.106952 +  */
1.106953 +  pTabList->a[0].colUsed = 0;
1.106954 +
1.106955 +  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
1.106956 +
1.106957 +  /* There is one entry in the aRegIdx[] array for each index on the table
1.106958 +  ** being updated.  Fill in aRegIdx[] with a register number that will hold
1.106959 +  ** the key for accessing each index.  
1.106960 +  */
1.106961 +  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
1.106962 +    int reg;
1.106963 +    if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
1.106964 +      reg = ++pParse->nMem;
1.106965 +    }else{
1.106966 +      reg = 0;
1.106967 +      for(i=0; i<pIdx->nKeyCol; i++){
1.106968 +        if( aXRef[pIdx->aiColumn[i]]>=0 ){
1.106969 +          reg = ++pParse->nMem;
1.106970 +          break;
1.106971 +        }
1.106972 +      }
1.106973 +    }
1.106974 +    if( reg==0 ) aToOpen[j+1] = 0;
1.106975 +    aRegIdx[j] = reg;
1.106976 +  }
1.106977 +
1.106978 +  /* Begin generating code. */
1.106979 +  v = sqlite3GetVdbe(pParse);
1.106980 +  if( v==0 ) goto update_cleanup;
1.106981 +  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
1.106982 +  sqlite3BeginWriteOperation(pParse, 1, iDb);
1.106983 +
1.106984 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.106985 +  /* Virtual tables must be handled separately */
1.106986 +  if( IsVirtual(pTab) ){
1.106987 +    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
1.106988 +                       pWhere, onError);
1.106989 +    pWhere = 0;
1.106990 +    pTabList = 0;
1.106991 +    goto update_cleanup;
1.106992 +  }
1.106993 +#endif
1.106994 +
1.106995 +  /* Allocate required registers. */
1.106996 +  regRowSet = ++pParse->nMem;
1.106997 +  regOldRowid = regNewRowid = ++pParse->nMem;
1.106998 +  if( chngPk || pTrigger || hasFK ){
1.106999 +    regOld = pParse->nMem + 1;
1.107000 +    pParse->nMem += pTab->nCol;
1.107001 +  }
1.107002 +  if( chngKey || pTrigger || hasFK ){
1.107003 +    regNewRowid = ++pParse->nMem;
1.107004 +  }
1.107005 +  regNew = pParse->nMem + 1;
1.107006 +  pParse->nMem += pTab->nCol;
1.107007 +
1.107008 +  /* Start the view context. */
1.107009 +  if( isView ){
1.107010 +    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
1.107011 +  }
1.107012 +
1.107013 +  /* If we are trying to update a view, realize that view into
1.107014 +  ** a ephemeral table.
1.107015 +  */
1.107016 +#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
1.107017 +  if( isView ){
1.107018 +    sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
1.107019 +  }
1.107020 +#endif
1.107021 +
1.107022 +  /* Resolve the column names in all the expressions in the
1.107023 +  ** WHERE clause.
1.107024 +  */
1.107025 +  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
1.107026 +    goto update_cleanup;
1.107027 +  }
1.107028 +
1.107029 +  /* Begin the database scan
1.107030 +  */
1.107031 +  if( HasRowid(pTab) ){
1.107032 +    sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
1.107033 +    pWInfo = sqlite3WhereBegin(
1.107034 +        pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
1.107035 +    );
1.107036 +    if( pWInfo==0 ) goto update_cleanup;
1.107037 +    okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
1.107038 +  
1.107039 +    /* Remember the rowid of every item to be updated.
1.107040 +    */
1.107041 +    sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
1.107042 +    if( !okOnePass ){
1.107043 +      sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
1.107044 +    }
1.107045 +  
1.107046 +    /* End the database scan loop.
1.107047 +    */
1.107048 +    sqlite3WhereEnd(pWInfo);
1.107049 +  }else{
1.107050 +    int iPk;         /* First of nPk memory cells holding PRIMARY KEY value */
1.107051 +    i16 nPk;         /* Number of components of the PRIMARY KEY */
1.107052 +    int addrOpen;    /* Address of the OpenEphemeral instruction */
1.107053 +
1.107054 +    assert( pPk!=0 );
1.107055 +    nPk = pPk->nKeyCol;
1.107056 +    iPk = pParse->nMem+1;
1.107057 +    pParse->nMem += nPk;
1.107058 +    regKey = ++pParse->nMem;
1.107059 +    iEph = pParse->nTab++;
1.107060 +    sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
1.107061 +    addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
1.107062 +    sqlite3VdbeSetP4KeyInfo(pParse, pPk);
1.107063 +    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, 
1.107064 +                               WHERE_ONEPASS_DESIRED, iIdxCur);
1.107065 +    if( pWInfo==0 ) goto update_cleanup;
1.107066 +    okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
1.107067 +    for(i=0; i<nPk; i++){
1.107068 +      sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
1.107069 +                                      iPk+i);
1.107070 +    }
1.107071 +    if( okOnePass ){
1.107072 +      sqlite3VdbeChangeToNoop(v, addrOpen);
1.107073 +      nKey = nPk;
1.107074 +      regKey = iPk;
1.107075 +    }else{
1.107076 +      sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
1.107077 +                        sqlite3IndexAffinityStr(v, pPk), nPk);
1.107078 +      sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
1.107079 +    }
1.107080 +    sqlite3WhereEnd(pWInfo);
1.107081 +  }
1.107082 +
1.107083 +  /* Initialize the count of updated rows
1.107084 +  */
1.107085 +  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
1.107086 +    regRowCount = ++pParse->nMem;
1.107087 +    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
1.107088 +  }
1.107089 +
1.107090 +  labelBreak = sqlite3VdbeMakeLabel(v);
1.107091 +  if( !isView ){
1.107092 +    /* 
1.107093 +    ** Open every index that needs updating.  Note that if any
1.107094 +    ** index could potentially invoke a REPLACE conflict resolution 
1.107095 +    ** action, then we need to open all indices because we might need
1.107096 +    ** to be deleting some records.
1.107097 +    */
1.107098 +    if( onError==OE_Replace ){
1.107099 +      memset(aToOpen, 1, nIdx+1);
1.107100 +    }else{
1.107101 +      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1.107102 +        if( pIdx->onError==OE_Replace ){
1.107103 +          memset(aToOpen, 1, nIdx+1);
1.107104 +          break;
1.107105 +        }
1.107106 +      }
1.107107 +    }
1.107108 +    if( okOnePass ){
1.107109 +      if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
1.107110 +      if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
1.107111 +    }
1.107112 +    sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iBaseCur, aToOpen,
1.107113 +                               0, 0);
1.107114 +  }
1.107115 +
1.107116 +  /* Top of the update loop */
1.107117 +  if( okOnePass ){
1.107118 +    if( aToOpen[iDataCur-iBaseCur] ){
1.107119 +      assert( pPk!=0 );
1.107120 +      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
1.107121 +      VdbeCoverageNeverTaken(v);
1.107122 +    }
1.107123 +    labelContinue = labelBreak;
1.107124 +    sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
1.107125 +    VdbeCoverage(v);
1.107126 +  }else if( pPk ){
1.107127 +    labelContinue = sqlite3VdbeMakeLabel(v);
1.107128 +    sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
1.107129 +    addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
1.107130 +    sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
1.107131 +    VdbeCoverage(v);
1.107132 +  }else{
1.107133 +    labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
1.107134 +                             regOldRowid);
1.107135 +    VdbeCoverage(v);
1.107136 +    sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
1.107137 +    VdbeCoverage(v);
1.107138 +  }
1.107139 +
1.107140 +  /* If the record number will change, set register regNewRowid to
1.107141 +  ** contain the new value. If the record number is not being modified,
1.107142 +  ** then regNewRowid is the same register as regOldRowid, which is
1.107143 +  ** already populated.  */
1.107144 +  assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
1.107145 +  if( chngRowid ){
1.107146 +    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
1.107147 +    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
1.107148 +  }
1.107149 +
1.107150 +  /* Compute the old pre-UPDATE content of the row being changed, if that
1.107151 +  ** information is needed */
1.107152 +  if( chngPk || hasFK || pTrigger ){
1.107153 +    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
1.107154 +    oldmask |= sqlite3TriggerColmask(pParse, 
1.107155 +        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
1.107156 +    );
1.107157 +    for(i=0; i<pTab->nCol; i++){
1.107158 +      if( oldmask==0xffffffff
1.107159 +       || (i<32 && (oldmask & MASKBIT32(i))!=0)
1.107160 +       || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
1.107161 +      ){
1.107162 +        testcase(  oldmask!=0xffffffff && i==31 );
1.107163 +        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
1.107164 +      }else{
1.107165 +        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
1.107166 +      }
1.107167 +    }
1.107168 +    if( chngRowid==0 && pPk==0 ){
1.107169 +      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
1.107170 +    }
1.107171 +  }
1.107172 +
1.107173 +  /* Populate the array of registers beginning at regNew with the new
1.107174 +  ** row data. This array is used to check constaints, create the new
1.107175 +  ** table and index records, and as the values for any new.* references
1.107176 +  ** made by triggers.
1.107177 +  **
1.107178 +  ** If there are one or more BEFORE triggers, then do not populate the
1.107179 +  ** registers associated with columns that are (a) not modified by
1.107180 +  ** this UPDATE statement and (b) not accessed by new.* references. The
1.107181 +  ** values for registers not modified by the UPDATE must be reloaded from 
1.107182 +  ** the database after the BEFORE triggers are fired anyway (as the trigger 
1.107183 +  ** may have modified them). So not loading those that are not going to
1.107184 +  ** be used eliminates some redundant opcodes.
1.107185 +  */
1.107186 +  newmask = sqlite3TriggerColmask(
1.107187 +      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
1.107188 +  );
1.107189 +  /*sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);*/
1.107190 +  for(i=0; i<pTab->nCol; i++){
1.107191 +    if( i==pTab->iPKey ){
1.107192 +      sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
1.107193 +    }else{
1.107194 +      j = aXRef[i];
1.107195 +      if( j>=0 ){
1.107196 +        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
1.107197 +      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
1.107198 +        /* This branch loads the value of a column that will not be changed 
1.107199 +        ** into a register. This is done if there are no BEFORE triggers, or
1.107200 +        ** if there are one or more BEFORE triggers that use this value via
1.107201 +        ** a new.* reference in a trigger program.
1.107202 +        */
1.107203 +        testcase( i==31 );
1.107204 +        testcase( i==32 );
1.107205 +        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
1.107206 +      }else{
1.107207 +        sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
1.107208 +      }
1.107209 +    }
1.107210 +  }
1.107211 +
1.107212 +  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
1.107213 +  ** verified. One could argue that this is wrong.
1.107214 +  */
1.107215 +  if( tmask&TRIGGER_BEFORE ){
1.107216 +    sqlite3TableAffinity(v, pTab, regNew);
1.107217 +    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
1.107218 +        TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
1.107219 +
1.107220 +    /* The row-trigger may have deleted the row being updated. In this
1.107221 +    ** case, jump to the next row. No updates or AFTER triggers are 
1.107222 +    ** required. This behavior - what happens when the row being updated
1.107223 +    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
1.107224 +    ** documentation.
1.107225 +    */
1.107226 +    if( pPk ){
1.107227 +      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
1.107228 +      VdbeCoverage(v);
1.107229 +    }else{
1.107230 +      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
1.107231 +      VdbeCoverage(v);
1.107232 +    }
1.107233 +
1.107234 +    /* If it did not delete it, the row-trigger may still have modified 
1.107235 +    ** some of the columns of the row being updated. Load the values for 
1.107236 +    ** all columns not modified by the update statement into their 
1.107237 +    ** registers in case this has happened.
1.107238 +    */
1.107239 +    for(i=0; i<pTab->nCol; i++){
1.107240 +      if( aXRef[i]<0 && i!=pTab->iPKey ){
1.107241 +        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
1.107242 +      }
1.107243 +    }
1.107244 +  }
1.107245 +
1.107246 +  if( !isView ){
1.107247 +    int j1 = 0;           /* Address of jump instruction */
1.107248 +    int bReplace = 0;     /* True if REPLACE conflict resolution might happen */
1.107249 +
1.107250 +    /* Do constraint checks. */
1.107251 +    assert( regOldRowid>0 );
1.107252 +    sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
1.107253 +        regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace);
1.107254 +
1.107255 +    /* Do FK constraint checks. */
1.107256 +    if( hasFK ){
1.107257 +      sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
1.107258 +    }
1.107259 +
1.107260 +    /* Delete the index entries associated with the current record.  */
1.107261 +    if( bReplace || chngKey ){
1.107262 +      if( pPk ){
1.107263 +        j1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
1.107264 +      }else{
1.107265 +        j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
1.107266 +      }
1.107267 +      VdbeCoverageNeverTaken(v);
1.107268 +    }
1.107269 +    sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx);
1.107270 +  
1.107271 +    /* If changing the record number, delete the old record.  */
1.107272 +    if( hasFK || chngKey || pPk!=0 ){
1.107273 +      sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
1.107274 +    }
1.107275 +    if( bReplace || chngKey ){
1.107276 +      sqlite3VdbeJumpHere(v, j1);
1.107277 +    }
1.107278 +
1.107279 +    if( hasFK ){
1.107280 +      sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
1.107281 +    }
1.107282 +  
1.107283 +    /* Insert the new index entries and the new record. */
1.107284 +    sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
1.107285 +                             regNewRowid, aRegIdx, 1, 0, 0);
1.107286 +
1.107287 +    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
1.107288 +    ** handle rows (possibly in other tables) that refer via a foreign key
1.107289 +    ** to the row just updated. */ 
1.107290 +    if( hasFK ){
1.107291 +      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
1.107292 +    }
1.107293 +  }
1.107294 +
1.107295 +  /* Increment the row counter 
1.107296 +  */
1.107297 +  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
1.107298 +    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
1.107299 +  }
1.107300 +
1.107301 +  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
1.107302 +      TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
1.107303 +
1.107304 +  /* Repeat the above with the next record to be updated, until
1.107305 +  ** all record selected by the WHERE clause have been updated.
1.107306 +  */
1.107307 +  if( okOnePass ){
1.107308 +    /* Nothing to do at end-of-loop for a single-pass */
1.107309 +  }else if( pPk ){
1.107310 +    sqlite3VdbeResolveLabel(v, labelContinue);
1.107311 +    sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
1.107312 +  }else{
1.107313 +    sqlite3VdbeAddOp2(v, OP_Goto, 0, labelContinue);
1.107314 +  }
1.107315 +  sqlite3VdbeResolveLabel(v, labelBreak);
1.107316 +
1.107317 +  /* Close all tables */
1.107318 +  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1.107319 +    assert( aRegIdx );
1.107320 +    if( aToOpen[i+1] ){
1.107321 +      sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
1.107322 +    }
1.107323 +  }
1.107324 +  if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
1.107325 +
1.107326 +  /* Update the sqlite_sequence table by storing the content of the
1.107327 +  ** maximum rowid counter values recorded while inserting into
1.107328 +  ** autoincrement tables.
1.107329 +  */
1.107330 +  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
1.107331 +    sqlite3AutoincrementEnd(pParse);
1.107332 +  }
1.107333 +
1.107334 +  /*
1.107335 +  ** Return the number of rows that were changed. If this routine is 
1.107336 +  ** generating code because of a call to sqlite3NestedParse(), do not
1.107337 +  ** invoke the callback function.
1.107338 +  */
1.107339 +  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
1.107340 +    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
1.107341 +    sqlite3VdbeSetNumCols(v, 1);
1.107342 +    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
1.107343 +  }
1.107344 +
1.107345 +update_cleanup:
1.107346 +  sqlite3AuthContextPop(&sContext);
1.107347 +  sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
1.107348 +  sqlite3SrcListDelete(db, pTabList);
1.107349 +  sqlite3ExprListDelete(db, pChanges);
1.107350 +  sqlite3ExprDelete(db, pWhere);
1.107351 +  return;
1.107352 +}
1.107353 +/* Make sure "isView" and other macros defined above are undefined. Otherwise
1.107354 +** thely may interfere with compilation of other functions in this file
1.107355 +** (or in another file, if this file becomes part of the amalgamation).  */
1.107356 +#ifdef isView
1.107357 + #undef isView
1.107358 +#endif
1.107359 +#ifdef pTrigger
1.107360 + #undef pTrigger
1.107361 +#endif
1.107362 +
1.107363 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.107364 +/*
1.107365 +** Generate code for an UPDATE of a virtual table.
1.107366 +**
1.107367 +** The strategy is that we create an ephemerial table that contains
1.107368 +** for each row to be changed:
1.107369 +**
1.107370 +**   (A)  The original rowid of that row.
1.107371 +**   (B)  The revised rowid for the row. (note1)
1.107372 +**   (C)  The content of every column in the row.
1.107373 +**
1.107374 +** Then we loop over this ephemeral table and for each row in
1.107375 +** the ephermeral table call VUpdate.
1.107376 +**
1.107377 +** When finished, drop the ephemeral table.
1.107378 +**
1.107379 +** (note1) Actually, if we know in advance that (A) is always the same
1.107380 +** as (B) we only store (A), then duplicate (A) when pulling
1.107381 +** it out of the ephemeral table before calling VUpdate.
1.107382 +*/
1.107383 +static void updateVirtualTable(
1.107384 +  Parse *pParse,       /* The parsing context */
1.107385 +  SrcList *pSrc,       /* The virtual table to be modified */
1.107386 +  Table *pTab,         /* The virtual table */
1.107387 +  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
1.107388 +  Expr *pRowid,        /* Expression used to recompute the rowid */
1.107389 +  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
1.107390 +  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
1.107391 +  int onError          /* ON CONFLICT strategy */
1.107392 +){
1.107393 +  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
1.107394 +  ExprList *pEList = 0;     /* The result set of the SELECT statement */
1.107395 +  Select *pSelect = 0;      /* The SELECT statement */
1.107396 +  Expr *pExpr;              /* Temporary expression */
1.107397 +  int ephemTab;             /* Table holding the result of the SELECT */
1.107398 +  int i;                    /* Loop counter */
1.107399 +  int addr;                 /* Address of top of loop */
1.107400 +  int iReg;                 /* First register in set passed to OP_VUpdate */
1.107401 +  sqlite3 *db = pParse->db; /* Database connection */
1.107402 +  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
1.107403 +  SelectDest dest;
1.107404 +
1.107405 +  /* Construct the SELECT statement that will find the new values for
1.107406 +  ** all updated rows. 
1.107407 +  */
1.107408 +  pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
1.107409 +  if( pRowid ){
1.107410 +    pEList = sqlite3ExprListAppend(pParse, pEList,
1.107411 +                                   sqlite3ExprDup(db, pRowid, 0));
1.107412 +  }
1.107413 +  assert( pTab->iPKey<0 );
1.107414 +  for(i=0; i<pTab->nCol; i++){
1.107415 +    if( aXRef[i]>=0 ){
1.107416 +      pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
1.107417 +    }else{
1.107418 +      pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
1.107419 +    }
1.107420 +    pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
1.107421 +  }
1.107422 +  pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
1.107423 +  
1.107424 +  /* Create the ephemeral table into which the update results will
1.107425 +  ** be stored.
1.107426 +  */
1.107427 +  assert( v );
1.107428 +  ephemTab = pParse->nTab++;
1.107429 +  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
1.107430 +  sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
1.107431 +
1.107432 +  /* fill the ephemeral table 
1.107433 +  */
1.107434 +  sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
1.107435 +  sqlite3Select(pParse, pSelect, &dest);
1.107436 +
1.107437 +  /* Generate code to scan the ephemeral table and call VUpdate. */
1.107438 +  iReg = ++pParse->nMem;
1.107439 +  pParse->nMem += pTab->nCol+1;
1.107440 +  addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0); VdbeCoverage(v);
1.107441 +  sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
1.107442 +  sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
1.107443 +  for(i=0; i<pTab->nCol; i++){
1.107444 +    sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
1.107445 +  }
1.107446 +  sqlite3VtabMakeWritable(pParse, pTab);
1.107447 +  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
1.107448 +  sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
1.107449 +  sqlite3MayAbort(pParse);
1.107450 +  sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
1.107451 +  sqlite3VdbeJumpHere(v, addr);
1.107452 +  sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
1.107453 +
1.107454 +  /* Cleanup */
1.107455 +  sqlite3SelectDelete(db, pSelect);  
1.107456 +}
1.107457 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
1.107458 +
1.107459 +/************** End of update.c **********************************************/
1.107460 +/************** Begin file vacuum.c ******************************************/
1.107461 +/*
1.107462 +** 2003 April 6
1.107463 +**
1.107464 +** The author disclaims copyright to this source code.  In place of
1.107465 +** a legal notice, here is a blessing:
1.107466 +**
1.107467 +**    May you do good and not evil.
1.107468 +**    May you find forgiveness for yourself and forgive others.
1.107469 +**    May you share freely, never taking more than you give.
1.107470 +**
1.107471 +*************************************************************************
1.107472 +** This file contains code used to implement the VACUUM command.
1.107473 +**
1.107474 +** Most of the code in this file may be omitted by defining the
1.107475 +** SQLITE_OMIT_VACUUM macro.
1.107476 +*/
1.107477 +
1.107478 +#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
1.107479 +/*
1.107480 +** Finalize a prepared statement.  If there was an error, store the
1.107481 +** text of the error message in *pzErrMsg.  Return the result code.
1.107482 +*/
1.107483 +static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
1.107484 +  int rc;
1.107485 +  rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
1.107486 +  if( rc ){
1.107487 +    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
1.107488 +  }
1.107489 +  return rc;
1.107490 +}
1.107491 +
1.107492 +/*
1.107493 +** Execute zSql on database db. Return an error code.
1.107494 +*/
1.107495 +static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
1.107496 +  sqlite3_stmt *pStmt;
1.107497 +  VVA_ONLY( int rc; )
1.107498 +  if( !zSql ){
1.107499 +    return SQLITE_NOMEM;
1.107500 +  }
1.107501 +  if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
1.107502 +    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
1.107503 +    return sqlite3_errcode(db);
1.107504 +  }
1.107505 +  VVA_ONLY( rc = ) sqlite3_step(pStmt);
1.107506 +  assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
1.107507 +  return vacuumFinalize(db, pStmt, pzErrMsg);
1.107508 +}
1.107509 +
1.107510 +/*
1.107511 +** Execute zSql on database db. The statement returns exactly
1.107512 +** one column. Execute this as SQL on the same database.
1.107513 +*/
1.107514 +static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
1.107515 +  sqlite3_stmt *pStmt;
1.107516 +  int rc;
1.107517 +
1.107518 +  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
1.107519 +  if( rc!=SQLITE_OK ) return rc;
1.107520 +
1.107521 +  while( SQLITE_ROW==sqlite3_step(pStmt) ){
1.107522 +    rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
1.107523 +    if( rc!=SQLITE_OK ){
1.107524 +      vacuumFinalize(db, pStmt, pzErrMsg);
1.107525 +      return rc;
1.107526 +    }
1.107527 +  }
1.107528 +
1.107529 +  return vacuumFinalize(db, pStmt, pzErrMsg);
1.107530 +}
1.107531 +
1.107532 +/*
1.107533 +** The VACUUM command is used to clean up the database,
1.107534 +** collapse free space, etc.  It is modelled after the VACUUM command
1.107535 +** in PostgreSQL.  The VACUUM command works as follows:
1.107536 +**
1.107537 +**   (1)  Create a new transient database file
1.107538 +**   (2)  Copy all content from the database being vacuumed into
1.107539 +**        the new transient database file
1.107540 +**   (3)  Copy content from the transient database back into the
1.107541 +**        original database.
1.107542 +**
1.107543 +** The transient database requires temporary disk space approximately
1.107544 +** equal to the size of the original database.  The copy operation of
1.107545 +** step (3) requires additional temporary disk space approximately equal
1.107546 +** to the size of the original database for the rollback journal.
1.107547 +** Hence, temporary disk space that is approximately 2x the size of the
1.107548 +** orginal database is required.  Every page of the database is written
1.107549 +** approximately 3 times:  Once for step (2) and twice for step (3).
1.107550 +** Two writes per page are required in step (3) because the original
1.107551 +** database content must be written into the rollback journal prior to
1.107552 +** overwriting the database with the vacuumed content.
1.107553 +**
1.107554 +** Only 1x temporary space and only 1x writes would be required if
1.107555 +** the copy of step (3) were replace by deleting the original database
1.107556 +** and renaming the transient database as the original.  But that will
1.107557 +** not work if other processes are attached to the original database.
1.107558 +** And a power loss in between deleting the original and renaming the
1.107559 +** transient would cause the database file to appear to be deleted
1.107560 +** following reboot.
1.107561 +*/
1.107562 +SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
1.107563 +  Vdbe *v = sqlite3GetVdbe(pParse);
1.107564 +  if( v ){
1.107565 +    sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
1.107566 +    sqlite3VdbeUsesBtree(v, 0);
1.107567 +  }
1.107568 +  return;
1.107569 +}
1.107570 +
1.107571 +/*
1.107572 +** This routine implements the OP_Vacuum opcode of the VDBE.
1.107573 +*/
1.107574 +SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
1.107575 +  int rc = SQLITE_OK;     /* Return code from service routines */
1.107576 +  Btree *pMain;           /* The database being vacuumed */
1.107577 +  Btree *pTemp;           /* The temporary database we vacuum into */
1.107578 +  char *zSql = 0;         /* SQL statements */
1.107579 +  int saved_flags;        /* Saved value of the db->flags */
1.107580 +  int saved_nChange;      /* Saved value of db->nChange */
1.107581 +  int saved_nTotalChange; /* Saved value of db->nTotalChange */
1.107582 +  void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
1.107583 +  Db *pDb = 0;            /* Database to detach at end of vacuum */
1.107584 +  int isMemDb;            /* True if vacuuming a :memory: database */
1.107585 +  int nRes;               /* Bytes of reserved space at the end of each page */
1.107586 +  int nDb;                /* Number of attached databases */
1.107587 +
1.107588 +  if( !db->autoCommit ){
1.107589 +    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
1.107590 +    return SQLITE_ERROR;
1.107591 +  }
1.107592 +  if( db->nVdbeActive>1 ){
1.107593 +    sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
1.107594 +    return SQLITE_ERROR;
1.107595 +  }
1.107596 +
1.107597 +  /* Save the current value of the database flags so that it can be 
1.107598 +  ** restored before returning. Then set the writable-schema flag, and
1.107599 +  ** disable CHECK and foreign key constraints.  */
1.107600 +  saved_flags = db->flags;
1.107601 +  saved_nChange = db->nChange;
1.107602 +  saved_nTotalChange = db->nTotalChange;
1.107603 +  saved_xTrace = db->xTrace;
1.107604 +  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
1.107605 +  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
1.107606 +  db->xTrace = 0;
1.107607 +
1.107608 +  pMain = db->aDb[0].pBt;
1.107609 +  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
1.107610 +
1.107611 +  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
1.107612 +  ** can be set to 'off' for this file, as it is not recovered if a crash
1.107613 +  ** occurs anyway. The integrity of the database is maintained by a
1.107614 +  ** (possibly synchronous) transaction opened on the main database before
1.107615 +  ** sqlite3BtreeCopyFile() is called.
1.107616 +  **
1.107617 +  ** An optimisation would be to use a non-journaled pager.
1.107618 +  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
1.107619 +  ** that actually made the VACUUM run slower.  Very little journalling
1.107620 +  ** actually occurs when doing a vacuum since the vacuum_db is initially
1.107621 +  ** empty.  Only the journal header is written.  Apparently it takes more
1.107622 +  ** time to parse and run the PRAGMA to turn journalling off than it does
1.107623 +  ** to write the journal header file.
1.107624 +  */
1.107625 +  nDb = db->nDb;
1.107626 +  if( sqlite3TempInMemory(db) ){
1.107627 +    zSql = "ATTACH ':memory:' AS vacuum_db;";
1.107628 +  }else{
1.107629 +    zSql = "ATTACH '' AS vacuum_db;";
1.107630 +  }
1.107631 +  rc = execSql(db, pzErrMsg, zSql);
1.107632 +  if( db->nDb>nDb ){
1.107633 +    pDb = &db->aDb[db->nDb-1];
1.107634 +    assert( strcmp(pDb->zName,"vacuum_db")==0 );
1.107635 +  }
1.107636 +  if( rc!=SQLITE_OK ) goto end_of_vacuum;
1.107637 +  pTemp = db->aDb[db->nDb-1].pBt;
1.107638 +
1.107639 +  /* The call to execSql() to attach the temp database has left the file
1.107640 +  ** locked (as there was more than one active statement when the transaction
1.107641 +  ** to read the schema was concluded. Unlock it here so that this doesn't
1.107642 +  ** cause problems for the call to BtreeSetPageSize() below.  */
1.107643 +  sqlite3BtreeCommit(pTemp);
1.107644 +
1.107645 +  nRes = sqlite3BtreeGetReserve(pMain);
1.107646 +
1.107647 +  /* A VACUUM cannot change the pagesize of an encrypted database. */
1.107648 +#ifdef SQLITE_HAS_CODEC
1.107649 +  if( db->nextPagesize ){
1.107650 +    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
1.107651 +    int nKey;
1.107652 +    char *zKey;
1.107653 +    sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
1.107654 +    if( nKey ) db->nextPagesize = 0;
1.107655 +  }
1.107656 +#endif
1.107657 +
1.107658 +  rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
1.107659 +  if( rc!=SQLITE_OK ) goto end_of_vacuum;
1.107660 +
1.107661 +  /* Begin a transaction and take an exclusive lock on the main database
1.107662 +  ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
1.107663 +  ** to ensure that we do not try to change the page-size on a WAL database.
1.107664 +  */
1.107665 +  rc = execSql(db, pzErrMsg, "BEGIN;");
1.107666 +  if( rc!=SQLITE_OK ) goto end_of_vacuum;
1.107667 +  rc = sqlite3BtreeBeginTrans(pMain, 2);
1.107668 +  if( rc!=SQLITE_OK ) goto end_of_vacuum;
1.107669 +
1.107670 +  /* Do not attempt to change the page size for a WAL database */
1.107671 +  if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
1.107672 +                                               ==PAGER_JOURNALMODE_WAL ){
1.107673 +    db->nextPagesize = 0;
1.107674 +  }
1.107675 +
1.107676 +  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
1.107677 +   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
1.107678 +   || NEVER(db->mallocFailed)
1.107679 +  ){
1.107680 +    rc = SQLITE_NOMEM;
1.107681 +    goto end_of_vacuum;
1.107682 +  }
1.107683 +
1.107684 +#ifndef SQLITE_OMIT_AUTOVACUUM
1.107685 +  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
1.107686 +                                           sqlite3BtreeGetAutoVacuum(pMain));
1.107687 +#endif
1.107688 +
1.107689 +  /* Query the schema of the main database. Create a mirror schema
1.107690 +  ** in the temporary database.
1.107691 +  */
1.107692 +  rc = execExecSql(db, pzErrMsg,
1.107693 +      "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
1.107694 +      "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
1.107695 +      "   AND coalesce(rootpage,1)>0"
1.107696 +  );
1.107697 +  if( rc!=SQLITE_OK ) goto end_of_vacuum;
1.107698 +  rc = execExecSql(db, pzErrMsg,
1.107699 +      "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
1.107700 +      "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
1.107701 +  if( rc!=SQLITE_OK ) goto end_of_vacuum;
1.107702 +  rc = execExecSql(db, pzErrMsg,
1.107703 +      "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
1.107704 +      "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
1.107705 +  if( rc!=SQLITE_OK ) goto end_of_vacuum;
1.107706 +
1.107707 +  /* Loop through the tables in the main database. For each, do
1.107708 +  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
1.107709 +  ** the contents to the temporary database.
1.107710 +  */
1.107711 +  rc = execExecSql(db, pzErrMsg,
1.107712 +      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
1.107713 +      "|| ' SELECT * FROM main.' || quote(name) || ';'"
1.107714 +      "FROM main.sqlite_master "
1.107715 +      "WHERE type = 'table' AND name!='sqlite_sequence' "
1.107716 +      "  AND coalesce(rootpage,1)>0"
1.107717 +  );
1.107718 +  if( rc!=SQLITE_OK ) goto end_of_vacuum;
1.107719 +
1.107720 +  /* Copy over the sequence table
1.107721 +  */
1.107722 +  rc = execExecSql(db, pzErrMsg,
1.107723 +      "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
1.107724 +      "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
1.107725 +  );
1.107726 +  if( rc!=SQLITE_OK ) goto end_of_vacuum;
1.107727 +  rc = execExecSql(db, pzErrMsg,
1.107728 +      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
1.107729 +      "|| ' SELECT * FROM main.' || quote(name) || ';' "
1.107730 +      "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
1.107731 +  );
1.107732 +  if( rc!=SQLITE_OK ) goto end_of_vacuum;
1.107733 +
1.107734 +
1.107735 +  /* Copy the triggers, views, and virtual tables from the main database
1.107736 +  ** over to the temporary database.  None of these objects has any
1.107737 +  ** associated storage, so all we have to do is copy their entries
1.107738 +  ** from the SQLITE_MASTER table.
1.107739 +  */
1.107740 +  rc = execSql(db, pzErrMsg,
1.107741 +      "INSERT INTO vacuum_db.sqlite_master "
1.107742 +      "  SELECT type, name, tbl_name, rootpage, sql"
1.107743 +      "    FROM main.sqlite_master"
1.107744 +      "   WHERE type='view' OR type='trigger'"
1.107745 +      "      OR (type='table' AND rootpage=0)"
1.107746 +  );
1.107747 +  if( rc ) goto end_of_vacuum;
1.107748 +
1.107749 +  /* At this point, there is a write transaction open on both the 
1.107750 +  ** vacuum database and the main database. Assuming no error occurs,
1.107751 +  ** both transactions are closed by this block - the main database
1.107752 +  ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
1.107753 +  ** call to sqlite3BtreeCommit().
1.107754 +  */
1.107755 +  {
1.107756 +    u32 meta;
1.107757 +    int i;
1.107758 +
1.107759 +    /* This array determines which meta meta values are preserved in the
1.107760 +    ** vacuum.  Even entries are the meta value number and odd entries
1.107761 +    ** are an increment to apply to the meta value after the vacuum.
1.107762 +    ** The increment is used to increase the schema cookie so that other
1.107763 +    ** connections to the same database will know to reread the schema.
1.107764 +    */
1.107765 +    static const unsigned char aCopy[] = {
1.107766 +       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
1.107767 +       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
1.107768 +       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
1.107769 +       BTREE_USER_VERSION,       0,  /* Preserve the user version */
1.107770 +       BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
1.107771 +    };
1.107772 +
1.107773 +    assert( 1==sqlite3BtreeIsInTrans(pTemp) );
1.107774 +    assert( 1==sqlite3BtreeIsInTrans(pMain) );
1.107775 +
1.107776 +    /* Copy Btree meta values */
1.107777 +    for(i=0; i<ArraySize(aCopy); i+=2){
1.107778 +      /* GetMeta() and UpdateMeta() cannot fail in this context because
1.107779 +      ** we already have page 1 loaded into cache and marked dirty. */
1.107780 +      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
1.107781 +      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
1.107782 +      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
1.107783 +    }
1.107784 +
1.107785 +    rc = sqlite3BtreeCopyFile(pMain, pTemp);
1.107786 +    if( rc!=SQLITE_OK ) goto end_of_vacuum;
1.107787 +    rc = sqlite3BtreeCommit(pTemp);
1.107788 +    if( rc!=SQLITE_OK ) goto end_of_vacuum;
1.107789 +#ifndef SQLITE_OMIT_AUTOVACUUM
1.107790 +    sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
1.107791 +#endif
1.107792 +  }
1.107793 +
1.107794 +  assert( rc==SQLITE_OK );
1.107795 +  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
1.107796 +
1.107797 +end_of_vacuum:
1.107798 +  /* Restore the original value of db->flags */
1.107799 +  db->flags = saved_flags;
1.107800 +  db->nChange = saved_nChange;
1.107801 +  db->nTotalChange = saved_nTotalChange;
1.107802 +  db->xTrace = saved_xTrace;
1.107803 +  sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
1.107804 +
1.107805 +  /* Currently there is an SQL level transaction open on the vacuum
1.107806 +  ** database. No locks are held on any other files (since the main file
1.107807 +  ** was committed at the btree level). So it safe to end the transaction
1.107808 +  ** by manually setting the autoCommit flag to true and detaching the
1.107809 +  ** vacuum database. The vacuum_db journal file is deleted when the pager
1.107810 +  ** is closed by the DETACH.
1.107811 +  */
1.107812 +  db->autoCommit = 1;
1.107813 +
1.107814 +  if( pDb ){
1.107815 +    sqlite3BtreeClose(pDb->pBt);
1.107816 +    pDb->pBt = 0;
1.107817 +    pDb->pSchema = 0;
1.107818 +  }
1.107819 +
1.107820 +  /* This both clears the schemas and reduces the size of the db->aDb[]
1.107821 +  ** array. */ 
1.107822 +  sqlite3ResetAllSchemasOfConnection(db);
1.107823 +
1.107824 +  return rc;
1.107825 +}
1.107826 +
1.107827 +#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
1.107828 +
1.107829 +/************** End of vacuum.c **********************************************/
1.107830 +/************** Begin file vtab.c ********************************************/
1.107831 +/*
1.107832 +** 2006 June 10
1.107833 +**
1.107834 +** The author disclaims copyright to this source code.  In place of
1.107835 +** a legal notice, here is a blessing:
1.107836 +**
1.107837 +**    May you do good and not evil.
1.107838 +**    May you find forgiveness for yourself and forgive others.
1.107839 +**    May you share freely, never taking more than you give.
1.107840 +**
1.107841 +*************************************************************************
1.107842 +** This file contains code used to help implement virtual tables.
1.107843 +*/
1.107844 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.107845 +
1.107846 +/*
1.107847 +** Before a virtual table xCreate() or xConnect() method is invoked, the
1.107848 +** sqlite3.pVtabCtx member variable is set to point to an instance of
1.107849 +** this struct allocated on the stack. It is used by the implementation of 
1.107850 +** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
1.107851 +** are invoked only from within xCreate and xConnect methods.
1.107852 +*/
1.107853 +struct VtabCtx {
1.107854 +  VTable *pVTable;    /* The virtual table being constructed */
1.107855 +  Table *pTab;        /* The Table object to which the virtual table belongs */
1.107856 +};
1.107857 +
1.107858 +/*
1.107859 +** The actual function that does the work of creating a new module.
1.107860 +** This function implements the sqlite3_create_module() and
1.107861 +** sqlite3_create_module_v2() interfaces.
1.107862 +*/
1.107863 +static int createModule(
1.107864 +  sqlite3 *db,                    /* Database in which module is registered */
1.107865 +  const char *zName,              /* Name assigned to this module */
1.107866 +  const sqlite3_module *pModule,  /* The definition of the module */
1.107867 +  void *pAux,                     /* Context pointer for xCreate/xConnect */
1.107868 +  void (*xDestroy)(void *)        /* Module destructor function */
1.107869 +){
1.107870 +  int rc = SQLITE_OK;
1.107871 +  int nName;
1.107872 +
1.107873 +  sqlite3_mutex_enter(db->mutex);
1.107874 +  nName = sqlite3Strlen30(zName);
1.107875 +  if( sqlite3HashFind(&db->aModule, zName, nName) ){
1.107876 +    rc = SQLITE_MISUSE_BKPT;
1.107877 +  }else{
1.107878 +    Module *pMod;
1.107879 +    pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
1.107880 +    if( pMod ){
1.107881 +      Module *pDel;
1.107882 +      char *zCopy = (char *)(&pMod[1]);
1.107883 +      memcpy(zCopy, zName, nName+1);
1.107884 +      pMod->zName = zCopy;
1.107885 +      pMod->pModule = pModule;
1.107886 +      pMod->pAux = pAux;
1.107887 +      pMod->xDestroy = xDestroy;
1.107888 +      pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
1.107889 +      assert( pDel==0 || pDel==pMod );
1.107890 +      if( pDel ){
1.107891 +        db->mallocFailed = 1;
1.107892 +        sqlite3DbFree(db, pDel);
1.107893 +      }
1.107894 +    }
1.107895 +  }
1.107896 +  rc = sqlite3ApiExit(db, rc);
1.107897 +  if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
1.107898 +
1.107899 +  sqlite3_mutex_leave(db->mutex);
1.107900 +  return rc;
1.107901 +}
1.107902 +
1.107903 +
1.107904 +/*
1.107905 +** External API function used to create a new virtual-table module.
1.107906 +*/
1.107907 +SQLITE_API int sqlite3_create_module(
1.107908 +  sqlite3 *db,                    /* Database in which module is registered */
1.107909 +  const char *zName,              /* Name assigned to this module */
1.107910 +  const sqlite3_module *pModule,  /* The definition of the module */
1.107911 +  void *pAux                      /* Context pointer for xCreate/xConnect */
1.107912 +){
1.107913 +  return createModule(db, zName, pModule, pAux, 0);
1.107914 +}
1.107915 +
1.107916 +/*
1.107917 +** External API function used to create a new virtual-table module.
1.107918 +*/
1.107919 +SQLITE_API int sqlite3_create_module_v2(
1.107920 +  sqlite3 *db,                    /* Database in which module is registered */
1.107921 +  const char *zName,              /* Name assigned to this module */
1.107922 +  const sqlite3_module *pModule,  /* The definition of the module */
1.107923 +  void *pAux,                     /* Context pointer for xCreate/xConnect */
1.107924 +  void (*xDestroy)(void *)        /* Module destructor function */
1.107925 +){
1.107926 +  return createModule(db, zName, pModule, pAux, xDestroy);
1.107927 +}
1.107928 +
1.107929 +/*
1.107930 +** Lock the virtual table so that it cannot be disconnected.
1.107931 +** Locks nest.  Every lock should have a corresponding unlock.
1.107932 +** If an unlock is omitted, resources leaks will occur.  
1.107933 +**
1.107934 +** If a disconnect is attempted while a virtual table is locked,
1.107935 +** the disconnect is deferred until all locks have been removed.
1.107936 +*/
1.107937 +SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
1.107938 +  pVTab->nRef++;
1.107939 +}
1.107940 +
1.107941 +
1.107942 +/*
1.107943 +** pTab is a pointer to a Table structure representing a virtual-table.
1.107944 +** Return a pointer to the VTable object used by connection db to access 
1.107945 +** this virtual-table, if one has been created, or NULL otherwise.
1.107946 +*/
1.107947 +SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
1.107948 +  VTable *pVtab;
1.107949 +  assert( IsVirtual(pTab) );
1.107950 +  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
1.107951 +  return pVtab;
1.107952 +}
1.107953 +
1.107954 +/*
1.107955 +** Decrement the ref-count on a virtual table object. When the ref-count
1.107956 +** reaches zero, call the xDisconnect() method to delete the object.
1.107957 +*/
1.107958 +SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
1.107959 +  sqlite3 *db = pVTab->db;
1.107960 +
1.107961 +  assert( db );
1.107962 +  assert( pVTab->nRef>0 );
1.107963 +  assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
1.107964 +
1.107965 +  pVTab->nRef--;
1.107966 +  if( pVTab->nRef==0 ){
1.107967 +    sqlite3_vtab *p = pVTab->pVtab;
1.107968 +    if( p ){
1.107969 +      p->pModule->xDisconnect(p);
1.107970 +    }
1.107971 +    sqlite3DbFree(db, pVTab);
1.107972 +  }
1.107973 +}
1.107974 +
1.107975 +/*
1.107976 +** Table p is a virtual table. This function moves all elements in the
1.107977 +** p->pVTable list to the sqlite3.pDisconnect lists of their associated
1.107978 +** database connections to be disconnected at the next opportunity. 
1.107979 +** Except, if argument db is not NULL, then the entry associated with
1.107980 +** connection db is left in the p->pVTable list.
1.107981 +*/
1.107982 +static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
1.107983 +  VTable *pRet = 0;
1.107984 +  VTable *pVTable = p->pVTable;
1.107985 +  p->pVTable = 0;
1.107986 +
1.107987 +  /* Assert that the mutex (if any) associated with the BtShared database 
1.107988 +  ** that contains table p is held by the caller. See header comments 
1.107989 +  ** above function sqlite3VtabUnlockList() for an explanation of why
1.107990 +  ** this makes it safe to access the sqlite3.pDisconnect list of any
1.107991 +  ** database connection that may have an entry in the p->pVTable list.
1.107992 +  */
1.107993 +  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
1.107994 +
1.107995 +  while( pVTable ){
1.107996 +    sqlite3 *db2 = pVTable->db;
1.107997 +    VTable *pNext = pVTable->pNext;
1.107998 +    assert( db2 );
1.107999 +    if( db2==db ){
1.108000 +      pRet = pVTable;
1.108001 +      p->pVTable = pRet;
1.108002 +      pRet->pNext = 0;
1.108003 +    }else{
1.108004 +      pVTable->pNext = db2->pDisconnect;
1.108005 +      db2->pDisconnect = pVTable;
1.108006 +    }
1.108007 +    pVTable = pNext;
1.108008 +  }
1.108009 +
1.108010 +  assert( !db || pRet );
1.108011 +  return pRet;
1.108012 +}
1.108013 +
1.108014 +/*
1.108015 +** Table *p is a virtual table. This function removes the VTable object
1.108016 +** for table *p associated with database connection db from the linked
1.108017 +** list in p->pVTab. It also decrements the VTable ref count. This is
1.108018 +** used when closing database connection db to free all of its VTable
1.108019 +** objects without disturbing the rest of the Schema object (which may
1.108020 +** be being used by other shared-cache connections).
1.108021 +*/
1.108022 +SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
1.108023 +  VTable **ppVTab;
1.108024 +
1.108025 +  assert( IsVirtual(p) );
1.108026 +  assert( sqlite3BtreeHoldsAllMutexes(db) );
1.108027 +  assert( sqlite3_mutex_held(db->mutex) );
1.108028 +
1.108029 +  for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
1.108030 +    if( (*ppVTab)->db==db  ){
1.108031 +      VTable *pVTab = *ppVTab;
1.108032 +      *ppVTab = pVTab->pNext;
1.108033 +      sqlite3VtabUnlock(pVTab);
1.108034 +      break;
1.108035 +    }
1.108036 +  }
1.108037 +}
1.108038 +
1.108039 +
1.108040 +/*
1.108041 +** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
1.108042 +**
1.108043 +** This function may only be called when the mutexes associated with all
1.108044 +** shared b-tree databases opened using connection db are held by the 
1.108045 +** caller. This is done to protect the sqlite3.pDisconnect list. The
1.108046 +** sqlite3.pDisconnect list is accessed only as follows:
1.108047 +**
1.108048 +**   1) By this function. In this case, all BtShared mutexes and the mutex
1.108049 +**      associated with the database handle itself must be held.
1.108050 +**
1.108051 +**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
1.108052 +**      the sqlite3.pDisconnect list. In this case either the BtShared mutex
1.108053 +**      associated with the database the virtual table is stored in is held
1.108054 +**      or, if the virtual table is stored in a non-sharable database, then
1.108055 +**      the database handle mutex is held.
1.108056 +**
1.108057 +** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
1.108058 +** by multiple threads. It is thread-safe.
1.108059 +*/
1.108060 +SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
1.108061 +  VTable *p = db->pDisconnect;
1.108062 +  db->pDisconnect = 0;
1.108063 +
1.108064 +  assert( sqlite3BtreeHoldsAllMutexes(db) );
1.108065 +  assert( sqlite3_mutex_held(db->mutex) );
1.108066 +
1.108067 +  if( p ){
1.108068 +    sqlite3ExpirePreparedStatements(db);
1.108069 +    do {
1.108070 +      VTable *pNext = p->pNext;
1.108071 +      sqlite3VtabUnlock(p);
1.108072 +      p = pNext;
1.108073 +    }while( p );
1.108074 +  }
1.108075 +}
1.108076 +
1.108077 +/*
1.108078 +** Clear any and all virtual-table information from the Table record.
1.108079 +** This routine is called, for example, just before deleting the Table
1.108080 +** record.
1.108081 +**
1.108082 +** Since it is a virtual-table, the Table structure contains a pointer
1.108083 +** to the head of a linked list of VTable structures. Each VTable 
1.108084 +** structure is associated with a single sqlite3* user of the schema.
1.108085 +** The reference count of the VTable structure associated with database 
1.108086 +** connection db is decremented immediately (which may lead to the 
1.108087 +** structure being xDisconnected and free). Any other VTable structures
1.108088 +** in the list are moved to the sqlite3.pDisconnect list of the associated 
1.108089 +** database connection.
1.108090 +*/
1.108091 +SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
1.108092 +  if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
1.108093 +  if( p->azModuleArg ){
1.108094 +    int i;
1.108095 +    for(i=0; i<p->nModuleArg; i++){
1.108096 +      if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
1.108097 +    }
1.108098 +    sqlite3DbFree(db, p->azModuleArg);
1.108099 +  }
1.108100 +}
1.108101 +
1.108102 +/*
1.108103 +** Add a new module argument to pTable->azModuleArg[].
1.108104 +** The string is not copied - the pointer is stored.  The
1.108105 +** string will be freed automatically when the table is
1.108106 +** deleted.
1.108107 +*/
1.108108 +static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
1.108109 +  int i = pTable->nModuleArg++;
1.108110 +  int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
1.108111 +  char **azModuleArg;
1.108112 +  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
1.108113 +  if( azModuleArg==0 ){
1.108114 +    int j;
1.108115 +    for(j=0; j<i; j++){
1.108116 +      sqlite3DbFree(db, pTable->azModuleArg[j]);
1.108117 +    }
1.108118 +    sqlite3DbFree(db, zArg);
1.108119 +    sqlite3DbFree(db, pTable->azModuleArg);
1.108120 +    pTable->nModuleArg = 0;
1.108121 +  }else{
1.108122 +    azModuleArg[i] = zArg;
1.108123 +    azModuleArg[i+1] = 0;
1.108124 +  }
1.108125 +  pTable->azModuleArg = azModuleArg;
1.108126 +}
1.108127 +
1.108128 +/*
1.108129 +** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
1.108130 +** statement.  The module name has been parsed, but the optional list
1.108131 +** of parameters that follow the module name are still pending.
1.108132 +*/
1.108133 +SQLITE_PRIVATE void sqlite3VtabBeginParse(
1.108134 +  Parse *pParse,        /* Parsing context */
1.108135 +  Token *pName1,        /* Name of new table, or database name */
1.108136 +  Token *pName2,        /* Name of new table or NULL */
1.108137 +  Token *pModuleName,   /* Name of the module for the virtual table */
1.108138 +  int ifNotExists       /* No error if the table already exists */
1.108139 +){
1.108140 +  int iDb;              /* The database the table is being created in */
1.108141 +  Table *pTable;        /* The new virtual table */
1.108142 +  sqlite3 *db;          /* Database connection */
1.108143 +
1.108144 +  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
1.108145 +  pTable = pParse->pNewTable;
1.108146 +  if( pTable==0 ) return;
1.108147 +  assert( 0==pTable->pIndex );
1.108148 +
1.108149 +  db = pParse->db;
1.108150 +  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
1.108151 +  assert( iDb>=0 );
1.108152 +
1.108153 +  pTable->tabFlags |= TF_Virtual;
1.108154 +  pTable->nModuleArg = 0;
1.108155 +  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
1.108156 +  addModuleArgument(db, pTable, 0);
1.108157 +  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
1.108158 +  pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
1.108159 +
1.108160 +#ifndef SQLITE_OMIT_AUTHORIZATION
1.108161 +  /* Creating a virtual table invokes the authorization callback twice.
1.108162 +  ** The first invocation, to obtain permission to INSERT a row into the
1.108163 +  ** sqlite_master table, has already been made by sqlite3StartTable().
1.108164 +  ** The second call, to obtain permission to create the table, is made now.
1.108165 +  */
1.108166 +  if( pTable->azModuleArg ){
1.108167 +    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
1.108168 +            pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
1.108169 +  }
1.108170 +#endif
1.108171 +}
1.108172 +
1.108173 +/*
1.108174 +** This routine takes the module argument that has been accumulating
1.108175 +** in pParse->zArg[] and appends it to the list of arguments on the
1.108176 +** virtual table currently under construction in pParse->pTable.
1.108177 +*/
1.108178 +static void addArgumentToVtab(Parse *pParse){
1.108179 +  if( pParse->sArg.z && pParse->pNewTable ){
1.108180 +    const char *z = (const char*)pParse->sArg.z;
1.108181 +    int n = pParse->sArg.n;
1.108182 +    sqlite3 *db = pParse->db;
1.108183 +    addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
1.108184 +  }
1.108185 +}
1.108186 +
1.108187 +/*
1.108188 +** The parser calls this routine after the CREATE VIRTUAL TABLE statement
1.108189 +** has been completely parsed.
1.108190 +*/
1.108191 +SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
1.108192 +  Table *pTab = pParse->pNewTable;  /* The table being constructed */
1.108193 +  sqlite3 *db = pParse->db;         /* The database connection */
1.108194 +
1.108195 +  if( pTab==0 ) return;
1.108196 +  addArgumentToVtab(pParse);
1.108197 +  pParse->sArg.z = 0;
1.108198 +  if( pTab->nModuleArg<1 ) return;
1.108199 +  
1.108200 +  /* If the CREATE VIRTUAL TABLE statement is being entered for the
1.108201 +  ** first time (in other words if the virtual table is actually being
1.108202 +  ** created now instead of just being read out of sqlite_master) then
1.108203 +  ** do additional initialization work and store the statement text
1.108204 +  ** in the sqlite_master table.
1.108205 +  */
1.108206 +  if( !db->init.busy ){
1.108207 +    char *zStmt;
1.108208 +    char *zWhere;
1.108209 +    int iDb;
1.108210 +    Vdbe *v;
1.108211 +
1.108212 +    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
1.108213 +    if( pEnd ){
1.108214 +      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
1.108215 +    }
1.108216 +    zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
1.108217 +
1.108218 +    /* A slot for the record has already been allocated in the 
1.108219 +    ** SQLITE_MASTER table.  We just need to update that slot with all
1.108220 +    ** the information we've collected.  
1.108221 +    **
1.108222 +    ** The VM register number pParse->regRowid holds the rowid of an
1.108223 +    ** entry in the sqlite_master table tht was created for this vtab
1.108224 +    ** by sqlite3StartTable().
1.108225 +    */
1.108226 +    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1.108227 +    sqlite3NestedParse(pParse,
1.108228 +      "UPDATE %Q.%s "
1.108229 +         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
1.108230 +       "WHERE rowid=#%d",
1.108231 +      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
1.108232 +      pTab->zName,
1.108233 +      pTab->zName,
1.108234 +      zStmt,
1.108235 +      pParse->regRowid
1.108236 +    );
1.108237 +    sqlite3DbFree(db, zStmt);
1.108238 +    v = sqlite3GetVdbe(pParse);
1.108239 +    sqlite3ChangeCookie(pParse, iDb);
1.108240 +
1.108241 +    sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
1.108242 +    zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
1.108243 +    sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
1.108244 +    sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
1.108245 +                         pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
1.108246 +  }
1.108247 +
1.108248 +  /* If we are rereading the sqlite_master table create the in-memory
1.108249 +  ** record of the table. The xConnect() method is not called until
1.108250 +  ** the first time the virtual table is used in an SQL statement. This
1.108251 +  ** allows a schema that contains virtual tables to be loaded before
1.108252 +  ** the required virtual table implementations are registered.  */
1.108253 +  else {
1.108254 +    Table *pOld;
1.108255 +    Schema *pSchema = pTab->pSchema;
1.108256 +    const char *zName = pTab->zName;
1.108257 +    int nName = sqlite3Strlen30(zName);
1.108258 +    assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
1.108259 +    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
1.108260 +    if( pOld ){
1.108261 +      db->mallocFailed = 1;
1.108262 +      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
1.108263 +      return;
1.108264 +    }
1.108265 +    pParse->pNewTable = 0;
1.108266 +  }
1.108267 +}
1.108268 +
1.108269 +/*
1.108270 +** The parser calls this routine when it sees the first token
1.108271 +** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
1.108272 +*/
1.108273 +SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
1.108274 +  addArgumentToVtab(pParse);
1.108275 +  pParse->sArg.z = 0;
1.108276 +  pParse->sArg.n = 0;
1.108277 +}
1.108278 +
1.108279 +/*
1.108280 +** The parser calls this routine for each token after the first token
1.108281 +** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
1.108282 +*/
1.108283 +SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
1.108284 +  Token *pArg = &pParse->sArg;
1.108285 +  if( pArg->z==0 ){
1.108286 +    pArg->z = p->z;
1.108287 +    pArg->n = p->n;
1.108288 +  }else{
1.108289 +    assert(pArg->z < p->z);
1.108290 +    pArg->n = (int)(&p->z[p->n] - pArg->z);
1.108291 +  }
1.108292 +}
1.108293 +
1.108294 +/*
1.108295 +** Invoke a virtual table constructor (either xCreate or xConnect). The
1.108296 +** pointer to the function to invoke is passed as the fourth parameter
1.108297 +** to this procedure.
1.108298 +*/
1.108299 +static int vtabCallConstructor(
1.108300 +  sqlite3 *db, 
1.108301 +  Table *pTab,
1.108302 +  Module *pMod,
1.108303 +  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
1.108304 +  char **pzErr
1.108305 +){
1.108306 +  VtabCtx sCtx, *pPriorCtx;
1.108307 +  VTable *pVTable;
1.108308 +  int rc;
1.108309 +  const char *const*azArg = (const char *const*)pTab->azModuleArg;
1.108310 +  int nArg = pTab->nModuleArg;
1.108311 +  char *zErr = 0;
1.108312 +  char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
1.108313 +  int iDb;
1.108314 +
1.108315 +  if( !zModuleName ){
1.108316 +    return SQLITE_NOMEM;
1.108317 +  }
1.108318 +
1.108319 +  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
1.108320 +  if( !pVTable ){
1.108321 +    sqlite3DbFree(db, zModuleName);
1.108322 +    return SQLITE_NOMEM;
1.108323 +  }
1.108324 +  pVTable->db = db;
1.108325 +  pVTable->pMod = pMod;
1.108326 +
1.108327 +  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1.108328 +  pTab->azModuleArg[1] = db->aDb[iDb].zName;
1.108329 +
1.108330 +  /* Invoke the virtual table constructor */
1.108331 +  assert( &db->pVtabCtx );
1.108332 +  assert( xConstruct );
1.108333 +  sCtx.pTab = pTab;
1.108334 +  sCtx.pVTable = pVTable;
1.108335 +  pPriorCtx = db->pVtabCtx;
1.108336 +  db->pVtabCtx = &sCtx;
1.108337 +  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
1.108338 +  db->pVtabCtx = pPriorCtx;
1.108339 +  if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
1.108340 +
1.108341 +  if( SQLITE_OK!=rc ){
1.108342 +    if( zErr==0 ){
1.108343 +      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
1.108344 +    }else {
1.108345 +      *pzErr = sqlite3MPrintf(db, "%s", zErr);
1.108346 +      sqlite3_free(zErr);
1.108347 +    }
1.108348 +    sqlite3DbFree(db, pVTable);
1.108349 +  }else if( ALWAYS(pVTable->pVtab) ){
1.108350 +    /* Justification of ALWAYS():  A correct vtab constructor must allocate
1.108351 +    ** the sqlite3_vtab object if successful.  */
1.108352 +    pVTable->pVtab->pModule = pMod->pModule;
1.108353 +    pVTable->nRef = 1;
1.108354 +    if( sCtx.pTab ){
1.108355 +      const char *zFormat = "vtable constructor did not declare schema: %s";
1.108356 +      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
1.108357 +      sqlite3VtabUnlock(pVTable);
1.108358 +      rc = SQLITE_ERROR;
1.108359 +    }else{
1.108360 +      int iCol;
1.108361 +      /* If everything went according to plan, link the new VTable structure
1.108362 +      ** into the linked list headed by pTab->pVTable. Then loop through the 
1.108363 +      ** columns of the table to see if any of them contain the token "hidden".
1.108364 +      ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
1.108365 +      ** the type string.  */
1.108366 +      pVTable->pNext = pTab->pVTable;
1.108367 +      pTab->pVTable = pVTable;
1.108368 +
1.108369 +      for(iCol=0; iCol<pTab->nCol; iCol++){
1.108370 +        char *zType = pTab->aCol[iCol].zType;
1.108371 +        int nType;
1.108372 +        int i = 0;
1.108373 +        if( !zType ) continue;
1.108374 +        nType = sqlite3Strlen30(zType);
1.108375 +        if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
1.108376 +          for(i=0; i<nType; i++){
1.108377 +            if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
1.108378 +             && (zType[i+7]=='\0' || zType[i+7]==' ')
1.108379 +            ){
1.108380 +              i++;
1.108381 +              break;
1.108382 +            }
1.108383 +          }
1.108384 +        }
1.108385 +        if( i<nType ){
1.108386 +          int j;
1.108387 +          int nDel = 6 + (zType[i+6] ? 1 : 0);
1.108388 +          for(j=i; (j+nDel)<=nType; j++){
1.108389 +            zType[j] = zType[j+nDel];
1.108390 +          }
1.108391 +          if( zType[i]=='\0' && i>0 ){
1.108392 +            assert(zType[i-1]==' ');
1.108393 +            zType[i-1] = '\0';
1.108394 +          }
1.108395 +          pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
1.108396 +        }
1.108397 +      }
1.108398 +    }
1.108399 +  }
1.108400 +
1.108401 +  sqlite3DbFree(db, zModuleName);
1.108402 +  return rc;
1.108403 +}
1.108404 +
1.108405 +/*
1.108406 +** This function is invoked by the parser to call the xConnect() method
1.108407 +** of the virtual table pTab. If an error occurs, an error code is returned 
1.108408 +** and an error left in pParse.
1.108409 +**
1.108410 +** This call is a no-op if table pTab is not a virtual table.
1.108411 +*/
1.108412 +SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
1.108413 +  sqlite3 *db = pParse->db;
1.108414 +  const char *zMod;
1.108415 +  Module *pMod;
1.108416 +  int rc;
1.108417 +
1.108418 +  assert( pTab );
1.108419 +  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
1.108420 +    return SQLITE_OK;
1.108421 +  }
1.108422 +
1.108423 +  /* Locate the required virtual table module */
1.108424 +  zMod = pTab->azModuleArg[0];
1.108425 +  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
1.108426 +
1.108427 +  if( !pMod ){
1.108428 +    const char *zModule = pTab->azModuleArg[0];
1.108429 +    sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
1.108430 +    rc = SQLITE_ERROR;
1.108431 +  }else{
1.108432 +    char *zErr = 0;
1.108433 +    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
1.108434 +    if( rc!=SQLITE_OK ){
1.108435 +      sqlite3ErrorMsg(pParse, "%s", zErr);
1.108436 +    }
1.108437 +    sqlite3DbFree(db, zErr);
1.108438 +  }
1.108439 +
1.108440 +  return rc;
1.108441 +}
1.108442 +/*
1.108443 +** Grow the db->aVTrans[] array so that there is room for at least one
1.108444 +** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
1.108445 +*/
1.108446 +static int growVTrans(sqlite3 *db){
1.108447 +  const int ARRAY_INCR = 5;
1.108448 +
1.108449 +  /* Grow the sqlite3.aVTrans array if required */
1.108450 +  if( (db->nVTrans%ARRAY_INCR)==0 ){
1.108451 +    VTable **aVTrans;
1.108452 +    int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
1.108453 +    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
1.108454 +    if( !aVTrans ){
1.108455 +      return SQLITE_NOMEM;
1.108456 +    }
1.108457 +    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
1.108458 +    db->aVTrans = aVTrans;
1.108459 +  }
1.108460 +
1.108461 +  return SQLITE_OK;
1.108462 +}
1.108463 +
1.108464 +/*
1.108465 +** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
1.108466 +** have already been reserved using growVTrans().
1.108467 +*/
1.108468 +static void addToVTrans(sqlite3 *db, VTable *pVTab){
1.108469 +  /* Add pVtab to the end of sqlite3.aVTrans */
1.108470 +  db->aVTrans[db->nVTrans++] = pVTab;
1.108471 +  sqlite3VtabLock(pVTab);
1.108472 +}
1.108473 +
1.108474 +/*
1.108475 +** This function is invoked by the vdbe to call the xCreate method
1.108476 +** of the virtual table named zTab in database iDb. 
1.108477 +**
1.108478 +** If an error occurs, *pzErr is set to point an an English language
1.108479 +** description of the error and an SQLITE_XXX error code is returned.
1.108480 +** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
1.108481 +*/
1.108482 +SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
1.108483 +  int rc = SQLITE_OK;
1.108484 +  Table *pTab;
1.108485 +  Module *pMod;
1.108486 +  const char *zMod;
1.108487 +
1.108488 +  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
1.108489 +  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
1.108490 +
1.108491 +  /* Locate the required virtual table module */
1.108492 +  zMod = pTab->azModuleArg[0];
1.108493 +  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
1.108494 +
1.108495 +  /* If the module has been registered and includes a Create method, 
1.108496 +  ** invoke it now. If the module has not been registered, return an 
1.108497 +  ** error. Otherwise, do nothing.
1.108498 +  */
1.108499 +  if( !pMod ){
1.108500 +    *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
1.108501 +    rc = SQLITE_ERROR;
1.108502 +  }else{
1.108503 +    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
1.108504 +  }
1.108505 +
1.108506 +  /* Justification of ALWAYS():  The xConstructor method is required to
1.108507 +  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
1.108508 +  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
1.108509 +    rc = growVTrans(db);
1.108510 +    if( rc==SQLITE_OK ){
1.108511 +      addToVTrans(db, sqlite3GetVTable(db, pTab));
1.108512 +    }
1.108513 +  }
1.108514 +
1.108515 +  return rc;
1.108516 +}
1.108517 +
1.108518 +/*
1.108519 +** This function is used to set the schema of a virtual table.  It is only
1.108520 +** valid to call this function from within the xCreate() or xConnect() of a
1.108521 +** virtual table module.
1.108522 +*/
1.108523 +SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
1.108524 +  Parse *pParse;
1.108525 +
1.108526 +  int rc = SQLITE_OK;
1.108527 +  Table *pTab;
1.108528 +  char *zErr = 0;
1.108529 +
1.108530 +  sqlite3_mutex_enter(db->mutex);
1.108531 +  if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
1.108532 +    sqlite3Error(db, SQLITE_MISUSE, 0);
1.108533 +    sqlite3_mutex_leave(db->mutex);
1.108534 +    return SQLITE_MISUSE_BKPT;
1.108535 +  }
1.108536 +  assert( (pTab->tabFlags & TF_Virtual)!=0 );
1.108537 +
1.108538 +  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
1.108539 +  if( pParse==0 ){
1.108540 +    rc = SQLITE_NOMEM;
1.108541 +  }else{
1.108542 +    pParse->declareVtab = 1;
1.108543 +    pParse->db = db;
1.108544 +    pParse->nQueryLoop = 1;
1.108545 +  
1.108546 +    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
1.108547 +     && pParse->pNewTable
1.108548 +     && !db->mallocFailed
1.108549 +     && !pParse->pNewTable->pSelect
1.108550 +     && (pParse->pNewTable->tabFlags & TF_Virtual)==0
1.108551 +    ){
1.108552 +      if( !pTab->aCol ){
1.108553 +        pTab->aCol = pParse->pNewTable->aCol;
1.108554 +        pTab->nCol = pParse->pNewTable->nCol;
1.108555 +        pParse->pNewTable->nCol = 0;
1.108556 +        pParse->pNewTable->aCol = 0;
1.108557 +      }
1.108558 +      db->pVtabCtx->pTab = 0;
1.108559 +    }else{
1.108560 +      sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
1.108561 +      sqlite3DbFree(db, zErr);
1.108562 +      rc = SQLITE_ERROR;
1.108563 +    }
1.108564 +    pParse->declareVtab = 0;
1.108565 +  
1.108566 +    if( pParse->pVdbe ){
1.108567 +      sqlite3VdbeFinalize(pParse->pVdbe);
1.108568 +    }
1.108569 +    sqlite3DeleteTable(db, pParse->pNewTable);
1.108570 +    sqlite3ParserReset(pParse);
1.108571 +    sqlite3StackFree(db, pParse);
1.108572 +  }
1.108573 +
1.108574 +  assert( (rc&0xff)==rc );
1.108575 +  rc = sqlite3ApiExit(db, rc);
1.108576 +  sqlite3_mutex_leave(db->mutex);
1.108577 +  return rc;
1.108578 +}
1.108579 +
1.108580 +/*
1.108581 +** This function is invoked by the vdbe to call the xDestroy method
1.108582 +** of the virtual table named zTab in database iDb. This occurs
1.108583 +** when a DROP TABLE is mentioned.
1.108584 +**
1.108585 +** This call is a no-op if zTab is not a virtual table.
1.108586 +*/
1.108587 +SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
1.108588 +  int rc = SQLITE_OK;
1.108589 +  Table *pTab;
1.108590 +
1.108591 +  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
1.108592 +  if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
1.108593 +    VTable *p = vtabDisconnectAll(db, pTab);
1.108594 +
1.108595 +    assert( rc==SQLITE_OK );
1.108596 +    rc = p->pMod->pModule->xDestroy(p->pVtab);
1.108597 +
1.108598 +    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
1.108599 +    if( rc==SQLITE_OK ){
1.108600 +      assert( pTab->pVTable==p && p->pNext==0 );
1.108601 +      p->pVtab = 0;
1.108602 +      pTab->pVTable = 0;
1.108603 +      sqlite3VtabUnlock(p);
1.108604 +    }
1.108605 +  }
1.108606 +
1.108607 +  return rc;
1.108608 +}
1.108609 +
1.108610 +/*
1.108611 +** This function invokes either the xRollback or xCommit method
1.108612 +** of each of the virtual tables in the sqlite3.aVTrans array. The method
1.108613 +** called is identified by the second argument, "offset", which is
1.108614 +** the offset of the method to call in the sqlite3_module structure.
1.108615 +**
1.108616 +** The array is cleared after invoking the callbacks. 
1.108617 +*/
1.108618 +static void callFinaliser(sqlite3 *db, int offset){
1.108619 +  int i;
1.108620 +  if( db->aVTrans ){
1.108621 +    for(i=0; i<db->nVTrans; i++){
1.108622 +      VTable *pVTab = db->aVTrans[i];
1.108623 +      sqlite3_vtab *p = pVTab->pVtab;
1.108624 +      if( p ){
1.108625 +        int (*x)(sqlite3_vtab *);
1.108626 +        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
1.108627 +        if( x ) x(p);
1.108628 +      }
1.108629 +      pVTab->iSavepoint = 0;
1.108630 +      sqlite3VtabUnlock(pVTab);
1.108631 +    }
1.108632 +    sqlite3DbFree(db, db->aVTrans);
1.108633 +    db->nVTrans = 0;
1.108634 +    db->aVTrans = 0;
1.108635 +  }
1.108636 +}
1.108637 +
1.108638 +/*
1.108639 +** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
1.108640 +** array. Return the error code for the first error that occurs, or
1.108641 +** SQLITE_OK if all xSync operations are successful.
1.108642 +**
1.108643 +** If an error message is available, leave it in p->zErrMsg.
1.108644 +*/
1.108645 +SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
1.108646 +  int i;
1.108647 +  int rc = SQLITE_OK;
1.108648 +  VTable **aVTrans = db->aVTrans;
1.108649 +
1.108650 +  db->aVTrans = 0;
1.108651 +  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
1.108652 +    int (*x)(sqlite3_vtab *);
1.108653 +    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
1.108654 +    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
1.108655 +      rc = x(pVtab);
1.108656 +      sqlite3VtabImportErrmsg(p, pVtab);
1.108657 +    }
1.108658 +  }
1.108659 +  db->aVTrans = aVTrans;
1.108660 +  return rc;
1.108661 +}
1.108662 +
1.108663 +/*
1.108664 +** Invoke the xRollback method of all virtual tables in the 
1.108665 +** sqlite3.aVTrans array. Then clear the array itself.
1.108666 +*/
1.108667 +SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
1.108668 +  callFinaliser(db, offsetof(sqlite3_module,xRollback));
1.108669 +  return SQLITE_OK;
1.108670 +}
1.108671 +
1.108672 +/*
1.108673 +** Invoke the xCommit method of all virtual tables in the 
1.108674 +** sqlite3.aVTrans array. Then clear the array itself.
1.108675 +*/
1.108676 +SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
1.108677 +  callFinaliser(db, offsetof(sqlite3_module,xCommit));
1.108678 +  return SQLITE_OK;
1.108679 +}
1.108680 +
1.108681 +/*
1.108682 +** If the virtual table pVtab supports the transaction interface
1.108683 +** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
1.108684 +** not currently open, invoke the xBegin method now.
1.108685 +**
1.108686 +** If the xBegin call is successful, place the sqlite3_vtab pointer
1.108687 +** in the sqlite3.aVTrans array.
1.108688 +*/
1.108689 +SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
1.108690 +  int rc = SQLITE_OK;
1.108691 +  const sqlite3_module *pModule;
1.108692 +
1.108693 +  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
1.108694 +  ** than zero, then this function is being called from within a
1.108695 +  ** virtual module xSync() callback. It is illegal to write to 
1.108696 +  ** virtual module tables in this case, so return SQLITE_LOCKED.
1.108697 +  */
1.108698 +  if( sqlite3VtabInSync(db) ){
1.108699 +    return SQLITE_LOCKED;
1.108700 +  }
1.108701 +  if( !pVTab ){
1.108702 +    return SQLITE_OK;
1.108703 +  } 
1.108704 +  pModule = pVTab->pVtab->pModule;
1.108705 +
1.108706 +  if( pModule->xBegin ){
1.108707 +    int i;
1.108708 +
1.108709 +    /* If pVtab is already in the aVTrans array, return early */
1.108710 +    for(i=0; i<db->nVTrans; i++){
1.108711 +      if( db->aVTrans[i]==pVTab ){
1.108712 +        return SQLITE_OK;
1.108713 +      }
1.108714 +    }
1.108715 +
1.108716 +    /* Invoke the xBegin method. If successful, add the vtab to the 
1.108717 +    ** sqlite3.aVTrans[] array. */
1.108718 +    rc = growVTrans(db);
1.108719 +    if( rc==SQLITE_OK ){
1.108720 +      rc = pModule->xBegin(pVTab->pVtab);
1.108721 +      if( rc==SQLITE_OK ){
1.108722 +        addToVTrans(db, pVTab);
1.108723 +      }
1.108724 +    }
1.108725 +  }
1.108726 +  return rc;
1.108727 +}
1.108728 +
1.108729 +/*
1.108730 +** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
1.108731 +** virtual tables that currently have an open transaction. Pass iSavepoint
1.108732 +** as the second argument to the virtual table method invoked.
1.108733 +**
1.108734 +** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
1.108735 +** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is 
1.108736 +** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
1.108737 +** an open transaction is invoked.
1.108738 +**
1.108739 +** If any virtual table method returns an error code other than SQLITE_OK, 
1.108740 +** processing is abandoned and the error returned to the caller of this
1.108741 +** function immediately. If all calls to virtual table methods are successful,
1.108742 +** SQLITE_OK is returned.
1.108743 +*/
1.108744 +SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
1.108745 +  int rc = SQLITE_OK;
1.108746 +
1.108747 +  assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
1.108748 +  assert( iSavepoint>=0 );
1.108749 +  if( db->aVTrans ){
1.108750 +    int i;
1.108751 +    for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
1.108752 +      VTable *pVTab = db->aVTrans[i];
1.108753 +      const sqlite3_module *pMod = pVTab->pMod->pModule;
1.108754 +      if( pVTab->pVtab && pMod->iVersion>=2 ){
1.108755 +        int (*xMethod)(sqlite3_vtab *, int);
1.108756 +        switch( op ){
1.108757 +          case SAVEPOINT_BEGIN:
1.108758 +            xMethod = pMod->xSavepoint;
1.108759 +            pVTab->iSavepoint = iSavepoint+1;
1.108760 +            break;
1.108761 +          case SAVEPOINT_ROLLBACK:
1.108762 +            xMethod = pMod->xRollbackTo;
1.108763 +            break;
1.108764 +          default:
1.108765 +            xMethod = pMod->xRelease;
1.108766 +            break;
1.108767 +        }
1.108768 +        if( xMethod && pVTab->iSavepoint>iSavepoint ){
1.108769 +          rc = xMethod(pVTab->pVtab, iSavepoint);
1.108770 +        }
1.108771 +      }
1.108772 +    }
1.108773 +  }
1.108774 +  return rc;
1.108775 +}
1.108776 +
1.108777 +/*
1.108778 +** The first parameter (pDef) is a function implementation.  The
1.108779 +** second parameter (pExpr) is the first argument to this function.
1.108780 +** If pExpr is a column in a virtual table, then let the virtual
1.108781 +** table implementation have an opportunity to overload the function.
1.108782 +**
1.108783 +** This routine is used to allow virtual table implementations to
1.108784 +** overload MATCH, LIKE, GLOB, and REGEXP operators.
1.108785 +**
1.108786 +** Return either the pDef argument (indicating no change) or a 
1.108787 +** new FuncDef structure that is marked as ephemeral using the
1.108788 +** SQLITE_FUNC_EPHEM flag.
1.108789 +*/
1.108790 +SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
1.108791 +  sqlite3 *db,    /* Database connection for reporting malloc problems */
1.108792 +  FuncDef *pDef,  /* Function to possibly overload */
1.108793 +  int nArg,       /* Number of arguments to the function */
1.108794 +  Expr *pExpr     /* First argument to the function */
1.108795 +){
1.108796 +  Table *pTab;
1.108797 +  sqlite3_vtab *pVtab;
1.108798 +  sqlite3_module *pMod;
1.108799 +  void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
1.108800 +  void *pArg = 0;
1.108801 +  FuncDef *pNew;
1.108802 +  int rc = 0;
1.108803 +  char *zLowerName;
1.108804 +  unsigned char *z;
1.108805 +
1.108806 +
1.108807 +  /* Check to see the left operand is a column in a virtual table */
1.108808 +  if( NEVER(pExpr==0) ) return pDef;
1.108809 +  if( pExpr->op!=TK_COLUMN ) return pDef;
1.108810 +  pTab = pExpr->pTab;
1.108811 +  if( NEVER(pTab==0) ) return pDef;
1.108812 +  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
1.108813 +  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
1.108814 +  assert( pVtab!=0 );
1.108815 +  assert( pVtab->pModule!=0 );
1.108816 +  pMod = (sqlite3_module *)pVtab->pModule;
1.108817 +  if( pMod->xFindFunction==0 ) return pDef;
1.108818 + 
1.108819 +  /* Call the xFindFunction method on the virtual table implementation
1.108820 +  ** to see if the implementation wants to overload this function 
1.108821 +  */
1.108822 +  zLowerName = sqlite3DbStrDup(db, pDef->zName);
1.108823 +  if( zLowerName ){
1.108824 +    for(z=(unsigned char*)zLowerName; *z; z++){
1.108825 +      *z = sqlite3UpperToLower[*z];
1.108826 +    }
1.108827 +    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
1.108828 +    sqlite3DbFree(db, zLowerName);
1.108829 +  }
1.108830 +  if( rc==0 ){
1.108831 +    return pDef;
1.108832 +  }
1.108833 +
1.108834 +  /* Create a new ephemeral function definition for the overloaded
1.108835 +  ** function */
1.108836 +  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
1.108837 +                             + sqlite3Strlen30(pDef->zName) + 1);
1.108838 +  if( pNew==0 ){
1.108839 +    return pDef;
1.108840 +  }
1.108841 +  *pNew = *pDef;
1.108842 +  pNew->zName = (char *)&pNew[1];
1.108843 +  memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
1.108844 +  pNew->xFunc = xFunc;
1.108845 +  pNew->pUserData = pArg;
1.108846 +  pNew->funcFlags |= SQLITE_FUNC_EPHEM;
1.108847 +  return pNew;
1.108848 +}
1.108849 +
1.108850 +/*
1.108851 +** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
1.108852 +** array so that an OP_VBegin will get generated for it.  Add pTab to the
1.108853 +** array if it is missing.  If pTab is already in the array, this routine
1.108854 +** is a no-op.
1.108855 +*/
1.108856 +SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
1.108857 +  Parse *pToplevel = sqlite3ParseToplevel(pParse);
1.108858 +  int i, n;
1.108859 +  Table **apVtabLock;
1.108860 +
1.108861 +  assert( IsVirtual(pTab) );
1.108862 +  for(i=0; i<pToplevel->nVtabLock; i++){
1.108863 +    if( pTab==pToplevel->apVtabLock[i] ) return;
1.108864 +  }
1.108865 +  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
1.108866 +  apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
1.108867 +  if( apVtabLock ){
1.108868 +    pToplevel->apVtabLock = apVtabLock;
1.108869 +    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
1.108870 +  }else{
1.108871 +    pToplevel->db->mallocFailed = 1;
1.108872 +  }
1.108873 +}
1.108874 +
1.108875 +/*
1.108876 +** Return the ON CONFLICT resolution mode in effect for the virtual
1.108877 +** table update operation currently in progress.
1.108878 +**
1.108879 +** The results of this routine are undefined unless it is called from
1.108880 +** within an xUpdate method.
1.108881 +*/
1.108882 +SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
1.108883 +  static const unsigned char aMap[] = { 
1.108884 +    SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE 
1.108885 +  };
1.108886 +  assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
1.108887 +  assert( OE_Ignore==4 && OE_Replace==5 );
1.108888 +  assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
1.108889 +  return (int)aMap[db->vtabOnConflict-1];
1.108890 +}
1.108891 +
1.108892 +/*
1.108893 +** Call from within the xCreate() or xConnect() methods to provide 
1.108894 +** the SQLite core with additional information about the behavior
1.108895 +** of the virtual table being implemented.
1.108896 +*/
1.108897 +SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
1.108898 +  va_list ap;
1.108899 +  int rc = SQLITE_OK;
1.108900 +
1.108901 +  sqlite3_mutex_enter(db->mutex);
1.108902 +
1.108903 +  va_start(ap, op);
1.108904 +  switch( op ){
1.108905 +    case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
1.108906 +      VtabCtx *p = db->pVtabCtx;
1.108907 +      if( !p ){
1.108908 +        rc = SQLITE_MISUSE_BKPT;
1.108909 +      }else{
1.108910 +        assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
1.108911 +        p->pVTable->bConstraint = (u8)va_arg(ap, int);
1.108912 +      }
1.108913 +      break;
1.108914 +    }
1.108915 +    default:
1.108916 +      rc = SQLITE_MISUSE_BKPT;
1.108917 +      break;
1.108918 +  }
1.108919 +  va_end(ap);
1.108920 +
1.108921 +  if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
1.108922 +  sqlite3_mutex_leave(db->mutex);
1.108923 +  return rc;
1.108924 +}
1.108925 +
1.108926 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
1.108927 +
1.108928 +/************** End of vtab.c ************************************************/
1.108929 +/************** Begin file where.c *******************************************/
1.108930 +/*
1.108931 +** 2001 September 15
1.108932 +**
1.108933 +** The author disclaims copyright to this source code.  In place of
1.108934 +** a legal notice, here is a blessing:
1.108935 +**
1.108936 +**    May you do good and not evil.
1.108937 +**    May you find forgiveness for yourself and forgive others.
1.108938 +**    May you share freely, never taking more than you give.
1.108939 +**
1.108940 +*************************************************************************
1.108941 +** This module contains C code that generates VDBE code used to process
1.108942 +** the WHERE clause of SQL statements.  This module is responsible for
1.108943 +** generating the code that loops through a table looking for applicable
1.108944 +** rows.  Indices are selected and used to speed the search when doing
1.108945 +** so is applicable.  Because this module is responsible for selecting
1.108946 +** indices, you might also think of this module as the "query optimizer".
1.108947 +*/
1.108948 +/************** Include whereInt.h in the middle of where.c ******************/
1.108949 +/************** Begin file whereInt.h ****************************************/
1.108950 +/*
1.108951 +** 2013-11-12
1.108952 +**
1.108953 +** The author disclaims copyright to this source code.  In place of
1.108954 +** a legal notice, here is a blessing:
1.108955 +**
1.108956 +**    May you do good and not evil.
1.108957 +**    May you find forgiveness for yourself and forgive others.
1.108958 +**    May you share freely, never taking more than you give.
1.108959 +**
1.108960 +*************************************************************************
1.108961 +**
1.108962 +** This file contains structure and macro definitions for the query
1.108963 +** planner logic in "where.c".  These definitions are broken out into
1.108964 +** a separate source file for easier editing.
1.108965 +*/
1.108966 +
1.108967 +/*
1.108968 +** Trace output macros
1.108969 +*/
1.108970 +#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
1.108971 +/***/ int sqlite3WhereTrace = 0;
1.108972 +#endif
1.108973 +#if defined(SQLITE_DEBUG) \
1.108974 +    && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
1.108975 +# define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
1.108976 +# define WHERETRACE_ENABLED 1
1.108977 +#else
1.108978 +# define WHERETRACE(K,X)
1.108979 +#endif
1.108980 +
1.108981 +/* Forward references
1.108982 +*/
1.108983 +typedef struct WhereClause WhereClause;
1.108984 +typedef struct WhereMaskSet WhereMaskSet;
1.108985 +typedef struct WhereOrInfo WhereOrInfo;
1.108986 +typedef struct WhereAndInfo WhereAndInfo;
1.108987 +typedef struct WhereLevel WhereLevel;
1.108988 +typedef struct WhereLoop WhereLoop;
1.108989 +typedef struct WherePath WherePath;
1.108990 +typedef struct WhereTerm WhereTerm;
1.108991 +typedef struct WhereLoopBuilder WhereLoopBuilder;
1.108992 +typedef struct WhereScan WhereScan;
1.108993 +typedef struct WhereOrCost WhereOrCost;
1.108994 +typedef struct WhereOrSet WhereOrSet;
1.108995 +
1.108996 +/*
1.108997 +** This object contains information needed to implement a single nested
1.108998 +** loop in WHERE clause.
1.108999 +**
1.109000 +** Contrast this object with WhereLoop.  This object describes the
1.109001 +** implementation of the loop.  WhereLoop describes the algorithm.
1.109002 +** This object contains a pointer to the WhereLoop algorithm as one of
1.109003 +** its elements.
1.109004 +**
1.109005 +** The WhereInfo object contains a single instance of this object for
1.109006 +** each term in the FROM clause (which is to say, for each of the
1.109007 +** nested loops as implemented).  The order of WhereLevel objects determines
1.109008 +** the loop nested order, with WhereInfo.a[0] being the outer loop and
1.109009 +** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
1.109010 +*/
1.109011 +struct WhereLevel {
1.109012 +  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
1.109013 +  int iTabCur;          /* The VDBE cursor used to access the table */
1.109014 +  int iIdxCur;          /* The VDBE cursor used to access pIdx */
1.109015 +  int addrBrk;          /* Jump here to break out of the loop */
1.109016 +  int addrNxt;          /* Jump here to start the next IN combination */
1.109017 +  int addrSkip;         /* Jump here for next iteration of skip-scan */
1.109018 +  int addrCont;         /* Jump here to continue with the next loop cycle */
1.109019 +  int addrFirst;        /* First instruction of interior of the loop */
1.109020 +  int addrBody;         /* Beginning of the body of this loop */
1.109021 +  u8 iFrom;             /* Which entry in the FROM clause */
1.109022 +  u8 op, p3, p5;        /* Opcode, P3 & P5 of the opcode that ends the loop */
1.109023 +  int p1, p2;           /* Operands of the opcode used to ends the loop */
1.109024 +  union {               /* Information that depends on pWLoop->wsFlags */
1.109025 +    struct {
1.109026 +      int nIn;              /* Number of entries in aInLoop[] */
1.109027 +      struct InLoop {
1.109028 +        int iCur;              /* The VDBE cursor used by this IN operator */
1.109029 +        int addrInTop;         /* Top of the IN loop */
1.109030 +        u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
1.109031 +      } *aInLoop;           /* Information about each nested IN operator */
1.109032 +    } in;                 /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
1.109033 +    Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
1.109034 +  } u;
1.109035 +  struct WhereLoop *pWLoop;  /* The selected WhereLoop object */
1.109036 +  Bitmask notReady;          /* FROM entries not usable at this level */
1.109037 +};
1.109038 +
1.109039 +/*
1.109040 +** Each instance of this object represents an algorithm for evaluating one
1.109041 +** term of a join.  Every term of the FROM clause will have at least
1.109042 +** one corresponding WhereLoop object (unless INDEXED BY constraints
1.109043 +** prevent a query solution - which is an error) and many terms of the
1.109044 +** FROM clause will have multiple WhereLoop objects, each describing a
1.109045 +** potential way of implementing that FROM-clause term, together with
1.109046 +** dependencies and cost estimates for using the chosen algorithm.
1.109047 +**
1.109048 +** Query planning consists of building up a collection of these WhereLoop
1.109049 +** objects, then computing a particular sequence of WhereLoop objects, with
1.109050 +** one WhereLoop object per FROM clause term, that satisfy all dependencies
1.109051 +** and that minimize the overall cost.
1.109052 +*/
1.109053 +struct WhereLoop {
1.109054 +  Bitmask prereq;       /* Bitmask of other loops that must run first */
1.109055 +  Bitmask maskSelf;     /* Bitmask identifying table iTab */
1.109056 +#ifdef SQLITE_DEBUG
1.109057 +  char cId;             /* Symbolic ID of this loop for debugging use */
1.109058 +#endif
1.109059 +  u8 iTab;              /* Position in FROM clause of table for this loop */
1.109060 +  u8 iSortIdx;          /* Sorting index number.  0==None */
1.109061 +  LogEst rSetup;        /* One-time setup cost (ex: create transient index) */
1.109062 +  LogEst rRun;          /* Cost of running each loop */
1.109063 +  LogEst nOut;          /* Estimated number of output rows */
1.109064 +  union {
1.109065 +    struct {               /* Information for internal btree tables */
1.109066 +      u16 nEq;               /* Number of equality constraints */
1.109067 +      u16 nSkip;             /* Number of initial index columns to skip */
1.109068 +      Index *pIndex;         /* Index used, or NULL */
1.109069 +    } btree;
1.109070 +    struct {               /* Information for virtual tables */
1.109071 +      int idxNum;            /* Index number */
1.109072 +      u8 needFree;           /* True if sqlite3_free(idxStr) is needed */
1.109073 +      u8 isOrdered;          /* True if satisfies ORDER BY */
1.109074 +      u16 omitMask;          /* Terms that may be omitted */
1.109075 +      char *idxStr;          /* Index identifier string */
1.109076 +    } vtab;
1.109077 +  } u;
1.109078 +  u32 wsFlags;          /* WHERE_* flags describing the plan */
1.109079 +  u16 nLTerm;           /* Number of entries in aLTerm[] */
1.109080 +  /**** whereLoopXfer() copies fields above ***********************/
1.109081 +# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
1.109082 +  u16 nLSlot;           /* Number of slots allocated for aLTerm[] */
1.109083 +  WhereTerm **aLTerm;   /* WhereTerms used */
1.109084 +  WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
1.109085 +  WhereTerm *aLTermSpace[4];  /* Initial aLTerm[] space */
1.109086 +};
1.109087 +
1.109088 +/* This object holds the prerequisites and the cost of running a
1.109089 +** subquery on one operand of an OR operator in the WHERE clause.
1.109090 +** See WhereOrSet for additional information 
1.109091 +*/
1.109092 +struct WhereOrCost {
1.109093 +  Bitmask prereq;     /* Prerequisites */
1.109094 +  LogEst rRun;        /* Cost of running this subquery */
1.109095 +  LogEst nOut;        /* Number of outputs for this subquery */
1.109096 +};
1.109097 +
1.109098 +/* The WhereOrSet object holds a set of possible WhereOrCosts that
1.109099 +** correspond to the subquery(s) of OR-clause processing.  Only the
1.109100 +** best N_OR_COST elements are retained.
1.109101 +*/
1.109102 +#define N_OR_COST 3
1.109103 +struct WhereOrSet {
1.109104 +  u16 n;                      /* Number of valid a[] entries */
1.109105 +  WhereOrCost a[N_OR_COST];   /* Set of best costs */
1.109106 +};
1.109107 +
1.109108 +
1.109109 +/* Forward declaration of methods */
1.109110 +static int whereLoopResize(sqlite3*, WhereLoop*, int);
1.109111 +
1.109112 +/*
1.109113 +** Each instance of this object holds a sequence of WhereLoop objects
1.109114 +** that implement some or all of a query plan.
1.109115 +**
1.109116 +** Think of each WhereLoop object as a node in a graph with arcs
1.109117 +** showing dependencies and costs for travelling between nodes.  (That is
1.109118 +** not a completely accurate description because WhereLoop costs are a
1.109119 +** vector, not a scalar, and because dependencies are many-to-one, not
1.109120 +** one-to-one as are graph nodes.  But it is a useful visualization aid.)
1.109121 +** Then a WherePath object is a path through the graph that visits some
1.109122 +** or all of the WhereLoop objects once.
1.109123 +**
1.109124 +** The "solver" works by creating the N best WherePath objects of length
1.109125 +** 1.  Then using those as a basis to compute the N best WherePath objects
1.109126 +** of length 2.  And so forth until the length of WherePaths equals the
1.109127 +** number of nodes in the FROM clause.  The best (lowest cost) WherePath
1.109128 +** at the end is the choosen query plan.
1.109129 +*/
1.109130 +struct WherePath {
1.109131 +  Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */
1.109132 +  Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */
1.109133 +  LogEst nRow;          /* Estimated number of rows generated by this path */
1.109134 +  LogEst rCost;         /* Total cost of this path */
1.109135 +  u8 isOrdered;         /* True if this path satisfies ORDER BY */
1.109136 +  u8 isOrderedValid;    /* True if the isOrdered field is valid */
1.109137 +  WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */
1.109138 +};
1.109139 +
1.109140 +/*
1.109141 +** The query generator uses an array of instances of this structure to
1.109142 +** help it analyze the subexpressions of the WHERE clause.  Each WHERE
1.109143 +** clause subexpression is separated from the others by AND operators,
1.109144 +** usually, or sometimes subexpressions separated by OR.
1.109145 +**
1.109146 +** All WhereTerms are collected into a single WhereClause structure.  
1.109147 +** The following identity holds:
1.109148 +**
1.109149 +**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
1.109150 +**
1.109151 +** When a term is of the form:
1.109152 +**
1.109153 +**              X <op> <expr>
1.109154 +**
1.109155 +** where X is a column name and <op> is one of certain operators,
1.109156 +** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
1.109157 +** cursor number and column number for X.  WhereTerm.eOperator records
1.109158 +** the <op> using a bitmask encoding defined by WO_xxx below.  The
1.109159 +** use of a bitmask encoding for the operator allows us to search
1.109160 +** quickly for terms that match any of several different operators.
1.109161 +**
1.109162 +** A WhereTerm might also be two or more subterms connected by OR:
1.109163 +**
1.109164 +**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
1.109165 +**
1.109166 +** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
1.109167 +** and the WhereTerm.u.pOrInfo field points to auxiliary information that
1.109168 +** is collected about the OR clause.
1.109169 +**
1.109170 +** If a term in the WHERE clause does not match either of the two previous
1.109171 +** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
1.109172 +** to the original subexpression content and wtFlags is set up appropriately
1.109173 +** but no other fields in the WhereTerm object are meaningful.
1.109174 +**
1.109175 +** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
1.109176 +** but they do so indirectly.  A single WhereMaskSet structure translates
1.109177 +** cursor number into bits and the translated bit is stored in the prereq
1.109178 +** fields.  The translation is used in order to maximize the number of
1.109179 +** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
1.109180 +** spread out over the non-negative integers.  For example, the cursor
1.109181 +** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
1.109182 +** translates these sparse cursor numbers into consecutive integers
1.109183 +** beginning with 0 in order to make the best possible use of the available
1.109184 +** bits in the Bitmask.  So, in the example above, the cursor numbers
1.109185 +** would be mapped into integers 0 through 7.
1.109186 +**
1.109187 +** The number of terms in a join is limited by the number of bits
1.109188 +** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
1.109189 +** is only able to process joins with 64 or fewer tables.
1.109190 +*/
1.109191 +struct WhereTerm {
1.109192 +  Expr *pExpr;            /* Pointer to the subexpression that is this term */
1.109193 +  int iParent;            /* Disable pWC->a[iParent] when this term disabled */
1.109194 +  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
1.109195 +  union {
1.109196 +    int leftColumn;         /* Column number of X in "X <op> <expr>" */
1.109197 +    WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
1.109198 +    WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
1.109199 +  } u;
1.109200 +  LogEst truthProb;       /* Probability of truth for this expression */
1.109201 +  u16 eOperator;          /* A WO_xx value describing <op> */
1.109202 +  u8 wtFlags;             /* TERM_xxx bit flags.  See below */
1.109203 +  u8 nChild;              /* Number of children that must disable us */
1.109204 +  WhereClause *pWC;       /* The clause this term is part of */
1.109205 +  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
1.109206 +  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
1.109207 +};
1.109208 +
1.109209 +/*
1.109210 +** Allowed values of WhereTerm.wtFlags
1.109211 +*/
1.109212 +#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
1.109213 +#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
1.109214 +#define TERM_CODED      0x04   /* This term is already coded */
1.109215 +#define TERM_COPIED     0x08   /* Has a child */
1.109216 +#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
1.109217 +#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
1.109218 +#define TERM_OR_OK      0x40   /* Used during OR-clause processing */
1.109219 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1.109220 +#  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
1.109221 +#else
1.109222 +#  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
1.109223 +#endif
1.109224 +
1.109225 +/*
1.109226 +** An instance of the WhereScan object is used as an iterator for locating
1.109227 +** terms in the WHERE clause that are useful to the query planner.
1.109228 +*/
1.109229 +struct WhereScan {
1.109230 +  WhereClause *pOrigWC;      /* Original, innermost WhereClause */
1.109231 +  WhereClause *pWC;          /* WhereClause currently being scanned */
1.109232 +  char *zCollName;           /* Required collating sequence, if not NULL */
1.109233 +  char idxaff;               /* Must match this affinity, if zCollName!=NULL */
1.109234 +  unsigned char nEquiv;      /* Number of entries in aEquiv[] */
1.109235 +  unsigned char iEquiv;      /* Next unused slot in aEquiv[] */
1.109236 +  u32 opMask;                /* Acceptable operators */
1.109237 +  int k;                     /* Resume scanning at this->pWC->a[this->k] */
1.109238 +  int aEquiv[22];            /* Cursor,Column pairs for equivalence classes */
1.109239 +};
1.109240 +
1.109241 +/*
1.109242 +** An instance of the following structure holds all information about a
1.109243 +** WHERE clause.  Mostly this is a container for one or more WhereTerms.
1.109244 +**
1.109245 +** Explanation of pOuter:  For a WHERE clause of the form
1.109246 +**
1.109247 +**           a AND ((b AND c) OR (d AND e)) AND f
1.109248 +**
1.109249 +** There are separate WhereClause objects for the whole clause and for
1.109250 +** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
1.109251 +** subclauses points to the WhereClause object for the whole clause.
1.109252 +*/
1.109253 +struct WhereClause {
1.109254 +  WhereInfo *pWInfo;       /* WHERE clause processing context */
1.109255 +  WhereClause *pOuter;     /* Outer conjunction */
1.109256 +  u8 op;                   /* Split operator.  TK_AND or TK_OR */
1.109257 +  int nTerm;               /* Number of terms */
1.109258 +  int nSlot;               /* Number of entries in a[] */
1.109259 +  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
1.109260 +#if defined(SQLITE_SMALL_STACK)
1.109261 +  WhereTerm aStatic[1];    /* Initial static space for a[] */
1.109262 +#else
1.109263 +  WhereTerm aStatic[8];    /* Initial static space for a[] */
1.109264 +#endif
1.109265 +};
1.109266 +
1.109267 +/*
1.109268 +** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
1.109269 +** a dynamically allocated instance of the following structure.
1.109270 +*/
1.109271 +struct WhereOrInfo {
1.109272 +  WhereClause wc;          /* Decomposition into subterms */
1.109273 +  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
1.109274 +};
1.109275 +
1.109276 +/*
1.109277 +** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
1.109278 +** a dynamically allocated instance of the following structure.
1.109279 +*/
1.109280 +struct WhereAndInfo {
1.109281 +  WhereClause wc;          /* The subexpression broken out */
1.109282 +};
1.109283 +
1.109284 +/*
1.109285 +** An instance of the following structure keeps track of a mapping
1.109286 +** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
1.109287 +**
1.109288 +** The VDBE cursor numbers are small integers contained in 
1.109289 +** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
1.109290 +** clause, the cursor numbers might not begin with 0 and they might
1.109291 +** contain gaps in the numbering sequence.  But we want to make maximum
1.109292 +** use of the bits in our bitmasks.  This structure provides a mapping
1.109293 +** from the sparse cursor numbers into consecutive integers beginning
1.109294 +** with 0.
1.109295 +**
1.109296 +** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
1.109297 +** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
1.109298 +**
1.109299 +** For example, if the WHERE clause expression used these VDBE
1.109300 +** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
1.109301 +** would map those cursor numbers into bits 0 through 5.
1.109302 +**
1.109303 +** Note that the mapping is not necessarily ordered.  In the example
1.109304 +** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
1.109305 +** 57->5, 73->4.  Or one of 719 other combinations might be used. It
1.109306 +** does not really matter.  What is important is that sparse cursor
1.109307 +** numbers all get mapped into bit numbers that begin with 0 and contain
1.109308 +** no gaps.
1.109309 +*/
1.109310 +struct WhereMaskSet {
1.109311 +  int n;                        /* Number of assigned cursor values */
1.109312 +  int ix[BMS];                  /* Cursor assigned to each bit */
1.109313 +};
1.109314 +
1.109315 +/*
1.109316 +** This object is a convenience wrapper holding all information needed
1.109317 +** to construct WhereLoop objects for a particular query.
1.109318 +*/
1.109319 +struct WhereLoopBuilder {
1.109320 +  WhereInfo *pWInfo;        /* Information about this WHERE */
1.109321 +  WhereClause *pWC;         /* WHERE clause terms */
1.109322 +  ExprList *pOrderBy;       /* ORDER BY clause */
1.109323 +  WhereLoop *pNew;          /* Template WhereLoop */
1.109324 +  WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */
1.109325 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1.109326 +  UnpackedRecord *pRec;     /* Probe for stat4 (if required) */
1.109327 +  int nRecValid;            /* Number of valid fields currently in pRec */
1.109328 +#endif
1.109329 +};
1.109330 +
1.109331 +/*
1.109332 +** The WHERE clause processing routine has two halves.  The
1.109333 +** first part does the start of the WHERE loop and the second
1.109334 +** half does the tail of the WHERE loop.  An instance of
1.109335 +** this structure is returned by the first half and passed
1.109336 +** into the second half to give some continuity.
1.109337 +**
1.109338 +** An instance of this object holds the complete state of the query
1.109339 +** planner.
1.109340 +*/
1.109341 +struct WhereInfo {
1.109342 +  Parse *pParse;            /* Parsing and code generating context */
1.109343 +  SrcList *pTabList;        /* List of tables in the join */
1.109344 +  ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
1.109345 +  ExprList *pResultSet;     /* Result set. DISTINCT operates on these */
1.109346 +  WhereLoop *pLoops;        /* List of all WhereLoop objects */
1.109347 +  Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
1.109348 +  LogEst nRowOut;           /* Estimated number of output rows */
1.109349 +  u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
1.109350 +  u8 bOBSat;                /* ORDER BY satisfied by indices */
1.109351 +  u8 okOnePass;             /* Ok to use one-pass algorithm for UPDATE/DELETE */
1.109352 +  u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
1.109353 +  u8 eDistinct;             /* One of the WHERE_DISTINCT_* values below */
1.109354 +  u8 nLevel;                /* Number of nested loop */
1.109355 +  int iTop;                 /* The very beginning of the WHERE loop */
1.109356 +  int iContinue;            /* Jump here to continue with next record */
1.109357 +  int iBreak;               /* Jump here to break out of the loop */
1.109358 +  int savedNQueryLoop;      /* pParse->nQueryLoop outside the WHERE loop */
1.109359 +  int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */
1.109360 +  WhereMaskSet sMaskSet;    /* Map cursor numbers to bitmasks */
1.109361 +  WhereClause sWC;          /* Decomposition of the WHERE clause */
1.109362 +  WhereLevel a[1];          /* Information about each nest loop in WHERE */
1.109363 +};
1.109364 +
1.109365 +/*
1.109366 +** Bitmasks for the operators on WhereTerm objects.  These are all
1.109367 +** operators that are of interest to the query planner.  An
1.109368 +** OR-ed combination of these values can be used when searching for
1.109369 +** particular WhereTerms within a WhereClause.
1.109370 +*/
1.109371 +#define WO_IN     0x001
1.109372 +#define WO_EQ     0x002
1.109373 +#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
1.109374 +#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
1.109375 +#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
1.109376 +#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
1.109377 +#define WO_MATCH  0x040
1.109378 +#define WO_ISNULL 0x080
1.109379 +#define WO_OR     0x100       /* Two or more OR-connected terms */
1.109380 +#define WO_AND    0x200       /* Two or more AND-connected terms */
1.109381 +#define WO_EQUIV  0x400       /* Of the form A==B, both columns */
1.109382 +#define WO_NOOP   0x800       /* This term does not restrict search space */
1.109383 +
1.109384 +#define WO_ALL    0xfff       /* Mask of all possible WO_* values */
1.109385 +#define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
1.109386 +
1.109387 +/*
1.109388 +** These are definitions of bits in the WhereLoop.wsFlags field.
1.109389 +** The particular combination of bits in each WhereLoop help to
1.109390 +** determine the algorithm that WhereLoop represents.
1.109391 +*/
1.109392 +#define WHERE_COLUMN_EQ    0x00000001  /* x=EXPR */
1.109393 +#define WHERE_COLUMN_RANGE 0x00000002  /* x<EXPR and/or x>EXPR */
1.109394 +#define WHERE_COLUMN_IN    0x00000004  /* x IN (...) */
1.109395 +#define WHERE_COLUMN_NULL  0x00000008  /* x IS NULL */
1.109396 +#define WHERE_CONSTRAINT   0x0000000f  /* Any of the WHERE_COLUMN_xxx values */
1.109397 +#define WHERE_TOP_LIMIT    0x00000010  /* x<EXPR or x<=EXPR constraint */
1.109398 +#define WHERE_BTM_LIMIT    0x00000020  /* x>EXPR or x>=EXPR constraint */
1.109399 +#define WHERE_BOTH_LIMIT   0x00000030  /* Both x>EXPR and x<EXPR */
1.109400 +#define WHERE_IDX_ONLY     0x00000040  /* Use index only - omit table */
1.109401 +#define WHERE_IPK          0x00000100  /* x is the INTEGER PRIMARY KEY */
1.109402 +#define WHERE_INDEXED      0x00000200  /* WhereLoop.u.btree.pIndex is valid */
1.109403 +#define WHERE_VIRTUALTABLE 0x00000400  /* WhereLoop.u.vtab is valid */
1.109404 +#define WHERE_IN_ABLE      0x00000800  /* Able to support an IN operator */
1.109405 +#define WHERE_ONEROW       0x00001000  /* Selects no more than one row */
1.109406 +#define WHERE_MULTI_OR     0x00002000  /* OR using multiple indices */
1.109407 +#define WHERE_AUTO_INDEX   0x00004000  /* Uses an ephemeral index */
1.109408 +#define WHERE_SKIPSCAN     0x00008000  /* Uses the skip-scan algorithm */
1.109409 +#define WHERE_UNQ_WANTED   0x00010000  /* WHERE_ONEROW would have been helpful*/
1.109410 +
1.109411 +/************** End of whereInt.h ********************************************/
1.109412 +/************** Continuing where we left off in where.c **********************/
1.109413 +
1.109414 +/*
1.109415 +** Return the estimated number of output rows from a WHERE clause
1.109416 +*/
1.109417 +SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
1.109418 +  return sqlite3LogEstToInt(pWInfo->nRowOut);
1.109419 +}
1.109420 +
1.109421 +/*
1.109422 +** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
1.109423 +** WHERE clause returns outputs for DISTINCT processing.
1.109424 +*/
1.109425 +SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
1.109426 +  return pWInfo->eDistinct;
1.109427 +}
1.109428 +
1.109429 +/*
1.109430 +** Return TRUE if the WHERE clause returns rows in ORDER BY order.
1.109431 +** Return FALSE if the output needs to be sorted.
1.109432 +*/
1.109433 +SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
1.109434 +  return pWInfo->bOBSat!=0;
1.109435 +}
1.109436 +
1.109437 +/*
1.109438 +** Return the VDBE address or label to jump to in order to continue
1.109439 +** immediately with the next row of a WHERE clause.
1.109440 +*/
1.109441 +SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
1.109442 +  return pWInfo->iContinue;
1.109443 +}
1.109444 +
1.109445 +/*
1.109446 +** Return the VDBE address or label to jump to in order to break
1.109447 +** out of a WHERE loop.
1.109448 +*/
1.109449 +SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
1.109450 +  return pWInfo->iBreak;
1.109451 +}
1.109452 +
1.109453 +/*
1.109454 +** Return TRUE if an UPDATE or DELETE statement can operate directly on
1.109455 +** the rowids returned by a WHERE clause.  Return FALSE if doing an
1.109456 +** UPDATE or DELETE might change subsequent WHERE clause results.
1.109457 +**
1.109458 +** If the ONEPASS optimization is used (if this routine returns true)
1.109459 +** then also write the indices of open cursors used by ONEPASS
1.109460 +** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
1.109461 +** table and iaCur[1] gets the cursor used by an auxiliary index.
1.109462 +** Either value may be -1, indicating that cursor is not used.
1.109463 +** Any cursors returned will have been opened for writing.
1.109464 +**
1.109465 +** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
1.109466 +** unable to use the ONEPASS optimization.
1.109467 +*/
1.109468 +SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
1.109469 +  memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
1.109470 +  return pWInfo->okOnePass;
1.109471 +}
1.109472 +
1.109473 +/*
1.109474 +** Move the content of pSrc into pDest
1.109475 +*/
1.109476 +static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
1.109477 +  pDest->n = pSrc->n;
1.109478 +  memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
1.109479 +}
1.109480 +
1.109481 +/*
1.109482 +** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
1.109483 +**
1.109484 +** The new entry might overwrite an existing entry, or it might be
1.109485 +** appended, or it might be discarded.  Do whatever is the right thing
1.109486 +** so that pSet keeps the N_OR_COST best entries seen so far.
1.109487 +*/
1.109488 +static int whereOrInsert(
1.109489 +  WhereOrSet *pSet,      /* The WhereOrSet to be updated */
1.109490 +  Bitmask prereq,        /* Prerequisites of the new entry */
1.109491 +  LogEst rRun,           /* Run-cost of the new entry */
1.109492 +  LogEst nOut            /* Number of outputs for the new entry */
1.109493 +){
1.109494 +  u16 i;
1.109495 +  WhereOrCost *p;
1.109496 +  for(i=pSet->n, p=pSet->a; i>0; i--, p++){
1.109497 +    if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
1.109498 +      goto whereOrInsert_done;
1.109499 +    }
1.109500 +    if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
1.109501 +      return 0;
1.109502 +    }
1.109503 +  }
1.109504 +  if( pSet->n<N_OR_COST ){
1.109505 +    p = &pSet->a[pSet->n++];
1.109506 +    p->nOut = nOut;
1.109507 +  }else{
1.109508 +    p = pSet->a;
1.109509 +    for(i=1; i<pSet->n; i++){
1.109510 +      if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
1.109511 +    }
1.109512 +    if( p->rRun<=rRun ) return 0;
1.109513 +  }
1.109514 +whereOrInsert_done:
1.109515 +  p->prereq = prereq;
1.109516 +  p->rRun = rRun;
1.109517 +  if( p->nOut>nOut ) p->nOut = nOut;
1.109518 +  return 1;
1.109519 +}
1.109520 +
1.109521 +/*
1.109522 +** Initialize a preallocated WhereClause structure.
1.109523 +*/
1.109524 +static void whereClauseInit(
1.109525 +  WhereClause *pWC,        /* The WhereClause to be initialized */
1.109526 +  WhereInfo *pWInfo        /* The WHERE processing context */
1.109527 +){
1.109528 +  pWC->pWInfo = pWInfo;
1.109529 +  pWC->pOuter = 0;
1.109530 +  pWC->nTerm = 0;
1.109531 +  pWC->nSlot = ArraySize(pWC->aStatic);
1.109532 +  pWC->a = pWC->aStatic;
1.109533 +}
1.109534 +
1.109535 +/* Forward reference */
1.109536 +static void whereClauseClear(WhereClause*);
1.109537 +
1.109538 +/*
1.109539 +** Deallocate all memory associated with a WhereOrInfo object.
1.109540 +*/
1.109541 +static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
1.109542 +  whereClauseClear(&p->wc);
1.109543 +  sqlite3DbFree(db, p);
1.109544 +}
1.109545 +
1.109546 +/*
1.109547 +** Deallocate all memory associated with a WhereAndInfo object.
1.109548 +*/
1.109549 +static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
1.109550 +  whereClauseClear(&p->wc);
1.109551 +  sqlite3DbFree(db, p);
1.109552 +}
1.109553 +
1.109554 +/*
1.109555 +** Deallocate a WhereClause structure.  The WhereClause structure
1.109556 +** itself is not freed.  This routine is the inverse of whereClauseInit().
1.109557 +*/
1.109558 +static void whereClauseClear(WhereClause *pWC){
1.109559 +  int i;
1.109560 +  WhereTerm *a;
1.109561 +  sqlite3 *db = pWC->pWInfo->pParse->db;
1.109562 +  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
1.109563 +    if( a->wtFlags & TERM_DYNAMIC ){
1.109564 +      sqlite3ExprDelete(db, a->pExpr);
1.109565 +    }
1.109566 +    if( a->wtFlags & TERM_ORINFO ){
1.109567 +      whereOrInfoDelete(db, a->u.pOrInfo);
1.109568 +    }else if( a->wtFlags & TERM_ANDINFO ){
1.109569 +      whereAndInfoDelete(db, a->u.pAndInfo);
1.109570 +    }
1.109571 +  }
1.109572 +  if( pWC->a!=pWC->aStatic ){
1.109573 +    sqlite3DbFree(db, pWC->a);
1.109574 +  }
1.109575 +}
1.109576 +
1.109577 +/*
1.109578 +** Add a single new WhereTerm entry to the WhereClause object pWC.
1.109579 +** The new WhereTerm object is constructed from Expr p and with wtFlags.
1.109580 +** The index in pWC->a[] of the new WhereTerm is returned on success.
1.109581 +** 0 is returned if the new WhereTerm could not be added due to a memory
1.109582 +** allocation error.  The memory allocation failure will be recorded in
1.109583 +** the db->mallocFailed flag so that higher-level functions can detect it.
1.109584 +**
1.109585 +** This routine will increase the size of the pWC->a[] array as necessary.
1.109586 +**
1.109587 +** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
1.109588 +** for freeing the expression p is assumed by the WhereClause object pWC.
1.109589 +** This is true even if this routine fails to allocate a new WhereTerm.
1.109590 +**
1.109591 +** WARNING:  This routine might reallocate the space used to store
1.109592 +** WhereTerms.  All pointers to WhereTerms should be invalidated after
1.109593 +** calling this routine.  Such pointers may be reinitialized by referencing
1.109594 +** the pWC->a[] array.
1.109595 +*/
1.109596 +static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
1.109597 +  WhereTerm *pTerm;
1.109598 +  int idx;
1.109599 +  testcase( wtFlags & TERM_VIRTUAL );
1.109600 +  if( pWC->nTerm>=pWC->nSlot ){
1.109601 +    WhereTerm *pOld = pWC->a;
1.109602 +    sqlite3 *db = pWC->pWInfo->pParse->db;
1.109603 +    pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
1.109604 +    if( pWC->a==0 ){
1.109605 +      if( wtFlags & TERM_DYNAMIC ){
1.109606 +        sqlite3ExprDelete(db, p);
1.109607 +      }
1.109608 +      pWC->a = pOld;
1.109609 +      return 0;
1.109610 +    }
1.109611 +    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
1.109612 +    if( pOld!=pWC->aStatic ){
1.109613 +      sqlite3DbFree(db, pOld);
1.109614 +    }
1.109615 +    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
1.109616 +  }
1.109617 +  pTerm = &pWC->a[idx = pWC->nTerm++];
1.109618 +  if( p && ExprHasProperty(p, EP_Unlikely) ){
1.109619 +    pTerm->truthProb = sqlite3LogEst(p->iTable) - 99;
1.109620 +  }else{
1.109621 +    pTerm->truthProb = -1;
1.109622 +  }
1.109623 +  pTerm->pExpr = sqlite3ExprSkipCollate(p);
1.109624 +  pTerm->wtFlags = wtFlags;
1.109625 +  pTerm->pWC = pWC;
1.109626 +  pTerm->iParent = -1;
1.109627 +  return idx;
1.109628 +}
1.109629 +
1.109630 +/*
1.109631 +** This routine identifies subexpressions in the WHERE clause where
1.109632 +** each subexpression is separated by the AND operator or some other
1.109633 +** operator specified in the op parameter.  The WhereClause structure
1.109634 +** is filled with pointers to subexpressions.  For example:
1.109635 +**
1.109636 +**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
1.109637 +**           \________/     \_______________/     \________________/
1.109638 +**            slot[0]            slot[1]               slot[2]
1.109639 +**
1.109640 +** The original WHERE clause in pExpr is unaltered.  All this routine
1.109641 +** does is make slot[] entries point to substructure within pExpr.
1.109642 +**
1.109643 +** In the previous sentence and in the diagram, "slot[]" refers to
1.109644 +** the WhereClause.a[] array.  The slot[] array grows as needed to contain
1.109645 +** all terms of the WHERE clause.
1.109646 +*/
1.109647 +static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
1.109648 +  pWC->op = op;
1.109649 +  if( pExpr==0 ) return;
1.109650 +  if( pExpr->op!=op ){
1.109651 +    whereClauseInsert(pWC, pExpr, 0);
1.109652 +  }else{
1.109653 +    whereSplit(pWC, pExpr->pLeft, op);
1.109654 +    whereSplit(pWC, pExpr->pRight, op);
1.109655 +  }
1.109656 +}
1.109657 +
1.109658 +/*
1.109659 +** Initialize a WhereMaskSet object
1.109660 +*/
1.109661 +#define initMaskSet(P)  (P)->n=0
1.109662 +
1.109663 +/*
1.109664 +** Return the bitmask for the given cursor number.  Return 0 if
1.109665 +** iCursor is not in the set.
1.109666 +*/
1.109667 +static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
1.109668 +  int i;
1.109669 +  assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
1.109670 +  for(i=0; i<pMaskSet->n; i++){
1.109671 +    if( pMaskSet->ix[i]==iCursor ){
1.109672 +      return MASKBIT(i);
1.109673 +    }
1.109674 +  }
1.109675 +  return 0;
1.109676 +}
1.109677 +
1.109678 +/*
1.109679 +** Create a new mask for cursor iCursor.
1.109680 +**
1.109681 +** There is one cursor per table in the FROM clause.  The number of
1.109682 +** tables in the FROM clause is limited by a test early in the
1.109683 +** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
1.109684 +** array will never overflow.
1.109685 +*/
1.109686 +static void createMask(WhereMaskSet *pMaskSet, int iCursor){
1.109687 +  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
1.109688 +  pMaskSet->ix[pMaskSet->n++] = iCursor;
1.109689 +}
1.109690 +
1.109691 +/*
1.109692 +** These routines walk (recursively) an expression tree and generate
1.109693 +** a bitmask indicating which tables are used in that expression
1.109694 +** tree.
1.109695 +*/
1.109696 +static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
1.109697 +static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
1.109698 +static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
1.109699 +  Bitmask mask = 0;
1.109700 +  if( p==0 ) return 0;
1.109701 +  if( p->op==TK_COLUMN ){
1.109702 +    mask = getMask(pMaskSet, p->iTable);
1.109703 +    return mask;
1.109704 +  }
1.109705 +  mask = exprTableUsage(pMaskSet, p->pRight);
1.109706 +  mask |= exprTableUsage(pMaskSet, p->pLeft);
1.109707 +  if( ExprHasProperty(p, EP_xIsSelect) ){
1.109708 +    mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
1.109709 +  }else{
1.109710 +    mask |= exprListTableUsage(pMaskSet, p->x.pList);
1.109711 +  }
1.109712 +  return mask;
1.109713 +}
1.109714 +static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
1.109715 +  int i;
1.109716 +  Bitmask mask = 0;
1.109717 +  if( pList ){
1.109718 +    for(i=0; i<pList->nExpr; i++){
1.109719 +      mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
1.109720 +    }
1.109721 +  }
1.109722 +  return mask;
1.109723 +}
1.109724 +static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
1.109725 +  Bitmask mask = 0;
1.109726 +  while( pS ){
1.109727 +    SrcList *pSrc = pS->pSrc;
1.109728 +    mask |= exprListTableUsage(pMaskSet, pS->pEList);
1.109729 +    mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
1.109730 +    mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
1.109731 +    mask |= exprTableUsage(pMaskSet, pS->pWhere);
1.109732 +    mask |= exprTableUsage(pMaskSet, pS->pHaving);
1.109733 +    if( ALWAYS(pSrc!=0) ){
1.109734 +      int i;
1.109735 +      for(i=0; i<pSrc->nSrc; i++){
1.109736 +        mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
1.109737 +        mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
1.109738 +      }
1.109739 +    }
1.109740 +    pS = pS->pPrior;
1.109741 +  }
1.109742 +  return mask;
1.109743 +}
1.109744 +
1.109745 +/*
1.109746 +** Return TRUE if the given operator is one of the operators that is
1.109747 +** allowed for an indexable WHERE clause term.  The allowed operators are
1.109748 +** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
1.109749 +*/
1.109750 +static int allowedOp(int op){
1.109751 +  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
1.109752 +  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
1.109753 +  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
1.109754 +  assert( TK_GE==TK_EQ+4 );
1.109755 +  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
1.109756 +}
1.109757 +
1.109758 +/*
1.109759 +** Swap two objects of type TYPE.
1.109760 +*/
1.109761 +#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
1.109762 +
1.109763 +/*
1.109764 +** Commute a comparison operator.  Expressions of the form "X op Y"
1.109765 +** are converted into "Y op X".
1.109766 +**
1.109767 +** If left/right precedence rules come into play when determining the
1.109768 +** collating sequence, then COLLATE operators are adjusted to ensure
1.109769 +** that the collating sequence does not change.  For example:
1.109770 +** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
1.109771 +** the left hand side of a comparison overrides any collation sequence 
1.109772 +** attached to the right. For the same reason the EP_Collate flag
1.109773 +** is not commuted.
1.109774 +*/
1.109775 +static void exprCommute(Parse *pParse, Expr *pExpr){
1.109776 +  u16 expRight = (pExpr->pRight->flags & EP_Collate);
1.109777 +  u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
1.109778 +  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
1.109779 +  if( expRight==expLeft ){
1.109780 +    /* Either X and Y both have COLLATE operator or neither do */
1.109781 +    if( expRight ){
1.109782 +      /* Both X and Y have COLLATE operators.  Make sure X is always
1.109783 +      ** used by clearing the EP_Collate flag from Y. */
1.109784 +      pExpr->pRight->flags &= ~EP_Collate;
1.109785 +    }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
1.109786 +      /* Neither X nor Y have COLLATE operators, but X has a non-default
1.109787 +      ** collating sequence.  So add the EP_Collate marker on X to cause
1.109788 +      ** it to be searched first. */
1.109789 +      pExpr->pLeft->flags |= EP_Collate;
1.109790 +    }
1.109791 +  }
1.109792 +  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
1.109793 +  if( pExpr->op>=TK_GT ){
1.109794 +    assert( TK_LT==TK_GT+2 );
1.109795 +    assert( TK_GE==TK_LE+2 );
1.109796 +    assert( TK_GT>TK_EQ );
1.109797 +    assert( TK_GT<TK_LE );
1.109798 +    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
1.109799 +    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
1.109800 +  }
1.109801 +}
1.109802 +
1.109803 +/*
1.109804 +** Translate from TK_xx operator to WO_xx bitmask.
1.109805 +*/
1.109806 +static u16 operatorMask(int op){
1.109807 +  u16 c;
1.109808 +  assert( allowedOp(op) );
1.109809 +  if( op==TK_IN ){
1.109810 +    c = WO_IN;
1.109811 +  }else if( op==TK_ISNULL ){
1.109812 +    c = WO_ISNULL;
1.109813 +  }else{
1.109814 +    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
1.109815 +    c = (u16)(WO_EQ<<(op-TK_EQ));
1.109816 +  }
1.109817 +  assert( op!=TK_ISNULL || c==WO_ISNULL );
1.109818 +  assert( op!=TK_IN || c==WO_IN );
1.109819 +  assert( op!=TK_EQ || c==WO_EQ );
1.109820 +  assert( op!=TK_LT || c==WO_LT );
1.109821 +  assert( op!=TK_LE || c==WO_LE );
1.109822 +  assert( op!=TK_GT || c==WO_GT );
1.109823 +  assert( op!=TK_GE || c==WO_GE );
1.109824 +  return c;
1.109825 +}
1.109826 +
1.109827 +/*
1.109828 +** Advance to the next WhereTerm that matches according to the criteria
1.109829 +** established when the pScan object was initialized by whereScanInit().
1.109830 +** Return NULL if there are no more matching WhereTerms.
1.109831 +*/
1.109832 +static WhereTerm *whereScanNext(WhereScan *pScan){
1.109833 +  int iCur;            /* The cursor on the LHS of the term */
1.109834 +  int iColumn;         /* The column on the LHS of the term.  -1 for IPK */
1.109835 +  Expr *pX;            /* An expression being tested */
1.109836 +  WhereClause *pWC;    /* Shorthand for pScan->pWC */
1.109837 +  WhereTerm *pTerm;    /* The term being tested */
1.109838 +  int k = pScan->k;    /* Where to start scanning */
1.109839 +
1.109840 +  while( pScan->iEquiv<=pScan->nEquiv ){
1.109841 +    iCur = pScan->aEquiv[pScan->iEquiv-2];
1.109842 +    iColumn = pScan->aEquiv[pScan->iEquiv-1];
1.109843 +    while( (pWC = pScan->pWC)!=0 ){
1.109844 +      for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
1.109845 +        if( pTerm->leftCursor==iCur
1.109846 +         && pTerm->u.leftColumn==iColumn
1.109847 +         && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
1.109848 +        ){
1.109849 +          if( (pTerm->eOperator & WO_EQUIV)!=0
1.109850 +           && pScan->nEquiv<ArraySize(pScan->aEquiv)
1.109851 +          ){
1.109852 +            int j;
1.109853 +            pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
1.109854 +            assert( pX->op==TK_COLUMN );
1.109855 +            for(j=0; j<pScan->nEquiv; j+=2){
1.109856 +              if( pScan->aEquiv[j]==pX->iTable
1.109857 +               && pScan->aEquiv[j+1]==pX->iColumn ){
1.109858 +                  break;
1.109859 +              }
1.109860 +            }
1.109861 +            if( j==pScan->nEquiv ){
1.109862 +              pScan->aEquiv[j] = pX->iTable;
1.109863 +              pScan->aEquiv[j+1] = pX->iColumn;
1.109864 +              pScan->nEquiv += 2;
1.109865 +            }
1.109866 +          }
1.109867 +          if( (pTerm->eOperator & pScan->opMask)!=0 ){
1.109868 +            /* Verify the affinity and collating sequence match */
1.109869 +            if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
1.109870 +              CollSeq *pColl;
1.109871 +              Parse *pParse = pWC->pWInfo->pParse;
1.109872 +              pX = pTerm->pExpr;
1.109873 +              if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
1.109874 +                continue;
1.109875 +              }
1.109876 +              assert(pX->pLeft);
1.109877 +              pColl = sqlite3BinaryCompareCollSeq(pParse,
1.109878 +                                                  pX->pLeft, pX->pRight);
1.109879 +              if( pColl==0 ) pColl = pParse->db->pDfltColl;
1.109880 +              if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
1.109881 +                continue;
1.109882 +              }
1.109883 +            }
1.109884 +            if( (pTerm->eOperator & WO_EQ)!=0
1.109885 +             && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
1.109886 +             && pX->iTable==pScan->aEquiv[0]
1.109887 +             && pX->iColumn==pScan->aEquiv[1]
1.109888 +            ){
1.109889 +              continue;
1.109890 +            }
1.109891 +            pScan->k = k+1;
1.109892 +            return pTerm;
1.109893 +          }
1.109894 +        }
1.109895 +      }
1.109896 +      pScan->pWC = pScan->pWC->pOuter;
1.109897 +      k = 0;
1.109898 +    }
1.109899 +    pScan->pWC = pScan->pOrigWC;
1.109900 +    k = 0;
1.109901 +    pScan->iEquiv += 2;
1.109902 +  }
1.109903 +  return 0;
1.109904 +}
1.109905 +
1.109906 +/*
1.109907 +** Initialize a WHERE clause scanner object.  Return a pointer to the
1.109908 +** first match.  Return NULL if there are no matches.
1.109909 +**
1.109910 +** The scanner will be searching the WHERE clause pWC.  It will look
1.109911 +** for terms of the form "X <op> <expr>" where X is column iColumn of table
1.109912 +** iCur.  The <op> must be one of the operators described by opMask.
1.109913 +**
1.109914 +** If the search is for X and the WHERE clause contains terms of the
1.109915 +** form X=Y then this routine might also return terms of the form
1.109916 +** "Y <op> <expr>".  The number of levels of transitivity is limited,
1.109917 +** but is enough to handle most commonly occurring SQL statements.
1.109918 +**
1.109919 +** If X is not the INTEGER PRIMARY KEY then X must be compatible with
1.109920 +** index pIdx.
1.109921 +*/
1.109922 +static WhereTerm *whereScanInit(
1.109923 +  WhereScan *pScan,       /* The WhereScan object being initialized */
1.109924 +  WhereClause *pWC,       /* The WHERE clause to be scanned */
1.109925 +  int iCur,               /* Cursor to scan for */
1.109926 +  int iColumn,            /* Column to scan for */
1.109927 +  u32 opMask,             /* Operator(s) to scan for */
1.109928 +  Index *pIdx             /* Must be compatible with this index */
1.109929 +){
1.109930 +  int j;
1.109931 +
1.109932 +  /* memset(pScan, 0, sizeof(*pScan)); */
1.109933 +  pScan->pOrigWC = pWC;
1.109934 +  pScan->pWC = pWC;
1.109935 +  if( pIdx && iColumn>=0 ){
1.109936 +    pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
1.109937 +    for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
1.109938 +      if( NEVER(j>=pIdx->nKeyCol) ) return 0;
1.109939 +    }
1.109940 +    pScan->zCollName = pIdx->azColl[j];
1.109941 +  }else{
1.109942 +    pScan->idxaff = 0;
1.109943 +    pScan->zCollName = 0;
1.109944 +  }
1.109945 +  pScan->opMask = opMask;
1.109946 +  pScan->k = 0;
1.109947 +  pScan->aEquiv[0] = iCur;
1.109948 +  pScan->aEquiv[1] = iColumn;
1.109949 +  pScan->nEquiv = 2;
1.109950 +  pScan->iEquiv = 2;
1.109951 +  return whereScanNext(pScan);
1.109952 +}
1.109953 +
1.109954 +/*
1.109955 +** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
1.109956 +** where X is a reference to the iColumn of table iCur and <op> is one of
1.109957 +** the WO_xx operator codes specified by the op parameter.
1.109958 +** Return a pointer to the term.  Return 0 if not found.
1.109959 +**
1.109960 +** The term returned might by Y=<expr> if there is another constraint in
1.109961 +** the WHERE clause that specifies that X=Y.  Any such constraints will be
1.109962 +** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
1.109963 +** aEquiv[] array holds X and all its equivalents, with each SQL variable
1.109964 +** taking up two slots in aEquiv[].  The first slot is for the cursor number
1.109965 +** and the second is for the column number.  There are 22 slots in aEquiv[]
1.109966 +** so that means we can look for X plus up to 10 other equivalent values.
1.109967 +** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
1.109968 +** and ... and A9=A10 and A10=<expr>.
1.109969 +**
1.109970 +** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
1.109971 +** then try for the one with no dependencies on <expr> - in other words where
1.109972 +** <expr> is a constant expression of some kind.  Only return entries of
1.109973 +** the form "X <op> Y" where Y is a column in another table if no terms of
1.109974 +** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
1.109975 +** exist, try to return a term that does not use WO_EQUIV.
1.109976 +*/
1.109977 +static WhereTerm *findTerm(
1.109978 +  WhereClause *pWC,     /* The WHERE clause to be searched */
1.109979 +  int iCur,             /* Cursor number of LHS */
1.109980 +  int iColumn,          /* Column number of LHS */
1.109981 +  Bitmask notReady,     /* RHS must not overlap with this mask */
1.109982 +  u32 op,               /* Mask of WO_xx values describing operator */
1.109983 +  Index *pIdx           /* Must be compatible with this index, if not NULL */
1.109984 +){
1.109985 +  WhereTerm *pResult = 0;
1.109986 +  WhereTerm *p;
1.109987 +  WhereScan scan;
1.109988 +
1.109989 +  p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
1.109990 +  while( p ){
1.109991 +    if( (p->prereqRight & notReady)==0 ){
1.109992 +      if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
1.109993 +        return p;
1.109994 +      }
1.109995 +      if( pResult==0 ) pResult = p;
1.109996 +    }
1.109997 +    p = whereScanNext(&scan);
1.109998 +  }
1.109999 +  return pResult;
1.110000 +}
1.110001 +
1.110002 +/* Forward reference */
1.110003 +static void exprAnalyze(SrcList*, WhereClause*, int);
1.110004 +
1.110005 +/*
1.110006 +** Call exprAnalyze on all terms in a WHERE clause.  
1.110007 +*/
1.110008 +static void exprAnalyzeAll(
1.110009 +  SrcList *pTabList,       /* the FROM clause */
1.110010 +  WhereClause *pWC         /* the WHERE clause to be analyzed */
1.110011 +){
1.110012 +  int i;
1.110013 +  for(i=pWC->nTerm-1; i>=0; i--){
1.110014 +    exprAnalyze(pTabList, pWC, i);
1.110015 +  }
1.110016 +}
1.110017 +
1.110018 +#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1.110019 +/*
1.110020 +** Check to see if the given expression is a LIKE or GLOB operator that
1.110021 +** can be optimized using inequality constraints.  Return TRUE if it is
1.110022 +** so and false if not.
1.110023 +**
1.110024 +** In order for the operator to be optimizible, the RHS must be a string
1.110025 +** literal that does not begin with a wildcard.  
1.110026 +*/
1.110027 +static int isLikeOrGlob(
1.110028 +  Parse *pParse,    /* Parsing and code generating context */
1.110029 +  Expr *pExpr,      /* Test this expression */
1.110030 +  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
1.110031 +  int *pisComplete, /* True if the only wildcard is % in the last character */
1.110032 +  int *pnoCase      /* True if uppercase is equivalent to lowercase */
1.110033 +){
1.110034 +  const char *z = 0;         /* String on RHS of LIKE operator */
1.110035 +  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
1.110036 +  ExprList *pList;           /* List of operands to the LIKE operator */
1.110037 +  int c;                     /* One character in z[] */
1.110038 +  int cnt;                   /* Number of non-wildcard prefix characters */
1.110039 +  char wc[3];                /* Wildcard characters */
1.110040 +  sqlite3 *db = pParse->db;  /* Database connection */
1.110041 +  sqlite3_value *pVal = 0;
1.110042 +  int op;                    /* Opcode of pRight */
1.110043 +
1.110044 +  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
1.110045 +    return 0;
1.110046 +  }
1.110047 +#ifdef SQLITE_EBCDIC
1.110048 +  if( *pnoCase ) return 0;
1.110049 +#endif
1.110050 +  pList = pExpr->x.pList;
1.110051 +  pLeft = pList->a[1].pExpr;
1.110052 +  if( pLeft->op!=TK_COLUMN 
1.110053 +   || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT 
1.110054 +   || IsVirtual(pLeft->pTab)
1.110055 +  ){
1.110056 +    /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
1.110057 +    ** be the name of an indexed column with TEXT affinity. */
1.110058 +    return 0;
1.110059 +  }
1.110060 +  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
1.110061 +
1.110062 +  pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
1.110063 +  op = pRight->op;
1.110064 +  if( op==TK_VARIABLE ){
1.110065 +    Vdbe *pReprepare = pParse->pReprepare;
1.110066 +    int iCol = pRight->iColumn;
1.110067 +    pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
1.110068 +    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
1.110069 +      z = (char *)sqlite3_value_text(pVal);
1.110070 +    }
1.110071 +    sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
1.110072 +    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
1.110073 +  }else if( op==TK_STRING ){
1.110074 +    z = pRight->u.zToken;
1.110075 +  }
1.110076 +  if( z ){
1.110077 +    cnt = 0;
1.110078 +    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
1.110079 +      cnt++;
1.110080 +    }
1.110081 +    if( cnt!=0 && 255!=(u8)z[cnt-1] ){
1.110082 +      Expr *pPrefix;
1.110083 +      *pisComplete = c==wc[0] && z[cnt+1]==0;
1.110084 +      pPrefix = sqlite3Expr(db, TK_STRING, z);
1.110085 +      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
1.110086 +      *ppPrefix = pPrefix;
1.110087 +      if( op==TK_VARIABLE ){
1.110088 +        Vdbe *v = pParse->pVdbe;
1.110089 +        sqlite3VdbeSetVarmask(v, pRight->iColumn);
1.110090 +        if( *pisComplete && pRight->u.zToken[1] ){
1.110091 +          /* If the rhs of the LIKE expression is a variable, and the current
1.110092 +          ** value of the variable means there is no need to invoke the LIKE
1.110093 +          ** function, then no OP_Variable will be added to the program.
1.110094 +          ** This causes problems for the sqlite3_bind_parameter_name()
1.110095 +          ** API. To workaround them, add a dummy OP_Variable here.
1.110096 +          */ 
1.110097 +          int r1 = sqlite3GetTempReg(pParse);
1.110098 +          sqlite3ExprCodeTarget(pParse, pRight, r1);
1.110099 +          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
1.110100 +          sqlite3ReleaseTempReg(pParse, r1);
1.110101 +        }
1.110102 +      }
1.110103 +    }else{
1.110104 +      z = 0;
1.110105 +    }
1.110106 +  }
1.110107 +
1.110108 +  sqlite3ValueFree(pVal);
1.110109 +  return (z!=0);
1.110110 +}
1.110111 +#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1.110112 +
1.110113 +
1.110114 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.110115 +/*
1.110116 +** Check to see if the given expression is of the form
1.110117 +**
1.110118 +**         column MATCH expr
1.110119 +**
1.110120 +** If it is then return TRUE.  If not, return FALSE.
1.110121 +*/
1.110122 +static int isMatchOfColumn(
1.110123 +  Expr *pExpr      /* Test this expression */
1.110124 +){
1.110125 +  ExprList *pList;
1.110126 +
1.110127 +  if( pExpr->op!=TK_FUNCTION ){
1.110128 +    return 0;
1.110129 +  }
1.110130 +  if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
1.110131 +    return 0;
1.110132 +  }
1.110133 +  pList = pExpr->x.pList;
1.110134 +  if( pList->nExpr!=2 ){
1.110135 +    return 0;
1.110136 +  }
1.110137 +  if( pList->a[1].pExpr->op != TK_COLUMN ){
1.110138 +    return 0;
1.110139 +  }
1.110140 +  return 1;
1.110141 +}
1.110142 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
1.110143 +
1.110144 +/*
1.110145 +** If the pBase expression originated in the ON or USING clause of
1.110146 +** a join, then transfer the appropriate markings over to derived.
1.110147 +*/
1.110148 +static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
1.110149 +  if( pDerived ){
1.110150 +    pDerived->flags |= pBase->flags & EP_FromJoin;
1.110151 +    pDerived->iRightJoinTable = pBase->iRightJoinTable;
1.110152 +  }
1.110153 +}
1.110154 +
1.110155 +#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1.110156 +/*
1.110157 +** Analyze a term that consists of two or more OR-connected
1.110158 +** subterms.  So in:
1.110159 +**
1.110160 +**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
1.110161 +**                          ^^^^^^^^^^^^^^^^^^^^
1.110162 +**
1.110163 +** This routine analyzes terms such as the middle term in the above example.
1.110164 +** A WhereOrTerm object is computed and attached to the term under
1.110165 +** analysis, regardless of the outcome of the analysis.  Hence:
1.110166 +**
1.110167 +**     WhereTerm.wtFlags   |=  TERM_ORINFO
1.110168 +**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
1.110169 +**
1.110170 +** The term being analyzed must have two or more of OR-connected subterms.
1.110171 +** A single subterm might be a set of AND-connected sub-subterms.
1.110172 +** Examples of terms under analysis:
1.110173 +**
1.110174 +**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
1.110175 +**     (B)     x=expr1 OR expr2=x OR x=expr3
1.110176 +**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
1.110177 +**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
1.110178 +**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
1.110179 +**
1.110180 +** CASE 1:
1.110181 +**
1.110182 +** If all subterms are of the form T.C=expr for some single column of C and
1.110183 +** a single table T (as shown in example B above) then create a new virtual
1.110184 +** term that is an equivalent IN expression.  In other words, if the term
1.110185 +** being analyzed is:
1.110186 +**
1.110187 +**      x = expr1  OR  expr2 = x  OR  x = expr3
1.110188 +**
1.110189 +** then create a new virtual term like this:
1.110190 +**
1.110191 +**      x IN (expr1,expr2,expr3)
1.110192 +**
1.110193 +** CASE 2:
1.110194 +**
1.110195 +** If all subterms are indexable by a single table T, then set
1.110196 +**
1.110197 +**     WhereTerm.eOperator              =  WO_OR
1.110198 +**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
1.110199 +**
1.110200 +** A subterm is "indexable" if it is of the form
1.110201 +** "T.C <op> <expr>" where C is any column of table T and 
1.110202 +** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
1.110203 +** A subterm is also indexable if it is an AND of two or more
1.110204 +** subsubterms at least one of which is indexable.  Indexable AND 
1.110205 +** subterms have their eOperator set to WO_AND and they have
1.110206 +** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
1.110207 +**
1.110208 +** From another point of view, "indexable" means that the subterm could
1.110209 +** potentially be used with an index if an appropriate index exists.
1.110210 +** This analysis does not consider whether or not the index exists; that
1.110211 +** is decided elsewhere.  This analysis only looks at whether subterms
1.110212 +** appropriate for indexing exist.
1.110213 +**
1.110214 +** All examples A through E above satisfy case 2.  But if a term
1.110215 +** also statisfies case 1 (such as B) we know that the optimizer will
1.110216 +** always prefer case 1, so in that case we pretend that case 2 is not
1.110217 +** satisfied.
1.110218 +**
1.110219 +** It might be the case that multiple tables are indexable.  For example,
1.110220 +** (E) above is indexable on tables P, Q, and R.
1.110221 +**
1.110222 +** Terms that satisfy case 2 are candidates for lookup by using
1.110223 +** separate indices to find rowids for each subterm and composing
1.110224 +** the union of all rowids using a RowSet object.  This is similar
1.110225 +** to "bitmap indices" in other database engines.
1.110226 +**
1.110227 +** OTHERWISE:
1.110228 +**
1.110229 +** If neither case 1 nor case 2 apply, then leave the eOperator set to
1.110230 +** zero.  This term is not useful for search.
1.110231 +*/
1.110232 +static void exprAnalyzeOrTerm(
1.110233 +  SrcList *pSrc,            /* the FROM clause */
1.110234 +  WhereClause *pWC,         /* the complete WHERE clause */
1.110235 +  int idxTerm               /* Index of the OR-term to be analyzed */
1.110236 +){
1.110237 +  WhereInfo *pWInfo = pWC->pWInfo;        /* WHERE clause processing context */
1.110238 +  Parse *pParse = pWInfo->pParse;         /* Parser context */
1.110239 +  sqlite3 *db = pParse->db;               /* Database connection */
1.110240 +  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
1.110241 +  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
1.110242 +  int i;                                  /* Loop counters */
1.110243 +  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
1.110244 +  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
1.110245 +  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
1.110246 +  Bitmask chngToIN;         /* Tables that might satisfy case 1 */
1.110247 +  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
1.110248 +
1.110249 +  /*
1.110250 +  ** Break the OR clause into its separate subterms.  The subterms are
1.110251 +  ** stored in a WhereClause structure containing within the WhereOrInfo
1.110252 +  ** object that is attached to the original OR clause term.
1.110253 +  */
1.110254 +  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
1.110255 +  assert( pExpr->op==TK_OR );
1.110256 +  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
1.110257 +  if( pOrInfo==0 ) return;
1.110258 +  pTerm->wtFlags |= TERM_ORINFO;
1.110259 +  pOrWc = &pOrInfo->wc;
1.110260 +  whereClauseInit(pOrWc, pWInfo);
1.110261 +  whereSplit(pOrWc, pExpr, TK_OR);
1.110262 +  exprAnalyzeAll(pSrc, pOrWc);
1.110263 +  if( db->mallocFailed ) return;
1.110264 +  assert( pOrWc->nTerm>=2 );
1.110265 +
1.110266 +  /*
1.110267 +  ** Compute the set of tables that might satisfy cases 1 or 2.
1.110268 +  */
1.110269 +  indexable = ~(Bitmask)0;
1.110270 +  chngToIN = ~(Bitmask)0;
1.110271 +  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
1.110272 +    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
1.110273 +      WhereAndInfo *pAndInfo;
1.110274 +      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
1.110275 +      chngToIN = 0;
1.110276 +      pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
1.110277 +      if( pAndInfo ){
1.110278 +        WhereClause *pAndWC;
1.110279 +        WhereTerm *pAndTerm;
1.110280 +        int j;
1.110281 +        Bitmask b = 0;
1.110282 +        pOrTerm->u.pAndInfo = pAndInfo;
1.110283 +        pOrTerm->wtFlags |= TERM_ANDINFO;
1.110284 +        pOrTerm->eOperator = WO_AND;
1.110285 +        pAndWC = &pAndInfo->wc;
1.110286 +        whereClauseInit(pAndWC, pWC->pWInfo);
1.110287 +        whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
1.110288 +        exprAnalyzeAll(pSrc, pAndWC);
1.110289 +        pAndWC->pOuter = pWC;
1.110290 +        testcase( db->mallocFailed );
1.110291 +        if( !db->mallocFailed ){
1.110292 +          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
1.110293 +            assert( pAndTerm->pExpr );
1.110294 +            if( allowedOp(pAndTerm->pExpr->op) ){
1.110295 +              b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
1.110296 +            }
1.110297 +          }
1.110298 +        }
1.110299 +        indexable &= b;
1.110300 +      }
1.110301 +    }else if( pOrTerm->wtFlags & TERM_COPIED ){
1.110302 +      /* Skip this term for now.  We revisit it when we process the
1.110303 +      ** corresponding TERM_VIRTUAL term */
1.110304 +    }else{
1.110305 +      Bitmask b;
1.110306 +      b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
1.110307 +      if( pOrTerm->wtFlags & TERM_VIRTUAL ){
1.110308 +        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
1.110309 +        b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
1.110310 +      }
1.110311 +      indexable &= b;
1.110312 +      if( (pOrTerm->eOperator & WO_EQ)==0 ){
1.110313 +        chngToIN = 0;
1.110314 +      }else{
1.110315 +        chngToIN &= b;
1.110316 +      }
1.110317 +    }
1.110318 +  }
1.110319 +
1.110320 +  /*
1.110321 +  ** Record the set of tables that satisfy case 2.  The set might be
1.110322 +  ** empty.
1.110323 +  */
1.110324 +  pOrInfo->indexable = indexable;
1.110325 +  pTerm->eOperator = indexable==0 ? 0 : WO_OR;
1.110326 +
1.110327 +  /*
1.110328 +  ** chngToIN holds a set of tables that *might* satisfy case 1.  But
1.110329 +  ** we have to do some additional checking to see if case 1 really
1.110330 +  ** is satisfied.
1.110331 +  **
1.110332 +  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
1.110333 +  ** that there is no possibility of transforming the OR clause into an
1.110334 +  ** IN operator because one or more terms in the OR clause contain
1.110335 +  ** something other than == on a column in the single table.  The 1-bit
1.110336 +  ** case means that every term of the OR clause is of the form
1.110337 +  ** "table.column=expr" for some single table.  The one bit that is set
1.110338 +  ** will correspond to the common table.  We still need to check to make
1.110339 +  ** sure the same column is used on all terms.  The 2-bit case is when
1.110340 +  ** the all terms are of the form "table1.column=table2.column".  It
1.110341 +  ** might be possible to form an IN operator with either table1.column
1.110342 +  ** or table2.column as the LHS if either is common to every term of
1.110343 +  ** the OR clause.
1.110344 +  **
1.110345 +  ** Note that terms of the form "table.column1=table.column2" (the
1.110346 +  ** same table on both sizes of the ==) cannot be optimized.
1.110347 +  */
1.110348 +  if( chngToIN ){
1.110349 +    int okToChngToIN = 0;     /* True if the conversion to IN is valid */
1.110350 +    int iColumn = -1;         /* Column index on lhs of IN operator */
1.110351 +    int iCursor = -1;         /* Table cursor common to all terms */
1.110352 +    int j = 0;                /* Loop counter */
1.110353 +
1.110354 +    /* Search for a table and column that appears on one side or the
1.110355 +    ** other of the == operator in every subterm.  That table and column
1.110356 +    ** will be recorded in iCursor and iColumn.  There might not be any
1.110357 +    ** such table and column.  Set okToChngToIN if an appropriate table
1.110358 +    ** and column is found but leave okToChngToIN false if not found.
1.110359 +    */
1.110360 +    for(j=0; j<2 && !okToChngToIN; j++){
1.110361 +      pOrTerm = pOrWc->a;
1.110362 +      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
1.110363 +        assert( pOrTerm->eOperator & WO_EQ );
1.110364 +        pOrTerm->wtFlags &= ~TERM_OR_OK;
1.110365 +        if( pOrTerm->leftCursor==iCursor ){
1.110366 +          /* This is the 2-bit case and we are on the second iteration and
1.110367 +          ** current term is from the first iteration.  So skip this term. */
1.110368 +          assert( j==1 );
1.110369 +          continue;
1.110370 +        }
1.110371 +        if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
1.110372 +          /* This term must be of the form t1.a==t2.b where t2 is in the
1.110373 +          ** chngToIN set but t1 is not.  This term will be either preceeded
1.110374 +          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
1.110375 +          ** and use its inversion. */
1.110376 +          testcase( pOrTerm->wtFlags & TERM_COPIED );
1.110377 +          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
1.110378 +          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
1.110379 +          continue;
1.110380 +        }
1.110381 +        iColumn = pOrTerm->u.leftColumn;
1.110382 +        iCursor = pOrTerm->leftCursor;
1.110383 +        break;
1.110384 +      }
1.110385 +      if( i<0 ){
1.110386 +        /* No candidate table+column was found.  This can only occur
1.110387 +        ** on the second iteration */
1.110388 +        assert( j==1 );
1.110389 +        assert( IsPowerOfTwo(chngToIN) );
1.110390 +        assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
1.110391 +        break;
1.110392 +      }
1.110393 +      testcase( j==1 );
1.110394 +
1.110395 +      /* We have found a candidate table and column.  Check to see if that
1.110396 +      ** table and column is common to every term in the OR clause */
1.110397 +      okToChngToIN = 1;
1.110398 +      for(; i>=0 && okToChngToIN; i--, pOrTerm++){
1.110399 +        assert( pOrTerm->eOperator & WO_EQ );
1.110400 +        if( pOrTerm->leftCursor!=iCursor ){
1.110401 +          pOrTerm->wtFlags &= ~TERM_OR_OK;
1.110402 +        }else if( pOrTerm->u.leftColumn!=iColumn ){
1.110403 +          okToChngToIN = 0;
1.110404 +        }else{
1.110405 +          int affLeft, affRight;
1.110406 +          /* If the right-hand side is also a column, then the affinities
1.110407 +          ** of both right and left sides must be such that no type
1.110408 +          ** conversions are required on the right.  (Ticket #2249)
1.110409 +          */
1.110410 +          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
1.110411 +          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
1.110412 +          if( affRight!=0 && affRight!=affLeft ){
1.110413 +            okToChngToIN = 0;
1.110414 +          }else{
1.110415 +            pOrTerm->wtFlags |= TERM_OR_OK;
1.110416 +          }
1.110417 +        }
1.110418 +      }
1.110419 +    }
1.110420 +
1.110421 +    /* At this point, okToChngToIN is true if original pTerm satisfies
1.110422 +    ** case 1.  In that case, construct a new virtual term that is 
1.110423 +    ** pTerm converted into an IN operator.
1.110424 +    */
1.110425 +    if( okToChngToIN ){
1.110426 +      Expr *pDup;            /* A transient duplicate expression */
1.110427 +      ExprList *pList = 0;   /* The RHS of the IN operator */
1.110428 +      Expr *pLeft = 0;       /* The LHS of the IN operator */
1.110429 +      Expr *pNew;            /* The complete IN operator */
1.110430 +
1.110431 +      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
1.110432 +        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
1.110433 +        assert( pOrTerm->eOperator & WO_EQ );
1.110434 +        assert( pOrTerm->leftCursor==iCursor );
1.110435 +        assert( pOrTerm->u.leftColumn==iColumn );
1.110436 +        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
1.110437 +        pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
1.110438 +        pLeft = pOrTerm->pExpr->pLeft;
1.110439 +      }
1.110440 +      assert( pLeft!=0 );
1.110441 +      pDup = sqlite3ExprDup(db, pLeft, 0);
1.110442 +      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
1.110443 +      if( pNew ){
1.110444 +        int idxNew;
1.110445 +        transferJoinMarkings(pNew, pExpr);
1.110446 +        assert( !ExprHasProperty(pNew, EP_xIsSelect) );
1.110447 +        pNew->x.pList = pList;
1.110448 +        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
1.110449 +        testcase( idxNew==0 );
1.110450 +        exprAnalyze(pSrc, pWC, idxNew);
1.110451 +        pTerm = &pWC->a[idxTerm];
1.110452 +        pWC->a[idxNew].iParent = idxTerm;
1.110453 +        pTerm->nChild = 1;
1.110454 +      }else{
1.110455 +        sqlite3ExprListDelete(db, pList);
1.110456 +      }
1.110457 +      pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
1.110458 +    }
1.110459 +  }
1.110460 +}
1.110461 +#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
1.110462 +
1.110463 +/*
1.110464 +** The input to this routine is an WhereTerm structure with only the
1.110465 +** "pExpr" field filled in.  The job of this routine is to analyze the
1.110466 +** subexpression and populate all the other fields of the WhereTerm
1.110467 +** structure.
1.110468 +**
1.110469 +** If the expression is of the form "<expr> <op> X" it gets commuted
1.110470 +** to the standard form of "X <op> <expr>".
1.110471 +**
1.110472 +** If the expression is of the form "X <op> Y" where both X and Y are
1.110473 +** columns, then the original expression is unchanged and a new virtual
1.110474 +** term of the form "Y <op> X" is added to the WHERE clause and
1.110475 +** analyzed separately.  The original term is marked with TERM_COPIED
1.110476 +** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1.110477 +** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1.110478 +** is a commuted copy of a prior term.)  The original term has nChild=1
1.110479 +** and the copy has idxParent set to the index of the original term.
1.110480 +*/
1.110481 +static void exprAnalyze(
1.110482 +  SrcList *pSrc,            /* the FROM clause */
1.110483 +  WhereClause *pWC,         /* the WHERE clause */
1.110484 +  int idxTerm               /* Index of the term to be analyzed */
1.110485 +){
1.110486 +  WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
1.110487 +  WhereTerm *pTerm;                /* The term to be analyzed */
1.110488 +  WhereMaskSet *pMaskSet;          /* Set of table index masks */
1.110489 +  Expr *pExpr;                     /* The expression to be analyzed */
1.110490 +  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
1.110491 +  Bitmask prereqAll;               /* Prerequesites of pExpr */
1.110492 +  Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
1.110493 +  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
1.110494 +  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
1.110495 +  int noCase = 0;                  /* LIKE/GLOB distinguishes case */
1.110496 +  int op;                          /* Top-level operator.  pExpr->op */
1.110497 +  Parse *pParse = pWInfo->pParse;  /* Parsing context */
1.110498 +  sqlite3 *db = pParse->db;        /* Database connection */
1.110499 +
1.110500 +  if( db->mallocFailed ){
1.110501 +    return;
1.110502 +  }
1.110503 +  pTerm = &pWC->a[idxTerm];
1.110504 +  pMaskSet = &pWInfo->sMaskSet;
1.110505 +  pExpr = pTerm->pExpr;
1.110506 +  assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
1.110507 +  prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
1.110508 +  op = pExpr->op;
1.110509 +  if( op==TK_IN ){
1.110510 +    assert( pExpr->pRight==0 );
1.110511 +    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1.110512 +      pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
1.110513 +    }else{
1.110514 +      pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
1.110515 +    }
1.110516 +  }else if( op==TK_ISNULL ){
1.110517 +    pTerm->prereqRight = 0;
1.110518 +  }else{
1.110519 +    pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
1.110520 +  }
1.110521 +  prereqAll = exprTableUsage(pMaskSet, pExpr);
1.110522 +  if( ExprHasProperty(pExpr, EP_FromJoin) ){
1.110523 +    Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
1.110524 +    prereqAll |= x;
1.110525 +    extraRight = x-1;  /* ON clause terms may not be used with an index
1.110526 +                       ** on left table of a LEFT JOIN.  Ticket #3015 */
1.110527 +  }
1.110528 +  pTerm->prereqAll = prereqAll;
1.110529 +  pTerm->leftCursor = -1;
1.110530 +  pTerm->iParent = -1;
1.110531 +  pTerm->eOperator = 0;
1.110532 +  if( allowedOp(op) ){
1.110533 +    Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1.110534 +    Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
1.110535 +    u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
1.110536 +    if( pLeft->op==TK_COLUMN ){
1.110537 +      pTerm->leftCursor = pLeft->iTable;
1.110538 +      pTerm->u.leftColumn = pLeft->iColumn;
1.110539 +      pTerm->eOperator = operatorMask(op) & opMask;
1.110540 +    }
1.110541 +    if( pRight && pRight->op==TK_COLUMN ){
1.110542 +      WhereTerm *pNew;
1.110543 +      Expr *pDup;
1.110544 +      u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
1.110545 +      if( pTerm->leftCursor>=0 ){
1.110546 +        int idxNew;
1.110547 +        pDup = sqlite3ExprDup(db, pExpr, 0);
1.110548 +        if( db->mallocFailed ){
1.110549 +          sqlite3ExprDelete(db, pDup);
1.110550 +          return;
1.110551 +        }
1.110552 +        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1.110553 +        if( idxNew==0 ) return;
1.110554 +        pNew = &pWC->a[idxNew];
1.110555 +        pNew->iParent = idxTerm;
1.110556 +        pTerm = &pWC->a[idxTerm];
1.110557 +        pTerm->nChild = 1;
1.110558 +        pTerm->wtFlags |= TERM_COPIED;
1.110559 +        if( pExpr->op==TK_EQ
1.110560 +         && !ExprHasProperty(pExpr, EP_FromJoin)
1.110561 +         && OptimizationEnabled(db, SQLITE_Transitive)
1.110562 +        ){
1.110563 +          pTerm->eOperator |= WO_EQUIV;
1.110564 +          eExtraOp = WO_EQUIV;
1.110565 +        }
1.110566 +      }else{
1.110567 +        pDup = pExpr;
1.110568 +        pNew = pTerm;
1.110569 +      }
1.110570 +      exprCommute(pParse, pDup);
1.110571 +      pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
1.110572 +      pNew->leftCursor = pLeft->iTable;
1.110573 +      pNew->u.leftColumn = pLeft->iColumn;
1.110574 +      testcase( (prereqLeft | extraRight) != prereqLeft );
1.110575 +      pNew->prereqRight = prereqLeft | extraRight;
1.110576 +      pNew->prereqAll = prereqAll;
1.110577 +      pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
1.110578 +    }
1.110579 +  }
1.110580 +
1.110581 +#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
1.110582 +  /* If a term is the BETWEEN operator, create two new virtual terms
1.110583 +  ** that define the range that the BETWEEN implements.  For example:
1.110584 +  **
1.110585 +  **      a BETWEEN b AND c
1.110586 +  **
1.110587 +  ** is converted into:
1.110588 +  **
1.110589 +  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1.110590 +  **
1.110591 +  ** The two new terms are added onto the end of the WhereClause object.
1.110592 +  ** The new terms are "dynamic" and are children of the original BETWEEN
1.110593 +  ** term.  That means that if the BETWEEN term is coded, the children are
1.110594 +  ** skipped.  Or, if the children are satisfied by an index, the original
1.110595 +  ** BETWEEN term is skipped.
1.110596 +  */
1.110597 +  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
1.110598 +    ExprList *pList = pExpr->x.pList;
1.110599 +    int i;
1.110600 +    static const u8 ops[] = {TK_GE, TK_LE};
1.110601 +    assert( pList!=0 );
1.110602 +    assert( pList->nExpr==2 );
1.110603 +    for(i=0; i<2; i++){
1.110604 +      Expr *pNewExpr;
1.110605 +      int idxNew;
1.110606 +      pNewExpr = sqlite3PExpr(pParse, ops[i], 
1.110607 +                             sqlite3ExprDup(db, pExpr->pLeft, 0),
1.110608 +                             sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
1.110609 +      transferJoinMarkings(pNewExpr, pExpr);
1.110610 +      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1.110611 +      testcase( idxNew==0 );
1.110612 +      exprAnalyze(pSrc, pWC, idxNew);
1.110613 +      pTerm = &pWC->a[idxTerm];
1.110614 +      pWC->a[idxNew].iParent = idxTerm;
1.110615 +    }
1.110616 +    pTerm->nChild = 2;
1.110617 +  }
1.110618 +#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
1.110619 +
1.110620 +#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1.110621 +  /* Analyze a term that is composed of two or more subterms connected by
1.110622 +  ** an OR operator.
1.110623 +  */
1.110624 +  else if( pExpr->op==TK_OR ){
1.110625 +    assert( pWC->op==TK_AND );
1.110626 +    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
1.110627 +    pTerm = &pWC->a[idxTerm];
1.110628 +  }
1.110629 +#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1.110630 +
1.110631 +#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1.110632 +  /* Add constraints to reduce the search space on a LIKE or GLOB
1.110633 +  ** operator.
1.110634 +  **
1.110635 +  ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
1.110636 +  **
1.110637 +  **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
1.110638 +  **
1.110639 +  ** The last character of the prefix "abc" is incremented to form the
1.110640 +  ** termination condition "abd".
1.110641 +  */
1.110642 +  if( pWC->op==TK_AND 
1.110643 +   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1.110644 +  ){
1.110645 +    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
1.110646 +    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1.110647 +    Expr *pNewExpr1;
1.110648 +    Expr *pNewExpr2;
1.110649 +    int idxNew1;
1.110650 +    int idxNew2;
1.110651 +    Token sCollSeqName;  /* Name of collating sequence */
1.110652 +
1.110653 +    pLeft = pExpr->x.pList->a[1].pExpr;
1.110654 +    pStr2 = sqlite3ExprDup(db, pStr1, 0);
1.110655 +    if( !db->mallocFailed ){
1.110656 +      u8 c, *pC;       /* Last character before the first wildcard */
1.110657 +      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
1.110658 +      c = *pC;
1.110659 +      if( noCase ){
1.110660 +        /* The point is to increment the last character before the first
1.110661 +        ** wildcard.  But if we increment '@', that will push it into the
1.110662 +        ** alphabetic range where case conversions will mess up the 
1.110663 +        ** inequality.  To avoid this, make sure to also run the full
1.110664 +        ** LIKE on all candidate expressions by clearing the isComplete flag
1.110665 +        */
1.110666 +        if( c=='A'-1 ) isComplete = 0;
1.110667 +        c = sqlite3UpperToLower[c];
1.110668 +      }
1.110669 +      *pC = c + 1;
1.110670 +    }
1.110671 +    sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
1.110672 +    sCollSeqName.n = 6;
1.110673 +    pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
1.110674 +    pNewExpr1 = sqlite3PExpr(pParse, TK_GE, 
1.110675 +           sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
1.110676 +           pStr1, 0);
1.110677 +    transferJoinMarkings(pNewExpr1, pExpr);
1.110678 +    idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
1.110679 +    testcase( idxNew1==0 );
1.110680 +    exprAnalyze(pSrc, pWC, idxNew1);
1.110681 +    pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
1.110682 +    pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
1.110683 +           sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
1.110684 +           pStr2, 0);
1.110685 +    transferJoinMarkings(pNewExpr2, pExpr);
1.110686 +    idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
1.110687 +    testcase( idxNew2==0 );
1.110688 +    exprAnalyze(pSrc, pWC, idxNew2);
1.110689 +    pTerm = &pWC->a[idxTerm];
1.110690 +    if( isComplete ){
1.110691 +      pWC->a[idxNew1].iParent = idxTerm;
1.110692 +      pWC->a[idxNew2].iParent = idxTerm;
1.110693 +      pTerm->nChild = 2;
1.110694 +    }
1.110695 +  }
1.110696 +#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1.110697 +
1.110698 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.110699 +  /* Add a WO_MATCH auxiliary term to the constraint set if the
1.110700 +  ** current expression is of the form:  column MATCH expr.
1.110701 +  ** This information is used by the xBestIndex methods of
1.110702 +  ** virtual tables.  The native query optimizer does not attempt
1.110703 +  ** to do anything with MATCH functions.
1.110704 +  */
1.110705 +  if( isMatchOfColumn(pExpr) ){
1.110706 +    int idxNew;
1.110707 +    Expr *pRight, *pLeft;
1.110708 +    WhereTerm *pNewTerm;
1.110709 +    Bitmask prereqColumn, prereqExpr;
1.110710 +
1.110711 +    pRight = pExpr->x.pList->a[0].pExpr;
1.110712 +    pLeft = pExpr->x.pList->a[1].pExpr;
1.110713 +    prereqExpr = exprTableUsage(pMaskSet, pRight);
1.110714 +    prereqColumn = exprTableUsage(pMaskSet, pLeft);
1.110715 +    if( (prereqExpr & prereqColumn)==0 ){
1.110716 +      Expr *pNewExpr;
1.110717 +      pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
1.110718 +                              0, sqlite3ExprDup(db, pRight, 0), 0);
1.110719 +      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1.110720 +      testcase( idxNew==0 );
1.110721 +      pNewTerm = &pWC->a[idxNew];
1.110722 +      pNewTerm->prereqRight = prereqExpr;
1.110723 +      pNewTerm->leftCursor = pLeft->iTable;
1.110724 +      pNewTerm->u.leftColumn = pLeft->iColumn;
1.110725 +      pNewTerm->eOperator = WO_MATCH;
1.110726 +      pNewTerm->iParent = idxTerm;
1.110727 +      pTerm = &pWC->a[idxTerm];
1.110728 +      pTerm->nChild = 1;
1.110729 +      pTerm->wtFlags |= TERM_COPIED;
1.110730 +      pNewTerm->prereqAll = pTerm->prereqAll;
1.110731 +    }
1.110732 +  }
1.110733 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
1.110734 +
1.110735 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1.110736 +  /* When sqlite_stat3 histogram data is available an operator of the
1.110737 +  ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1.110738 +  ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
1.110739 +  ** virtual term of that form.
1.110740 +  **
1.110741 +  ** Note that the virtual term must be tagged with TERM_VNULL.  This
1.110742 +  ** TERM_VNULL tag will suppress the not-null check at the beginning
1.110743 +  ** of the loop.  Without the TERM_VNULL flag, the not-null check at
1.110744 +  ** the start of the loop will prevent any results from being returned.
1.110745 +  */
1.110746 +  if( pExpr->op==TK_NOTNULL
1.110747 +   && pExpr->pLeft->op==TK_COLUMN
1.110748 +   && pExpr->pLeft->iColumn>=0
1.110749 +   && OptimizationEnabled(db, SQLITE_Stat3)
1.110750 +  ){
1.110751 +    Expr *pNewExpr;
1.110752 +    Expr *pLeft = pExpr->pLeft;
1.110753 +    int idxNew;
1.110754 +    WhereTerm *pNewTerm;
1.110755 +
1.110756 +    pNewExpr = sqlite3PExpr(pParse, TK_GT,
1.110757 +                            sqlite3ExprDup(db, pLeft, 0),
1.110758 +                            sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
1.110759 +
1.110760 +    idxNew = whereClauseInsert(pWC, pNewExpr,
1.110761 +                              TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
1.110762 +    if( idxNew ){
1.110763 +      pNewTerm = &pWC->a[idxNew];
1.110764 +      pNewTerm->prereqRight = 0;
1.110765 +      pNewTerm->leftCursor = pLeft->iTable;
1.110766 +      pNewTerm->u.leftColumn = pLeft->iColumn;
1.110767 +      pNewTerm->eOperator = WO_GT;
1.110768 +      pNewTerm->iParent = idxTerm;
1.110769 +      pTerm = &pWC->a[idxTerm];
1.110770 +      pTerm->nChild = 1;
1.110771 +      pTerm->wtFlags |= TERM_COPIED;
1.110772 +      pNewTerm->prereqAll = pTerm->prereqAll;
1.110773 +    }
1.110774 +  }
1.110775 +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
1.110776 +
1.110777 +  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1.110778 +  ** an index for tables to the left of the join.
1.110779 +  */
1.110780 +  pTerm->prereqRight |= extraRight;
1.110781 +}
1.110782 +
1.110783 +/*
1.110784 +** This function searches pList for a entry that matches the iCol-th column
1.110785 +** of index pIdx.
1.110786 +**
1.110787 +** If such an expression is found, its index in pList->a[] is returned. If
1.110788 +** no expression is found, -1 is returned.
1.110789 +*/
1.110790 +static int findIndexCol(
1.110791 +  Parse *pParse,                  /* Parse context */
1.110792 +  ExprList *pList,                /* Expression list to search */
1.110793 +  int iBase,                      /* Cursor for table associated with pIdx */
1.110794 +  Index *pIdx,                    /* Index to match column of */
1.110795 +  int iCol                        /* Column of index to match */
1.110796 +){
1.110797 +  int i;
1.110798 +  const char *zColl = pIdx->azColl[iCol];
1.110799 +
1.110800 +  for(i=0; i<pList->nExpr; i++){
1.110801 +    Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
1.110802 +    if( p->op==TK_COLUMN
1.110803 +     && p->iColumn==pIdx->aiColumn[iCol]
1.110804 +     && p->iTable==iBase
1.110805 +    ){
1.110806 +      CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
1.110807 +      if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
1.110808 +        return i;
1.110809 +      }
1.110810 +    }
1.110811 +  }
1.110812 +
1.110813 +  return -1;
1.110814 +}
1.110815 +
1.110816 +/*
1.110817 +** Return true if the DISTINCT expression-list passed as the third argument
1.110818 +** is redundant.
1.110819 +**
1.110820 +** A DISTINCT list is redundant if the database contains some subset of
1.110821 +** columns that are unique and non-null.
1.110822 +*/
1.110823 +static int isDistinctRedundant(
1.110824 +  Parse *pParse,            /* Parsing context */
1.110825 +  SrcList *pTabList,        /* The FROM clause */
1.110826 +  WhereClause *pWC,         /* The WHERE clause */
1.110827 +  ExprList *pDistinct       /* The result set that needs to be DISTINCT */
1.110828 +){
1.110829 +  Table *pTab;
1.110830 +  Index *pIdx;
1.110831 +  int i;                          
1.110832 +  int iBase;
1.110833 +
1.110834 +  /* If there is more than one table or sub-select in the FROM clause of
1.110835 +  ** this query, then it will not be possible to show that the DISTINCT 
1.110836 +  ** clause is redundant. */
1.110837 +  if( pTabList->nSrc!=1 ) return 0;
1.110838 +  iBase = pTabList->a[0].iCursor;
1.110839 +  pTab = pTabList->a[0].pTab;
1.110840 +
1.110841 +  /* If any of the expressions is an IPK column on table iBase, then return 
1.110842 +  ** true. Note: The (p->iTable==iBase) part of this test may be false if the
1.110843 +  ** current SELECT is a correlated sub-query.
1.110844 +  */
1.110845 +  for(i=0; i<pDistinct->nExpr; i++){
1.110846 +    Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
1.110847 +    if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
1.110848 +  }
1.110849 +
1.110850 +  /* Loop through all indices on the table, checking each to see if it makes
1.110851 +  ** the DISTINCT qualifier redundant. It does so if:
1.110852 +  **
1.110853 +  **   1. The index is itself UNIQUE, and
1.110854 +  **
1.110855 +  **   2. All of the columns in the index are either part of the pDistinct
1.110856 +  **      list, or else the WHERE clause contains a term of the form "col=X",
1.110857 +  **      where X is a constant value. The collation sequences of the
1.110858 +  **      comparison and select-list expressions must match those of the index.
1.110859 +  **
1.110860 +  **   3. All of those index columns for which the WHERE clause does not
1.110861 +  **      contain a "col=X" term are subject to a NOT NULL constraint.
1.110862 +  */
1.110863 +  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1.110864 +    if( pIdx->onError==OE_None ) continue;
1.110865 +    for(i=0; i<pIdx->nKeyCol; i++){
1.110866 +      i16 iCol = pIdx->aiColumn[i];
1.110867 +      if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
1.110868 +        int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
1.110869 +        if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
1.110870 +          break;
1.110871 +        }
1.110872 +      }
1.110873 +    }
1.110874 +    if( i==pIdx->nKeyCol ){
1.110875 +      /* This index implies that the DISTINCT qualifier is redundant. */
1.110876 +      return 1;
1.110877 +    }
1.110878 +  }
1.110879 +
1.110880 +  return 0;
1.110881 +}
1.110882 +
1.110883 +
1.110884 +/*
1.110885 +** Estimate the logarithm of the input value to base 2.
1.110886 +*/
1.110887 +static LogEst estLog(LogEst N){
1.110888 +  LogEst x = sqlite3LogEst(N);
1.110889 +  return x>33 ? x - 33 : 0;
1.110890 +}
1.110891 +
1.110892 +/*
1.110893 +** Two routines for printing the content of an sqlite3_index_info
1.110894 +** structure.  Used for testing and debugging only.  If neither
1.110895 +** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
1.110896 +** are no-ops.
1.110897 +*/
1.110898 +#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
1.110899 +static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
1.110900 +  int i;
1.110901 +  if( !sqlite3WhereTrace ) return;
1.110902 +  for(i=0; i<p->nConstraint; i++){
1.110903 +    sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
1.110904 +       i,
1.110905 +       p->aConstraint[i].iColumn,
1.110906 +       p->aConstraint[i].iTermOffset,
1.110907 +       p->aConstraint[i].op,
1.110908 +       p->aConstraint[i].usable);
1.110909 +  }
1.110910 +  for(i=0; i<p->nOrderBy; i++){
1.110911 +    sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
1.110912 +       i,
1.110913 +       p->aOrderBy[i].iColumn,
1.110914 +       p->aOrderBy[i].desc);
1.110915 +  }
1.110916 +}
1.110917 +static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
1.110918 +  int i;
1.110919 +  if( !sqlite3WhereTrace ) return;
1.110920 +  for(i=0; i<p->nConstraint; i++){
1.110921 +    sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
1.110922 +       i,
1.110923 +       p->aConstraintUsage[i].argvIndex,
1.110924 +       p->aConstraintUsage[i].omit);
1.110925 +  }
1.110926 +  sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
1.110927 +  sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
1.110928 +  sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
1.110929 +  sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
1.110930 +  sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
1.110931 +}
1.110932 +#else
1.110933 +#define TRACE_IDX_INPUTS(A)
1.110934 +#define TRACE_IDX_OUTPUTS(A)
1.110935 +#endif
1.110936 +
1.110937 +#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
1.110938 +/*
1.110939 +** Return TRUE if the WHERE clause term pTerm is of a form where it
1.110940 +** could be used with an index to access pSrc, assuming an appropriate
1.110941 +** index existed.
1.110942 +*/
1.110943 +static int termCanDriveIndex(
1.110944 +  WhereTerm *pTerm,              /* WHERE clause term to check */
1.110945 +  struct SrcList_item *pSrc,     /* Table we are trying to access */
1.110946 +  Bitmask notReady               /* Tables in outer loops of the join */
1.110947 +){
1.110948 +  char aff;
1.110949 +  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
1.110950 +  if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
1.110951 +  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
1.110952 +  if( pTerm->u.leftColumn<0 ) return 0;
1.110953 +  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
1.110954 +  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
1.110955 +  return 1;
1.110956 +}
1.110957 +#endif
1.110958 +
1.110959 +
1.110960 +#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
1.110961 +/*
1.110962 +** Generate code to construct the Index object for an automatic index
1.110963 +** and to set up the WhereLevel object pLevel so that the code generator
1.110964 +** makes use of the automatic index.
1.110965 +*/
1.110966 +static void constructAutomaticIndex(
1.110967 +  Parse *pParse,              /* The parsing context */
1.110968 +  WhereClause *pWC,           /* The WHERE clause */
1.110969 +  struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
1.110970 +  Bitmask notReady,           /* Mask of cursors that are not available */
1.110971 +  WhereLevel *pLevel          /* Write new index here */
1.110972 +){
1.110973 +  int nKeyCol;                /* Number of columns in the constructed index */
1.110974 +  WhereTerm *pTerm;           /* A single term of the WHERE clause */
1.110975 +  WhereTerm *pWCEnd;          /* End of pWC->a[] */
1.110976 +  Index *pIdx;                /* Object describing the transient index */
1.110977 +  Vdbe *v;                    /* Prepared statement under construction */
1.110978 +  int addrInit;               /* Address of the initialization bypass jump */
1.110979 +  Table *pTable;              /* The table being indexed */
1.110980 +  int addrTop;                /* Top of the index fill loop */
1.110981 +  int regRecord;              /* Register holding an index record */
1.110982 +  int n;                      /* Column counter */
1.110983 +  int i;                      /* Loop counter */
1.110984 +  int mxBitCol;               /* Maximum column in pSrc->colUsed */
1.110985 +  CollSeq *pColl;             /* Collating sequence to on a column */
1.110986 +  WhereLoop *pLoop;           /* The Loop object */
1.110987 +  char *zNotUsed;             /* Extra space on the end of pIdx */
1.110988 +  Bitmask idxCols;            /* Bitmap of columns used for indexing */
1.110989 +  Bitmask extraCols;          /* Bitmap of additional columns */
1.110990 +  u8 sentWarning = 0;         /* True if a warnning has been issued */
1.110991 +
1.110992 +  /* Generate code to skip over the creation and initialization of the
1.110993 +  ** transient index on 2nd and subsequent iterations of the loop. */
1.110994 +  v = pParse->pVdbe;
1.110995 +  assert( v!=0 );
1.110996 +  addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
1.110997 +
1.110998 +  /* Count the number of columns that will be added to the index
1.110999 +  ** and used to match WHERE clause constraints */
1.111000 +  nKeyCol = 0;
1.111001 +  pTable = pSrc->pTab;
1.111002 +  pWCEnd = &pWC->a[pWC->nTerm];
1.111003 +  pLoop = pLevel->pWLoop;
1.111004 +  idxCols = 0;
1.111005 +  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
1.111006 +    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
1.111007 +      int iCol = pTerm->u.leftColumn;
1.111008 +      Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
1.111009 +      testcase( iCol==BMS );
1.111010 +      testcase( iCol==BMS-1 );
1.111011 +      if( !sentWarning ){
1.111012 +        sqlite3_log(SQLITE_WARNING_AUTOINDEX,
1.111013 +            "automatic index on %s(%s)", pTable->zName,
1.111014 +            pTable->aCol[iCol].zName);
1.111015 +        sentWarning = 1;
1.111016 +      }
1.111017 +      if( (idxCols & cMask)==0 ){
1.111018 +        if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ) return;
1.111019 +        pLoop->aLTerm[nKeyCol++] = pTerm;
1.111020 +        idxCols |= cMask;
1.111021 +      }
1.111022 +    }
1.111023 +  }
1.111024 +  assert( nKeyCol>0 );
1.111025 +  pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
1.111026 +  pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
1.111027 +                     | WHERE_AUTO_INDEX;
1.111028 +
1.111029 +  /* Count the number of additional columns needed to create a
1.111030 +  ** covering index.  A "covering index" is an index that contains all
1.111031 +  ** columns that are needed by the query.  With a covering index, the
1.111032 +  ** original table never needs to be accessed.  Automatic indices must
1.111033 +  ** be a covering index because the index will not be updated if the
1.111034 +  ** original table changes and the index and table cannot both be used
1.111035 +  ** if they go out of sync.
1.111036 +  */
1.111037 +  extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
1.111038 +  mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
1.111039 +  testcase( pTable->nCol==BMS-1 );
1.111040 +  testcase( pTable->nCol==BMS-2 );
1.111041 +  for(i=0; i<mxBitCol; i++){
1.111042 +    if( extraCols & MASKBIT(i) ) nKeyCol++;
1.111043 +  }
1.111044 +  if( pSrc->colUsed & MASKBIT(BMS-1) ){
1.111045 +    nKeyCol += pTable->nCol - BMS + 1;
1.111046 +  }
1.111047 +  pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
1.111048 +
1.111049 +  /* Construct the Index object to describe this index */
1.111050 +  pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
1.111051 +  if( pIdx==0 ) return;
1.111052 +  pLoop->u.btree.pIndex = pIdx;
1.111053 +  pIdx->zName = "auto-index";
1.111054 +  pIdx->pTable = pTable;
1.111055 +  n = 0;
1.111056 +  idxCols = 0;
1.111057 +  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
1.111058 +    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
1.111059 +      int iCol = pTerm->u.leftColumn;
1.111060 +      Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
1.111061 +      testcase( iCol==BMS-1 );
1.111062 +      testcase( iCol==BMS );
1.111063 +      if( (idxCols & cMask)==0 ){
1.111064 +        Expr *pX = pTerm->pExpr;
1.111065 +        idxCols |= cMask;
1.111066 +        pIdx->aiColumn[n] = pTerm->u.leftColumn;
1.111067 +        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
1.111068 +        pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
1.111069 +        n++;
1.111070 +      }
1.111071 +    }
1.111072 +  }
1.111073 +  assert( (u32)n==pLoop->u.btree.nEq );
1.111074 +
1.111075 +  /* Add additional columns needed to make the automatic index into
1.111076 +  ** a covering index */
1.111077 +  for(i=0; i<mxBitCol; i++){
1.111078 +    if( extraCols & MASKBIT(i) ){
1.111079 +      pIdx->aiColumn[n] = i;
1.111080 +      pIdx->azColl[n] = "BINARY";
1.111081 +      n++;
1.111082 +    }
1.111083 +  }
1.111084 +  if( pSrc->colUsed & MASKBIT(BMS-1) ){
1.111085 +    for(i=BMS-1; i<pTable->nCol; i++){
1.111086 +      pIdx->aiColumn[n] = i;
1.111087 +      pIdx->azColl[n] = "BINARY";
1.111088 +      n++;
1.111089 +    }
1.111090 +  }
1.111091 +  assert( n==nKeyCol );
1.111092 +  pIdx->aiColumn[n] = -1;
1.111093 +  pIdx->azColl[n] = "BINARY";
1.111094 +
1.111095 +  /* Create the automatic index */
1.111096 +  assert( pLevel->iIdxCur>=0 );
1.111097 +  pLevel->iIdxCur = pParse->nTab++;
1.111098 +  sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
1.111099 +  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
1.111100 +  VdbeComment((v, "for %s", pTable->zName));
1.111101 +
1.111102 +  /* Fill the automatic index with content */
1.111103 +  addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
1.111104 +  regRecord = sqlite3GetTempReg(pParse);
1.111105 +  sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
1.111106 +  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
1.111107 +  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1.111108 +  sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
1.111109 +  sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
1.111110 +  sqlite3VdbeJumpHere(v, addrTop);
1.111111 +  sqlite3ReleaseTempReg(pParse, regRecord);
1.111112 +  
1.111113 +  /* Jump here when skipping the initialization */
1.111114 +  sqlite3VdbeJumpHere(v, addrInit);
1.111115 +}
1.111116 +#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
1.111117 +
1.111118 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.111119 +/*
1.111120 +** Allocate and populate an sqlite3_index_info structure. It is the 
1.111121 +** responsibility of the caller to eventually release the structure
1.111122 +** by passing the pointer returned by this function to sqlite3_free().
1.111123 +*/
1.111124 +static sqlite3_index_info *allocateIndexInfo(
1.111125 +  Parse *pParse,
1.111126 +  WhereClause *pWC,
1.111127 +  struct SrcList_item *pSrc,
1.111128 +  ExprList *pOrderBy
1.111129 +){
1.111130 +  int i, j;
1.111131 +  int nTerm;
1.111132 +  struct sqlite3_index_constraint *pIdxCons;
1.111133 +  struct sqlite3_index_orderby *pIdxOrderBy;
1.111134 +  struct sqlite3_index_constraint_usage *pUsage;
1.111135 +  WhereTerm *pTerm;
1.111136 +  int nOrderBy;
1.111137 +  sqlite3_index_info *pIdxInfo;
1.111138 +
1.111139 +  /* Count the number of possible WHERE clause constraints referring
1.111140 +  ** to this virtual table */
1.111141 +  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1.111142 +    if( pTerm->leftCursor != pSrc->iCursor ) continue;
1.111143 +    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
1.111144 +    testcase( pTerm->eOperator & WO_IN );
1.111145 +    testcase( pTerm->eOperator & WO_ISNULL );
1.111146 +    testcase( pTerm->eOperator & WO_ALL );
1.111147 +    if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
1.111148 +    if( pTerm->wtFlags & TERM_VNULL ) continue;
1.111149 +    nTerm++;
1.111150 +  }
1.111151 +
1.111152 +  /* If the ORDER BY clause contains only columns in the current 
1.111153 +  ** virtual table then allocate space for the aOrderBy part of
1.111154 +  ** the sqlite3_index_info structure.
1.111155 +  */
1.111156 +  nOrderBy = 0;
1.111157 +  if( pOrderBy ){
1.111158 +    int n = pOrderBy->nExpr;
1.111159 +    for(i=0; i<n; i++){
1.111160 +      Expr *pExpr = pOrderBy->a[i].pExpr;
1.111161 +      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
1.111162 +    }
1.111163 +    if( i==n){
1.111164 +      nOrderBy = n;
1.111165 +    }
1.111166 +  }
1.111167 +
1.111168 +  /* Allocate the sqlite3_index_info structure
1.111169 +  */
1.111170 +  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
1.111171 +                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
1.111172 +                           + sizeof(*pIdxOrderBy)*nOrderBy );
1.111173 +  if( pIdxInfo==0 ){
1.111174 +    sqlite3ErrorMsg(pParse, "out of memory");
1.111175 +    return 0;
1.111176 +  }
1.111177 +
1.111178 +  /* Initialize the structure.  The sqlite3_index_info structure contains
1.111179 +  ** many fields that are declared "const" to prevent xBestIndex from
1.111180 +  ** changing them.  We have to do some funky casting in order to
1.111181 +  ** initialize those fields.
1.111182 +  */
1.111183 +  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
1.111184 +  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
1.111185 +  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
1.111186 +  *(int*)&pIdxInfo->nConstraint = nTerm;
1.111187 +  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
1.111188 +  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
1.111189 +  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
1.111190 +  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
1.111191 +                                                                   pUsage;
1.111192 +
1.111193 +  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1.111194 +    u8 op;
1.111195 +    if( pTerm->leftCursor != pSrc->iCursor ) continue;
1.111196 +    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
1.111197 +    testcase( pTerm->eOperator & WO_IN );
1.111198 +    testcase( pTerm->eOperator & WO_ISNULL );
1.111199 +    testcase( pTerm->eOperator & WO_ALL );
1.111200 +    if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
1.111201 +    if( pTerm->wtFlags & TERM_VNULL ) continue;
1.111202 +    pIdxCons[j].iColumn = pTerm->u.leftColumn;
1.111203 +    pIdxCons[j].iTermOffset = i;
1.111204 +    op = (u8)pTerm->eOperator & WO_ALL;
1.111205 +    if( op==WO_IN ) op = WO_EQ;
1.111206 +    pIdxCons[j].op = op;
1.111207 +    /* The direct assignment in the previous line is possible only because
1.111208 +    ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
1.111209 +    ** following asserts verify this fact. */
1.111210 +    assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
1.111211 +    assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
1.111212 +    assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
1.111213 +    assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
1.111214 +    assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
1.111215 +    assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
1.111216 +    assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
1.111217 +    j++;
1.111218 +  }
1.111219 +  for(i=0; i<nOrderBy; i++){
1.111220 +    Expr *pExpr = pOrderBy->a[i].pExpr;
1.111221 +    pIdxOrderBy[i].iColumn = pExpr->iColumn;
1.111222 +    pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
1.111223 +  }
1.111224 +
1.111225 +  return pIdxInfo;
1.111226 +}
1.111227 +
1.111228 +/*
1.111229 +** The table object reference passed as the second argument to this function
1.111230 +** must represent a virtual table. This function invokes the xBestIndex()
1.111231 +** method of the virtual table with the sqlite3_index_info object that
1.111232 +** comes in as the 3rd argument to this function.
1.111233 +**
1.111234 +** If an error occurs, pParse is populated with an error message and a
1.111235 +** non-zero value is returned. Otherwise, 0 is returned and the output
1.111236 +** part of the sqlite3_index_info structure is left populated.
1.111237 +**
1.111238 +** Whether or not an error is returned, it is the responsibility of the
1.111239 +** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
1.111240 +** that this is required.
1.111241 +*/
1.111242 +static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
1.111243 +  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
1.111244 +  int i;
1.111245 +  int rc;
1.111246 +
1.111247 +  TRACE_IDX_INPUTS(p);
1.111248 +  rc = pVtab->pModule->xBestIndex(pVtab, p);
1.111249 +  TRACE_IDX_OUTPUTS(p);
1.111250 +
1.111251 +  if( rc!=SQLITE_OK ){
1.111252 +    if( rc==SQLITE_NOMEM ){
1.111253 +      pParse->db->mallocFailed = 1;
1.111254 +    }else if( !pVtab->zErrMsg ){
1.111255 +      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
1.111256 +    }else{
1.111257 +      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
1.111258 +    }
1.111259 +  }
1.111260 +  sqlite3_free(pVtab->zErrMsg);
1.111261 +  pVtab->zErrMsg = 0;
1.111262 +
1.111263 +  for(i=0; i<p->nConstraint; i++){
1.111264 +    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
1.111265 +      sqlite3ErrorMsg(pParse, 
1.111266 +          "table %s: xBestIndex returned an invalid plan", pTab->zName);
1.111267 +    }
1.111268 +  }
1.111269 +
1.111270 +  return pParse->nErr;
1.111271 +}
1.111272 +#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
1.111273 +
1.111274 +
1.111275 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1.111276 +/*
1.111277 +** Estimate the location of a particular key among all keys in an
1.111278 +** index.  Store the results in aStat as follows:
1.111279 +**
1.111280 +**    aStat[0]      Est. number of rows less than pVal
1.111281 +**    aStat[1]      Est. number of rows equal to pVal
1.111282 +**
1.111283 +** Return SQLITE_OK on success.
1.111284 +*/
1.111285 +static void whereKeyStats(
1.111286 +  Parse *pParse,              /* Database connection */
1.111287 +  Index *pIdx,                /* Index to consider domain of */
1.111288 +  UnpackedRecord *pRec,       /* Vector of values to consider */
1.111289 +  int roundUp,                /* Round up if true.  Round down if false */
1.111290 +  tRowcnt *aStat              /* OUT: stats written here */
1.111291 +){
1.111292 +  IndexSample *aSample = pIdx->aSample;
1.111293 +  int iCol;                   /* Index of required stats in anEq[] etc. */
1.111294 +  int iMin = 0;               /* Smallest sample not yet tested */
1.111295 +  int i = pIdx->nSample;      /* Smallest sample larger than or equal to pRec */
1.111296 +  int iTest;                  /* Next sample to test */
1.111297 +  int res;                    /* Result of comparison operation */
1.111298 +
1.111299 +#ifndef SQLITE_DEBUG
1.111300 +  UNUSED_PARAMETER( pParse );
1.111301 +#endif
1.111302 +  assert( pRec!=0 );
1.111303 +  iCol = pRec->nField - 1;
1.111304 +  assert( pIdx->nSample>0 );
1.111305 +  assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
1.111306 +  do{
1.111307 +    iTest = (iMin+i)/2;
1.111308 +    res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec, 0);
1.111309 +    if( res<0 ){
1.111310 +      iMin = iTest+1;
1.111311 +    }else{
1.111312 +      i = iTest;
1.111313 +    }
1.111314 +  }while( res && iMin<i );
1.111315 +
1.111316 +#ifdef SQLITE_DEBUG
1.111317 +  /* The following assert statements check that the binary search code
1.111318 +  ** above found the right answer. This block serves no purpose other
1.111319 +  ** than to invoke the asserts.  */
1.111320 +  if( res==0 ){
1.111321 +    /* If (res==0) is true, then sample $i must be equal to pRec */
1.111322 +    assert( i<pIdx->nSample );
1.111323 +    assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec, 0)
1.111324 +         || pParse->db->mallocFailed );
1.111325 +  }else{
1.111326 +    /* Otherwise, pRec must be smaller than sample $i and larger than
1.111327 +    ** sample ($i-1).  */
1.111328 +    assert( i==pIdx->nSample 
1.111329 +         || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec, 0)>0
1.111330 +         || pParse->db->mallocFailed );
1.111331 +    assert( i==0
1.111332 +         || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec, 0)<0
1.111333 +         || pParse->db->mallocFailed );
1.111334 +  }
1.111335 +#endif /* ifdef SQLITE_DEBUG */
1.111336 +
1.111337 +  /* At this point, aSample[i] is the first sample that is greater than
1.111338 +  ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
1.111339 +  ** than pVal.  If aSample[i]==pVal, then res==0.
1.111340 +  */
1.111341 +  if( res==0 ){
1.111342 +    aStat[0] = aSample[i].anLt[iCol];
1.111343 +    aStat[1] = aSample[i].anEq[iCol];
1.111344 +  }else{
1.111345 +    tRowcnt iLower, iUpper, iGap;
1.111346 +    if( i==0 ){
1.111347 +      iLower = 0;
1.111348 +      iUpper = aSample[0].anLt[iCol];
1.111349 +    }else{
1.111350 +      iUpper = i>=pIdx->nSample ? pIdx->aiRowEst[0] : aSample[i].anLt[iCol];
1.111351 +      iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
1.111352 +    }
1.111353 +    aStat[1] = (pIdx->nKeyCol>iCol ? pIdx->aAvgEq[iCol] : 1);
1.111354 +    if( iLower>=iUpper ){
1.111355 +      iGap = 0;
1.111356 +    }else{
1.111357 +      iGap = iUpper - iLower;
1.111358 +    }
1.111359 +    if( roundUp ){
1.111360 +      iGap = (iGap*2)/3;
1.111361 +    }else{
1.111362 +      iGap = iGap/3;
1.111363 +    }
1.111364 +    aStat[0] = iLower + iGap;
1.111365 +  }
1.111366 +}
1.111367 +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
1.111368 +
1.111369 +/*
1.111370 +** This function is used to estimate the number of rows that will be visited
1.111371 +** by scanning an index for a range of values. The range may have an upper
1.111372 +** bound, a lower bound, or both. The WHERE clause terms that set the upper
1.111373 +** and lower bounds are represented by pLower and pUpper respectively. For
1.111374 +** example, assuming that index p is on t1(a):
1.111375 +**
1.111376 +**   ... FROM t1 WHERE a > ? AND a < ? ...
1.111377 +**                    |_____|   |_____|
1.111378 +**                       |         |
1.111379 +**                     pLower    pUpper
1.111380 +**
1.111381 +** If either of the upper or lower bound is not present, then NULL is passed in
1.111382 +** place of the corresponding WhereTerm.
1.111383 +**
1.111384 +** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
1.111385 +** column subject to the range constraint. Or, equivalently, the number of
1.111386 +** equality constraints optimized by the proposed index scan. For example,
1.111387 +** assuming index p is on t1(a, b), and the SQL query is:
1.111388 +**
1.111389 +**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
1.111390 +**
1.111391 +** then nEq is set to 1 (as the range restricted column, b, is the second 
1.111392 +** left-most column of the index). Or, if the query is:
1.111393 +**
1.111394 +**   ... FROM t1 WHERE a > ? AND a < ? ...
1.111395 +**
1.111396 +** then nEq is set to 0.
1.111397 +**
1.111398 +** When this function is called, *pnOut is set to the sqlite3LogEst() of the
1.111399 +** number of rows that the index scan is expected to visit without 
1.111400 +** considering the range constraints. If nEq is 0, this is the number of 
1.111401 +** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
1.111402 +** to account for the range contraints pLower and pUpper.
1.111403 +** 
1.111404 +** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
1.111405 +** used, each range inequality reduces the search space by a factor of 4. 
1.111406 +** Hence a pair of constraints (x>? AND x<?) reduces the expected number of
1.111407 +** rows visited by a factor of 16.
1.111408 +*/
1.111409 +static int whereRangeScanEst(
1.111410 +  Parse *pParse,       /* Parsing & code generating context */
1.111411 +  WhereLoopBuilder *pBuilder,
1.111412 +  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
1.111413 +  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
1.111414 +  WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
1.111415 +){
1.111416 +  int rc = SQLITE_OK;
1.111417 +  int nOut = pLoop->nOut;
1.111418 +  LogEst nNew;
1.111419 +
1.111420 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1.111421 +  Index *p = pLoop->u.btree.pIndex;
1.111422 +  int nEq = pLoop->u.btree.nEq;
1.111423 +
1.111424 +  if( p->nSample>0
1.111425 +   && nEq==pBuilder->nRecValid
1.111426 +   && nEq<p->nSampleCol
1.111427 +   && OptimizationEnabled(pParse->db, SQLITE_Stat3) 
1.111428 +  ){
1.111429 +    UnpackedRecord *pRec = pBuilder->pRec;
1.111430 +    tRowcnt a[2];
1.111431 +    u8 aff;
1.111432 +
1.111433 +    /* Variable iLower will be set to the estimate of the number of rows in 
1.111434 +    ** the index that are less than the lower bound of the range query. The
1.111435 +    ** lower bound being the concatenation of $P and $L, where $P is the
1.111436 +    ** key-prefix formed by the nEq values matched against the nEq left-most
1.111437 +    ** columns of the index, and $L is the value in pLower.
1.111438 +    **
1.111439 +    ** Or, if pLower is NULL or $L cannot be extracted from it (because it
1.111440 +    ** is not a simple variable or literal value), the lower bound of the
1.111441 +    ** range is $P. Due to a quirk in the way whereKeyStats() works, even
1.111442 +    ** if $L is available, whereKeyStats() is called for both ($P) and 
1.111443 +    ** ($P:$L) and the larger of the two returned values used.
1.111444 +    **
1.111445 +    ** Similarly, iUpper is to be set to the estimate of the number of rows
1.111446 +    ** less than the upper bound of the range query. Where the upper bound
1.111447 +    ** is either ($P) or ($P:$U). Again, even if $U is available, both values
1.111448 +    ** of iUpper are requested of whereKeyStats() and the smaller used.
1.111449 +    */
1.111450 +    tRowcnt iLower;
1.111451 +    tRowcnt iUpper;
1.111452 +
1.111453 +    if( nEq==p->nKeyCol ){
1.111454 +      aff = SQLITE_AFF_INTEGER;
1.111455 +    }else{
1.111456 +      aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
1.111457 +    }
1.111458 +    /* Determine iLower and iUpper using ($P) only. */
1.111459 +    if( nEq==0 ){
1.111460 +      iLower = 0;
1.111461 +      iUpper = p->aiRowEst[0];
1.111462 +    }else{
1.111463 +      /* Note: this call could be optimized away - since the same values must 
1.111464 +      ** have been requested when testing key $P in whereEqualScanEst().  */
1.111465 +      whereKeyStats(pParse, p, pRec, 0, a);
1.111466 +      iLower = a[0];
1.111467 +      iUpper = a[0] + a[1];
1.111468 +    }
1.111469 +
1.111470 +    /* If possible, improve on the iLower estimate using ($P:$L). */
1.111471 +    if( pLower ){
1.111472 +      int bOk;                    /* True if value is extracted from pExpr */
1.111473 +      Expr *pExpr = pLower->pExpr->pRight;
1.111474 +      assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
1.111475 +      rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
1.111476 +      if( rc==SQLITE_OK && bOk ){
1.111477 +        tRowcnt iNew;
1.111478 +        whereKeyStats(pParse, p, pRec, 0, a);
1.111479 +        iNew = a[0] + ((pLower->eOperator & WO_GT) ? a[1] : 0);
1.111480 +        if( iNew>iLower ) iLower = iNew;
1.111481 +        nOut--;
1.111482 +      }
1.111483 +    }
1.111484 +
1.111485 +    /* If possible, improve on the iUpper estimate using ($P:$U). */
1.111486 +    if( pUpper ){
1.111487 +      int bOk;                    /* True if value is extracted from pExpr */
1.111488 +      Expr *pExpr = pUpper->pExpr->pRight;
1.111489 +      assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
1.111490 +      rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
1.111491 +      if( rc==SQLITE_OK && bOk ){
1.111492 +        tRowcnt iNew;
1.111493 +        whereKeyStats(pParse, p, pRec, 1, a);
1.111494 +        iNew = a[0] + ((pUpper->eOperator & WO_LE) ? a[1] : 0);
1.111495 +        if( iNew<iUpper ) iUpper = iNew;
1.111496 +        nOut--;
1.111497 +      }
1.111498 +    }
1.111499 +
1.111500 +    pBuilder->pRec = pRec;
1.111501 +    if( rc==SQLITE_OK ){
1.111502 +      if( iUpper>iLower ){
1.111503 +        nNew = sqlite3LogEst(iUpper - iLower);
1.111504 +      }else{
1.111505 +        nNew = 10;        assert( 10==sqlite3LogEst(2) );
1.111506 +      }
1.111507 +      if( nNew<nOut ){
1.111508 +        nOut = nNew;
1.111509 +      }
1.111510 +      pLoop->nOut = (LogEst)nOut;
1.111511 +      WHERETRACE(0x10, ("range scan regions: %u..%u  est=%d\n",
1.111512 +                         (u32)iLower, (u32)iUpper, nOut));
1.111513 +      return SQLITE_OK;
1.111514 +    }
1.111515 +  }
1.111516 +#else
1.111517 +  UNUSED_PARAMETER(pParse);
1.111518 +  UNUSED_PARAMETER(pBuilder);
1.111519 +#endif
1.111520 +  assert( pLower || pUpper );
1.111521 +  /* TUNING:  Each inequality constraint reduces the search space 4-fold.
1.111522 +  ** A BETWEEN operator, therefore, reduces the search space 16-fold */
1.111523 +  nNew = nOut;
1.111524 +  if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){
1.111525 +    nNew -= 20;        assert( 20==sqlite3LogEst(4) );
1.111526 +    nOut--;
1.111527 +  }
1.111528 +  if( pUpper ){
1.111529 +    nNew -= 20;        assert( 20==sqlite3LogEst(4) );
1.111530 +    nOut--;
1.111531 +  }
1.111532 +  if( nNew<10 ) nNew = 10;
1.111533 +  if( nNew<nOut ) nOut = nNew;
1.111534 +  pLoop->nOut = (LogEst)nOut;
1.111535 +  return rc;
1.111536 +}
1.111537 +
1.111538 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1.111539 +/*
1.111540 +** Estimate the number of rows that will be returned based on
1.111541 +** an equality constraint x=VALUE and where that VALUE occurs in
1.111542 +** the histogram data.  This only works when x is the left-most
1.111543 +** column of an index and sqlite_stat3 histogram data is available
1.111544 +** for that index.  When pExpr==NULL that means the constraint is
1.111545 +** "x IS NULL" instead of "x=VALUE".
1.111546 +**
1.111547 +** Write the estimated row count into *pnRow and return SQLITE_OK. 
1.111548 +** If unable to make an estimate, leave *pnRow unchanged and return
1.111549 +** non-zero.
1.111550 +**
1.111551 +** This routine can fail if it is unable to load a collating sequence
1.111552 +** required for string comparison, or if unable to allocate memory
1.111553 +** for a UTF conversion required for comparison.  The error is stored
1.111554 +** in the pParse structure.
1.111555 +*/
1.111556 +static int whereEqualScanEst(
1.111557 +  Parse *pParse,       /* Parsing & code generating context */
1.111558 +  WhereLoopBuilder *pBuilder,
1.111559 +  Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
1.111560 +  tRowcnt *pnRow       /* Write the revised row estimate here */
1.111561 +){
1.111562 +  Index *p = pBuilder->pNew->u.btree.pIndex;
1.111563 +  int nEq = pBuilder->pNew->u.btree.nEq;
1.111564 +  UnpackedRecord *pRec = pBuilder->pRec;
1.111565 +  u8 aff;                   /* Column affinity */
1.111566 +  int rc;                   /* Subfunction return code */
1.111567 +  tRowcnt a[2];             /* Statistics */
1.111568 +  int bOk;
1.111569 +
1.111570 +  assert( nEq>=1 );
1.111571 +  assert( nEq<=(p->nKeyCol+1) );
1.111572 +  assert( p->aSample!=0 );
1.111573 +  assert( p->nSample>0 );
1.111574 +  assert( pBuilder->nRecValid<nEq );
1.111575 +
1.111576 +  /* If values are not available for all fields of the index to the left
1.111577 +  ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
1.111578 +  if( pBuilder->nRecValid<(nEq-1) ){
1.111579 +    return SQLITE_NOTFOUND;
1.111580 +  }
1.111581 +
1.111582 +  /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
1.111583 +  ** below would return the same value.  */
1.111584 +  if( nEq>p->nKeyCol ){
1.111585 +    *pnRow = 1;
1.111586 +    return SQLITE_OK;
1.111587 +  }
1.111588 +
1.111589 +  aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
1.111590 +  rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
1.111591 +  pBuilder->pRec = pRec;
1.111592 +  if( rc!=SQLITE_OK ) return rc;
1.111593 +  if( bOk==0 ) return SQLITE_NOTFOUND;
1.111594 +  pBuilder->nRecValid = nEq;
1.111595 +
1.111596 +  whereKeyStats(pParse, p, pRec, 0, a);
1.111597 +  WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
1.111598 +  *pnRow = a[1];
1.111599 +  
1.111600 +  return rc;
1.111601 +}
1.111602 +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
1.111603 +
1.111604 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1.111605 +/*
1.111606 +** Estimate the number of rows that will be returned based on
1.111607 +** an IN constraint where the right-hand side of the IN operator
1.111608 +** is a list of values.  Example:
1.111609 +**
1.111610 +**        WHERE x IN (1,2,3,4)
1.111611 +**
1.111612 +** Write the estimated row count into *pnRow and return SQLITE_OK. 
1.111613 +** If unable to make an estimate, leave *pnRow unchanged and return
1.111614 +** non-zero.
1.111615 +**
1.111616 +** This routine can fail if it is unable to load a collating sequence
1.111617 +** required for string comparison, or if unable to allocate memory
1.111618 +** for a UTF conversion required for comparison.  The error is stored
1.111619 +** in the pParse structure.
1.111620 +*/
1.111621 +static int whereInScanEst(
1.111622 +  Parse *pParse,       /* Parsing & code generating context */
1.111623 +  WhereLoopBuilder *pBuilder,
1.111624 +  ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
1.111625 +  tRowcnt *pnRow       /* Write the revised row estimate here */
1.111626 +){
1.111627 +  Index *p = pBuilder->pNew->u.btree.pIndex;
1.111628 +  int nRecValid = pBuilder->nRecValid;
1.111629 +  int rc = SQLITE_OK;     /* Subfunction return code */
1.111630 +  tRowcnt nEst;           /* Number of rows for a single term */
1.111631 +  tRowcnt nRowEst = 0;    /* New estimate of the number of rows */
1.111632 +  int i;                  /* Loop counter */
1.111633 +
1.111634 +  assert( p->aSample!=0 );
1.111635 +  for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
1.111636 +    nEst = p->aiRowEst[0];
1.111637 +    rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
1.111638 +    nRowEst += nEst;
1.111639 +    pBuilder->nRecValid = nRecValid;
1.111640 +  }
1.111641 +
1.111642 +  if( rc==SQLITE_OK ){
1.111643 +    if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
1.111644 +    *pnRow = nRowEst;
1.111645 +    WHERETRACE(0x10,("IN row estimate: est=%g\n", nRowEst));
1.111646 +  }
1.111647 +  assert( pBuilder->nRecValid==nRecValid );
1.111648 +  return rc;
1.111649 +}
1.111650 +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
1.111651 +
1.111652 +/*
1.111653 +** Disable a term in the WHERE clause.  Except, do not disable the term
1.111654 +** if it controls a LEFT OUTER JOIN and it did not originate in the ON
1.111655 +** or USING clause of that join.
1.111656 +**
1.111657 +** Consider the term t2.z='ok' in the following queries:
1.111658 +**
1.111659 +**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
1.111660 +**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
1.111661 +**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
1.111662 +**
1.111663 +** The t2.z='ok' is disabled in the in (2) because it originates
1.111664 +** in the ON clause.  The term is disabled in (3) because it is not part
1.111665 +** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
1.111666 +**
1.111667 +** Disabling a term causes that term to not be tested in the inner loop
1.111668 +** of the join.  Disabling is an optimization.  When terms are satisfied
1.111669 +** by indices, we disable them to prevent redundant tests in the inner
1.111670 +** loop.  We would get the correct results if nothing were ever disabled,
1.111671 +** but joins might run a little slower.  The trick is to disable as much
1.111672 +** as we can without disabling too much.  If we disabled in (1), we'd get
1.111673 +** the wrong answer.  See ticket #813.
1.111674 +*/
1.111675 +static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
1.111676 +  if( pTerm
1.111677 +      && (pTerm->wtFlags & TERM_CODED)==0
1.111678 +      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
1.111679 +      && (pLevel->notReady & pTerm->prereqAll)==0
1.111680 +  ){
1.111681 +    pTerm->wtFlags |= TERM_CODED;
1.111682 +    if( pTerm->iParent>=0 ){
1.111683 +      WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
1.111684 +      if( (--pOther->nChild)==0 ){
1.111685 +        disableTerm(pLevel, pOther);
1.111686 +      }
1.111687 +    }
1.111688 +  }
1.111689 +}
1.111690 +
1.111691 +/*
1.111692 +** Code an OP_Affinity opcode to apply the column affinity string zAff
1.111693 +** to the n registers starting at base. 
1.111694 +**
1.111695 +** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
1.111696 +** beginning and end of zAff are ignored.  If all entries in zAff are
1.111697 +** SQLITE_AFF_NONE, then no code gets generated.
1.111698 +**
1.111699 +** This routine makes its own copy of zAff so that the caller is free
1.111700 +** to modify zAff after this routine returns.
1.111701 +*/
1.111702 +static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
1.111703 +  Vdbe *v = pParse->pVdbe;
1.111704 +  if( zAff==0 ){
1.111705 +    assert( pParse->db->mallocFailed );
1.111706 +    return;
1.111707 +  }
1.111708 +  assert( v!=0 );
1.111709 +
1.111710 +  /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
1.111711 +  ** and end of the affinity string.
1.111712 +  */
1.111713 +  while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
1.111714 +    n--;
1.111715 +    base++;
1.111716 +    zAff++;
1.111717 +  }
1.111718 +  while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
1.111719 +    n--;
1.111720 +  }
1.111721 +
1.111722 +  /* Code the OP_Affinity opcode if there is anything left to do. */
1.111723 +  if( n>0 ){
1.111724 +    sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
1.111725 +    sqlite3VdbeChangeP4(v, -1, zAff, n);
1.111726 +    sqlite3ExprCacheAffinityChange(pParse, base, n);
1.111727 +  }
1.111728 +}
1.111729 +
1.111730 +
1.111731 +/*
1.111732 +** Generate code for a single equality term of the WHERE clause.  An equality
1.111733 +** term can be either X=expr or X IN (...).   pTerm is the term to be 
1.111734 +** coded.
1.111735 +**
1.111736 +** The current value for the constraint is left in register iReg.
1.111737 +**
1.111738 +** For a constraint of the form X=expr, the expression is evaluated and its
1.111739 +** result is left on the stack.  For constraints of the form X IN (...)
1.111740 +** this routine sets up a loop that will iterate over all values of X.
1.111741 +*/
1.111742 +static int codeEqualityTerm(
1.111743 +  Parse *pParse,      /* The parsing context */
1.111744 +  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
1.111745 +  WhereLevel *pLevel, /* The level of the FROM clause we are working on */
1.111746 +  int iEq,            /* Index of the equality term within this level */
1.111747 +  int bRev,           /* True for reverse-order IN operations */
1.111748 +  int iTarget         /* Attempt to leave results in this register */
1.111749 +){
1.111750 +  Expr *pX = pTerm->pExpr;
1.111751 +  Vdbe *v = pParse->pVdbe;
1.111752 +  int iReg;                  /* Register holding results */
1.111753 +
1.111754 +  assert( iTarget>0 );
1.111755 +  if( pX->op==TK_EQ ){
1.111756 +    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
1.111757 +  }else if( pX->op==TK_ISNULL ){
1.111758 +    iReg = iTarget;
1.111759 +    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
1.111760 +#ifndef SQLITE_OMIT_SUBQUERY
1.111761 +  }else{
1.111762 +    int eType;
1.111763 +    int iTab;
1.111764 +    struct InLoop *pIn;
1.111765 +    WhereLoop *pLoop = pLevel->pWLoop;
1.111766 +
1.111767 +    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
1.111768 +      && pLoop->u.btree.pIndex!=0
1.111769 +      && pLoop->u.btree.pIndex->aSortOrder[iEq]
1.111770 +    ){
1.111771 +      testcase( iEq==0 );
1.111772 +      testcase( bRev );
1.111773 +      bRev = !bRev;
1.111774 +    }
1.111775 +    assert( pX->op==TK_IN );
1.111776 +    iReg = iTarget;
1.111777 +    eType = sqlite3FindInIndex(pParse, pX, 0);
1.111778 +    if( eType==IN_INDEX_INDEX_DESC ){
1.111779 +      testcase( bRev );
1.111780 +      bRev = !bRev;
1.111781 +    }
1.111782 +    iTab = pX->iTable;
1.111783 +    sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
1.111784 +    VdbeCoverageIf(v, bRev);
1.111785 +    VdbeCoverageIf(v, !bRev);
1.111786 +    assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
1.111787 +    pLoop->wsFlags |= WHERE_IN_ABLE;
1.111788 +    if( pLevel->u.in.nIn==0 ){
1.111789 +      pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
1.111790 +    }
1.111791 +    pLevel->u.in.nIn++;
1.111792 +    pLevel->u.in.aInLoop =
1.111793 +       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
1.111794 +                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
1.111795 +    pIn = pLevel->u.in.aInLoop;
1.111796 +    if( pIn ){
1.111797 +      pIn += pLevel->u.in.nIn - 1;
1.111798 +      pIn->iCur = iTab;
1.111799 +      if( eType==IN_INDEX_ROWID ){
1.111800 +        pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
1.111801 +      }else{
1.111802 +        pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
1.111803 +      }
1.111804 +      pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
1.111805 +      sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
1.111806 +    }else{
1.111807 +      pLevel->u.in.nIn = 0;
1.111808 +    }
1.111809 +#endif
1.111810 +  }
1.111811 +  disableTerm(pLevel, pTerm);
1.111812 +  return iReg;
1.111813 +}
1.111814 +
1.111815 +/*
1.111816 +** Generate code that will evaluate all == and IN constraints for an
1.111817 +** index scan.
1.111818 +**
1.111819 +** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
1.111820 +** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
1.111821 +** The index has as many as three equality constraints, but in this
1.111822 +** example, the third "c" value is an inequality.  So only two 
1.111823 +** constraints are coded.  This routine will generate code to evaluate
1.111824 +** a==5 and b IN (1,2,3).  The current values for a and b will be stored
1.111825 +** in consecutive registers and the index of the first register is returned.
1.111826 +**
1.111827 +** In the example above nEq==2.  But this subroutine works for any value
1.111828 +** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
1.111829 +** The only thing it does is allocate the pLevel->iMem memory cell and
1.111830 +** compute the affinity string.
1.111831 +**
1.111832 +** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints
1.111833 +** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is
1.111834 +** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
1.111835 +** occurs after the nEq quality constraints.
1.111836 +**
1.111837 +** This routine allocates a range of nEq+nExtraReg memory cells and returns
1.111838 +** the index of the first memory cell in that range. The code that
1.111839 +** calls this routine will use that memory range to store keys for
1.111840 +** start and termination conditions of the loop.
1.111841 +** key value of the loop.  If one or more IN operators appear, then
1.111842 +** this routine allocates an additional nEq memory cells for internal
1.111843 +** use.
1.111844 +**
1.111845 +** Before returning, *pzAff is set to point to a buffer containing a
1.111846 +** copy of the column affinity string of the index allocated using
1.111847 +** sqlite3DbMalloc(). Except, entries in the copy of the string associated
1.111848 +** with equality constraints that use NONE affinity are set to
1.111849 +** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
1.111850 +**
1.111851 +**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
1.111852 +**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
1.111853 +**
1.111854 +** In the example above, the index on t1(a) has TEXT affinity. But since
1.111855 +** the right hand side of the equality constraint (t2.b) has NONE affinity,
1.111856 +** no conversion should be attempted before using a t2.b value as part of
1.111857 +** a key to search the index. Hence the first byte in the returned affinity
1.111858 +** string in this example would be set to SQLITE_AFF_NONE.
1.111859 +*/
1.111860 +static int codeAllEqualityTerms(
1.111861 +  Parse *pParse,        /* Parsing context */
1.111862 +  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
1.111863 +  int bRev,             /* Reverse the order of IN operators */
1.111864 +  int nExtraReg,        /* Number of extra registers to allocate */
1.111865 +  char **pzAff          /* OUT: Set to point to affinity string */
1.111866 +){
1.111867 +  u16 nEq;                      /* The number of == or IN constraints to code */
1.111868 +  u16 nSkip;                    /* Number of left-most columns to skip */
1.111869 +  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
1.111870 +  Index *pIdx;                  /* The index being used for this loop */
1.111871 +  WhereTerm *pTerm;             /* A single constraint term */
1.111872 +  WhereLoop *pLoop;             /* The WhereLoop object */
1.111873 +  int j;                        /* Loop counter */
1.111874 +  int regBase;                  /* Base register */
1.111875 +  int nReg;                     /* Number of registers to allocate */
1.111876 +  char *zAff;                   /* Affinity string to return */
1.111877 +
1.111878 +  /* This module is only called on query plans that use an index. */
1.111879 +  pLoop = pLevel->pWLoop;
1.111880 +  assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
1.111881 +  nEq = pLoop->u.btree.nEq;
1.111882 +  nSkip = pLoop->u.btree.nSkip;
1.111883 +  pIdx = pLoop->u.btree.pIndex;
1.111884 +  assert( pIdx!=0 );
1.111885 +
1.111886 +  /* Figure out how many memory cells we will need then allocate them.
1.111887 +  */
1.111888 +  regBase = pParse->nMem + 1;
1.111889 +  nReg = pLoop->u.btree.nEq + nExtraReg;
1.111890 +  pParse->nMem += nReg;
1.111891 +
1.111892 +  zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
1.111893 +  if( !zAff ){
1.111894 +    pParse->db->mallocFailed = 1;
1.111895 +  }
1.111896 +
1.111897 +  if( nSkip ){
1.111898 +    int iIdxCur = pLevel->iIdxCur;
1.111899 +    sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
1.111900 +    VdbeCoverageIf(v, bRev==0);
1.111901 +    VdbeCoverageIf(v, bRev!=0);
1.111902 +    VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
1.111903 +    j = sqlite3VdbeAddOp0(v, OP_Goto);
1.111904 +    pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
1.111905 +                            iIdxCur, 0, regBase, nSkip);
1.111906 +    VdbeCoverageIf(v, bRev==0);
1.111907 +    VdbeCoverageIf(v, bRev!=0);
1.111908 +    sqlite3VdbeJumpHere(v, j);
1.111909 +    for(j=0; j<nSkip; j++){
1.111910 +      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
1.111911 +      assert( pIdx->aiColumn[j]>=0 );
1.111912 +      VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
1.111913 +    }
1.111914 +  }    
1.111915 +
1.111916 +  /* Evaluate the equality constraints
1.111917 +  */
1.111918 +  assert( zAff==0 || (int)strlen(zAff)>=nEq );
1.111919 +  for(j=nSkip; j<nEq; j++){
1.111920 +    int r1;
1.111921 +    pTerm = pLoop->aLTerm[j];
1.111922 +    assert( pTerm!=0 );
1.111923 +    /* The following testcase is true for indices with redundant columns. 
1.111924 +    ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
1.111925 +    testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
1.111926 +    testcase( pTerm->wtFlags & TERM_VIRTUAL );
1.111927 +    r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
1.111928 +    if( r1!=regBase+j ){
1.111929 +      if( nReg==1 ){
1.111930 +        sqlite3ReleaseTempReg(pParse, regBase);
1.111931 +        regBase = r1;
1.111932 +      }else{
1.111933 +        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
1.111934 +      }
1.111935 +    }
1.111936 +    testcase( pTerm->eOperator & WO_ISNULL );
1.111937 +    testcase( pTerm->eOperator & WO_IN );
1.111938 +    if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
1.111939 +      Expr *pRight = pTerm->pExpr->pRight;
1.111940 +      if( sqlite3ExprCanBeNull(pRight) ){
1.111941 +        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
1.111942 +        VdbeCoverage(v);
1.111943 +      }
1.111944 +      if( zAff ){
1.111945 +        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
1.111946 +          zAff[j] = SQLITE_AFF_NONE;
1.111947 +        }
1.111948 +        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
1.111949 +          zAff[j] = SQLITE_AFF_NONE;
1.111950 +        }
1.111951 +      }
1.111952 +    }
1.111953 +  }
1.111954 +  *pzAff = zAff;
1.111955 +  return regBase;
1.111956 +}
1.111957 +
1.111958 +#ifndef SQLITE_OMIT_EXPLAIN
1.111959 +/*
1.111960 +** This routine is a helper for explainIndexRange() below
1.111961 +**
1.111962 +** pStr holds the text of an expression that we are building up one term
1.111963 +** at a time.  This routine adds a new term to the end of the expression.
1.111964 +** Terms are separated by AND so add the "AND" text for second and subsequent
1.111965 +** terms only.
1.111966 +*/
1.111967 +static void explainAppendTerm(
1.111968 +  StrAccum *pStr,             /* The text expression being built */
1.111969 +  int iTerm,                  /* Index of this term.  First is zero */
1.111970 +  const char *zColumn,        /* Name of the column */
1.111971 +  const char *zOp             /* Name of the operator */
1.111972 +){
1.111973 +  if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
1.111974 +  sqlite3StrAccumAppendAll(pStr, zColumn);
1.111975 +  sqlite3StrAccumAppend(pStr, zOp, 1);
1.111976 +  sqlite3StrAccumAppend(pStr, "?", 1);
1.111977 +}
1.111978 +
1.111979 +/*
1.111980 +** Argument pLevel describes a strategy for scanning table pTab. This 
1.111981 +** function returns a pointer to a string buffer containing a description
1.111982 +** of the subset of table rows scanned by the strategy in the form of an
1.111983 +** SQL expression. Or, if all rows are scanned, NULL is returned.
1.111984 +**
1.111985 +** For example, if the query:
1.111986 +**
1.111987 +**   SELECT * FROM t1 WHERE a=1 AND b>2;
1.111988 +**
1.111989 +** is run and there is an index on (a, b), then this function returns a
1.111990 +** string similar to:
1.111991 +**
1.111992 +**   "a=? AND b>?"
1.111993 +**
1.111994 +** The returned pointer points to memory obtained from sqlite3DbMalloc().
1.111995 +** It is the responsibility of the caller to free the buffer when it is
1.111996 +** no longer required.
1.111997 +*/
1.111998 +static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
1.111999 +  Index *pIndex = pLoop->u.btree.pIndex;
1.112000 +  u16 nEq = pLoop->u.btree.nEq;
1.112001 +  u16 nSkip = pLoop->u.btree.nSkip;
1.112002 +  int i, j;
1.112003 +  Column *aCol = pTab->aCol;
1.112004 +  i16 *aiColumn = pIndex->aiColumn;
1.112005 +  StrAccum txt;
1.112006 +
1.112007 +  if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
1.112008 +    return 0;
1.112009 +  }
1.112010 +  sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
1.112011 +  txt.db = db;
1.112012 +  sqlite3StrAccumAppend(&txt, " (", 2);
1.112013 +  for(i=0; i<nEq; i++){
1.112014 +    char *z = (i==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[i]].zName;
1.112015 +    if( i>=nSkip ){
1.112016 +      explainAppendTerm(&txt, i, z, "=");
1.112017 +    }else{
1.112018 +      if( i ) sqlite3StrAccumAppend(&txt, " AND ", 5);
1.112019 +      sqlite3StrAccumAppend(&txt, "ANY(", 4);
1.112020 +      sqlite3StrAccumAppendAll(&txt, z);
1.112021 +      sqlite3StrAccumAppend(&txt, ")", 1);
1.112022 +    }
1.112023 +  }
1.112024 +
1.112025 +  j = i;
1.112026 +  if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
1.112027 +    char *z = (j==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[j]].zName;
1.112028 +    explainAppendTerm(&txt, i++, z, ">");
1.112029 +  }
1.112030 +  if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
1.112031 +    char *z = (j==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[j]].zName;
1.112032 +    explainAppendTerm(&txt, i, z, "<");
1.112033 +  }
1.112034 +  sqlite3StrAccumAppend(&txt, ")", 1);
1.112035 +  return sqlite3StrAccumFinish(&txt);
1.112036 +}
1.112037 +
1.112038 +/*
1.112039 +** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
1.112040 +** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
1.112041 +** record is added to the output to describe the table scan strategy in 
1.112042 +** pLevel.
1.112043 +*/
1.112044 +static void explainOneScan(
1.112045 +  Parse *pParse,                  /* Parse context */
1.112046 +  SrcList *pTabList,              /* Table list this loop refers to */
1.112047 +  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
1.112048 +  int iLevel,                     /* Value for "level" column of output */
1.112049 +  int iFrom,                      /* Value for "from" column of output */
1.112050 +  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
1.112051 +){
1.112052 +#ifndef SQLITE_DEBUG
1.112053 +  if( pParse->explain==2 )
1.112054 +#endif
1.112055 +  {
1.112056 +    struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
1.112057 +    Vdbe *v = pParse->pVdbe;      /* VM being constructed */
1.112058 +    sqlite3 *db = pParse->db;     /* Database handle */
1.112059 +    char *zMsg;                   /* Text to add to EQP output */
1.112060 +    int iId = pParse->iSelectId;  /* Select id (left-most output column) */
1.112061 +    int isSearch;                 /* True for a SEARCH. False for SCAN. */
1.112062 +    WhereLoop *pLoop;             /* The controlling WhereLoop object */
1.112063 +    u32 flags;                    /* Flags that describe this loop */
1.112064 +
1.112065 +    pLoop = pLevel->pWLoop;
1.112066 +    flags = pLoop->wsFlags;
1.112067 +    if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
1.112068 +
1.112069 +    isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
1.112070 +            || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
1.112071 +            || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
1.112072 +
1.112073 +    zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
1.112074 +    if( pItem->pSelect ){
1.112075 +      zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
1.112076 +    }else{
1.112077 +      zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
1.112078 +    }
1.112079 +
1.112080 +    if( pItem->zAlias ){
1.112081 +      zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
1.112082 +    }
1.112083 +    if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
1.112084 +     && ALWAYS(pLoop->u.btree.pIndex!=0)
1.112085 +    ){
1.112086 +      char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
1.112087 +      zMsg = sqlite3MAppendf(db, zMsg,
1.112088 +               ((flags & WHERE_AUTO_INDEX) ? 
1.112089 +                   "%s USING AUTOMATIC %sINDEX%.0s%s" :
1.112090 +                   "%s USING %sINDEX %s%s"), 
1.112091 +               zMsg, ((flags & WHERE_IDX_ONLY) ? "COVERING " : ""),
1.112092 +               pLoop->u.btree.pIndex->zName, zWhere);
1.112093 +      sqlite3DbFree(db, zWhere);
1.112094 +    }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
1.112095 +      zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
1.112096 +
1.112097 +      if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
1.112098 +        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
1.112099 +      }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
1.112100 +        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
1.112101 +      }else if( flags&WHERE_BTM_LIMIT ){
1.112102 +        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
1.112103 +      }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
1.112104 +        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
1.112105 +      }
1.112106 +    }
1.112107 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.112108 +    else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
1.112109 +      zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
1.112110 +                  pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
1.112111 +    }
1.112112 +#endif
1.112113 +    zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
1.112114 +    sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
1.112115 +  }
1.112116 +}
1.112117 +#else
1.112118 +# define explainOneScan(u,v,w,x,y,z)
1.112119 +#endif /* SQLITE_OMIT_EXPLAIN */
1.112120 +
1.112121 +
1.112122 +/*
1.112123 +** Generate code for the start of the iLevel-th loop in the WHERE clause
1.112124 +** implementation described by pWInfo.
1.112125 +*/
1.112126 +static Bitmask codeOneLoopStart(
1.112127 +  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
1.112128 +  int iLevel,          /* Which level of pWInfo->a[] should be coded */
1.112129 +  Bitmask notReady     /* Which tables are currently available */
1.112130 +){
1.112131 +  int j, k;            /* Loop counters */
1.112132 +  int iCur;            /* The VDBE cursor for the table */
1.112133 +  int addrNxt;         /* Where to jump to continue with the next IN case */
1.112134 +  int omitTable;       /* True if we use the index only */
1.112135 +  int bRev;            /* True if we need to scan in reverse order */
1.112136 +  WhereLevel *pLevel;  /* The where level to be coded */
1.112137 +  WhereLoop *pLoop;    /* The WhereLoop object being coded */
1.112138 +  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
1.112139 +  WhereTerm *pTerm;               /* A WHERE clause term */
1.112140 +  Parse *pParse;                  /* Parsing context */
1.112141 +  sqlite3 *db;                    /* Database connection */
1.112142 +  Vdbe *v;                        /* The prepared stmt under constructions */
1.112143 +  struct SrcList_item *pTabItem;  /* FROM clause term being coded */
1.112144 +  int addrBrk;                    /* Jump here to break out of the loop */
1.112145 +  int addrCont;                   /* Jump here to continue with next cycle */
1.112146 +  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
1.112147 +  int iReleaseReg = 0;      /* Temp register to free before returning */
1.112148 +
1.112149 +  pParse = pWInfo->pParse;
1.112150 +  v = pParse->pVdbe;
1.112151 +  pWC = &pWInfo->sWC;
1.112152 +  db = pParse->db;
1.112153 +  pLevel = &pWInfo->a[iLevel];
1.112154 +  pLoop = pLevel->pWLoop;
1.112155 +  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
1.112156 +  iCur = pTabItem->iCursor;
1.112157 +  pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
1.112158 +  bRev = (pWInfo->revMask>>iLevel)&1;
1.112159 +  omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 
1.112160 +           && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
1.112161 +  VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
1.112162 +
1.112163 +  /* Create labels for the "break" and "continue" instructions
1.112164 +  ** for the current loop.  Jump to addrBrk to break out of a loop.
1.112165 +  ** Jump to cont to go immediately to the next iteration of the
1.112166 +  ** loop.
1.112167 +  **
1.112168 +  ** When there is an IN operator, we also have a "addrNxt" label that
1.112169 +  ** means to continue with the next IN value combination.  When
1.112170 +  ** there are no IN operators in the constraints, the "addrNxt" label
1.112171 +  ** is the same as "addrBrk".
1.112172 +  */
1.112173 +  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
1.112174 +  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
1.112175 +
1.112176 +  /* If this is the right table of a LEFT OUTER JOIN, allocate and
1.112177 +  ** initialize a memory cell that records if this table matches any
1.112178 +  ** row of the left table of the join.
1.112179 +  */
1.112180 +  if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
1.112181 +    pLevel->iLeftJoin = ++pParse->nMem;
1.112182 +    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
1.112183 +    VdbeComment((v, "init LEFT JOIN no-match flag"));
1.112184 +  }
1.112185 +
1.112186 +  /* Special case of a FROM clause subquery implemented as a co-routine */
1.112187 +  if( pTabItem->viaCoroutine ){
1.112188 +    int regYield = pTabItem->regReturn;
1.112189 +    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
1.112190 +    pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
1.112191 +    VdbeCoverage(v);
1.112192 +    VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
1.112193 +    pLevel->op = OP_Goto;
1.112194 +  }else
1.112195 +
1.112196 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.112197 +  if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
1.112198 +    /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
1.112199 +    **          to access the data.
1.112200 +    */
1.112201 +    int iReg;   /* P3 Value for OP_VFilter */
1.112202 +    int addrNotFound;
1.112203 +    int nConstraint = pLoop->nLTerm;
1.112204 +
1.112205 +    sqlite3ExprCachePush(pParse);
1.112206 +    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
1.112207 +    addrNotFound = pLevel->addrBrk;
1.112208 +    for(j=0; j<nConstraint; j++){
1.112209 +      int iTarget = iReg+j+2;
1.112210 +      pTerm = pLoop->aLTerm[j];
1.112211 +      if( pTerm==0 ) continue;
1.112212 +      if( pTerm->eOperator & WO_IN ){
1.112213 +        codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
1.112214 +        addrNotFound = pLevel->addrNxt;
1.112215 +      }else{
1.112216 +        sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
1.112217 +      }
1.112218 +    }
1.112219 +    sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
1.112220 +    sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
1.112221 +    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
1.112222 +                      pLoop->u.vtab.idxStr,
1.112223 +                      pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
1.112224 +    VdbeCoverage(v);
1.112225 +    pLoop->u.vtab.needFree = 0;
1.112226 +    for(j=0; j<nConstraint && j<16; j++){
1.112227 +      if( (pLoop->u.vtab.omitMask>>j)&1 ){
1.112228 +        disableTerm(pLevel, pLoop->aLTerm[j]);
1.112229 +      }
1.112230 +    }
1.112231 +    pLevel->op = OP_VNext;
1.112232 +    pLevel->p1 = iCur;
1.112233 +    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
1.112234 +    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
1.112235 +    sqlite3ExprCachePop(pParse, 1);
1.112236 +  }else
1.112237 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
1.112238 +
1.112239 +  if( (pLoop->wsFlags & WHERE_IPK)!=0
1.112240 +   && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
1.112241 +  ){
1.112242 +    /* Case 2:  We can directly reference a single row using an
1.112243 +    **          equality comparison against the ROWID field.  Or
1.112244 +    **          we reference multiple rows using a "rowid IN (...)"
1.112245 +    **          construct.
1.112246 +    */
1.112247 +    assert( pLoop->u.btree.nEq==1 );
1.112248 +    pTerm = pLoop->aLTerm[0];
1.112249 +    assert( pTerm!=0 );
1.112250 +    assert( pTerm->pExpr!=0 );
1.112251 +    assert( omitTable==0 );
1.112252 +    testcase( pTerm->wtFlags & TERM_VIRTUAL );
1.112253 +    iReleaseReg = ++pParse->nMem;
1.112254 +    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
1.112255 +    if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
1.112256 +    addrNxt = pLevel->addrNxt;
1.112257 +    sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
1.112258 +    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
1.112259 +    VdbeCoverage(v);
1.112260 +    sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
1.112261 +    sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
1.112262 +    VdbeComment((v, "pk"));
1.112263 +    pLevel->op = OP_Noop;
1.112264 +  }else if( (pLoop->wsFlags & WHERE_IPK)!=0
1.112265 +         && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
1.112266 +  ){
1.112267 +    /* Case 3:  We have an inequality comparison against the ROWID field.
1.112268 +    */
1.112269 +    int testOp = OP_Noop;
1.112270 +    int start;
1.112271 +    int memEndValue = 0;
1.112272 +    WhereTerm *pStart, *pEnd;
1.112273 +
1.112274 +    assert( omitTable==0 );
1.112275 +    j = 0;
1.112276 +    pStart = pEnd = 0;
1.112277 +    if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
1.112278 +    if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
1.112279 +    assert( pStart!=0 || pEnd!=0 );
1.112280 +    if( bRev ){
1.112281 +      pTerm = pStart;
1.112282 +      pStart = pEnd;
1.112283 +      pEnd = pTerm;
1.112284 +    }
1.112285 +    if( pStart ){
1.112286 +      Expr *pX;             /* The expression that defines the start bound */
1.112287 +      int r1, rTemp;        /* Registers for holding the start boundary */
1.112288 +
1.112289 +      /* The following constant maps TK_xx codes into corresponding 
1.112290 +      ** seek opcodes.  It depends on a particular ordering of TK_xx
1.112291 +      */
1.112292 +      const u8 aMoveOp[] = {
1.112293 +           /* TK_GT */  OP_SeekGT,
1.112294 +           /* TK_LE */  OP_SeekLE,
1.112295 +           /* TK_LT */  OP_SeekLT,
1.112296 +           /* TK_GE */  OP_SeekGE
1.112297 +      };
1.112298 +      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
1.112299 +      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
1.112300 +      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
1.112301 +
1.112302 +      assert( (pStart->wtFlags & TERM_VNULL)==0 );
1.112303 +      testcase( pStart->wtFlags & TERM_VIRTUAL );
1.112304 +      pX = pStart->pExpr;
1.112305 +      assert( pX!=0 );
1.112306 +      testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
1.112307 +      r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
1.112308 +      sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
1.112309 +      VdbeComment((v, "pk"));
1.112310 +      VdbeCoverageIf(v, pX->op==TK_GT);
1.112311 +      VdbeCoverageIf(v, pX->op==TK_LE);
1.112312 +      VdbeCoverageIf(v, pX->op==TK_LT);
1.112313 +      VdbeCoverageIf(v, pX->op==TK_GE);
1.112314 +      sqlite3ExprCacheAffinityChange(pParse, r1, 1);
1.112315 +      sqlite3ReleaseTempReg(pParse, rTemp);
1.112316 +      disableTerm(pLevel, pStart);
1.112317 +    }else{
1.112318 +      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
1.112319 +      VdbeCoverageIf(v, bRev==0);
1.112320 +      VdbeCoverageIf(v, bRev!=0);
1.112321 +    }
1.112322 +    if( pEnd ){
1.112323 +      Expr *pX;
1.112324 +      pX = pEnd->pExpr;
1.112325 +      assert( pX!=0 );
1.112326 +      assert( (pEnd->wtFlags & TERM_VNULL)==0 );
1.112327 +      testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
1.112328 +      testcase( pEnd->wtFlags & TERM_VIRTUAL );
1.112329 +      memEndValue = ++pParse->nMem;
1.112330 +      sqlite3ExprCode(pParse, pX->pRight, memEndValue);
1.112331 +      if( pX->op==TK_LT || pX->op==TK_GT ){
1.112332 +        testOp = bRev ? OP_Le : OP_Ge;
1.112333 +      }else{
1.112334 +        testOp = bRev ? OP_Lt : OP_Gt;
1.112335 +      }
1.112336 +      disableTerm(pLevel, pEnd);
1.112337 +    }
1.112338 +    start = sqlite3VdbeCurrentAddr(v);
1.112339 +    pLevel->op = bRev ? OP_Prev : OP_Next;
1.112340 +    pLevel->p1 = iCur;
1.112341 +    pLevel->p2 = start;
1.112342 +    assert( pLevel->p5==0 );
1.112343 +    if( testOp!=OP_Noop ){
1.112344 +      iRowidReg = ++pParse->nMem;
1.112345 +      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
1.112346 +      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
1.112347 +      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
1.112348 +      VdbeCoverageIf(v, testOp==OP_Le);
1.112349 +      VdbeCoverageIf(v, testOp==OP_Lt);
1.112350 +      VdbeCoverageIf(v, testOp==OP_Ge);
1.112351 +      VdbeCoverageIf(v, testOp==OP_Gt);
1.112352 +      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
1.112353 +    }
1.112354 +  }else if( pLoop->wsFlags & WHERE_INDEXED ){
1.112355 +    /* Case 4: A scan using an index.
1.112356 +    **
1.112357 +    **         The WHERE clause may contain zero or more equality 
1.112358 +    **         terms ("==" or "IN" operators) that refer to the N
1.112359 +    **         left-most columns of the index. It may also contain
1.112360 +    **         inequality constraints (>, <, >= or <=) on the indexed
1.112361 +    **         column that immediately follows the N equalities. Only 
1.112362 +    **         the right-most column can be an inequality - the rest must
1.112363 +    **         use the "==" and "IN" operators. For example, if the 
1.112364 +    **         index is on (x,y,z), then the following clauses are all 
1.112365 +    **         optimized:
1.112366 +    **
1.112367 +    **            x=5
1.112368 +    **            x=5 AND y=10
1.112369 +    **            x=5 AND y<10
1.112370 +    **            x=5 AND y>5 AND y<10
1.112371 +    **            x=5 AND y=5 AND z<=10
1.112372 +    **
1.112373 +    **         The z<10 term of the following cannot be used, only
1.112374 +    **         the x=5 term:
1.112375 +    **
1.112376 +    **            x=5 AND z<10
1.112377 +    **
1.112378 +    **         N may be zero if there are inequality constraints.
1.112379 +    **         If there are no inequality constraints, then N is at
1.112380 +    **         least one.
1.112381 +    **
1.112382 +    **         This case is also used when there are no WHERE clause
1.112383 +    **         constraints but an index is selected anyway, in order
1.112384 +    **         to force the output order to conform to an ORDER BY.
1.112385 +    */  
1.112386 +    static const u8 aStartOp[] = {
1.112387 +      0,
1.112388 +      0,
1.112389 +      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
1.112390 +      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
1.112391 +      OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
1.112392 +      OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
1.112393 +      OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
1.112394 +      OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
1.112395 +    };
1.112396 +    static const u8 aEndOp[] = {
1.112397 +      OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
1.112398 +      OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
1.112399 +      OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
1.112400 +      OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
1.112401 +    };
1.112402 +    u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
1.112403 +    int regBase;                 /* Base register holding constraint values */
1.112404 +    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
1.112405 +    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
1.112406 +    int startEq;                 /* True if range start uses ==, >= or <= */
1.112407 +    int endEq;                   /* True if range end uses ==, >= or <= */
1.112408 +    int start_constraints;       /* Start of range is constrained */
1.112409 +    int nConstraint;             /* Number of constraint terms */
1.112410 +    Index *pIdx;                 /* The index we will be using */
1.112411 +    int iIdxCur;                 /* The VDBE cursor for the index */
1.112412 +    int nExtraReg = 0;           /* Number of extra registers needed */
1.112413 +    int op;                      /* Instruction opcode */
1.112414 +    char *zStartAff;             /* Affinity for start of range constraint */
1.112415 +    char cEndAff = 0;            /* Affinity for end of range constraint */
1.112416 +    u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
1.112417 +    u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
1.112418 +
1.112419 +    pIdx = pLoop->u.btree.pIndex;
1.112420 +    iIdxCur = pLevel->iIdxCur;
1.112421 +    assert( nEq>=pLoop->u.btree.nSkip );
1.112422 +
1.112423 +    /* If this loop satisfies a sort order (pOrderBy) request that 
1.112424 +    ** was passed to this function to implement a "SELECT min(x) ..." 
1.112425 +    ** query, then the caller will only allow the loop to run for
1.112426 +    ** a single iteration. This means that the first row returned
1.112427 +    ** should not have a NULL value stored in 'x'. If column 'x' is
1.112428 +    ** the first one after the nEq equality constraints in the index,
1.112429 +    ** this requires some special handling.
1.112430 +    */
1.112431 +    if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
1.112432 +     && (pWInfo->bOBSat!=0)
1.112433 +     && (pIdx->nKeyCol>nEq)
1.112434 +    ){
1.112435 +      assert( pLoop->u.btree.nSkip==0 );
1.112436 +      bSeekPastNull = 1;
1.112437 +      nExtraReg = 1;
1.112438 +    }
1.112439 +
1.112440 +    /* Find any inequality constraint terms for the start and end 
1.112441 +    ** of the range. 
1.112442 +    */
1.112443 +    j = nEq;
1.112444 +    if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
1.112445 +      pRangeStart = pLoop->aLTerm[j++];
1.112446 +      nExtraReg = 1;
1.112447 +    }
1.112448 +    if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
1.112449 +      pRangeEnd = pLoop->aLTerm[j++];
1.112450 +      nExtraReg = 1;
1.112451 +      if( pRangeStart==0
1.112452 +       && (j = pIdx->aiColumn[nEq])>=0 
1.112453 +       && pIdx->pTable->aCol[j].notNull==0
1.112454 +      ){
1.112455 +        bSeekPastNull = 1;
1.112456 +      }
1.112457 +    }
1.112458 +    assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
1.112459 +
1.112460 +    /* Generate code to evaluate all constraint terms using == or IN
1.112461 +    ** and store the values of those terms in an array of registers
1.112462 +    ** starting at regBase.
1.112463 +    */
1.112464 +    regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
1.112465 +    assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
1.112466 +    if( zStartAff ) cEndAff = zStartAff[nEq];
1.112467 +    addrNxt = pLevel->addrNxt;
1.112468 +
1.112469 +    /* If we are doing a reverse order scan on an ascending index, or
1.112470 +    ** a forward order scan on a descending index, interchange the 
1.112471 +    ** start and end terms (pRangeStart and pRangeEnd).
1.112472 +    */
1.112473 +    if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
1.112474 +     || (bRev && pIdx->nKeyCol==nEq)
1.112475 +    ){
1.112476 +      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
1.112477 +      SWAP(u8, bSeekPastNull, bStopAtNull);
1.112478 +    }
1.112479 +
1.112480 +    testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
1.112481 +    testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
1.112482 +    testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
1.112483 +    testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
1.112484 +    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
1.112485 +    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
1.112486 +    start_constraints = pRangeStart || nEq>0;
1.112487 +
1.112488 +    /* Seek the index cursor to the start of the range. */
1.112489 +    nConstraint = nEq;
1.112490 +    if( pRangeStart ){
1.112491 +      Expr *pRight = pRangeStart->pExpr->pRight;
1.112492 +      sqlite3ExprCode(pParse, pRight, regBase+nEq);
1.112493 +      if( (pRangeStart->wtFlags & TERM_VNULL)==0
1.112494 +       && sqlite3ExprCanBeNull(pRight)
1.112495 +      ){
1.112496 +        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
1.112497 +        VdbeCoverage(v);
1.112498 +      }
1.112499 +      if( zStartAff ){
1.112500 +        if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
1.112501 +          /* Since the comparison is to be performed with no conversions
1.112502 +          ** applied to the operands, set the affinity to apply to pRight to 
1.112503 +          ** SQLITE_AFF_NONE.  */
1.112504 +          zStartAff[nEq] = SQLITE_AFF_NONE;
1.112505 +        }
1.112506 +        if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
1.112507 +          zStartAff[nEq] = SQLITE_AFF_NONE;
1.112508 +        }
1.112509 +      }  
1.112510 +      nConstraint++;
1.112511 +      testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
1.112512 +    }else if( bSeekPastNull ){
1.112513 +      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
1.112514 +      nConstraint++;
1.112515 +      startEq = 0;
1.112516 +      start_constraints = 1;
1.112517 +    }
1.112518 +    codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
1.112519 +    op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
1.112520 +    assert( op!=0 );
1.112521 +    sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
1.112522 +    VdbeCoverage(v);
1.112523 +    VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
1.112524 +    VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
1.112525 +    VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
1.112526 +    VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
1.112527 +    VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
1.112528 +    VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
1.112529 +
1.112530 +    /* Load the value for the inequality constraint at the end of the
1.112531 +    ** range (if any).
1.112532 +    */
1.112533 +    nConstraint = nEq;
1.112534 +    if( pRangeEnd ){
1.112535 +      Expr *pRight = pRangeEnd->pExpr->pRight;
1.112536 +      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
1.112537 +      sqlite3ExprCode(pParse, pRight, regBase+nEq);
1.112538 +      if( (pRangeEnd->wtFlags & TERM_VNULL)==0
1.112539 +       && sqlite3ExprCanBeNull(pRight)
1.112540 +      ){
1.112541 +        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
1.112542 +        VdbeCoverage(v);
1.112543 +      }
1.112544 +      if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
1.112545 +       && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
1.112546 +      ){
1.112547 +        codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
1.112548 +      }
1.112549 +      nConstraint++;
1.112550 +      testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
1.112551 +    }else if( bStopAtNull ){
1.112552 +      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
1.112553 +      endEq = 0;
1.112554 +      nConstraint++;
1.112555 +    }
1.112556 +    sqlite3DbFree(db, zStartAff);
1.112557 +
1.112558 +    /* Top of the loop body */
1.112559 +    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
1.112560 +
1.112561 +    /* Check if the index cursor is past the end of the range. */
1.112562 +    if( nConstraint ){
1.112563 +      op = aEndOp[bRev*2 + endEq];
1.112564 +      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
1.112565 +      testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
1.112566 +      testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
1.112567 +      testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
1.112568 +      testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
1.112569 +    }
1.112570 +
1.112571 +    /* Seek the table cursor, if required */
1.112572 +    disableTerm(pLevel, pRangeStart);
1.112573 +    disableTerm(pLevel, pRangeEnd);
1.112574 +    if( omitTable ){
1.112575 +      /* pIdx is a covering index.  No need to access the main table. */
1.112576 +    }else if( HasRowid(pIdx->pTable) ){
1.112577 +      iRowidReg = ++pParse->nMem;
1.112578 +      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
1.112579 +      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
1.112580 +      sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
1.112581 +    }else{
1.112582 +      Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
1.112583 +      iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
1.112584 +      for(j=0; j<pPk->nKeyCol; j++){
1.112585 +        k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
1.112586 +        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
1.112587 +      }
1.112588 +      sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
1.112589 +                           iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
1.112590 +    }
1.112591 +
1.112592 +    /* Record the instruction used to terminate the loop. Disable 
1.112593 +    ** WHERE clause terms made redundant by the index range scan.
1.112594 +    */
1.112595 +    if( pLoop->wsFlags & WHERE_ONEROW ){
1.112596 +      pLevel->op = OP_Noop;
1.112597 +    }else if( bRev ){
1.112598 +      pLevel->op = OP_Prev;
1.112599 +    }else{
1.112600 +      pLevel->op = OP_Next;
1.112601 +    }
1.112602 +    pLevel->p1 = iIdxCur;
1.112603 +    assert( (WHERE_UNQ_WANTED>>16)==1 );
1.112604 +    pLevel->p3 = (pLoop->wsFlags>>16)&1;
1.112605 +    if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
1.112606 +      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
1.112607 +    }else{
1.112608 +      assert( pLevel->p5==0 );
1.112609 +    }
1.112610 +  }else
1.112611 +
1.112612 +#ifndef SQLITE_OMIT_OR_OPTIMIZATION
1.112613 +  if( pLoop->wsFlags & WHERE_MULTI_OR ){
1.112614 +    /* Case 5:  Two or more separately indexed terms connected by OR
1.112615 +    **
1.112616 +    ** Example:
1.112617 +    **
1.112618 +    **   CREATE TABLE t1(a,b,c,d);
1.112619 +    **   CREATE INDEX i1 ON t1(a);
1.112620 +    **   CREATE INDEX i2 ON t1(b);
1.112621 +    **   CREATE INDEX i3 ON t1(c);
1.112622 +    **
1.112623 +    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
1.112624 +    **
1.112625 +    ** In the example, there are three indexed terms connected by OR.
1.112626 +    ** The top of the loop looks like this:
1.112627 +    **
1.112628 +    **          Null       1                # Zero the rowset in reg 1
1.112629 +    **
1.112630 +    ** Then, for each indexed term, the following. The arguments to
1.112631 +    ** RowSetTest are such that the rowid of the current row is inserted
1.112632 +    ** into the RowSet. If it is already present, control skips the
1.112633 +    ** Gosub opcode and jumps straight to the code generated by WhereEnd().
1.112634 +    **
1.112635 +    **        sqlite3WhereBegin(<term>)
1.112636 +    **          RowSetTest                  # Insert rowid into rowset
1.112637 +    **          Gosub      2 A
1.112638 +    **        sqlite3WhereEnd()
1.112639 +    **
1.112640 +    ** Following the above, code to terminate the loop. Label A, the target
1.112641 +    ** of the Gosub above, jumps to the instruction right after the Goto.
1.112642 +    **
1.112643 +    **          Null       1                # Zero the rowset in reg 1
1.112644 +    **          Goto       B                # The loop is finished.
1.112645 +    **
1.112646 +    **       A: <loop body>                 # Return data, whatever.
1.112647 +    **
1.112648 +    **          Return     2                # Jump back to the Gosub
1.112649 +    **
1.112650 +    **       B: <after the loop>
1.112651 +    **
1.112652 +    */
1.112653 +    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
1.112654 +    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
1.112655 +    Index *pCov = 0;             /* Potential covering index (or NULL) */
1.112656 +    int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
1.112657 +
1.112658 +    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
1.112659 +    int regRowset = 0;                        /* Register for RowSet object */
1.112660 +    int regRowid = 0;                         /* Register holding rowid */
1.112661 +    int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
1.112662 +    int iRetInit;                             /* Address of regReturn init */
1.112663 +    int untestedTerms = 0;             /* Some terms not completely tested */
1.112664 +    int ii;                            /* Loop counter */
1.112665 +    Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
1.112666 +   
1.112667 +    pTerm = pLoop->aLTerm[0];
1.112668 +    assert( pTerm!=0 );
1.112669 +    assert( pTerm->eOperator & WO_OR );
1.112670 +    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
1.112671 +    pOrWc = &pTerm->u.pOrInfo->wc;
1.112672 +    pLevel->op = OP_Return;
1.112673 +    pLevel->p1 = regReturn;
1.112674 +
1.112675 +    /* Set up a new SrcList in pOrTab containing the table being scanned
1.112676 +    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
1.112677 +    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
1.112678 +    */
1.112679 +    if( pWInfo->nLevel>1 ){
1.112680 +      int nNotReady;                 /* The number of notReady tables */
1.112681 +      struct SrcList_item *origSrc;     /* Original list of tables */
1.112682 +      nNotReady = pWInfo->nLevel - iLevel - 1;
1.112683 +      pOrTab = sqlite3StackAllocRaw(db,
1.112684 +                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
1.112685 +      if( pOrTab==0 ) return notReady;
1.112686 +      pOrTab->nAlloc = (u8)(nNotReady + 1);
1.112687 +      pOrTab->nSrc = pOrTab->nAlloc;
1.112688 +      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
1.112689 +      origSrc = pWInfo->pTabList->a;
1.112690 +      for(k=1; k<=nNotReady; k++){
1.112691 +        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
1.112692 +      }
1.112693 +    }else{
1.112694 +      pOrTab = pWInfo->pTabList;
1.112695 +    }
1.112696 +
1.112697 +    /* Initialize the rowset register to contain NULL. An SQL NULL is 
1.112698 +    ** equivalent to an empty rowset.
1.112699 +    **
1.112700 +    ** Also initialize regReturn to contain the address of the instruction 
1.112701 +    ** immediately following the OP_Return at the bottom of the loop. This
1.112702 +    ** is required in a few obscure LEFT JOIN cases where control jumps
1.112703 +    ** over the top of the loop into the body of it. In this case the 
1.112704 +    ** correct response for the end-of-loop code (the OP_Return) is to 
1.112705 +    ** fall through to the next instruction, just as an OP_Next does if
1.112706 +    ** called on an uninitialized cursor.
1.112707 +    */
1.112708 +    if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
1.112709 +      regRowset = ++pParse->nMem;
1.112710 +      regRowid = ++pParse->nMem;
1.112711 +      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
1.112712 +    }
1.112713 +    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
1.112714 +
1.112715 +    /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
1.112716 +    ** Then for every term xN, evaluate as the subexpression: xN AND z
1.112717 +    ** That way, terms in y that are factored into the disjunction will
1.112718 +    ** be picked up by the recursive calls to sqlite3WhereBegin() below.
1.112719 +    **
1.112720 +    ** Actually, each subexpression is converted to "xN AND w" where w is
1.112721 +    ** the "interesting" terms of z - terms that did not originate in the
1.112722 +    ** ON or USING clause of a LEFT JOIN, and terms that are usable as 
1.112723 +    ** indices.
1.112724 +    **
1.112725 +    ** This optimization also only applies if the (x1 OR x2 OR ...) term
1.112726 +    ** is not contained in the ON clause of a LEFT JOIN.
1.112727 +    ** See ticket http://www.sqlite.org/src/info/f2369304e4
1.112728 +    */
1.112729 +    if( pWC->nTerm>1 ){
1.112730 +      int iTerm;
1.112731 +      for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
1.112732 +        Expr *pExpr = pWC->a[iTerm].pExpr;
1.112733 +        if( &pWC->a[iTerm] == pTerm ) continue;
1.112734 +        if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
1.112735 +        testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
1.112736 +        testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
1.112737 +        if( pWC->a[iTerm].wtFlags & (TERM_ORINFO|TERM_VIRTUAL) ) continue;
1.112738 +        if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
1.112739 +        pExpr = sqlite3ExprDup(db, pExpr, 0);
1.112740 +        pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
1.112741 +      }
1.112742 +      if( pAndExpr ){
1.112743 +        pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
1.112744 +      }
1.112745 +    }
1.112746 +
1.112747 +    for(ii=0; ii<pOrWc->nTerm; ii++){
1.112748 +      WhereTerm *pOrTerm = &pOrWc->a[ii];
1.112749 +      if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
1.112750 +        WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
1.112751 +        Expr *pOrExpr = pOrTerm->pExpr;
1.112752 +        if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
1.112753 +          pAndExpr->pLeft = pOrExpr;
1.112754 +          pOrExpr = pAndExpr;
1.112755 +        }
1.112756 +        /* Loop through table entries that match term pOrTerm. */
1.112757 +        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
1.112758 +                        WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
1.112759 +                        WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
1.112760 +        assert( pSubWInfo || pParse->nErr || db->mallocFailed );
1.112761 +        if( pSubWInfo ){
1.112762 +          WhereLoop *pSubLoop;
1.112763 +          explainOneScan(
1.112764 +              pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
1.112765 +          );
1.112766 +          if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
1.112767 +            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
1.112768 +            int r;
1.112769 +            r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
1.112770 +                                         regRowid, 0);
1.112771 +            sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
1.112772 +                                 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
1.112773 +            VdbeCoverage(v);
1.112774 +          }
1.112775 +          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
1.112776 +
1.112777 +          /* The pSubWInfo->untestedTerms flag means that this OR term
1.112778 +          ** contained one or more AND term from a notReady table.  The
1.112779 +          ** terms from the notReady table could not be tested and will
1.112780 +          ** need to be tested later.
1.112781 +          */
1.112782 +          if( pSubWInfo->untestedTerms ) untestedTerms = 1;
1.112783 +
1.112784 +          /* If all of the OR-connected terms are optimized using the same
1.112785 +          ** index, and the index is opened using the same cursor number
1.112786 +          ** by each call to sqlite3WhereBegin() made by this loop, it may
1.112787 +          ** be possible to use that index as a covering index.
1.112788 +          **
1.112789 +          ** If the call to sqlite3WhereBegin() above resulted in a scan that
1.112790 +          ** uses an index, and this is either the first OR-connected term
1.112791 +          ** processed or the index is the same as that used by all previous
1.112792 +          ** terms, set pCov to the candidate covering index. Otherwise, set 
1.112793 +          ** pCov to NULL to indicate that no candidate covering index will 
1.112794 +          ** be available.
1.112795 +          */
1.112796 +          pSubLoop = pSubWInfo->a[0].pWLoop;
1.112797 +          assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
1.112798 +          if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
1.112799 +           && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
1.112800 +          ){
1.112801 +            assert( pSubWInfo->a[0].iIdxCur==iCovCur );
1.112802 +            pCov = pSubLoop->u.btree.pIndex;
1.112803 +          }else{
1.112804 +            pCov = 0;
1.112805 +          }
1.112806 +
1.112807 +          /* Finish the loop through table entries that match term pOrTerm. */
1.112808 +          sqlite3WhereEnd(pSubWInfo);
1.112809 +        }
1.112810 +      }
1.112811 +    }
1.112812 +    pLevel->u.pCovidx = pCov;
1.112813 +    if( pCov ) pLevel->iIdxCur = iCovCur;
1.112814 +    if( pAndExpr ){
1.112815 +      pAndExpr->pLeft = 0;
1.112816 +      sqlite3ExprDelete(db, pAndExpr);
1.112817 +    }
1.112818 +    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
1.112819 +    sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
1.112820 +    sqlite3VdbeResolveLabel(v, iLoopBody);
1.112821 +
1.112822 +    if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
1.112823 +    if( !untestedTerms ) disableTerm(pLevel, pTerm);
1.112824 +  }else
1.112825 +#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1.112826 +
1.112827 +  {
1.112828 +    /* Case 6:  There is no usable index.  We must do a complete
1.112829 +    **          scan of the entire table.
1.112830 +    */
1.112831 +    static const u8 aStep[] = { OP_Next, OP_Prev };
1.112832 +    static const u8 aStart[] = { OP_Rewind, OP_Last };
1.112833 +    assert( bRev==0 || bRev==1 );
1.112834 +    if( pTabItem->isRecursive ){
1.112835 +      /* Tables marked isRecursive have only a single row that is stored in
1.112836 +      ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
1.112837 +      pLevel->op = OP_Noop;
1.112838 +    }else{
1.112839 +      pLevel->op = aStep[bRev];
1.112840 +      pLevel->p1 = iCur;
1.112841 +      pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
1.112842 +      VdbeCoverageIf(v, bRev==0);
1.112843 +      VdbeCoverageIf(v, bRev!=0);
1.112844 +      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
1.112845 +    }
1.112846 +  }
1.112847 +
1.112848 +  /* Insert code to test every subexpression that can be completely
1.112849 +  ** computed using the current set of tables.
1.112850 +  */
1.112851 +  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
1.112852 +    Expr *pE;
1.112853 +    testcase( pTerm->wtFlags & TERM_VIRTUAL );
1.112854 +    testcase( pTerm->wtFlags & TERM_CODED );
1.112855 +    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
1.112856 +    if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
1.112857 +      testcase( pWInfo->untestedTerms==0
1.112858 +               && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
1.112859 +      pWInfo->untestedTerms = 1;
1.112860 +      continue;
1.112861 +    }
1.112862 +    pE = pTerm->pExpr;
1.112863 +    assert( pE!=0 );
1.112864 +    if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
1.112865 +      continue;
1.112866 +    }
1.112867 +    sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
1.112868 +    pTerm->wtFlags |= TERM_CODED;
1.112869 +  }
1.112870 +
1.112871 +  /* Insert code to test for implied constraints based on transitivity
1.112872 +  ** of the "==" operator.
1.112873 +  **
1.112874 +  ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
1.112875 +  ** and we are coding the t1 loop and the t2 loop has not yet coded,
1.112876 +  ** then we cannot use the "t1.a=t2.b" constraint, but we can code
1.112877 +  ** the implied "t1.a=123" constraint.
1.112878 +  */
1.112879 +  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
1.112880 +    Expr *pE, *pEAlt;
1.112881 +    WhereTerm *pAlt;
1.112882 +    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
1.112883 +    if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
1.112884 +    if( pTerm->leftCursor!=iCur ) continue;
1.112885 +    if( pLevel->iLeftJoin ) continue;
1.112886 +    pE = pTerm->pExpr;
1.112887 +    assert( !ExprHasProperty(pE, EP_FromJoin) );
1.112888 +    assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
1.112889 +    pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
1.112890 +    if( pAlt==0 ) continue;
1.112891 +    if( pAlt->wtFlags & (TERM_CODED) ) continue;
1.112892 +    testcase( pAlt->eOperator & WO_EQ );
1.112893 +    testcase( pAlt->eOperator & WO_IN );
1.112894 +    VdbeModuleComment((v, "begin transitive constraint"));
1.112895 +    pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
1.112896 +    if( pEAlt ){
1.112897 +      *pEAlt = *pAlt->pExpr;
1.112898 +      pEAlt->pLeft = pE->pLeft;
1.112899 +      sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
1.112900 +      sqlite3StackFree(db, pEAlt);
1.112901 +    }
1.112902 +  }
1.112903 +
1.112904 +  /* For a LEFT OUTER JOIN, generate code that will record the fact that
1.112905 +  ** at least one row of the right table has matched the left table.  
1.112906 +  */
1.112907 +  if( pLevel->iLeftJoin ){
1.112908 +    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
1.112909 +    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
1.112910 +    VdbeComment((v, "record LEFT JOIN hit"));
1.112911 +    sqlite3ExprCacheClear(pParse);
1.112912 +    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
1.112913 +      testcase( pTerm->wtFlags & TERM_VIRTUAL );
1.112914 +      testcase( pTerm->wtFlags & TERM_CODED );
1.112915 +      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
1.112916 +      if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
1.112917 +        assert( pWInfo->untestedTerms );
1.112918 +        continue;
1.112919 +      }
1.112920 +      assert( pTerm->pExpr );
1.112921 +      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
1.112922 +      pTerm->wtFlags |= TERM_CODED;
1.112923 +    }
1.112924 +  }
1.112925 +
1.112926 +  return pLevel->notReady;
1.112927 +}
1.112928 +
1.112929 +#if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN)
1.112930 +/*
1.112931 +** Generate "Explanation" text for a WhereTerm.
1.112932 +*/
1.112933 +static void whereExplainTerm(Vdbe *v, WhereTerm *pTerm){
1.112934 +  char zType[4];
1.112935 +  memcpy(zType, "...", 4);
1.112936 +  if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
1.112937 +  if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
1.112938 +  if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
1.112939 +  sqlite3ExplainPrintf(v, "%s ", zType);
1.112940 +  sqlite3ExplainExpr(v, pTerm->pExpr);
1.112941 +}
1.112942 +#endif /* WHERETRACE_ENABLED && SQLITE_ENABLE_TREE_EXPLAIN */
1.112943 +
1.112944 +
1.112945 +#ifdef WHERETRACE_ENABLED
1.112946 +/*
1.112947 +** Print a WhereLoop object for debugging purposes
1.112948 +*/
1.112949 +static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
1.112950 +  WhereInfo *pWInfo = pWC->pWInfo;
1.112951 +  int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
1.112952 +  struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
1.112953 +  Table *pTab = pItem->pTab;
1.112954 +  sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
1.112955 +                     p->iTab, nb, p->maskSelf, nb, p->prereq);
1.112956 +  sqlite3DebugPrintf(" %12s",
1.112957 +                     pItem->zAlias ? pItem->zAlias : pTab->zName);
1.112958 +  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
1.112959 +     const char *zName;
1.112960 +     if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
1.112961 +      if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
1.112962 +        int i = sqlite3Strlen30(zName) - 1;
1.112963 +        while( zName[i]!='_' ) i--;
1.112964 +        zName += i;
1.112965 +      }
1.112966 +      sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
1.112967 +    }else{
1.112968 +      sqlite3DebugPrintf("%20s","");
1.112969 +    }
1.112970 +  }else{
1.112971 +    char *z;
1.112972 +    if( p->u.vtab.idxStr ){
1.112973 +      z = sqlite3_mprintf("(%d,\"%s\",%x)",
1.112974 +                p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
1.112975 +    }else{
1.112976 +      z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
1.112977 +    }
1.112978 +    sqlite3DebugPrintf(" %-19s", z);
1.112979 +    sqlite3_free(z);
1.112980 +  }
1.112981 +  sqlite3DebugPrintf(" f %04x N %d", p->wsFlags, p->nLTerm);
1.112982 +  sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
1.112983 +#ifdef SQLITE_ENABLE_TREE_EXPLAIN
1.112984 +  /* If the 0x100 bit of wheretracing is set, then show all of the constraint
1.112985 +  ** expressions in the WhereLoop.aLTerm[] array.
1.112986 +  */
1.112987 +  if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){  /* WHERETRACE 0x100 */
1.112988 +    int i;
1.112989 +    Vdbe *v = pWInfo->pParse->pVdbe;
1.112990 +    sqlite3ExplainBegin(v);
1.112991 +    for(i=0; i<p->nLTerm; i++){
1.112992 +      WhereTerm *pTerm = p->aLTerm[i];
1.112993 +      if( pTerm==0 ) continue;
1.112994 +      sqlite3ExplainPrintf(v, "  (%d) #%-2d ", i+1, (int)(pTerm-pWC->a));
1.112995 +      sqlite3ExplainPush(v);
1.112996 +      whereExplainTerm(v, pTerm);
1.112997 +      sqlite3ExplainPop(v);
1.112998 +      sqlite3ExplainNL(v);
1.112999 +    }
1.113000 +    sqlite3ExplainFinish(v);
1.113001 +    sqlite3DebugPrintf("%s", sqlite3VdbeExplanation(v));
1.113002 +  }
1.113003 +#endif
1.113004 +}
1.113005 +#endif
1.113006 +
1.113007 +/*
1.113008 +** Convert bulk memory into a valid WhereLoop that can be passed
1.113009 +** to whereLoopClear harmlessly.
1.113010 +*/
1.113011 +static void whereLoopInit(WhereLoop *p){
1.113012 +  p->aLTerm = p->aLTermSpace;
1.113013 +  p->nLTerm = 0;
1.113014 +  p->nLSlot = ArraySize(p->aLTermSpace);
1.113015 +  p->wsFlags = 0;
1.113016 +}
1.113017 +
1.113018 +/*
1.113019 +** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
1.113020 +*/
1.113021 +static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
1.113022 +  if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
1.113023 +    if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
1.113024 +      sqlite3_free(p->u.vtab.idxStr);
1.113025 +      p->u.vtab.needFree = 0;
1.113026 +      p->u.vtab.idxStr = 0;
1.113027 +    }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
1.113028 +      sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
1.113029 +      sqlite3KeyInfoUnref(p->u.btree.pIndex->pKeyInfo);
1.113030 +      sqlite3DbFree(db, p->u.btree.pIndex);
1.113031 +      p->u.btree.pIndex = 0;
1.113032 +    }
1.113033 +  }
1.113034 +}
1.113035 +
1.113036 +/*
1.113037 +** Deallocate internal memory used by a WhereLoop object
1.113038 +*/
1.113039 +static void whereLoopClear(sqlite3 *db, WhereLoop *p){
1.113040 +  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
1.113041 +  whereLoopClearUnion(db, p);
1.113042 +  whereLoopInit(p);
1.113043 +}
1.113044 +
1.113045 +/*
1.113046 +** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
1.113047 +*/
1.113048 +static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
1.113049 +  WhereTerm **paNew;
1.113050 +  if( p->nLSlot>=n ) return SQLITE_OK;
1.113051 +  n = (n+7)&~7;
1.113052 +  paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
1.113053 +  if( paNew==0 ) return SQLITE_NOMEM;
1.113054 +  memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
1.113055 +  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
1.113056 +  p->aLTerm = paNew;
1.113057 +  p->nLSlot = n;
1.113058 +  return SQLITE_OK;
1.113059 +}
1.113060 +
1.113061 +/*
1.113062 +** Transfer content from the second pLoop into the first.
1.113063 +*/
1.113064 +static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
1.113065 +  whereLoopClearUnion(db, pTo);
1.113066 +  if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
1.113067 +    memset(&pTo->u, 0, sizeof(pTo->u));
1.113068 +    return SQLITE_NOMEM;
1.113069 +  }
1.113070 +  memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
1.113071 +  memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
1.113072 +  if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
1.113073 +    pFrom->u.vtab.needFree = 0;
1.113074 +  }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
1.113075 +    pFrom->u.btree.pIndex = 0;
1.113076 +  }
1.113077 +  return SQLITE_OK;
1.113078 +}
1.113079 +
1.113080 +/*
1.113081 +** Delete a WhereLoop object
1.113082 +*/
1.113083 +static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
1.113084 +  whereLoopClear(db, p);
1.113085 +  sqlite3DbFree(db, p);
1.113086 +}
1.113087 +
1.113088 +/*
1.113089 +** Free a WhereInfo structure
1.113090 +*/
1.113091 +static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
1.113092 +  if( ALWAYS(pWInfo) ){
1.113093 +    whereClauseClear(&pWInfo->sWC);
1.113094 +    while( pWInfo->pLoops ){
1.113095 +      WhereLoop *p = pWInfo->pLoops;
1.113096 +      pWInfo->pLoops = p->pNextLoop;
1.113097 +      whereLoopDelete(db, p);
1.113098 +    }
1.113099 +    sqlite3DbFree(db, pWInfo);
1.113100 +  }
1.113101 +}
1.113102 +
1.113103 +/*
1.113104 +** Insert or replace a WhereLoop entry using the template supplied.
1.113105 +**
1.113106 +** An existing WhereLoop entry might be overwritten if the new template
1.113107 +** is better and has fewer dependencies.  Or the template will be ignored
1.113108 +** and no insert will occur if an existing WhereLoop is faster and has
1.113109 +** fewer dependencies than the template.  Otherwise a new WhereLoop is
1.113110 +** added based on the template.
1.113111 +**
1.113112 +** If pBuilder->pOrSet is not NULL then we only care about only the
1.113113 +** prerequisites and rRun and nOut costs of the N best loops.  That
1.113114 +** information is gathered in the pBuilder->pOrSet object.  This special
1.113115 +** processing mode is used only for OR clause processing.
1.113116 +**
1.113117 +** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
1.113118 +** still might overwrite similar loops with the new template if the
1.113119 +** template is better.  Loops may be overwritten if the following 
1.113120 +** conditions are met:
1.113121 +**
1.113122 +**    (1)  They have the same iTab.
1.113123 +**    (2)  They have the same iSortIdx.
1.113124 +**    (3)  The template has same or fewer dependencies than the current loop
1.113125 +**    (4)  The template has the same or lower cost than the current loop
1.113126 +**    (5)  The template uses more terms of the same index but has no additional
1.113127 +**         dependencies          
1.113128 +*/
1.113129 +static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
1.113130 +  WhereLoop **ppPrev, *p, *pNext = 0;
1.113131 +  WhereInfo *pWInfo = pBuilder->pWInfo;
1.113132 +  sqlite3 *db = pWInfo->pParse->db;
1.113133 +
1.113134 +  /* If pBuilder->pOrSet is defined, then only keep track of the costs
1.113135 +  ** and prereqs.
1.113136 +  */
1.113137 +  if( pBuilder->pOrSet!=0 ){
1.113138 +#if WHERETRACE_ENABLED
1.113139 +    u16 n = pBuilder->pOrSet->n;
1.113140 +    int x =
1.113141 +#endif
1.113142 +    whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
1.113143 +                                    pTemplate->nOut);
1.113144 +#if WHERETRACE_ENABLED /* 0x8 */
1.113145 +    if( sqlite3WhereTrace & 0x8 ){
1.113146 +      sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
1.113147 +      whereLoopPrint(pTemplate, pBuilder->pWC);
1.113148 +    }
1.113149 +#endif
1.113150 +    return SQLITE_OK;
1.113151 +  }
1.113152 +
1.113153 +  /* Search for an existing WhereLoop to overwrite, or which takes
1.113154 +  ** priority over pTemplate.
1.113155 +  */
1.113156 +  for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
1.113157 +    if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
1.113158 +      /* If either the iTab or iSortIdx values for two WhereLoop are different
1.113159 +      ** then those WhereLoops need to be considered separately.  Neither is
1.113160 +      ** a candidate to replace the other. */
1.113161 +      continue;
1.113162 +    }
1.113163 +    /* In the current implementation, the rSetup value is either zero
1.113164 +    ** or the cost of building an automatic index (NlogN) and the NlogN
1.113165 +    ** is the same for compatible WhereLoops. */
1.113166 +    assert( p->rSetup==0 || pTemplate->rSetup==0 
1.113167 +                 || p->rSetup==pTemplate->rSetup );
1.113168 +
1.113169 +    /* whereLoopAddBtree() always generates and inserts the automatic index
1.113170 +    ** case first.  Hence compatible candidate WhereLoops never have a larger
1.113171 +    ** rSetup. Call this SETUP-INVARIANT */
1.113172 +    assert( p->rSetup>=pTemplate->rSetup );
1.113173 +
1.113174 +    if( (p->prereq & pTemplate->prereq)==p->prereq
1.113175 +     && p->rSetup<=pTemplate->rSetup
1.113176 +     && p->rRun<=pTemplate->rRun
1.113177 +     && p->nOut<=pTemplate->nOut
1.113178 +    ){
1.113179 +      /* This branch taken when p is equal or better than pTemplate in 
1.113180 +      ** all of (1) dependencies (2) setup-cost, (3) run-cost, and
1.113181 +      ** (4) number of output rows. */
1.113182 +      assert( p->rSetup==pTemplate->rSetup );
1.113183 +      if( p->prereq==pTemplate->prereq
1.113184 +       && p->nLTerm<pTemplate->nLTerm
1.113185 +       && (p->wsFlags & pTemplate->wsFlags & WHERE_INDEXED)!=0
1.113186 +       && (p->u.btree.pIndex==pTemplate->u.btree.pIndex
1.113187 +          || pTemplate->rRun+p->nLTerm<=p->rRun+pTemplate->nLTerm)
1.113188 +      ){
1.113189 +        /* Overwrite an existing WhereLoop with an similar one that uses
1.113190 +        ** more terms of the index */
1.113191 +        pNext = p->pNextLoop;
1.113192 +        break;
1.113193 +      }else{
1.113194 +        /* pTemplate is not helpful.
1.113195 +        ** Return without changing or adding anything */
1.113196 +        goto whereLoopInsert_noop;
1.113197 +      }
1.113198 +    }
1.113199 +    if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
1.113200 +     && p->rRun>=pTemplate->rRun
1.113201 +     && p->nOut>=pTemplate->nOut
1.113202 +    ){
1.113203 +      /* Overwrite an existing WhereLoop with a better one: one that is
1.113204 +      ** better at one of (1) dependencies, (2) setup-cost, (3) run-cost
1.113205 +      ** or (4) number of output rows, and is no worse in any of those
1.113206 +      ** categories. */
1.113207 +      assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
1.113208 +      pNext = p->pNextLoop;
1.113209 +      break;
1.113210 +    }
1.113211 +  }
1.113212 +
1.113213 +  /* If we reach this point it means that either p[] should be overwritten
1.113214 +  ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
1.113215 +  ** WhereLoop and insert it.
1.113216 +  */
1.113217 +#if WHERETRACE_ENABLED /* 0x8 */
1.113218 +  if( sqlite3WhereTrace & 0x8 ){
1.113219 +    if( p!=0 ){
1.113220 +      sqlite3DebugPrintf("ins-del:  ");
1.113221 +      whereLoopPrint(p, pBuilder->pWC);
1.113222 +    }
1.113223 +    sqlite3DebugPrintf("ins-new:  ");
1.113224 +    whereLoopPrint(pTemplate, pBuilder->pWC);
1.113225 +  }
1.113226 +#endif
1.113227 +  if( p==0 ){
1.113228 +    p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
1.113229 +    if( p==0 ) return SQLITE_NOMEM;
1.113230 +    whereLoopInit(p);
1.113231 +  }
1.113232 +  whereLoopXfer(db, p, pTemplate);
1.113233 +  p->pNextLoop = pNext;
1.113234 +  *ppPrev = p;
1.113235 +  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
1.113236 +    Index *pIndex = p->u.btree.pIndex;
1.113237 +    if( pIndex && pIndex->tnum==0 ){
1.113238 +      p->u.btree.pIndex = 0;
1.113239 +    }
1.113240 +  }
1.113241 +  return SQLITE_OK;
1.113242 +
1.113243 +  /* Jump here if the insert is a no-op */
1.113244 +whereLoopInsert_noop:
1.113245 +#if WHERETRACE_ENABLED /* 0x8 */
1.113246 +  if( sqlite3WhereTrace & 0x8 ){
1.113247 +    sqlite3DebugPrintf("ins-noop: ");
1.113248 +    whereLoopPrint(pTemplate, pBuilder->pWC);
1.113249 +  }
1.113250 +#endif
1.113251 +  return SQLITE_OK;  
1.113252 +}
1.113253 +
1.113254 +/*
1.113255 +** Adjust the WhereLoop.nOut value downward to account for terms of the
1.113256 +** WHERE clause that reference the loop but which are not used by an
1.113257 +** index.
1.113258 +**
1.113259 +** In the current implementation, the first extra WHERE clause term reduces
1.113260 +** the number of output rows by a factor of 10 and each additional term
1.113261 +** reduces the number of output rows by sqrt(2).
1.113262 +*/
1.113263 +static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop){
1.113264 +  WhereTerm *pTerm, *pX;
1.113265 +  Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
1.113266 +  int i, j;
1.113267 +
1.113268 +  if( !OptimizationEnabled(pWC->pWInfo->pParse->db, SQLITE_AdjustOutEst) ){
1.113269 +    return;
1.113270 +  }
1.113271 +  for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
1.113272 +    if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
1.113273 +    if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
1.113274 +    if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
1.113275 +    for(j=pLoop->nLTerm-1; j>=0; j--){
1.113276 +      pX = pLoop->aLTerm[j];
1.113277 +      if( pX==0 ) continue;
1.113278 +      if( pX==pTerm ) break;
1.113279 +      if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
1.113280 +    }
1.113281 +    if( j<0 ) pLoop->nOut += pTerm->truthProb;
1.113282 +  }
1.113283 +}
1.113284 +
1.113285 +/*
1.113286 +** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
1.113287 +** Try to match one more.
1.113288 +**
1.113289 +** If pProbe->tnum==0, that means pIndex is a fake index used for the
1.113290 +** INTEGER PRIMARY KEY.
1.113291 +*/
1.113292 +static int whereLoopAddBtreeIndex(
1.113293 +  WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
1.113294 +  struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
1.113295 +  Index *pProbe,                  /* An index on pSrc */
1.113296 +  LogEst nInMul                   /* log(Number of iterations due to IN) */
1.113297 +){
1.113298 +  WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
1.113299 +  Parse *pParse = pWInfo->pParse;        /* Parsing context */
1.113300 +  sqlite3 *db = pParse->db;       /* Database connection malloc context */
1.113301 +  WhereLoop *pNew;                /* Template WhereLoop under construction */
1.113302 +  WhereTerm *pTerm;               /* A WhereTerm under consideration */
1.113303 +  int opMask;                     /* Valid operators for constraints */
1.113304 +  WhereScan scan;                 /* Iterator for WHERE terms */
1.113305 +  Bitmask saved_prereq;           /* Original value of pNew->prereq */
1.113306 +  u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
1.113307 +  u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
1.113308 +  u16 saved_nSkip;                /* Original value of pNew->u.btree.nSkip */
1.113309 +  u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
1.113310 +  LogEst saved_nOut;              /* Original value of pNew->nOut */
1.113311 +  int iCol;                       /* Index of the column in the table */
1.113312 +  int rc = SQLITE_OK;             /* Return code */
1.113313 +  LogEst nRowEst;                 /* Estimated index selectivity */
1.113314 +  LogEst rLogSize;                /* Logarithm of table size */
1.113315 +  WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
1.113316 +
1.113317 +  pNew = pBuilder->pNew;
1.113318 +  if( db->mallocFailed ) return SQLITE_NOMEM;
1.113319 +
1.113320 +  assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
1.113321 +  assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
1.113322 +  if( pNew->wsFlags & WHERE_BTM_LIMIT ){
1.113323 +    opMask = WO_LT|WO_LE;
1.113324 +  }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
1.113325 +    opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
1.113326 +  }else{
1.113327 +    opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
1.113328 +  }
1.113329 +  if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
1.113330 +
1.113331 +  assert( pNew->u.btree.nEq<=pProbe->nKeyCol );
1.113332 +  if( pNew->u.btree.nEq < pProbe->nKeyCol ){
1.113333 +    iCol = pProbe->aiColumn[pNew->u.btree.nEq];
1.113334 +    nRowEst = sqlite3LogEst(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
1.113335 +    if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1;
1.113336 +  }else{
1.113337 +    iCol = -1;
1.113338 +    nRowEst = 0;
1.113339 +  }
1.113340 +  pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
1.113341 +                        opMask, pProbe);
1.113342 +  saved_nEq = pNew->u.btree.nEq;
1.113343 +  saved_nSkip = pNew->u.btree.nSkip;
1.113344 +  saved_nLTerm = pNew->nLTerm;
1.113345 +  saved_wsFlags = pNew->wsFlags;
1.113346 +  saved_prereq = pNew->prereq;
1.113347 +  saved_nOut = pNew->nOut;
1.113348 +  pNew->rSetup = 0;
1.113349 +  rLogSize = estLog(sqlite3LogEst(pProbe->aiRowEst[0]));
1.113350 +
1.113351 +  /* Consider using a skip-scan if there are no WHERE clause constraints
1.113352 +  ** available for the left-most terms of the index, and if the average
1.113353 +  ** number of repeats in the left-most terms is at least 18.  The magic
1.113354 +  ** number 18 was found by experimentation to be the payoff point where
1.113355 +  ** skip-scan become faster than a full-scan.
1.113356 +  */
1.113357 +  if( pTerm==0
1.113358 +   && saved_nEq==saved_nSkip
1.113359 +   && saved_nEq+1<pProbe->nKeyCol
1.113360 +   && pProbe->aiRowEst[saved_nEq+1]>=18  /* TUNING: Minimum for skip-scan */
1.113361 +   && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
1.113362 +  ){
1.113363 +    LogEst nIter;
1.113364 +    pNew->u.btree.nEq++;
1.113365 +    pNew->u.btree.nSkip++;
1.113366 +    pNew->aLTerm[pNew->nLTerm++] = 0;
1.113367 +    pNew->wsFlags |= WHERE_SKIPSCAN;
1.113368 +    nIter = sqlite3LogEst(pProbe->aiRowEst[0]/pProbe->aiRowEst[saved_nEq+1]);
1.113369 +    pNew->rRun = rLogSize + nIter;
1.113370 +    pNew->nOut += nIter;
1.113371 +    whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter);
1.113372 +    pNew->nOut = saved_nOut;
1.113373 +  }
1.113374 +  for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
1.113375 +    int nIn = 0;
1.113376 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1.113377 +    int nRecValid = pBuilder->nRecValid;
1.113378 +#endif
1.113379 +    if( (pTerm->eOperator==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
1.113380 +     && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
1.113381 +    ){
1.113382 +      continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
1.113383 +    }
1.113384 +    if( pTerm->prereqRight & pNew->maskSelf ) continue;
1.113385 +
1.113386 +    assert( pNew->nOut==saved_nOut );
1.113387 +
1.113388 +    pNew->wsFlags = saved_wsFlags;
1.113389 +    pNew->u.btree.nEq = saved_nEq;
1.113390 +    pNew->nLTerm = saved_nLTerm;
1.113391 +    if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
1.113392 +    pNew->aLTerm[pNew->nLTerm++] = pTerm;
1.113393 +    pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
1.113394 +    pNew->rRun = rLogSize; /* Baseline cost is log2(N).  Adjustments below */
1.113395 +    if( pTerm->eOperator & WO_IN ){
1.113396 +      Expr *pExpr = pTerm->pExpr;
1.113397 +      pNew->wsFlags |= WHERE_COLUMN_IN;
1.113398 +      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1.113399 +        /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
1.113400 +        nIn = 46;  assert( 46==sqlite3LogEst(25) );
1.113401 +      }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
1.113402 +        /* "x IN (value, value, ...)" */
1.113403 +        nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
1.113404 +      }
1.113405 +      pNew->rRun += nIn;
1.113406 +      pNew->u.btree.nEq++;
1.113407 +      pNew->nOut = nRowEst + nInMul + nIn;
1.113408 +    }else if( pTerm->eOperator & (WO_EQ) ){
1.113409 +      assert(
1.113410 +        (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN|WHERE_SKIPSCAN))!=0
1.113411 +        || nInMul==0
1.113412 +      );
1.113413 +      pNew->wsFlags |= WHERE_COLUMN_EQ;
1.113414 +      if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1)){
1.113415 +        assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 );
1.113416 +        if( iCol>=0 && pProbe->onError==OE_None ){
1.113417 +          pNew->wsFlags |= WHERE_UNQ_WANTED;
1.113418 +        }else{
1.113419 +          pNew->wsFlags |= WHERE_ONEROW;
1.113420 +        }
1.113421 +      }
1.113422 +      pNew->u.btree.nEq++;
1.113423 +      pNew->nOut = nRowEst + nInMul;
1.113424 +    }else if( pTerm->eOperator & (WO_ISNULL) ){
1.113425 +      pNew->wsFlags |= WHERE_COLUMN_NULL;
1.113426 +      pNew->u.btree.nEq++;
1.113427 +      /* TUNING: IS NULL selects 2 rows */
1.113428 +      nIn = 10;  assert( 10==sqlite3LogEst(2) );
1.113429 +      pNew->nOut = nRowEst + nInMul + nIn;
1.113430 +    }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
1.113431 +      testcase( pTerm->eOperator & WO_GT );
1.113432 +      testcase( pTerm->eOperator & WO_GE );
1.113433 +      pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
1.113434 +      pBtm = pTerm;
1.113435 +      pTop = 0;
1.113436 +    }else{
1.113437 +      assert( pTerm->eOperator & (WO_LT|WO_LE) );
1.113438 +      testcase( pTerm->eOperator & WO_LT );
1.113439 +      testcase( pTerm->eOperator & WO_LE );
1.113440 +      pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
1.113441 +      pTop = pTerm;
1.113442 +      pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
1.113443 +                     pNew->aLTerm[pNew->nLTerm-2] : 0;
1.113444 +    }
1.113445 +    if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
1.113446 +      /* Adjust nOut and rRun for STAT3 range values */
1.113447 +      assert( pNew->nOut==saved_nOut );
1.113448 +      whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
1.113449 +    }
1.113450 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1.113451 +    if( nInMul==0 
1.113452 +     && pProbe->nSample 
1.113453 +     && pNew->u.btree.nEq<=pProbe->nSampleCol
1.113454 +     && OptimizationEnabled(db, SQLITE_Stat3) 
1.113455 +    ){
1.113456 +      Expr *pExpr = pTerm->pExpr;
1.113457 +      tRowcnt nOut = 0;
1.113458 +      if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
1.113459 +        testcase( pTerm->eOperator & WO_EQ );
1.113460 +        testcase( pTerm->eOperator & WO_ISNULL );
1.113461 +        rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
1.113462 +      }else if( (pTerm->eOperator & WO_IN)
1.113463 +             &&  !ExprHasProperty(pExpr, EP_xIsSelect)  ){
1.113464 +        rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
1.113465 +      }
1.113466 +      assert( nOut==0 || rc==SQLITE_OK );
1.113467 +      if( nOut ){
1.113468 +        pNew->nOut = sqlite3LogEst(nOut);
1.113469 +        if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
1.113470 +      }
1.113471 +    }
1.113472 +#endif
1.113473 +    if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
1.113474 +      /* Each row involves a step of the index, then a binary search of
1.113475 +      ** the main table */
1.113476 +      pNew->rRun =  sqlite3LogEstAdd(pNew->rRun,rLogSize>27 ? rLogSize-17 : 10);
1.113477 +    }
1.113478 +    /* Step cost for each output row */
1.113479 +    pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut);
1.113480 +    whereLoopOutputAdjust(pBuilder->pWC, pNew);
1.113481 +    rc = whereLoopInsert(pBuilder, pNew);
1.113482 +    if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
1.113483 +     && pNew->u.btree.nEq<(pProbe->nKeyCol + (pProbe->zName!=0))
1.113484 +    ){
1.113485 +      whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
1.113486 +    }
1.113487 +    pNew->nOut = saved_nOut;
1.113488 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1.113489 +    pBuilder->nRecValid = nRecValid;
1.113490 +#endif
1.113491 +  }
1.113492 +  pNew->prereq = saved_prereq;
1.113493 +  pNew->u.btree.nEq = saved_nEq;
1.113494 +  pNew->u.btree.nSkip = saved_nSkip;
1.113495 +  pNew->wsFlags = saved_wsFlags;
1.113496 +  pNew->nOut = saved_nOut;
1.113497 +  pNew->nLTerm = saved_nLTerm;
1.113498 +  return rc;
1.113499 +}
1.113500 +
1.113501 +/*
1.113502 +** Return True if it is possible that pIndex might be useful in
1.113503 +** implementing the ORDER BY clause in pBuilder.
1.113504 +**
1.113505 +** Return False if pBuilder does not contain an ORDER BY clause or
1.113506 +** if there is no way for pIndex to be useful in implementing that
1.113507 +** ORDER BY clause.
1.113508 +*/
1.113509 +static int indexMightHelpWithOrderBy(
1.113510 +  WhereLoopBuilder *pBuilder,
1.113511 +  Index *pIndex,
1.113512 +  int iCursor
1.113513 +){
1.113514 +  ExprList *pOB;
1.113515 +  int ii, jj;
1.113516 +
1.113517 +  if( pIndex->bUnordered ) return 0;
1.113518 +  if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
1.113519 +  for(ii=0; ii<pOB->nExpr; ii++){
1.113520 +    Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
1.113521 +    if( pExpr->op!=TK_COLUMN ) return 0;
1.113522 +    if( pExpr->iTable==iCursor ){
1.113523 +      for(jj=0; jj<pIndex->nKeyCol; jj++){
1.113524 +        if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
1.113525 +      }
1.113526 +    }
1.113527 +  }
1.113528 +  return 0;
1.113529 +}
1.113530 +
1.113531 +/*
1.113532 +** Return a bitmask where 1s indicate that the corresponding column of
1.113533 +** the table is used by an index.  Only the first 63 columns are considered.
1.113534 +*/
1.113535 +static Bitmask columnsInIndex(Index *pIdx){
1.113536 +  Bitmask m = 0;
1.113537 +  int j;
1.113538 +  for(j=pIdx->nColumn-1; j>=0; j--){
1.113539 +    int x = pIdx->aiColumn[j];
1.113540 +    if( x>=0 ){
1.113541 +      testcase( x==BMS-1 );
1.113542 +      testcase( x==BMS-2 );
1.113543 +      if( x<BMS-1 ) m |= MASKBIT(x);
1.113544 +    }
1.113545 +  }
1.113546 +  return m;
1.113547 +}
1.113548 +
1.113549 +/* Check to see if a partial index with pPartIndexWhere can be used
1.113550 +** in the current query.  Return true if it can be and false if not.
1.113551 +*/
1.113552 +static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
1.113553 +  int i;
1.113554 +  WhereTerm *pTerm;
1.113555 +  for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1.113556 +    if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
1.113557 +  }
1.113558 +  return 0;
1.113559 +}
1.113560 +
1.113561 +/*
1.113562 +** Add all WhereLoop objects for a single table of the join where the table
1.113563 +** is idenfied by pBuilder->pNew->iTab.  That table is guaranteed to be
1.113564 +** a b-tree table, not a virtual table.
1.113565 +*/
1.113566 +static int whereLoopAddBtree(
1.113567 +  WhereLoopBuilder *pBuilder, /* WHERE clause information */
1.113568 +  Bitmask mExtra              /* Extra prerequesites for using this table */
1.113569 +){
1.113570 +  WhereInfo *pWInfo;          /* WHERE analysis context */
1.113571 +  Index *pProbe;              /* An index we are evaluating */
1.113572 +  Index sPk;                  /* A fake index object for the primary key */
1.113573 +  tRowcnt aiRowEstPk[2];      /* The aiRowEst[] value for the sPk index */
1.113574 +  i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
1.113575 +  SrcList *pTabList;          /* The FROM clause */
1.113576 +  struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
1.113577 +  WhereLoop *pNew;            /* Template WhereLoop object */
1.113578 +  int rc = SQLITE_OK;         /* Return code */
1.113579 +  int iSortIdx = 1;           /* Index number */
1.113580 +  int b;                      /* A boolean value */
1.113581 +  LogEst rSize;               /* number of rows in the table */
1.113582 +  LogEst rLogSize;            /* Logarithm of the number of rows in the table */
1.113583 +  WhereClause *pWC;           /* The parsed WHERE clause */
1.113584 +  Table *pTab;                /* Table being queried */
1.113585 +  
1.113586 +  pNew = pBuilder->pNew;
1.113587 +  pWInfo = pBuilder->pWInfo;
1.113588 +  pTabList = pWInfo->pTabList;
1.113589 +  pSrc = pTabList->a + pNew->iTab;
1.113590 +  pTab = pSrc->pTab;
1.113591 +  pWC = pBuilder->pWC;
1.113592 +  assert( !IsVirtual(pSrc->pTab) );
1.113593 +
1.113594 +  if( pSrc->pIndex ){
1.113595 +    /* An INDEXED BY clause specifies a particular index to use */
1.113596 +    pProbe = pSrc->pIndex;
1.113597 +  }else if( !HasRowid(pTab) ){
1.113598 +    pProbe = pTab->pIndex;
1.113599 +  }else{
1.113600 +    /* There is no INDEXED BY clause.  Create a fake Index object in local
1.113601 +    ** variable sPk to represent the rowid primary key index.  Make this
1.113602 +    ** fake index the first in a chain of Index objects with all of the real
1.113603 +    ** indices to follow */
1.113604 +    Index *pFirst;                  /* First of real indices on the table */
1.113605 +    memset(&sPk, 0, sizeof(Index));
1.113606 +    sPk.nKeyCol = 1;
1.113607 +    sPk.aiColumn = &aiColumnPk;
1.113608 +    sPk.aiRowEst = aiRowEstPk;
1.113609 +    sPk.onError = OE_Replace;
1.113610 +    sPk.pTable = pTab;
1.113611 +    aiRowEstPk[0] = pTab->nRowEst;
1.113612 +    aiRowEstPk[1] = 1;
1.113613 +    pFirst = pSrc->pTab->pIndex;
1.113614 +    if( pSrc->notIndexed==0 ){
1.113615 +      /* The real indices of the table are only considered if the
1.113616 +      ** NOT INDEXED qualifier is omitted from the FROM clause */
1.113617 +      sPk.pNext = pFirst;
1.113618 +    }
1.113619 +    pProbe = &sPk;
1.113620 +  }
1.113621 +  rSize = sqlite3LogEst(pTab->nRowEst);
1.113622 +  rLogSize = estLog(rSize);
1.113623 +
1.113624 +#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
1.113625 +  /* Automatic indexes */
1.113626 +  if( !pBuilder->pOrSet
1.113627 +   && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
1.113628 +   && pSrc->pIndex==0
1.113629 +   && !pSrc->viaCoroutine
1.113630 +   && !pSrc->notIndexed
1.113631 +   && HasRowid(pTab)
1.113632 +   && !pSrc->isCorrelated
1.113633 +   && !pSrc->isRecursive
1.113634 +  ){
1.113635 +    /* Generate auto-index WhereLoops */
1.113636 +    WhereTerm *pTerm;
1.113637 +    WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
1.113638 +    for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
1.113639 +      if( pTerm->prereqRight & pNew->maskSelf ) continue;
1.113640 +      if( termCanDriveIndex(pTerm, pSrc, 0) ){
1.113641 +        pNew->u.btree.nEq = 1;
1.113642 +        pNew->u.btree.nSkip = 0;
1.113643 +        pNew->u.btree.pIndex = 0;
1.113644 +        pNew->nLTerm = 1;
1.113645 +        pNew->aLTerm[0] = pTerm;
1.113646 +        /* TUNING: One-time cost for computing the automatic index is
1.113647 +        ** approximately 7*N*log2(N) where N is the number of rows in
1.113648 +        ** the table being indexed. */
1.113649 +        pNew->rSetup = rLogSize + rSize + 28;  assert( 28==sqlite3LogEst(7) );
1.113650 +        /* TUNING: Each index lookup yields 20 rows in the table.  This
1.113651 +        ** is more than the usual guess of 10 rows, since we have no way
1.113652 +        ** of knowning how selective the index will ultimately be.  It would
1.113653 +        ** not be unreasonable to make this value much larger. */
1.113654 +        pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
1.113655 +        pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
1.113656 +        pNew->wsFlags = WHERE_AUTO_INDEX;
1.113657 +        pNew->prereq = mExtra | pTerm->prereqRight;
1.113658 +        rc = whereLoopInsert(pBuilder, pNew);
1.113659 +      }
1.113660 +    }
1.113661 +  }
1.113662 +#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
1.113663 +
1.113664 +  /* Loop over all indices
1.113665 +  */
1.113666 +  for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
1.113667 +    if( pProbe->pPartIdxWhere!=0
1.113668 +     && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){
1.113669 +      continue;  /* Partial index inappropriate for this query */
1.113670 +    }
1.113671 +    pNew->u.btree.nEq = 0;
1.113672 +    pNew->u.btree.nSkip = 0;
1.113673 +    pNew->nLTerm = 0;
1.113674 +    pNew->iSortIdx = 0;
1.113675 +    pNew->rSetup = 0;
1.113676 +    pNew->prereq = mExtra;
1.113677 +    pNew->nOut = rSize;
1.113678 +    pNew->u.btree.pIndex = pProbe;
1.113679 +    b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
1.113680 +    /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
1.113681 +    assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
1.113682 +    if( pProbe->tnum<=0 ){
1.113683 +      /* Integer primary key index */
1.113684 +      pNew->wsFlags = WHERE_IPK;
1.113685 +
1.113686 +      /* Full table scan */
1.113687 +      pNew->iSortIdx = b ? iSortIdx : 0;
1.113688 +      /* TUNING: Cost of full table scan is 3*(N + log2(N)).
1.113689 +      **  +  The extra 3 factor is to encourage the use of indexed lookups
1.113690 +      **     over full scans.  FIXME */
1.113691 +      pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 16;
1.113692 +      whereLoopOutputAdjust(pWC, pNew);
1.113693 +      rc = whereLoopInsert(pBuilder, pNew);
1.113694 +      pNew->nOut = rSize;
1.113695 +      if( rc ) break;
1.113696 +    }else{
1.113697 +      Bitmask m;
1.113698 +      if( pProbe->isCovering ){
1.113699 +        pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
1.113700 +        m = 0;
1.113701 +      }else{
1.113702 +        m = pSrc->colUsed & ~columnsInIndex(pProbe);
1.113703 +        pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
1.113704 +      }
1.113705 +
1.113706 +      /* Full scan via index */
1.113707 +      if( b
1.113708 +       || !HasRowid(pTab)
1.113709 +       || ( m==0
1.113710 +         && pProbe->bUnordered==0
1.113711 +         && (pProbe->szIdxRow<pTab->szTabRow)
1.113712 +         && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
1.113713 +         && sqlite3GlobalConfig.bUseCis
1.113714 +         && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
1.113715 +          )
1.113716 +      ){
1.113717 +        pNew->iSortIdx = b ? iSortIdx : 0;
1.113718 +        if( m==0 ){
1.113719 +          /* TUNING: Cost of a covering index scan is K*(N + log2(N)).
1.113720 +          **  +  The extra factor K of between 1.1 and 3.0 that depends
1.113721 +          **     on the relative sizes of the table and the index.  K
1.113722 +          **     is smaller for smaller indices, thus favoring them.
1.113723 +          */
1.113724 +          pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 1 +
1.113725 +                        (15*pProbe->szIdxRow)/pTab->szTabRow;
1.113726 +        }else{
1.113727 +          /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
1.113728 +          ** which we will simplify to just N*log2(N) */
1.113729 +          pNew->rRun = rSize + rLogSize;
1.113730 +        }
1.113731 +        whereLoopOutputAdjust(pWC, pNew);
1.113732 +        rc = whereLoopInsert(pBuilder, pNew);
1.113733 +        pNew->nOut = rSize;
1.113734 +        if( rc ) break;
1.113735 +      }
1.113736 +    }
1.113737 +
1.113738 +    rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
1.113739 +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1.113740 +    sqlite3Stat4ProbeFree(pBuilder->pRec);
1.113741 +    pBuilder->nRecValid = 0;
1.113742 +    pBuilder->pRec = 0;
1.113743 +#endif
1.113744 +
1.113745 +    /* If there was an INDEXED BY clause, then only that one index is
1.113746 +    ** considered. */
1.113747 +    if( pSrc->pIndex ) break;
1.113748 +  }
1.113749 +  return rc;
1.113750 +}
1.113751 +
1.113752 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.113753 +/*
1.113754 +** Add all WhereLoop objects for a table of the join identified by
1.113755 +** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
1.113756 +*/
1.113757 +static int whereLoopAddVirtual(
1.113758 +  WhereLoopBuilder *pBuilder,  /* WHERE clause information */
1.113759 +  Bitmask mExtra
1.113760 +){
1.113761 +  WhereInfo *pWInfo;           /* WHERE analysis context */
1.113762 +  Parse *pParse;               /* The parsing context */
1.113763 +  WhereClause *pWC;            /* The WHERE clause */
1.113764 +  struct SrcList_item *pSrc;   /* The FROM clause term to search */
1.113765 +  Table *pTab;
1.113766 +  sqlite3 *db;
1.113767 +  sqlite3_index_info *pIdxInfo;
1.113768 +  struct sqlite3_index_constraint *pIdxCons;
1.113769 +  struct sqlite3_index_constraint_usage *pUsage;
1.113770 +  WhereTerm *pTerm;
1.113771 +  int i, j;
1.113772 +  int iTerm, mxTerm;
1.113773 +  int nConstraint;
1.113774 +  int seenIn = 0;              /* True if an IN operator is seen */
1.113775 +  int seenVar = 0;             /* True if a non-constant constraint is seen */
1.113776 +  int iPhase;                  /* 0: const w/o IN, 1: const, 2: no IN,  2: IN */
1.113777 +  WhereLoop *pNew;
1.113778 +  int rc = SQLITE_OK;
1.113779 +
1.113780 +  pWInfo = pBuilder->pWInfo;
1.113781 +  pParse = pWInfo->pParse;
1.113782 +  db = pParse->db;
1.113783 +  pWC = pBuilder->pWC;
1.113784 +  pNew = pBuilder->pNew;
1.113785 +  pSrc = &pWInfo->pTabList->a[pNew->iTab];
1.113786 +  pTab = pSrc->pTab;
1.113787 +  assert( IsVirtual(pTab) );
1.113788 +  pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
1.113789 +  if( pIdxInfo==0 ) return SQLITE_NOMEM;
1.113790 +  pNew->prereq = 0;
1.113791 +  pNew->rSetup = 0;
1.113792 +  pNew->wsFlags = WHERE_VIRTUALTABLE;
1.113793 +  pNew->nLTerm = 0;
1.113794 +  pNew->u.vtab.needFree = 0;
1.113795 +  pUsage = pIdxInfo->aConstraintUsage;
1.113796 +  nConstraint = pIdxInfo->nConstraint;
1.113797 +  if( whereLoopResize(db, pNew, nConstraint) ){
1.113798 +    sqlite3DbFree(db, pIdxInfo);
1.113799 +    return SQLITE_NOMEM;
1.113800 +  }
1.113801 +
1.113802 +  for(iPhase=0; iPhase<=3; iPhase++){
1.113803 +    if( !seenIn && (iPhase&1)!=0 ){
1.113804 +      iPhase++;
1.113805 +      if( iPhase>3 ) break;
1.113806 +    }
1.113807 +    if( !seenVar && iPhase>1 ) break;
1.113808 +    pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
1.113809 +    for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
1.113810 +      j = pIdxCons->iTermOffset;
1.113811 +      pTerm = &pWC->a[j];
1.113812 +      switch( iPhase ){
1.113813 +        case 0:    /* Constants without IN operator */
1.113814 +          pIdxCons->usable = 0;
1.113815 +          if( (pTerm->eOperator & WO_IN)!=0 ){
1.113816 +            seenIn = 1;
1.113817 +          }
1.113818 +          if( pTerm->prereqRight!=0 ){
1.113819 +            seenVar = 1;
1.113820 +          }else if( (pTerm->eOperator & WO_IN)==0 ){
1.113821 +            pIdxCons->usable = 1;
1.113822 +          }
1.113823 +          break;
1.113824 +        case 1:    /* Constants with IN operators */
1.113825 +          assert( seenIn );
1.113826 +          pIdxCons->usable = (pTerm->prereqRight==0);
1.113827 +          break;
1.113828 +        case 2:    /* Variables without IN */
1.113829 +          assert( seenVar );
1.113830 +          pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
1.113831 +          break;
1.113832 +        default:   /* Variables with IN */
1.113833 +          assert( seenVar && seenIn );
1.113834 +          pIdxCons->usable = 1;
1.113835 +          break;
1.113836 +      }
1.113837 +    }
1.113838 +    memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
1.113839 +    if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
1.113840 +    pIdxInfo->idxStr = 0;
1.113841 +    pIdxInfo->idxNum = 0;
1.113842 +    pIdxInfo->needToFreeIdxStr = 0;
1.113843 +    pIdxInfo->orderByConsumed = 0;
1.113844 +    pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
1.113845 +    pIdxInfo->estimatedRows = 25;
1.113846 +    rc = vtabBestIndex(pParse, pTab, pIdxInfo);
1.113847 +    if( rc ) goto whereLoopAddVtab_exit;
1.113848 +    pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
1.113849 +    pNew->prereq = mExtra;
1.113850 +    mxTerm = -1;
1.113851 +    assert( pNew->nLSlot>=nConstraint );
1.113852 +    for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
1.113853 +    pNew->u.vtab.omitMask = 0;
1.113854 +    for(i=0; i<nConstraint; i++, pIdxCons++){
1.113855 +      if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
1.113856 +        j = pIdxCons->iTermOffset;
1.113857 +        if( iTerm>=nConstraint
1.113858 +         || j<0
1.113859 +         || j>=pWC->nTerm
1.113860 +         || pNew->aLTerm[iTerm]!=0
1.113861 +        ){
1.113862 +          rc = SQLITE_ERROR;
1.113863 +          sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
1.113864 +          goto whereLoopAddVtab_exit;
1.113865 +        }
1.113866 +        testcase( iTerm==nConstraint-1 );
1.113867 +        testcase( j==0 );
1.113868 +        testcase( j==pWC->nTerm-1 );
1.113869 +        pTerm = &pWC->a[j];
1.113870 +        pNew->prereq |= pTerm->prereqRight;
1.113871 +        assert( iTerm<pNew->nLSlot );
1.113872 +        pNew->aLTerm[iTerm] = pTerm;
1.113873 +        if( iTerm>mxTerm ) mxTerm = iTerm;
1.113874 +        testcase( iTerm==15 );
1.113875 +        testcase( iTerm==16 );
1.113876 +        if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
1.113877 +        if( (pTerm->eOperator & WO_IN)!=0 ){
1.113878 +          if( pUsage[i].omit==0 ){
1.113879 +            /* Do not attempt to use an IN constraint if the virtual table
1.113880 +            ** says that the equivalent EQ constraint cannot be safely omitted.
1.113881 +            ** If we do attempt to use such a constraint, some rows might be
1.113882 +            ** repeated in the output. */
1.113883 +            break;
1.113884 +          }
1.113885 +          /* A virtual table that is constrained by an IN clause may not
1.113886 +          ** consume the ORDER BY clause because (1) the order of IN terms
1.113887 +          ** is not necessarily related to the order of output terms and
1.113888 +          ** (2) Multiple outputs from a single IN value will not merge
1.113889 +          ** together.  */
1.113890 +          pIdxInfo->orderByConsumed = 0;
1.113891 +        }
1.113892 +      }
1.113893 +    }
1.113894 +    if( i>=nConstraint ){
1.113895 +      pNew->nLTerm = mxTerm+1;
1.113896 +      assert( pNew->nLTerm<=pNew->nLSlot );
1.113897 +      pNew->u.vtab.idxNum = pIdxInfo->idxNum;
1.113898 +      pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
1.113899 +      pIdxInfo->needToFreeIdxStr = 0;
1.113900 +      pNew->u.vtab.idxStr = pIdxInfo->idxStr;
1.113901 +      pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
1.113902 +                                     && pIdxInfo->orderByConsumed);
1.113903 +      pNew->rSetup = 0;
1.113904 +      pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
1.113905 +      pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
1.113906 +      whereLoopInsert(pBuilder, pNew);
1.113907 +      if( pNew->u.vtab.needFree ){
1.113908 +        sqlite3_free(pNew->u.vtab.idxStr);
1.113909 +        pNew->u.vtab.needFree = 0;
1.113910 +      }
1.113911 +    }
1.113912 +  }  
1.113913 +
1.113914 +whereLoopAddVtab_exit:
1.113915 +  if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
1.113916 +  sqlite3DbFree(db, pIdxInfo);
1.113917 +  return rc;
1.113918 +}
1.113919 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
1.113920 +
1.113921 +/*
1.113922 +** Add WhereLoop entries to handle OR terms.  This works for either
1.113923 +** btrees or virtual tables.
1.113924 +*/
1.113925 +static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
1.113926 +  WhereInfo *pWInfo = pBuilder->pWInfo;
1.113927 +  WhereClause *pWC;
1.113928 +  WhereLoop *pNew;
1.113929 +  WhereTerm *pTerm, *pWCEnd;
1.113930 +  int rc = SQLITE_OK;
1.113931 +  int iCur;
1.113932 +  WhereClause tempWC;
1.113933 +  WhereLoopBuilder sSubBuild;
1.113934 +  WhereOrSet sSum, sCur, sPrev;
1.113935 +  struct SrcList_item *pItem;
1.113936 +  
1.113937 +  pWC = pBuilder->pWC;
1.113938 +  if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
1.113939 +  pWCEnd = pWC->a + pWC->nTerm;
1.113940 +  pNew = pBuilder->pNew;
1.113941 +  memset(&sSum, 0, sizeof(sSum));
1.113942 +  pItem = pWInfo->pTabList->a + pNew->iTab;
1.113943 +  if( !HasRowid(pItem->pTab) ) return SQLITE_OK;
1.113944 +  iCur = pItem->iCursor;
1.113945 +
1.113946 +  for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
1.113947 +    if( (pTerm->eOperator & WO_OR)!=0
1.113948 +     && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0 
1.113949 +    ){
1.113950 +      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
1.113951 +      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
1.113952 +      WhereTerm *pOrTerm;
1.113953 +      int once = 1;
1.113954 +      int i, j;
1.113955 +    
1.113956 +      sSubBuild = *pBuilder;
1.113957 +      sSubBuild.pOrderBy = 0;
1.113958 +      sSubBuild.pOrSet = &sCur;
1.113959 +
1.113960 +      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
1.113961 +        if( (pOrTerm->eOperator & WO_AND)!=0 ){
1.113962 +          sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
1.113963 +        }else if( pOrTerm->leftCursor==iCur ){
1.113964 +          tempWC.pWInfo = pWC->pWInfo;
1.113965 +          tempWC.pOuter = pWC;
1.113966 +          tempWC.op = TK_AND;
1.113967 +          tempWC.nTerm = 1;
1.113968 +          tempWC.a = pOrTerm;
1.113969 +          sSubBuild.pWC = &tempWC;
1.113970 +        }else{
1.113971 +          continue;
1.113972 +        }
1.113973 +        sCur.n = 0;
1.113974 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.113975 +        if( IsVirtual(pItem->pTab) ){
1.113976 +          rc = whereLoopAddVirtual(&sSubBuild, mExtra);
1.113977 +        }else
1.113978 +#endif
1.113979 +        {
1.113980 +          rc = whereLoopAddBtree(&sSubBuild, mExtra);
1.113981 +        }
1.113982 +        assert( rc==SQLITE_OK || sCur.n==0 );
1.113983 +        if( sCur.n==0 ){
1.113984 +          sSum.n = 0;
1.113985 +          break;
1.113986 +        }else if( once ){
1.113987 +          whereOrMove(&sSum, &sCur);
1.113988 +          once = 0;
1.113989 +        }else{
1.113990 +          whereOrMove(&sPrev, &sSum);
1.113991 +          sSum.n = 0;
1.113992 +          for(i=0; i<sPrev.n; i++){
1.113993 +            for(j=0; j<sCur.n; j++){
1.113994 +              whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
1.113995 +                            sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
1.113996 +                            sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
1.113997 +            }
1.113998 +          }
1.113999 +        }
1.114000 +      }
1.114001 +      pNew->nLTerm = 1;
1.114002 +      pNew->aLTerm[0] = pTerm;
1.114003 +      pNew->wsFlags = WHERE_MULTI_OR;
1.114004 +      pNew->rSetup = 0;
1.114005 +      pNew->iSortIdx = 0;
1.114006 +      memset(&pNew->u, 0, sizeof(pNew->u));
1.114007 +      for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
1.114008 +        /* TUNING: Multiple by 3.5 for the secondary table lookup */
1.114009 +        pNew->rRun = sSum.a[i].rRun + 18;
1.114010 +        pNew->nOut = sSum.a[i].nOut;
1.114011 +        pNew->prereq = sSum.a[i].prereq;
1.114012 +        rc = whereLoopInsert(pBuilder, pNew);
1.114013 +      }
1.114014 +    }
1.114015 +  }
1.114016 +  return rc;
1.114017 +}
1.114018 +
1.114019 +/*
1.114020 +** Add all WhereLoop objects for all tables 
1.114021 +*/
1.114022 +static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
1.114023 +  WhereInfo *pWInfo = pBuilder->pWInfo;
1.114024 +  Bitmask mExtra = 0;
1.114025 +  Bitmask mPrior = 0;
1.114026 +  int iTab;
1.114027 +  SrcList *pTabList = pWInfo->pTabList;
1.114028 +  struct SrcList_item *pItem;
1.114029 +  sqlite3 *db = pWInfo->pParse->db;
1.114030 +  int nTabList = pWInfo->nLevel;
1.114031 +  int rc = SQLITE_OK;
1.114032 +  u8 priorJoinType = 0;
1.114033 +  WhereLoop *pNew;
1.114034 +
1.114035 +  /* Loop over the tables in the join, from left to right */
1.114036 +  pNew = pBuilder->pNew;
1.114037 +  whereLoopInit(pNew);
1.114038 +  for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
1.114039 +    pNew->iTab = iTab;
1.114040 +    pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
1.114041 +    if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
1.114042 +      mExtra = mPrior;
1.114043 +    }
1.114044 +    priorJoinType = pItem->jointype;
1.114045 +    if( IsVirtual(pItem->pTab) ){
1.114046 +      rc = whereLoopAddVirtual(pBuilder, mExtra);
1.114047 +    }else{
1.114048 +      rc = whereLoopAddBtree(pBuilder, mExtra);
1.114049 +    }
1.114050 +    if( rc==SQLITE_OK ){
1.114051 +      rc = whereLoopAddOr(pBuilder, mExtra);
1.114052 +    }
1.114053 +    mPrior |= pNew->maskSelf;
1.114054 +    if( rc || db->mallocFailed ) break;
1.114055 +  }
1.114056 +  whereLoopClear(db, pNew);
1.114057 +  return rc;
1.114058 +}
1.114059 +
1.114060 +/*
1.114061 +** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
1.114062 +** parameters) to see if it outputs rows in the requested ORDER BY
1.114063 +** (or GROUP BY) without requiring a separate sort operation.  Return:
1.114064 +** 
1.114065 +**    0:  ORDER BY is not satisfied.  Sorting required
1.114066 +**    1:  ORDER BY is satisfied.      Omit sorting
1.114067 +**   -1:  Unknown at this time
1.114068 +**
1.114069 +** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
1.114070 +** strict.  With GROUP BY and DISTINCT the only requirement is that
1.114071 +** equivalent rows appear immediately adjacent to one another.  GROUP BY
1.114072 +** and DISTINT do not require rows to appear in any particular order as long
1.114073 +** as equivelent rows are grouped together.  Thus for GROUP BY and DISTINCT
1.114074 +** the pOrderBy terms can be matched in any order.  With ORDER BY, the 
1.114075 +** pOrderBy terms must be matched in strict left-to-right order.
1.114076 +*/
1.114077 +static int wherePathSatisfiesOrderBy(
1.114078 +  WhereInfo *pWInfo,    /* The WHERE clause */
1.114079 +  ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
1.114080 +  WherePath *pPath,     /* The WherePath to check */
1.114081 +  u16 wctrlFlags,       /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
1.114082 +  u16 nLoop,            /* Number of entries in pPath->aLoop[] */
1.114083 +  WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
1.114084 +  Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
1.114085 +){
1.114086 +  u8 revSet;            /* True if rev is known */
1.114087 +  u8 rev;               /* Composite sort order */
1.114088 +  u8 revIdx;            /* Index sort order */
1.114089 +  u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
1.114090 +  u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
1.114091 +  u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
1.114092 +  u16 nKeyCol;          /* Number of key columns in pIndex */
1.114093 +  u16 nColumn;          /* Total number of ordered columns in the index */
1.114094 +  u16 nOrderBy;         /* Number terms in the ORDER BY clause */
1.114095 +  int iLoop;            /* Index of WhereLoop in pPath being processed */
1.114096 +  int i, j;             /* Loop counters */
1.114097 +  int iCur;             /* Cursor number for current WhereLoop */
1.114098 +  int iColumn;          /* A column number within table iCur */
1.114099 +  WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
1.114100 +  WhereTerm *pTerm;     /* A single term of the WHERE clause */
1.114101 +  Expr *pOBExpr;        /* An expression from the ORDER BY clause */
1.114102 +  CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
1.114103 +  Index *pIndex;        /* The index associated with pLoop */
1.114104 +  sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
1.114105 +  Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
1.114106 +  Bitmask obDone;       /* Mask of all ORDER BY terms */
1.114107 +  Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
1.114108 +  Bitmask ready;              /* Mask of inner loops */
1.114109 +
1.114110 +  /*
1.114111 +  ** We say the WhereLoop is "one-row" if it generates no more than one
1.114112 +  ** row of output.  A WhereLoop is one-row if all of the following are true:
1.114113 +  **  (a) All index columns match with WHERE_COLUMN_EQ.
1.114114 +  **  (b) The index is unique
1.114115 +  ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
1.114116 +  ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
1.114117 +  **
1.114118 +  ** We say the WhereLoop is "order-distinct" if the set of columns from
1.114119 +  ** that WhereLoop that are in the ORDER BY clause are different for every
1.114120 +  ** row of the WhereLoop.  Every one-row WhereLoop is automatically
1.114121 +  ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
1.114122 +  ** is not order-distinct. To be order-distinct is not quite the same as being
1.114123 +  ** UNIQUE since a UNIQUE column or index can have multiple rows that 
1.114124 +  ** are NULL and NULL values are equivalent for the purpose of order-distinct.
1.114125 +  ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
1.114126 +  **
1.114127 +  ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
1.114128 +  ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
1.114129 +  ** automatically order-distinct.
1.114130 +  */
1.114131 +
1.114132 +  assert( pOrderBy!=0 );
1.114133 +
1.114134 +  /* Sortability of virtual tables is determined by the xBestIndex method
1.114135 +  ** of the virtual table itself */
1.114136 +  if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
1.114137 +    testcase( nLoop>0 );  /* True when outer loops are one-row and match 
1.114138 +                          ** no ORDER BY terms */
1.114139 +    return pLast->u.vtab.isOrdered;
1.114140 +  }
1.114141 +  if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
1.114142 +
1.114143 +  nOrderBy = pOrderBy->nExpr;
1.114144 +  testcase( nOrderBy==BMS-1 );
1.114145 +  if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
1.114146 +  isOrderDistinct = 1;
1.114147 +  obDone = MASKBIT(nOrderBy)-1;
1.114148 +  orderDistinctMask = 0;
1.114149 +  ready = 0;
1.114150 +  for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
1.114151 +    if( iLoop>0 ) ready |= pLoop->maskSelf;
1.114152 +    pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
1.114153 +    assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
1.114154 +    iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
1.114155 +
1.114156 +    /* Mark off any ORDER BY term X that is a column in the table of
1.114157 +    ** the current loop for which there is term in the WHERE
1.114158 +    ** clause of the form X IS NULL or X=? that reference only outer
1.114159 +    ** loops.
1.114160 +    */
1.114161 +    for(i=0; i<nOrderBy; i++){
1.114162 +      if( MASKBIT(i) & obSat ) continue;
1.114163 +      pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
1.114164 +      if( pOBExpr->op!=TK_COLUMN ) continue;
1.114165 +      if( pOBExpr->iTable!=iCur ) continue;
1.114166 +      pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
1.114167 +                       ~ready, WO_EQ|WO_ISNULL, 0);
1.114168 +      if( pTerm==0 ) continue;
1.114169 +      if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
1.114170 +        const char *z1, *z2;
1.114171 +        pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
1.114172 +        if( !pColl ) pColl = db->pDfltColl;
1.114173 +        z1 = pColl->zName;
1.114174 +        pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
1.114175 +        if( !pColl ) pColl = db->pDfltColl;
1.114176 +        z2 = pColl->zName;
1.114177 +        if( sqlite3StrICmp(z1, z2)!=0 ) continue;
1.114178 +      }
1.114179 +      obSat |= MASKBIT(i);
1.114180 +    }
1.114181 +
1.114182 +    if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
1.114183 +      if( pLoop->wsFlags & WHERE_IPK ){
1.114184 +        pIndex = 0;
1.114185 +        nKeyCol = 0;
1.114186 +        nColumn = 1;
1.114187 +      }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
1.114188 +        return 0;
1.114189 +      }else{
1.114190 +        nKeyCol = pIndex->nKeyCol;
1.114191 +        nColumn = pIndex->nColumn;
1.114192 +        assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
1.114193 +        assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
1.114194 +        isOrderDistinct = pIndex->onError!=OE_None;
1.114195 +      }
1.114196 +
1.114197 +      /* Loop through all columns of the index and deal with the ones
1.114198 +      ** that are not constrained by == or IN.
1.114199 +      */
1.114200 +      rev = revSet = 0;
1.114201 +      distinctColumns = 0;
1.114202 +      for(j=0; j<nColumn; j++){
1.114203 +        u8 bOnce;   /* True to run the ORDER BY search loop */
1.114204 +
1.114205 +        /* Skip over == and IS NULL terms */
1.114206 +        if( j<pLoop->u.btree.nEq
1.114207 +         && pLoop->u.btree.nSkip==0
1.114208 +         && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
1.114209 +        ){
1.114210 +          if( i & WO_ISNULL ){
1.114211 +            testcase( isOrderDistinct );
1.114212 +            isOrderDistinct = 0;
1.114213 +          }
1.114214 +          continue;  
1.114215 +        }
1.114216 +
1.114217 +        /* Get the column number in the table (iColumn) and sort order
1.114218 +        ** (revIdx) for the j-th column of the index.
1.114219 +        */
1.114220 +        if( pIndex ){
1.114221 +          iColumn = pIndex->aiColumn[j];
1.114222 +          revIdx = pIndex->aSortOrder[j];
1.114223 +          if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
1.114224 +        }else{
1.114225 +          iColumn = -1;
1.114226 +          revIdx = 0;
1.114227 +        }
1.114228 +
1.114229 +        /* An unconstrained column that might be NULL means that this
1.114230 +        ** WhereLoop is not well-ordered
1.114231 +        */
1.114232 +        if( isOrderDistinct
1.114233 +         && iColumn>=0
1.114234 +         && j>=pLoop->u.btree.nEq
1.114235 +         && pIndex->pTable->aCol[iColumn].notNull==0
1.114236 +        ){
1.114237 +          isOrderDistinct = 0;
1.114238 +        }
1.114239 +
1.114240 +        /* Find the ORDER BY term that corresponds to the j-th column
1.114241 +        ** of the index and and mark that ORDER BY term off 
1.114242 +        */
1.114243 +        bOnce = 1;
1.114244 +        isMatch = 0;
1.114245 +        for(i=0; bOnce && i<nOrderBy; i++){
1.114246 +          if( MASKBIT(i) & obSat ) continue;
1.114247 +          pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
1.114248 +          testcase( wctrlFlags & WHERE_GROUPBY );
1.114249 +          testcase( wctrlFlags & WHERE_DISTINCTBY );
1.114250 +          if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
1.114251 +          if( pOBExpr->op!=TK_COLUMN ) continue;
1.114252 +          if( pOBExpr->iTable!=iCur ) continue;
1.114253 +          if( pOBExpr->iColumn!=iColumn ) continue;
1.114254 +          if( iColumn>=0 ){
1.114255 +            pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
1.114256 +            if( !pColl ) pColl = db->pDfltColl;
1.114257 +            if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
1.114258 +          }
1.114259 +          isMatch = 1;
1.114260 +          break;
1.114261 +        }
1.114262 +        if( isMatch ){
1.114263 +          if( iColumn<0 ){
1.114264 +            testcase( distinctColumns==0 );
1.114265 +            distinctColumns = 1;
1.114266 +          }
1.114267 +          obSat |= MASKBIT(i);
1.114268 +          if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
1.114269 +            /* Make sure the sort order is compatible in an ORDER BY clause.
1.114270 +            ** Sort order is irrelevant for a GROUP BY clause. */
1.114271 +            if( revSet ){
1.114272 +              if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
1.114273 +            }else{
1.114274 +              rev = revIdx ^ pOrderBy->a[i].sortOrder;
1.114275 +              if( rev ) *pRevMask |= MASKBIT(iLoop);
1.114276 +              revSet = 1;
1.114277 +            }
1.114278 +          }
1.114279 +        }else{
1.114280 +          /* No match found */
1.114281 +          if( j==0 || j<nKeyCol ){
1.114282 +            testcase( isOrderDistinct!=0 );
1.114283 +            isOrderDistinct = 0;
1.114284 +          }
1.114285 +          break;
1.114286 +        }
1.114287 +      } /* end Loop over all index columns */
1.114288 +      if( distinctColumns ){
1.114289 +        testcase( isOrderDistinct==0 );
1.114290 +        isOrderDistinct = 1;
1.114291 +      }
1.114292 +    } /* end-if not one-row */
1.114293 +
1.114294 +    /* Mark off any other ORDER BY terms that reference pLoop */
1.114295 +    if( isOrderDistinct ){
1.114296 +      orderDistinctMask |= pLoop->maskSelf;
1.114297 +      for(i=0; i<nOrderBy; i++){
1.114298 +        Expr *p;
1.114299 +        Bitmask mTerm;
1.114300 +        if( MASKBIT(i) & obSat ) continue;
1.114301 +        p = pOrderBy->a[i].pExpr;
1.114302 +        mTerm = exprTableUsage(&pWInfo->sMaskSet,p);
1.114303 +        if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
1.114304 +        if( (mTerm&~orderDistinctMask)==0 ){
1.114305 +          obSat |= MASKBIT(i);
1.114306 +        }
1.114307 +      }
1.114308 +    }
1.114309 +  } /* End the loop over all WhereLoops from outer-most down to inner-most */
1.114310 +  if( obSat==obDone ) return 1;
1.114311 +  if( !isOrderDistinct ) return 0;
1.114312 +  return -1;
1.114313 +}
1.114314 +
1.114315 +#ifdef WHERETRACE_ENABLED
1.114316 +/* For debugging use only: */
1.114317 +static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
1.114318 +  static char zName[65];
1.114319 +  int i;
1.114320 +  for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
1.114321 +  if( pLast ) zName[i++] = pLast->cId;
1.114322 +  zName[i] = 0;
1.114323 +  return zName;
1.114324 +}
1.114325 +#endif
1.114326 +
1.114327 +
1.114328 +/*
1.114329 +** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
1.114330 +** attempts to find the lowest cost path that visits each WhereLoop
1.114331 +** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
1.114332 +**
1.114333 +** Assume that the total number of output rows that will need to be sorted
1.114334 +** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
1.114335 +** costs if nRowEst==0.
1.114336 +**
1.114337 +** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
1.114338 +** error occurs.
1.114339 +*/
1.114340 +static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
1.114341 +  int mxChoice;             /* Maximum number of simultaneous paths tracked */
1.114342 +  int nLoop;                /* Number of terms in the join */
1.114343 +  Parse *pParse;            /* Parsing context */
1.114344 +  sqlite3 *db;              /* The database connection */
1.114345 +  int iLoop;                /* Loop counter over the terms of the join */
1.114346 +  int ii, jj;               /* Loop counters */
1.114347 +  int mxI = 0;              /* Index of next entry to replace */
1.114348 +  LogEst rCost;             /* Cost of a path */
1.114349 +  LogEst nOut;              /* Number of outputs */
1.114350 +  LogEst mxCost = 0;        /* Maximum cost of a set of paths */
1.114351 +  LogEst mxOut = 0;         /* Maximum nOut value on the set of paths */
1.114352 +  LogEst rSortCost;         /* Cost to do a sort */
1.114353 +  int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
1.114354 +  WherePath *aFrom;         /* All nFrom paths at the previous level */
1.114355 +  WherePath *aTo;           /* The nTo best paths at the current level */
1.114356 +  WherePath *pFrom;         /* An element of aFrom[] that we are working on */
1.114357 +  WherePath *pTo;           /* An element of aTo[] that we are working on */
1.114358 +  WhereLoop *pWLoop;        /* One of the WhereLoop objects */
1.114359 +  WhereLoop **pX;           /* Used to divy up the pSpace memory */
1.114360 +  char *pSpace;             /* Temporary memory used by this routine */
1.114361 +
1.114362 +  pParse = pWInfo->pParse;
1.114363 +  db = pParse->db;
1.114364 +  nLoop = pWInfo->nLevel;
1.114365 +  /* TUNING: For simple queries, only the best path is tracked.
1.114366 +  ** For 2-way joins, the 5 best paths are followed.
1.114367 +  ** For joins of 3 or more tables, track the 10 best paths */
1.114368 +  mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
1.114369 +  assert( nLoop<=pWInfo->pTabList->nSrc );
1.114370 +  WHERETRACE(0x002, ("---- begin solver\n"));
1.114371 +
1.114372 +  /* Allocate and initialize space for aTo and aFrom */
1.114373 +  ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
1.114374 +  pSpace = sqlite3DbMallocRaw(db, ii);
1.114375 +  if( pSpace==0 ) return SQLITE_NOMEM;
1.114376 +  aTo = (WherePath*)pSpace;
1.114377 +  aFrom = aTo+mxChoice;
1.114378 +  memset(aFrom, 0, sizeof(aFrom[0]));
1.114379 +  pX = (WhereLoop**)(aFrom+mxChoice);
1.114380 +  for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
1.114381 +    pFrom->aLoop = pX;
1.114382 +  }
1.114383 +
1.114384 +  /* Seed the search with a single WherePath containing zero WhereLoops.
1.114385 +  **
1.114386 +  ** TUNING: Do not let the number of iterations go above 25.  If the cost
1.114387 +  ** of computing an automatic index is not paid back within the first 25
1.114388 +  ** rows, then do not use the automatic index. */
1.114389 +  aFrom[0].nRow = MIN(pParse->nQueryLoop, 46);  assert( 46==sqlite3LogEst(25) );
1.114390 +  nFrom = 1;
1.114391 +
1.114392 +  /* Precompute the cost of sorting the final result set, if the caller
1.114393 +  ** to sqlite3WhereBegin() was concerned about sorting */
1.114394 +  rSortCost = 0;
1.114395 +  if( pWInfo->pOrderBy==0 || nRowEst==0 ){
1.114396 +    aFrom[0].isOrderedValid = 1;
1.114397 +  }else{
1.114398 +    /* TUNING: Estimated cost of sorting is 48*N*log2(N) where N is the
1.114399 +    ** number of output rows. The 48 is the expected size of a row to sort. 
1.114400 +    ** FIXME:  compute a better estimate of the 48 multiplier based on the
1.114401 +    ** result set expressions. */
1.114402 +    rSortCost = nRowEst + estLog(nRowEst);
1.114403 +    WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
1.114404 +  }
1.114405 +
1.114406 +  /* Compute successively longer WherePaths using the previous generation
1.114407 +  ** of WherePaths as the basis for the next.  Keep track of the mxChoice
1.114408 +  ** best paths at each generation */
1.114409 +  for(iLoop=0; iLoop<nLoop; iLoop++){
1.114410 +    nTo = 0;
1.114411 +    for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
1.114412 +      for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
1.114413 +        Bitmask maskNew;
1.114414 +        Bitmask revMask = 0;
1.114415 +        u8 isOrderedValid = pFrom->isOrderedValid;
1.114416 +        u8 isOrdered = pFrom->isOrdered;
1.114417 +        if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
1.114418 +        if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
1.114419 +        /* At this point, pWLoop is a candidate to be the next loop. 
1.114420 +        ** Compute its cost */
1.114421 +        rCost = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
1.114422 +        rCost = sqlite3LogEstAdd(rCost, pFrom->rCost);
1.114423 +        nOut = pFrom->nRow + pWLoop->nOut;
1.114424 +        maskNew = pFrom->maskLoop | pWLoop->maskSelf;
1.114425 +        if( !isOrderedValid ){
1.114426 +          switch( wherePathSatisfiesOrderBy(pWInfo,
1.114427 +                       pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
1.114428 +                       iLoop, pWLoop, &revMask) ){
1.114429 +            case 1:  /* Yes.  pFrom+pWLoop does satisfy the ORDER BY clause */
1.114430 +              isOrdered = 1;
1.114431 +              isOrderedValid = 1;
1.114432 +              break;
1.114433 +            case 0:  /* No.  pFrom+pWLoop will require a separate sort */
1.114434 +              isOrdered = 0;
1.114435 +              isOrderedValid = 1;
1.114436 +              rCost = sqlite3LogEstAdd(rCost, rSortCost);
1.114437 +              break;
1.114438 +            default: /* Cannot tell yet.  Try again on the next iteration */
1.114439 +              break;
1.114440 +          }
1.114441 +        }else{
1.114442 +          revMask = pFrom->revLoop;
1.114443 +        }
1.114444 +        /* Check to see if pWLoop should be added to the mxChoice best so far */
1.114445 +        for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
1.114446 +          if( pTo->maskLoop==maskNew
1.114447 +           && pTo->isOrderedValid==isOrderedValid
1.114448 +           && ((pTo->rCost<=rCost && pTo->nRow<=nOut) ||
1.114449 +                (pTo->rCost>=rCost && pTo->nRow>=nOut))
1.114450 +          ){
1.114451 +            testcase( jj==nTo-1 );
1.114452 +            break;
1.114453 +          }
1.114454 +        }
1.114455 +        if( jj>=nTo ){
1.114456 +          if( nTo>=mxChoice && rCost>=mxCost ){
1.114457 +#ifdef WHERETRACE_ENABLED /* 0x4 */
1.114458 +            if( sqlite3WhereTrace&0x4 ){
1.114459 +              sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d order=%c\n",
1.114460 +                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
1.114461 +                  isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
1.114462 +            }
1.114463 +#endif
1.114464 +            continue;
1.114465 +          }
1.114466 +          /* Add a new Path to the aTo[] set */
1.114467 +          if( nTo<mxChoice ){
1.114468 +            /* Increase the size of the aTo set by one */
1.114469 +            jj = nTo++;
1.114470 +          }else{
1.114471 +            /* New path replaces the prior worst to keep count below mxChoice */
1.114472 +            jj = mxI;
1.114473 +          }
1.114474 +          pTo = &aTo[jj];
1.114475 +#ifdef WHERETRACE_ENABLED /* 0x4 */
1.114476 +          if( sqlite3WhereTrace&0x4 ){
1.114477 +            sqlite3DebugPrintf("New    %s cost=%-3d,%3d order=%c\n",
1.114478 +                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
1.114479 +                isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
1.114480 +          }
1.114481 +#endif
1.114482 +        }else{
1.114483 +          if( pTo->rCost<=rCost && pTo->nRow<=nOut ){
1.114484 +#ifdef WHERETRACE_ENABLED /* 0x4 */
1.114485 +            if( sqlite3WhereTrace&0x4 ){
1.114486 +              sqlite3DebugPrintf(
1.114487 +                  "Skip   %s cost=%-3d,%3d order=%c",
1.114488 +                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
1.114489 +                  isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
1.114490 +              sqlite3DebugPrintf("   vs %s cost=%-3d,%d order=%c\n",
1.114491 +                  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
1.114492 +                  pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
1.114493 +            }
1.114494 +#endif
1.114495 +            testcase( pTo->rCost==rCost );
1.114496 +            continue;
1.114497 +          }
1.114498 +          testcase( pTo->rCost==rCost+1 );
1.114499 +          /* A new and better score for a previously created equivalent path */
1.114500 +#ifdef WHERETRACE_ENABLED /* 0x4 */
1.114501 +          if( sqlite3WhereTrace&0x4 ){
1.114502 +            sqlite3DebugPrintf(
1.114503 +                "Update %s cost=%-3d,%3d order=%c",
1.114504 +                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
1.114505 +                isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
1.114506 +            sqlite3DebugPrintf("  was %s cost=%-3d,%3d order=%c\n",
1.114507 +                wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
1.114508 +                pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
1.114509 +          }
1.114510 +#endif
1.114511 +        }
1.114512 +        /* pWLoop is a winner.  Add it to the set of best so far */
1.114513 +        pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
1.114514 +        pTo->revLoop = revMask;
1.114515 +        pTo->nRow = nOut;
1.114516 +        pTo->rCost = rCost;
1.114517 +        pTo->isOrderedValid = isOrderedValid;
1.114518 +        pTo->isOrdered = isOrdered;
1.114519 +        memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
1.114520 +        pTo->aLoop[iLoop] = pWLoop;
1.114521 +        if( nTo>=mxChoice ){
1.114522 +          mxI = 0;
1.114523 +          mxCost = aTo[0].rCost;
1.114524 +          mxOut = aTo[0].nRow;
1.114525 +          for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
1.114526 +            if( pTo->rCost>mxCost || (pTo->rCost==mxCost && pTo->nRow>mxOut) ){
1.114527 +              mxCost = pTo->rCost;
1.114528 +              mxOut = pTo->nRow;
1.114529 +              mxI = jj;
1.114530 +            }
1.114531 +          }
1.114532 +        }
1.114533 +      }
1.114534 +    }
1.114535 +
1.114536 +#ifdef WHERETRACE_ENABLED  /* >=2 */
1.114537 +    if( sqlite3WhereTrace>=2 ){
1.114538 +      sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
1.114539 +      for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
1.114540 +        sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
1.114541 +           wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
1.114542 +           pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
1.114543 +        if( pTo->isOrderedValid && pTo->isOrdered ){
1.114544 +          sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
1.114545 +        }else{
1.114546 +          sqlite3DebugPrintf("\n");
1.114547 +        }
1.114548 +      }
1.114549 +    }
1.114550 +#endif
1.114551 +
1.114552 +    /* Swap the roles of aFrom and aTo for the next generation */
1.114553 +    pFrom = aTo;
1.114554 +    aTo = aFrom;
1.114555 +    aFrom = pFrom;
1.114556 +    nFrom = nTo;
1.114557 +  }
1.114558 +
1.114559 +  if( nFrom==0 ){
1.114560 +    sqlite3ErrorMsg(pParse, "no query solution");
1.114561 +    sqlite3DbFree(db, pSpace);
1.114562 +    return SQLITE_ERROR;
1.114563 +  }
1.114564 +  
1.114565 +  /* Find the lowest cost path.  pFrom will be left pointing to that path */
1.114566 +  pFrom = aFrom;
1.114567 +  for(ii=1; ii<nFrom; ii++){
1.114568 +    if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
1.114569 +  }
1.114570 +  assert( pWInfo->nLevel==nLoop );
1.114571 +  /* Load the lowest cost path into pWInfo */
1.114572 +  for(iLoop=0; iLoop<nLoop; iLoop++){
1.114573 +    WhereLevel *pLevel = pWInfo->a + iLoop;
1.114574 +    pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
1.114575 +    pLevel->iFrom = pWLoop->iTab;
1.114576 +    pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
1.114577 +  }
1.114578 +  if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
1.114579 +   && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
1.114580 +   && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
1.114581 +   && nRowEst
1.114582 +  ){
1.114583 +    Bitmask notUsed;
1.114584 +    int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
1.114585 +                 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
1.114586 +    if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
1.114587 +  }
1.114588 +  if( pFrom->isOrdered ){
1.114589 +    if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
1.114590 +      pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
1.114591 +    }else{
1.114592 +      pWInfo->bOBSat = 1;
1.114593 +      pWInfo->revMask = pFrom->revLoop;
1.114594 +    }
1.114595 +  }
1.114596 +  pWInfo->nRowOut = pFrom->nRow;
1.114597 +
1.114598 +  /* Free temporary memory and return success */
1.114599 +  sqlite3DbFree(db, pSpace);
1.114600 +  return SQLITE_OK;
1.114601 +}
1.114602 +
1.114603 +/*
1.114604 +** Most queries use only a single table (they are not joins) and have
1.114605 +** simple == constraints against indexed fields.  This routine attempts
1.114606 +** to plan those simple cases using much less ceremony than the
1.114607 +** general-purpose query planner, and thereby yield faster sqlite3_prepare()
1.114608 +** times for the common case.
1.114609 +**
1.114610 +** Return non-zero on success, if this query can be handled by this
1.114611 +** no-frills query planner.  Return zero if this query needs the 
1.114612 +** general-purpose query planner.
1.114613 +*/
1.114614 +static int whereShortCut(WhereLoopBuilder *pBuilder){
1.114615 +  WhereInfo *pWInfo;
1.114616 +  struct SrcList_item *pItem;
1.114617 +  WhereClause *pWC;
1.114618 +  WhereTerm *pTerm;
1.114619 +  WhereLoop *pLoop;
1.114620 +  int iCur;
1.114621 +  int j;
1.114622 +  Table *pTab;
1.114623 +  Index *pIdx;
1.114624 +  
1.114625 +  pWInfo = pBuilder->pWInfo;
1.114626 +  if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
1.114627 +  assert( pWInfo->pTabList->nSrc>=1 );
1.114628 +  pItem = pWInfo->pTabList->a;
1.114629 +  pTab = pItem->pTab;
1.114630 +  if( IsVirtual(pTab) ) return 0;
1.114631 +  if( pItem->zIndex ) return 0;
1.114632 +  iCur = pItem->iCursor;
1.114633 +  pWC = &pWInfo->sWC;
1.114634 +  pLoop = pBuilder->pNew;
1.114635 +  pLoop->wsFlags = 0;
1.114636 +  pLoop->u.btree.nSkip = 0;
1.114637 +  pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
1.114638 +  if( pTerm ){
1.114639 +    pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
1.114640 +    pLoop->aLTerm[0] = pTerm;
1.114641 +    pLoop->nLTerm = 1;
1.114642 +    pLoop->u.btree.nEq = 1;
1.114643 +    /* TUNING: Cost of a rowid lookup is 10 */
1.114644 +    pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
1.114645 +  }else{
1.114646 +    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1.114647 +      assert( pLoop->aLTermSpace==pLoop->aLTerm );
1.114648 +      assert( ArraySize(pLoop->aLTermSpace)==4 );
1.114649 +      if( pIdx->onError==OE_None 
1.114650 +       || pIdx->pPartIdxWhere!=0 
1.114651 +       || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace) 
1.114652 +      ) continue;
1.114653 +      for(j=0; j<pIdx->nKeyCol; j++){
1.114654 +        pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
1.114655 +        if( pTerm==0 ) break;
1.114656 +        pLoop->aLTerm[j] = pTerm;
1.114657 +      }
1.114658 +      if( j!=pIdx->nKeyCol ) continue;
1.114659 +      pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
1.114660 +      if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
1.114661 +        pLoop->wsFlags |= WHERE_IDX_ONLY;
1.114662 +      }
1.114663 +      pLoop->nLTerm = j;
1.114664 +      pLoop->u.btree.nEq = j;
1.114665 +      pLoop->u.btree.pIndex = pIdx;
1.114666 +      /* TUNING: Cost of a unique index lookup is 15 */
1.114667 +      pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
1.114668 +      break;
1.114669 +    }
1.114670 +  }
1.114671 +  if( pLoop->wsFlags ){
1.114672 +    pLoop->nOut = (LogEst)1;
1.114673 +    pWInfo->a[0].pWLoop = pLoop;
1.114674 +    pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
1.114675 +    pWInfo->a[0].iTabCur = iCur;
1.114676 +    pWInfo->nRowOut = 1;
1.114677 +    if( pWInfo->pOrderBy ) pWInfo->bOBSat =  1;
1.114678 +    if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
1.114679 +      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
1.114680 +    }
1.114681 +#ifdef SQLITE_DEBUG
1.114682 +    pLoop->cId = '0';
1.114683 +#endif
1.114684 +    return 1;
1.114685 +  }
1.114686 +  return 0;
1.114687 +}
1.114688 +
1.114689 +/*
1.114690 +** Generate the beginning of the loop used for WHERE clause processing.
1.114691 +** The return value is a pointer to an opaque structure that contains
1.114692 +** information needed to terminate the loop.  Later, the calling routine
1.114693 +** should invoke sqlite3WhereEnd() with the return value of this function
1.114694 +** in order to complete the WHERE clause processing.
1.114695 +**
1.114696 +** If an error occurs, this routine returns NULL.
1.114697 +**
1.114698 +** The basic idea is to do a nested loop, one loop for each table in
1.114699 +** the FROM clause of a select.  (INSERT and UPDATE statements are the
1.114700 +** same as a SELECT with only a single table in the FROM clause.)  For
1.114701 +** example, if the SQL is this:
1.114702 +**
1.114703 +**       SELECT * FROM t1, t2, t3 WHERE ...;
1.114704 +**
1.114705 +** Then the code generated is conceptually like the following:
1.114706 +**
1.114707 +**      foreach row1 in t1 do       \    Code generated
1.114708 +**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
1.114709 +**          foreach row3 in t3 do   /
1.114710 +**            ...
1.114711 +**          end                     \    Code generated
1.114712 +**        end                        |-- by sqlite3WhereEnd()
1.114713 +**      end                         /
1.114714 +**
1.114715 +** Note that the loops might not be nested in the order in which they
1.114716 +** appear in the FROM clause if a different order is better able to make
1.114717 +** use of indices.  Note also that when the IN operator appears in
1.114718 +** the WHERE clause, it might result in additional nested loops for
1.114719 +** scanning through all values on the right-hand side of the IN.
1.114720 +**
1.114721 +** There are Btree cursors associated with each table.  t1 uses cursor
1.114722 +** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
1.114723 +** And so forth.  This routine generates code to open those VDBE cursors
1.114724 +** and sqlite3WhereEnd() generates the code to close them.
1.114725 +**
1.114726 +** The code that sqlite3WhereBegin() generates leaves the cursors named
1.114727 +** in pTabList pointing at their appropriate entries.  The [...] code
1.114728 +** can use OP_Column and OP_Rowid opcodes on these cursors to extract
1.114729 +** data from the various tables of the loop.
1.114730 +**
1.114731 +** If the WHERE clause is empty, the foreach loops must each scan their
1.114732 +** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
1.114733 +** the tables have indices and there are terms in the WHERE clause that
1.114734 +** refer to those indices, a complete table scan can be avoided and the
1.114735 +** code will run much faster.  Most of the work of this routine is checking
1.114736 +** to see if there are indices that can be used to speed up the loop.
1.114737 +**
1.114738 +** Terms of the WHERE clause are also used to limit which rows actually
1.114739 +** make it to the "..." in the middle of the loop.  After each "foreach",
1.114740 +** terms of the WHERE clause that use only terms in that loop and outer
1.114741 +** loops are evaluated and if false a jump is made around all subsequent
1.114742 +** inner loops (or around the "..." if the test occurs within the inner-
1.114743 +** most loop)
1.114744 +**
1.114745 +** OUTER JOINS
1.114746 +**
1.114747 +** An outer join of tables t1 and t2 is conceptally coded as follows:
1.114748 +**
1.114749 +**    foreach row1 in t1 do
1.114750 +**      flag = 0
1.114751 +**      foreach row2 in t2 do
1.114752 +**        start:
1.114753 +**          ...
1.114754 +**          flag = 1
1.114755 +**      end
1.114756 +**      if flag==0 then
1.114757 +**        move the row2 cursor to a null row
1.114758 +**        goto start
1.114759 +**      fi
1.114760 +**    end
1.114761 +**
1.114762 +** ORDER BY CLAUSE PROCESSING
1.114763 +**
1.114764 +** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
1.114765 +** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
1.114766 +** if there is one.  If there is no ORDER BY clause or if this routine
1.114767 +** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
1.114768 +**
1.114769 +** The iIdxCur parameter is the cursor number of an index.  If 
1.114770 +** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
1.114771 +** to use for OR clause processing.  The WHERE clause should use this
1.114772 +** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
1.114773 +** the first cursor in an array of cursors for all indices.  iIdxCur should
1.114774 +** be used to compute the appropriate cursor depending on which index is
1.114775 +** used.
1.114776 +*/
1.114777 +SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
1.114778 +  Parse *pParse,        /* The parser context */
1.114779 +  SrcList *pTabList,    /* FROM clause: A list of all tables to be scanned */
1.114780 +  Expr *pWhere,         /* The WHERE clause */
1.114781 +  ExprList *pOrderBy,   /* An ORDER BY clause, or NULL */
1.114782 +  ExprList *pResultSet, /* Result set of the query */
1.114783 +  u16 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */
1.114784 +  int iIdxCur           /* If WHERE_ONETABLE_ONLY is set, index cursor number */
1.114785 +){
1.114786 +  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
1.114787 +  int nTabList;              /* Number of elements in pTabList */
1.114788 +  WhereInfo *pWInfo;         /* Will become the return value of this function */
1.114789 +  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
1.114790 +  Bitmask notReady;          /* Cursors that are not yet positioned */
1.114791 +  WhereLoopBuilder sWLB;     /* The WhereLoop builder */
1.114792 +  WhereMaskSet *pMaskSet;    /* The expression mask set */
1.114793 +  WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
1.114794 +  WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
1.114795 +  int ii;                    /* Loop counter */
1.114796 +  sqlite3 *db;               /* Database connection */
1.114797 +  int rc;                    /* Return code */
1.114798 +
1.114799 +
1.114800 +  /* Variable initialization */
1.114801 +  db = pParse->db;
1.114802 +  memset(&sWLB, 0, sizeof(sWLB));
1.114803 +  sWLB.pOrderBy = pOrderBy;
1.114804 +
1.114805 +  /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
1.114806 +  ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
1.114807 +  if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
1.114808 +    wctrlFlags &= ~WHERE_WANT_DISTINCT;
1.114809 +  }
1.114810 +
1.114811 +  /* The number of tables in the FROM clause is limited by the number of
1.114812 +  ** bits in a Bitmask 
1.114813 +  */
1.114814 +  testcase( pTabList->nSrc==BMS );
1.114815 +  if( pTabList->nSrc>BMS ){
1.114816 +    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
1.114817 +    return 0;
1.114818 +  }
1.114819 +
1.114820 +  /* This function normally generates a nested loop for all tables in 
1.114821 +  ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
1.114822 +  ** only generate code for the first table in pTabList and assume that
1.114823 +  ** any cursors associated with subsequent tables are uninitialized.
1.114824 +  */
1.114825 +  nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
1.114826 +
1.114827 +  /* Allocate and initialize the WhereInfo structure that will become the
1.114828 +  ** return value. A single allocation is used to store the WhereInfo
1.114829 +  ** struct, the contents of WhereInfo.a[], the WhereClause structure
1.114830 +  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
1.114831 +  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
1.114832 +  ** some architectures. Hence the ROUND8() below.
1.114833 +  */
1.114834 +  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
1.114835 +  pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
1.114836 +  if( db->mallocFailed ){
1.114837 +    sqlite3DbFree(db, pWInfo);
1.114838 +    pWInfo = 0;
1.114839 +    goto whereBeginError;
1.114840 +  }
1.114841 +  pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
1.114842 +  pWInfo->nLevel = nTabList;
1.114843 +  pWInfo->pParse = pParse;
1.114844 +  pWInfo->pTabList = pTabList;
1.114845 +  pWInfo->pOrderBy = pOrderBy;
1.114846 +  pWInfo->pResultSet = pResultSet;
1.114847 +  pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
1.114848 +  pWInfo->wctrlFlags = wctrlFlags;
1.114849 +  pWInfo->savedNQueryLoop = pParse->nQueryLoop;
1.114850 +  pMaskSet = &pWInfo->sMaskSet;
1.114851 +  sWLB.pWInfo = pWInfo;
1.114852 +  sWLB.pWC = &pWInfo->sWC;
1.114853 +  sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
1.114854 +  assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
1.114855 +  whereLoopInit(sWLB.pNew);
1.114856 +#ifdef SQLITE_DEBUG
1.114857 +  sWLB.pNew->cId = '*';
1.114858 +#endif
1.114859 +
1.114860 +  /* Split the WHERE clause into separate subexpressions where each
1.114861 +  ** subexpression is separated by an AND operator.
1.114862 +  */
1.114863 +  initMaskSet(pMaskSet);
1.114864 +  whereClauseInit(&pWInfo->sWC, pWInfo);
1.114865 +  whereSplit(&pWInfo->sWC, pWhere, TK_AND);
1.114866 +    
1.114867 +  /* Special case: a WHERE clause that is constant.  Evaluate the
1.114868 +  ** expression and either jump over all of the code or fall thru.
1.114869 +  */
1.114870 +  for(ii=0; ii<sWLB.pWC->nTerm; ii++){
1.114871 +    if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
1.114872 +      sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
1.114873 +                         SQLITE_JUMPIFNULL);
1.114874 +      sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
1.114875 +    }
1.114876 +  }
1.114877 +
1.114878 +  /* Special case: No FROM clause
1.114879 +  */
1.114880 +  if( nTabList==0 ){
1.114881 +    if( pOrderBy ) pWInfo->bOBSat = 1;
1.114882 +    if( wctrlFlags & WHERE_WANT_DISTINCT ){
1.114883 +      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
1.114884 +    }
1.114885 +  }
1.114886 +
1.114887 +  /* Assign a bit from the bitmask to every term in the FROM clause.
1.114888 +  **
1.114889 +  ** When assigning bitmask values to FROM clause cursors, it must be
1.114890 +  ** the case that if X is the bitmask for the N-th FROM clause term then
1.114891 +  ** the bitmask for all FROM clause terms to the left of the N-th term
1.114892 +  ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
1.114893 +  ** its Expr.iRightJoinTable value to find the bitmask of the right table
1.114894 +  ** of the join.  Subtracting one from the right table bitmask gives a
1.114895 +  ** bitmask for all tables to the left of the join.  Knowing the bitmask
1.114896 +  ** for all tables to the left of a left join is important.  Ticket #3015.
1.114897 +  **
1.114898 +  ** Note that bitmasks are created for all pTabList->nSrc tables in
1.114899 +  ** pTabList, not just the first nTabList tables.  nTabList is normally
1.114900 +  ** equal to pTabList->nSrc but might be shortened to 1 if the
1.114901 +  ** WHERE_ONETABLE_ONLY flag is set.
1.114902 +  */
1.114903 +  for(ii=0; ii<pTabList->nSrc; ii++){
1.114904 +    createMask(pMaskSet, pTabList->a[ii].iCursor);
1.114905 +  }
1.114906 +#ifndef NDEBUG
1.114907 +  {
1.114908 +    Bitmask toTheLeft = 0;
1.114909 +    for(ii=0; ii<pTabList->nSrc; ii++){
1.114910 +      Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
1.114911 +      assert( (m-1)==toTheLeft );
1.114912 +      toTheLeft |= m;
1.114913 +    }
1.114914 +  }
1.114915 +#endif
1.114916 +
1.114917 +  /* Analyze all of the subexpressions.  Note that exprAnalyze() might
1.114918 +  ** add new virtual terms onto the end of the WHERE clause.  We do not
1.114919 +  ** want to analyze these virtual terms, so start analyzing at the end
1.114920 +  ** and work forward so that the added virtual terms are never processed.
1.114921 +  */
1.114922 +  exprAnalyzeAll(pTabList, &pWInfo->sWC);
1.114923 +  if( db->mallocFailed ){
1.114924 +    goto whereBeginError;
1.114925 +  }
1.114926 +
1.114927 +  if( wctrlFlags & WHERE_WANT_DISTINCT ){
1.114928 +    if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
1.114929 +      /* The DISTINCT marking is pointless.  Ignore it. */
1.114930 +      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
1.114931 +    }else if( pOrderBy==0 ){
1.114932 +      /* Try to ORDER BY the result set to make distinct processing easier */
1.114933 +      pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
1.114934 +      pWInfo->pOrderBy = pResultSet;
1.114935 +    }
1.114936 +  }
1.114937 +
1.114938 +  /* Construct the WhereLoop objects */
1.114939 +  WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
1.114940 +  /* Display all terms of the WHERE clause */
1.114941 +#if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN)
1.114942 +  if( sqlite3WhereTrace & 0x100 ){
1.114943 +    int i;
1.114944 +    Vdbe *v = pParse->pVdbe;
1.114945 +    sqlite3ExplainBegin(v);
1.114946 +    for(i=0; i<sWLB.pWC->nTerm; i++){
1.114947 +      sqlite3ExplainPrintf(v, "#%-2d ", i);
1.114948 +      sqlite3ExplainPush(v);
1.114949 +      whereExplainTerm(v, &sWLB.pWC->a[i]);
1.114950 +      sqlite3ExplainPop(v);
1.114951 +      sqlite3ExplainNL(v);
1.114952 +    }
1.114953 +    sqlite3ExplainFinish(v);
1.114954 +    sqlite3DebugPrintf("%s", sqlite3VdbeExplanation(v));
1.114955 +  }
1.114956 +#endif
1.114957 +  if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
1.114958 +    rc = whereLoopAddAll(&sWLB);
1.114959 +    if( rc ) goto whereBeginError;
1.114960 +  
1.114961 +    /* Display all of the WhereLoop objects if wheretrace is enabled */
1.114962 +#ifdef WHERETRACE_ENABLED /* !=0 */
1.114963 +    if( sqlite3WhereTrace ){
1.114964 +      WhereLoop *p;
1.114965 +      int i;
1.114966 +      static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
1.114967 +                                       "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
1.114968 +      for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
1.114969 +        p->cId = zLabel[i%sizeof(zLabel)];
1.114970 +        whereLoopPrint(p, sWLB.pWC);
1.114971 +      }
1.114972 +    }
1.114973 +#endif
1.114974 +  
1.114975 +    wherePathSolver(pWInfo, 0);
1.114976 +    if( db->mallocFailed ) goto whereBeginError;
1.114977 +    if( pWInfo->pOrderBy ){
1.114978 +       wherePathSolver(pWInfo, pWInfo->nRowOut+1);
1.114979 +       if( db->mallocFailed ) goto whereBeginError;
1.114980 +    }
1.114981 +  }
1.114982 +  if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
1.114983 +     pWInfo->revMask = (Bitmask)(-1);
1.114984 +  }
1.114985 +  if( pParse->nErr || NEVER(db->mallocFailed) ){
1.114986 +    goto whereBeginError;
1.114987 +  }
1.114988 +#ifdef WHERETRACE_ENABLED /* !=0 */
1.114989 +  if( sqlite3WhereTrace ){
1.114990 +    int ii;
1.114991 +    sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
1.114992 +    if( pWInfo->bOBSat ){
1.114993 +      sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask);
1.114994 +    }
1.114995 +    switch( pWInfo->eDistinct ){
1.114996 +      case WHERE_DISTINCT_UNIQUE: {
1.114997 +        sqlite3DebugPrintf("  DISTINCT=unique");
1.114998 +        break;
1.114999 +      }
1.115000 +      case WHERE_DISTINCT_ORDERED: {
1.115001 +        sqlite3DebugPrintf("  DISTINCT=ordered");
1.115002 +        break;
1.115003 +      }
1.115004 +      case WHERE_DISTINCT_UNORDERED: {
1.115005 +        sqlite3DebugPrintf("  DISTINCT=unordered");
1.115006 +        break;
1.115007 +      }
1.115008 +    }
1.115009 +    sqlite3DebugPrintf("\n");
1.115010 +    for(ii=0; ii<pWInfo->nLevel; ii++){
1.115011 +      whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
1.115012 +    }
1.115013 +  }
1.115014 +#endif
1.115015 +  /* Attempt to omit tables from the join that do not effect the result */
1.115016 +  if( pWInfo->nLevel>=2
1.115017 +   && pResultSet!=0
1.115018 +   && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
1.115019 +  ){
1.115020 +    Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
1.115021 +    if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
1.115022 +    while( pWInfo->nLevel>=2 ){
1.115023 +      WhereTerm *pTerm, *pEnd;
1.115024 +      pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
1.115025 +      if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
1.115026 +      if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
1.115027 +       && (pLoop->wsFlags & WHERE_ONEROW)==0
1.115028 +      ){
1.115029 +        break;
1.115030 +      }
1.115031 +      if( (tabUsed & pLoop->maskSelf)!=0 ) break;
1.115032 +      pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
1.115033 +      for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
1.115034 +        if( (pTerm->prereqAll & pLoop->maskSelf)!=0
1.115035 +         && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
1.115036 +        ){
1.115037 +          break;
1.115038 +        }
1.115039 +      }
1.115040 +      if( pTerm<pEnd ) break;
1.115041 +      WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
1.115042 +      pWInfo->nLevel--;
1.115043 +      nTabList--;
1.115044 +    }
1.115045 +  }
1.115046 +  WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
1.115047 +  pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
1.115048 +
1.115049 +  /* If the caller is an UPDATE or DELETE statement that is requesting
1.115050 +  ** to use a one-pass algorithm, determine if this is appropriate.
1.115051 +  ** The one-pass algorithm only works if the WHERE clause constrains
1.115052 +  ** the statement to update a single row.
1.115053 +  */
1.115054 +  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
1.115055 +  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 
1.115056 +   && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
1.115057 +    pWInfo->okOnePass = 1;
1.115058 +    if( HasRowid(pTabList->a[0].pTab) ){
1.115059 +      pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
1.115060 +    }
1.115061 +  }
1.115062 +
1.115063 +  /* Open all tables in the pTabList and any indices selected for
1.115064 +  ** searching those tables.
1.115065 +  */
1.115066 +  notReady = ~(Bitmask)0;
1.115067 +  for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
1.115068 +    Table *pTab;     /* Table to open */
1.115069 +    int iDb;         /* Index of database containing table/index */
1.115070 +    struct SrcList_item *pTabItem;
1.115071 +
1.115072 +    pTabItem = &pTabList->a[pLevel->iFrom];
1.115073 +    pTab = pTabItem->pTab;
1.115074 +    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1.115075 +    pLoop = pLevel->pWLoop;
1.115076 +    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
1.115077 +      /* Do nothing */
1.115078 +    }else
1.115079 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.115080 +    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
1.115081 +      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
1.115082 +      int iCur = pTabItem->iCursor;
1.115083 +      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
1.115084 +    }else if( IsVirtual(pTab) ){
1.115085 +      /* noop */
1.115086 +    }else
1.115087 +#endif
1.115088 +    if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
1.115089 +         && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
1.115090 +      int op = OP_OpenRead;
1.115091 +      if( pWInfo->okOnePass ){
1.115092 +        op = OP_OpenWrite;
1.115093 +        pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
1.115094 +      };
1.115095 +      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
1.115096 +      assert( pTabItem->iCursor==pLevel->iTabCur );
1.115097 +      testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
1.115098 +      testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
1.115099 +      if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
1.115100 +        Bitmask b = pTabItem->colUsed;
1.115101 +        int n = 0;
1.115102 +        for(; b; b=b>>1, n++){}
1.115103 +        sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, 
1.115104 +                            SQLITE_INT_TO_PTR(n), P4_INT32);
1.115105 +        assert( n<=pTab->nCol );
1.115106 +      }
1.115107 +    }else{
1.115108 +      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
1.115109 +    }
1.115110 +    if( pLoop->wsFlags & WHERE_INDEXED ){
1.115111 +      Index *pIx = pLoop->u.btree.pIndex;
1.115112 +      int iIndexCur;
1.115113 +      int op = OP_OpenRead;
1.115114 +      /* iIdxCur is always set if to a positive value if ONEPASS is possible */
1.115115 +      assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
1.115116 +      if( pWInfo->okOnePass ){
1.115117 +        Index *pJ = pTabItem->pTab->pIndex;
1.115118 +        iIndexCur = iIdxCur;
1.115119 +        assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
1.115120 +        while( ALWAYS(pJ) && pJ!=pIx ){
1.115121 +          iIndexCur++;
1.115122 +          pJ = pJ->pNext;
1.115123 +        }
1.115124 +        op = OP_OpenWrite;
1.115125 +        pWInfo->aiCurOnePass[1] = iIndexCur;
1.115126 +      }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
1.115127 +        iIndexCur = iIdxCur;
1.115128 +      }else{
1.115129 +        iIndexCur = pParse->nTab++;
1.115130 +      }
1.115131 +      pLevel->iIdxCur = iIndexCur;
1.115132 +      assert( pIx->pSchema==pTab->pSchema );
1.115133 +      assert( iIndexCur>=0 );
1.115134 +      sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
1.115135 +      sqlite3VdbeSetP4KeyInfo(pParse, pIx);
1.115136 +      VdbeComment((v, "%s", pIx->zName));
1.115137 +    }
1.115138 +    if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
1.115139 +    notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
1.115140 +  }
1.115141 +  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
1.115142 +  if( db->mallocFailed ) goto whereBeginError;
1.115143 +
1.115144 +  /* Generate the code to do the search.  Each iteration of the for
1.115145 +  ** loop below generates code for a single nested loop of the VM
1.115146 +  ** program.
1.115147 +  */
1.115148 +  notReady = ~(Bitmask)0;
1.115149 +  for(ii=0; ii<nTabList; ii++){
1.115150 +    pLevel = &pWInfo->a[ii];
1.115151 +#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
1.115152 +    if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
1.115153 +      constructAutomaticIndex(pParse, &pWInfo->sWC,
1.115154 +                &pTabList->a[pLevel->iFrom], notReady, pLevel);
1.115155 +      if( db->mallocFailed ) goto whereBeginError;
1.115156 +    }
1.115157 +#endif
1.115158 +    explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
1.115159 +    pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
1.115160 +    notReady = codeOneLoopStart(pWInfo, ii, notReady);
1.115161 +    pWInfo->iContinue = pLevel->addrCont;
1.115162 +  }
1.115163 +
1.115164 +  /* Done. */
1.115165 +  VdbeModuleComment((v, "Begin WHERE-core"));
1.115166 +  return pWInfo;
1.115167 +
1.115168 +  /* Jump here if malloc fails */
1.115169 +whereBeginError:
1.115170 +  if( pWInfo ){
1.115171 +    pParse->nQueryLoop = pWInfo->savedNQueryLoop;
1.115172 +    whereInfoFree(db, pWInfo);
1.115173 +  }
1.115174 +  return 0;
1.115175 +}
1.115176 +
1.115177 +/*
1.115178 +** Generate the end of the WHERE loop.  See comments on 
1.115179 +** sqlite3WhereBegin() for additional information.
1.115180 +*/
1.115181 +SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
1.115182 +  Parse *pParse = pWInfo->pParse;
1.115183 +  Vdbe *v = pParse->pVdbe;
1.115184 +  int i;
1.115185 +  WhereLevel *pLevel;
1.115186 +  WhereLoop *pLoop;
1.115187 +  SrcList *pTabList = pWInfo->pTabList;
1.115188 +  sqlite3 *db = pParse->db;
1.115189 +
1.115190 +  /* Generate loop termination code.
1.115191 +  */
1.115192 +  VdbeModuleComment((v, "End WHERE-core"));
1.115193 +  sqlite3ExprCacheClear(pParse);
1.115194 +  for(i=pWInfo->nLevel-1; i>=0; i--){
1.115195 +    int addr;
1.115196 +    pLevel = &pWInfo->a[i];
1.115197 +    pLoop = pLevel->pWLoop;
1.115198 +    sqlite3VdbeResolveLabel(v, pLevel->addrCont);
1.115199 +    if( pLevel->op!=OP_Noop ){
1.115200 +      sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
1.115201 +      sqlite3VdbeChangeP5(v, pLevel->p5);
1.115202 +      VdbeCoverage(v);
1.115203 +      VdbeCoverageIf(v, pLevel->op==OP_Next);
1.115204 +      VdbeCoverageIf(v, pLevel->op==OP_Prev);
1.115205 +      VdbeCoverageIf(v, pLevel->op==OP_VNext);
1.115206 +    }
1.115207 +    if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
1.115208 +      struct InLoop *pIn;
1.115209 +      int j;
1.115210 +      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
1.115211 +      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
1.115212 +        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
1.115213 +        sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
1.115214 +        VdbeCoverage(v);
1.115215 +        VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
1.115216 +        VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
1.115217 +        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
1.115218 +      }
1.115219 +      sqlite3DbFree(db, pLevel->u.in.aInLoop);
1.115220 +    }
1.115221 +    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
1.115222 +    if( pLevel->addrSkip ){
1.115223 +      sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
1.115224 +      VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
1.115225 +      sqlite3VdbeJumpHere(v, pLevel->addrSkip);
1.115226 +      sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
1.115227 +    }
1.115228 +    if( pLevel->iLeftJoin ){
1.115229 +      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
1.115230 +      assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
1.115231 +           || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
1.115232 +      if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
1.115233 +        sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
1.115234 +      }
1.115235 +      if( pLoop->wsFlags & WHERE_INDEXED ){
1.115236 +        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
1.115237 +      }
1.115238 +      if( pLevel->op==OP_Return ){
1.115239 +        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
1.115240 +      }else{
1.115241 +        sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
1.115242 +      }
1.115243 +      sqlite3VdbeJumpHere(v, addr);
1.115244 +    }
1.115245 +    VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
1.115246 +                     pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
1.115247 +  }
1.115248 +
1.115249 +  /* The "break" point is here, just past the end of the outer loop.
1.115250 +  ** Set it.
1.115251 +  */
1.115252 +  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
1.115253 +
1.115254 +  assert( pWInfo->nLevel<=pTabList->nSrc );
1.115255 +  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
1.115256 +    int k, last;
1.115257 +    VdbeOp *pOp;
1.115258 +    Index *pIdx = 0;
1.115259 +    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
1.115260 +    Table *pTab = pTabItem->pTab;
1.115261 +    assert( pTab!=0 );
1.115262 +    pLoop = pLevel->pWLoop;
1.115263 +
1.115264 +    /* For a co-routine, change all OP_Column references to the table of
1.115265 +    ** the co-routine into OP_SCopy of result contained in a register.
1.115266 +    ** OP_Rowid becomes OP_Null.
1.115267 +    */
1.115268 +    if( pTabItem->viaCoroutine && !db->mallocFailed ){
1.115269 +      last = sqlite3VdbeCurrentAddr(v);
1.115270 +      k = pLevel->addrBody;
1.115271 +      pOp = sqlite3VdbeGetOp(v, k);
1.115272 +      for(; k<last; k++, pOp++){
1.115273 +        if( pOp->p1!=pLevel->iTabCur ) continue;
1.115274 +        if( pOp->opcode==OP_Column ){
1.115275 +          pOp->opcode = OP_SCopy;
1.115276 +          pOp->p1 = pOp->p2 + pTabItem->regResult;
1.115277 +          pOp->p2 = pOp->p3;
1.115278 +          pOp->p3 = 0;
1.115279 +        }else if( pOp->opcode==OP_Rowid ){
1.115280 +          pOp->opcode = OP_Null;
1.115281 +          pOp->p1 = 0;
1.115282 +          pOp->p3 = 0;
1.115283 +        }
1.115284 +      }
1.115285 +      continue;
1.115286 +    }
1.115287 +
1.115288 +    /* Close all of the cursors that were opened by sqlite3WhereBegin.
1.115289 +    ** Except, do not close cursors that will be reused by the OR optimization
1.115290 +    ** (WHERE_OMIT_OPEN_CLOSE).  And do not close the OP_OpenWrite cursors
1.115291 +    ** created for the ONEPASS optimization.
1.115292 +    */
1.115293 +    if( (pTab->tabFlags & TF_Ephemeral)==0
1.115294 +     && pTab->pSelect==0
1.115295 +     && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
1.115296 +    ){
1.115297 +      int ws = pLoop->wsFlags;
1.115298 +      if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
1.115299 +        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
1.115300 +      }
1.115301 +      if( (ws & WHERE_INDEXED)!=0
1.115302 +       && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 
1.115303 +       && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
1.115304 +      ){
1.115305 +        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
1.115306 +      }
1.115307 +    }
1.115308 +
1.115309 +    /* If this scan uses an index, make VDBE code substitutions to read data
1.115310 +    ** from the index instead of from the table where possible.  In some cases
1.115311 +    ** this optimization prevents the table from ever being read, which can
1.115312 +    ** yield a significant performance boost.
1.115313 +    ** 
1.115314 +    ** Calls to the code generator in between sqlite3WhereBegin and
1.115315 +    ** sqlite3WhereEnd will have created code that references the table
1.115316 +    ** directly.  This loop scans all that code looking for opcodes
1.115317 +    ** that reference the table and converts them into opcodes that
1.115318 +    ** reference the index.
1.115319 +    */
1.115320 +    if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
1.115321 +      pIdx = pLoop->u.btree.pIndex;
1.115322 +    }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
1.115323 +      pIdx = pLevel->u.pCovidx;
1.115324 +    }
1.115325 +    if( pIdx && !db->mallocFailed ){
1.115326 +      last = sqlite3VdbeCurrentAddr(v);
1.115327 +      k = pLevel->addrBody;
1.115328 +      pOp = sqlite3VdbeGetOp(v, k);
1.115329 +      for(; k<last; k++, pOp++){
1.115330 +        if( pOp->p1!=pLevel->iTabCur ) continue;
1.115331 +        if( pOp->opcode==OP_Column ){
1.115332 +          int x = pOp->p2;
1.115333 +          assert( pIdx->pTable==pTab );
1.115334 +          if( !HasRowid(pTab) ){
1.115335 +            Index *pPk = sqlite3PrimaryKeyIndex(pTab);
1.115336 +            x = pPk->aiColumn[x];
1.115337 +          }
1.115338 +          x = sqlite3ColumnOfIndex(pIdx, x);
1.115339 +          if( x>=0 ){
1.115340 +            pOp->p2 = x;
1.115341 +            pOp->p1 = pLevel->iIdxCur;
1.115342 +          }
1.115343 +          assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
1.115344 +        }else if( pOp->opcode==OP_Rowid ){
1.115345 +          pOp->p1 = pLevel->iIdxCur;
1.115346 +          pOp->opcode = OP_IdxRowid;
1.115347 +        }
1.115348 +      }
1.115349 +    }
1.115350 +  }
1.115351 +
1.115352 +  /* Final cleanup
1.115353 +  */
1.115354 +  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
1.115355 +  whereInfoFree(db, pWInfo);
1.115356 +  return;
1.115357 +}
1.115358 +
1.115359 +/************** End of where.c ***********************************************/
1.115360 +/************** Begin file parse.c *******************************************/
1.115361 +/* Driver template for the LEMON parser generator.
1.115362 +** The author disclaims copyright to this source code.
1.115363 +**
1.115364 +** This version of "lempar.c" is modified, slightly, for use by SQLite.
1.115365 +** The only modifications are the addition of a couple of NEVER()
1.115366 +** macros to disable tests that are needed in the case of a general
1.115367 +** LALR(1) grammar but which are always false in the
1.115368 +** specific grammar used by SQLite.
1.115369 +*/
1.115370 +/* First off, code is included that follows the "include" declaration
1.115371 +** in the input grammar file. */
1.115372 +/* #include <stdio.h> */
1.115373 +
1.115374 +
1.115375 +/*
1.115376 +** Disable all error recovery processing in the parser push-down
1.115377 +** automaton.
1.115378 +*/
1.115379 +#define YYNOERRORRECOVERY 1
1.115380 +
1.115381 +/*
1.115382 +** Make yytestcase() the same as testcase()
1.115383 +*/
1.115384 +#define yytestcase(X) testcase(X)
1.115385 +
1.115386 +/*
1.115387 +** An instance of this structure holds information about the
1.115388 +** LIMIT clause of a SELECT statement.
1.115389 +*/
1.115390 +struct LimitVal {
1.115391 +  Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
1.115392 +  Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
1.115393 +};
1.115394 +
1.115395 +/*
1.115396 +** An instance of this structure is used to store the LIKE,
1.115397 +** GLOB, NOT LIKE, and NOT GLOB operators.
1.115398 +*/
1.115399 +struct LikeOp {
1.115400 +  Token eOperator;  /* "like" or "glob" or "regexp" */
1.115401 +  int bNot;         /* True if the NOT keyword is present */
1.115402 +};
1.115403 +
1.115404 +/*
1.115405 +** An instance of the following structure describes the event of a
1.115406 +** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
1.115407 +** TK_DELETE, or TK_INSTEAD.  If the event is of the form
1.115408 +**
1.115409 +**      UPDATE ON (a,b,c)
1.115410 +**
1.115411 +** Then the "b" IdList records the list "a,b,c".
1.115412 +*/
1.115413 +struct TrigEvent { int a; IdList * b; };
1.115414 +
1.115415 +/*
1.115416 +** An instance of this structure holds the ATTACH key and the key type.
1.115417 +*/
1.115418 +struct AttachKey { int type;  Token key; };
1.115419 +
1.115420 +
1.115421 +  /* This is a utility routine used to set the ExprSpan.zStart and
1.115422 +  ** ExprSpan.zEnd values of pOut so that the span covers the complete
1.115423 +  ** range of text beginning with pStart and going to the end of pEnd.
1.115424 +  */
1.115425 +  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
1.115426 +    pOut->zStart = pStart->z;
1.115427 +    pOut->zEnd = &pEnd->z[pEnd->n];
1.115428 +  }
1.115429 +
1.115430 +  /* Construct a new Expr object from a single identifier.  Use the
1.115431 +  ** new Expr to populate pOut.  Set the span of pOut to be the identifier
1.115432 +  ** that created the expression.
1.115433 +  */
1.115434 +  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
1.115435 +    pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
1.115436 +    pOut->zStart = pValue->z;
1.115437 +    pOut->zEnd = &pValue->z[pValue->n];
1.115438 +  }
1.115439 +
1.115440 +  /* This routine constructs a binary expression node out of two ExprSpan
1.115441 +  ** objects and uses the result to populate a new ExprSpan object.
1.115442 +  */
1.115443 +  static void spanBinaryExpr(
1.115444 +    ExprSpan *pOut,     /* Write the result here */
1.115445 +    Parse *pParse,      /* The parsing context.  Errors accumulate here */
1.115446 +    int op,             /* The binary operation */
1.115447 +    ExprSpan *pLeft,    /* The left operand */
1.115448 +    ExprSpan *pRight    /* The right operand */
1.115449 +  ){
1.115450 +    pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
1.115451 +    pOut->zStart = pLeft->zStart;
1.115452 +    pOut->zEnd = pRight->zEnd;
1.115453 +  }
1.115454 +
1.115455 +  /* Construct an expression node for a unary postfix operator
1.115456 +  */
1.115457 +  static void spanUnaryPostfix(
1.115458 +    ExprSpan *pOut,        /* Write the new expression node here */
1.115459 +    Parse *pParse,         /* Parsing context to record errors */
1.115460 +    int op,                /* The operator */
1.115461 +    ExprSpan *pOperand,    /* The operand */
1.115462 +    Token *pPostOp         /* The operand token for setting the span */
1.115463 +  ){
1.115464 +    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
1.115465 +    pOut->zStart = pOperand->zStart;
1.115466 +    pOut->zEnd = &pPostOp->z[pPostOp->n];
1.115467 +  }                           
1.115468 +
1.115469 +  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
1.115470 +  ** unary TK_ISNULL or TK_NOTNULL expression. */
1.115471 +  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
1.115472 +    sqlite3 *db = pParse->db;
1.115473 +    if( db->mallocFailed==0 && pY->op==TK_NULL ){
1.115474 +      pA->op = (u8)op;
1.115475 +      sqlite3ExprDelete(db, pA->pRight);
1.115476 +      pA->pRight = 0;
1.115477 +    }
1.115478 +  }
1.115479 +
1.115480 +  /* Construct an expression node for a unary prefix operator
1.115481 +  */
1.115482 +  static void spanUnaryPrefix(
1.115483 +    ExprSpan *pOut,        /* Write the new expression node here */
1.115484 +    Parse *pParse,         /* Parsing context to record errors */
1.115485 +    int op,                /* The operator */
1.115486 +    ExprSpan *pOperand,    /* The operand */
1.115487 +    Token *pPreOp         /* The operand token for setting the span */
1.115488 +  ){
1.115489 +    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
1.115490 +    pOut->zStart = pPreOp->z;
1.115491 +    pOut->zEnd = pOperand->zEnd;
1.115492 +  }
1.115493 +/* Next is all token values, in a form suitable for use by makeheaders.
1.115494 +** This section will be null unless lemon is run with the -m switch.
1.115495 +*/
1.115496 +/* 
1.115497 +** These constants (all generated automatically by the parser generator)
1.115498 +** specify the various kinds of tokens (terminals) that the parser
1.115499 +** understands. 
1.115500 +**
1.115501 +** Each symbol here is a terminal symbol in the grammar.
1.115502 +*/
1.115503 +/* Make sure the INTERFACE macro is defined.
1.115504 +*/
1.115505 +#ifndef INTERFACE
1.115506 +# define INTERFACE 1
1.115507 +#endif
1.115508 +/* The next thing included is series of defines which control
1.115509 +** various aspects of the generated parser.
1.115510 +**    YYCODETYPE         is the data type used for storing terminal
1.115511 +**                       and nonterminal numbers.  "unsigned char" is
1.115512 +**                       used if there are fewer than 250 terminals
1.115513 +**                       and nonterminals.  "int" is used otherwise.
1.115514 +**    YYNOCODE           is a number of type YYCODETYPE which corresponds
1.115515 +**                       to no legal terminal or nonterminal number.  This
1.115516 +**                       number is used to fill in empty slots of the hash 
1.115517 +**                       table.
1.115518 +**    YYFALLBACK         If defined, this indicates that one or more tokens
1.115519 +**                       have fall-back values which should be used if the
1.115520 +**                       original value of the token will not parse.
1.115521 +**    YYACTIONTYPE       is the data type used for storing terminal
1.115522 +**                       and nonterminal numbers.  "unsigned char" is
1.115523 +**                       used if there are fewer than 250 rules and
1.115524 +**                       states combined.  "int" is used otherwise.
1.115525 +**    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
1.115526 +**                       directly to the parser from the tokenizer.
1.115527 +**    YYMINORTYPE        is the data type used for all minor tokens.
1.115528 +**                       This is typically a union of many types, one of
1.115529 +**                       which is sqlite3ParserTOKENTYPE.  The entry in the union
1.115530 +**                       for base tokens is called "yy0".
1.115531 +**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
1.115532 +**                       zero the stack is dynamically sized using realloc()
1.115533 +**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
1.115534 +**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
1.115535 +**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
1.115536 +**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
1.115537 +**    YYNSTATE           the combined number of states.
1.115538 +**    YYNRULE            the number of rules in the grammar
1.115539 +**    YYERRORSYMBOL      is the code number of the error symbol.  If not
1.115540 +**                       defined, then do no error processing.
1.115541 +*/
1.115542 +#define YYCODETYPE unsigned char
1.115543 +#define YYNOCODE 254
1.115544 +#define YYACTIONTYPE unsigned short int
1.115545 +#define YYWILDCARD 70
1.115546 +#define sqlite3ParserTOKENTYPE Token
1.115547 +typedef union {
1.115548 +  int yyinit;
1.115549 +  sqlite3ParserTOKENTYPE yy0;
1.115550 +  Select* yy3;
1.115551 +  ExprList* yy14;
1.115552 +  With* yy59;
1.115553 +  SrcList* yy65;
1.115554 +  struct LikeOp yy96;
1.115555 +  Expr* yy132;
1.115556 +  u8 yy186;
1.115557 +  int yy328;
1.115558 +  ExprSpan yy346;
1.115559 +  struct TrigEvent yy378;
1.115560 +  u16 yy381;
1.115561 +  IdList* yy408;
1.115562 +  struct {int value; int mask;} yy429;
1.115563 +  TriggerStep* yy473;
1.115564 +  struct LimitVal yy476;
1.115565 +} YYMINORTYPE;
1.115566 +#ifndef YYSTACKDEPTH
1.115567 +#define YYSTACKDEPTH 100
1.115568 +#endif
1.115569 +#define sqlite3ParserARG_SDECL Parse *pParse;
1.115570 +#define sqlite3ParserARG_PDECL ,Parse *pParse
1.115571 +#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
1.115572 +#define sqlite3ParserARG_STORE yypParser->pParse = pParse
1.115573 +#define YYNSTATE 642
1.115574 +#define YYNRULE 327
1.115575 +#define YYFALLBACK 1
1.115576 +#define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
1.115577 +#define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
1.115578 +#define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
1.115579 +
1.115580 +/* The yyzerominor constant is used to initialize instances of
1.115581 +** YYMINORTYPE objects to zero. */
1.115582 +static const YYMINORTYPE yyzerominor = { 0 };
1.115583 +
1.115584 +/* Define the yytestcase() macro to be a no-op if is not already defined
1.115585 +** otherwise.
1.115586 +**
1.115587 +** Applications can choose to define yytestcase() in the %include section
1.115588 +** to a macro that can assist in verifying code coverage.  For production
1.115589 +** code the yytestcase() macro should be turned off.  But it is useful
1.115590 +** for testing.
1.115591 +*/
1.115592 +#ifndef yytestcase
1.115593 +# define yytestcase(X)
1.115594 +#endif
1.115595 +
1.115596 +
1.115597 +/* Next are the tables used to determine what action to take based on the
1.115598 +** current state and lookahead token.  These tables are used to implement
1.115599 +** functions that take a state number and lookahead value and return an
1.115600 +** action integer.  
1.115601 +**
1.115602 +** Suppose the action integer is N.  Then the action is determined as
1.115603 +** follows
1.115604 +**
1.115605 +**   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
1.115606 +**                                      token onto the stack and goto state N.
1.115607 +**
1.115608 +**   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
1.115609 +**
1.115610 +**   N == YYNSTATE+YYNRULE              A syntax error has occurred.
1.115611 +**
1.115612 +**   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
1.115613 +**
1.115614 +**   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
1.115615 +**                                      slots in the yy_action[] table.
1.115616 +**
1.115617 +** The action table is constructed as a single large table named yy_action[].
1.115618 +** Given state S and lookahead X, the action is computed as
1.115619 +**
1.115620 +**      yy_action[ yy_shift_ofst[S] + X ]
1.115621 +**
1.115622 +** If the index value yy_shift_ofst[S]+X is out of range or if the value
1.115623 +** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
1.115624 +** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
1.115625 +** and that yy_default[S] should be used instead.  
1.115626 +**
1.115627 +** The formula above is for computing the action when the lookahead is
1.115628 +** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
1.115629 +** a reduce action) then the yy_reduce_ofst[] array is used in place of
1.115630 +** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
1.115631 +** YY_SHIFT_USE_DFLT.
1.115632 +**
1.115633 +** The following are the tables generated in this section:
1.115634 +**
1.115635 +**  yy_action[]        A single table containing all actions.
1.115636 +**  yy_lookahead[]     A table containing the lookahead for each entry in
1.115637 +**                     yy_action.  Used to detect hash collisions.
1.115638 +**  yy_shift_ofst[]    For each state, the offset into yy_action for
1.115639 +**                     shifting terminals.
1.115640 +**  yy_reduce_ofst[]   For each state, the offset into yy_action for
1.115641 +**                     shifting non-terminals after a reduce.
1.115642 +**  yy_default[]       Default action for each state.
1.115643 +*/
1.115644 +#define YY_ACTTAB_COUNT (1497)
1.115645 +static const YYACTIONTYPE yy_action[] = {
1.115646 + /*     0 */   306,  212,  432,  955,  639,  191,  955,  295,  559,   88,
1.115647 + /*    10 */    88,   88,   88,   81,   86,   86,   86,   86,   85,   85,
1.115648 + /*    20 */    84,   84,   84,   83,  330,  185,  184,  183,  635,  635,
1.115649 + /*    30 */   292,  606,  606,   88,   88,   88,   88,  683,   86,   86,
1.115650 + /*    40 */    86,   86,   85,   85,   84,   84,   84,   83,  330,   16,
1.115651 + /*    50 */   436,  597,   89,   90,   80,  600,  599,  601,  601,   87,
1.115652 + /*    60 */    87,   88,   88,   88,   88,  684,   86,   86,   86,   86,
1.115653 + /*    70 */    85,   85,   84,   84,   84,   83,  330,  306,  559,   84,
1.115654 + /*    80 */    84,   84,   83,  330,   65,   86,   86,   86,   86,   85,
1.115655 + /*    90 */    85,   84,   84,   84,   83,  330,  635,  635,  634,  633,
1.115656 + /*   100 */   182,  682,  550,  379,  376,  375,   17,  322,  606,  606,
1.115657 + /*   110 */   371,  198,  479,   91,  374,   82,   79,  165,   85,   85,
1.115658 + /*   120 */    84,   84,   84,   83,  330,  598,  635,  635,  107,   89,
1.115659 + /*   130 */    90,   80,  600,  599,  601,  601,   87,   87,   88,   88,
1.115660 + /*   140 */    88,   88,  186,   86,   86,   86,   86,   85,   85,   84,
1.115661 + /*   150 */    84,   84,   83,  330,  306,  594,  594,  142,  328,  327,
1.115662 + /*   160 */   484,  249,  344,  238,  635,  635,  634,  633,  585,  448,
1.115663 + /*   170 */   526,  525,  229,  388,    1,  394,  450,  584,  449,  635,
1.115664 + /*   180 */   635,  635,  635,  319,  395,  606,  606,  199,  157,  273,
1.115665 + /*   190 */   382,  268,  381,  187,  635,  635,  634,  633,  311,  555,
1.115666 + /*   200 */   266,  593,  593,  266,  347,  588,   89,   90,   80,  600,
1.115667 + /*   210 */   599,  601,  601,   87,   87,   88,   88,   88,   88,  478,
1.115668 + /*   220 */    86,   86,   86,   86,   85,   85,   84,   84,   84,   83,
1.115669 + /*   230 */   330,  306,  272,  536,  634,  633,  146,  610,  197,  310,
1.115670 + /*   240 */   575,  182,  482,  271,  379,  376,  375,  506,   21,  634,
1.115671 + /*   250 */   633,  634,  633,  635,  635,  374,  611,  574,  548,  440,
1.115672 + /*   260 */   111,  563,  606,  606,  634,  633,  324,  479,  608,  608,
1.115673 + /*   270 */   608,  300,  435,  573,  119,  407,  210,  162,  562,  883,
1.115674 + /*   280 */   592,  592,  306,   89,   90,   80,  600,  599,  601,  601,
1.115675 + /*   290 */    87,   87,   88,   88,   88,   88,  506,   86,   86,   86,
1.115676 + /*   300 */    86,   85,   85,   84,   84,   84,   83,  330,  620,  111,
1.115677 + /*   310 */   635,  635,  361,  606,  606,  358,  249,  349,  248,  433,
1.115678 + /*   320 */   243,  479,  586,  634,  633,  195,  611,   93,  119,  221,
1.115679 + /*   330 */   575,  497,  534,  534,   89,   90,   80,  600,  599,  601,
1.115680 + /*   340 */   601,   87,   87,   88,   88,   88,   88,  574,   86,   86,
1.115681 + /*   350 */    86,   86,   85,   85,   84,   84,   84,   83,  330,  306,
1.115682 + /*   360 */    77,  429,  638,  573,  589,  530,  240,  230,  242,  105,
1.115683 + /*   370 */   249,  349,  248,  515,  588,  208,  460,  529,  564,  173,
1.115684 + /*   380 */   634,  633,  970,  144,  430,    2,  424,  228,  380,  557,
1.115685 + /*   390 */   606,  606,  190,  153,  159,  158,  514,   51,  632,  631,
1.115686 + /*   400 */   630,   71,  536,  432,  954,  196,  610,  954,  614,   45,
1.115687 + /*   410 */    18,   89,   90,   80,  600,  599,  601,  601,   87,   87,
1.115688 + /*   420 */    88,   88,   88,   88,  261,   86,   86,   86,   86,   85,
1.115689 + /*   430 */    85,   84,   84,   84,   83,  330,  306,  608,  608,  608,
1.115690 + /*   440 */   542,  424,  402,  385,  241,  506,  451,  320,  211,  543,
1.115691 + /*   450 */   164,  436,  386,  293,  451,  587,  108,  496,  111,  334,
1.115692 + /*   460 */   391,  591,  424,  614,   27,  452,  453,  606,  606,   72,
1.115693 + /*   470 */   257,   70,  259,  452,  339,  342,  564,  582,   68,  415,
1.115694 + /*   480 */   469,  328,  327,   62,  614,   45,  110,  393,   89,   90,
1.115695 + /*   490 */    80,  600,  599,  601,  601,   87,   87,   88,   88,   88,
1.115696 + /*   500 */    88,  152,   86,   86,   86,   86,   85,   85,   84,   84,
1.115697 + /*   510 */    84,   83,  330,  306,  110,  499,  520,  538,  402,  389,
1.115698 + /*   520 */   424,  110,  566,  500,  593,  593,  454,   82,   79,  165,
1.115699 + /*   530 */   424,  591,  384,  564,  340,  615,  188,  162,  424,  350,
1.115700 + /*   540 */   616,  424,  614,   44,  606,  606,  445,  582,  300,  434,
1.115701 + /*   550 */   151,   19,  614,    9,  568,  580,  348,  615,  469,  567,
1.115702 + /*   560 */   614,   26,  616,  614,   45,   89,   90,   80,  600,  599,
1.115703 + /*   570 */   601,  601,   87,   87,   88,   88,   88,   88,  411,   86,
1.115704 + /*   580 */    86,   86,   86,   85,   85,   84,   84,   84,   83,  330,
1.115705 + /*   590 */   306,  579,  110,  578,  521,  282,  433,  398,  400,  255,
1.115706 + /*   600 */   486,   82,   79,  165,  487,  164,   82,   79,  165,  488,
1.115707 + /*   610 */   488,  364,  387,  424,  544,  544,  509,  350,  362,  155,
1.115708 + /*   620 */   191,  606,  606,  559,  642,  640,  333,   82,   79,  165,
1.115709 + /*   630 */   305,  564,  507,  312,  357,  614,   45,  329,  596,  595,
1.115710 + /*   640 */   194,  337,   89,   90,   80,  600,  599,  601,  601,   87,
1.115711 + /*   650 */    87,   88,   88,   88,   88,  424,   86,   86,   86,   86,
1.115712 + /*   660 */    85,   85,   84,   84,   84,   83,  330,  306,   20,  323,
1.115713 + /*   670 */   150,  263,  211,  543,  421,  596,  595,  614,   22,  424,
1.115714 + /*   680 */   193,  424,  284,  424,  391,  424,  509,  424,  577,  424,
1.115715 + /*   690 */   186,  335,  424,  559,  424,  313,  120,  546,  606,  606,
1.115716 + /*   700 */    67,  614,   47,  614,   50,  614,   48,  614,  100,  614,
1.115717 + /*   710 */    99,  614,  101,  576,  614,  102,  614,  109,  326,   89,
1.115718 + /*   720 */    90,   80,  600,  599,  601,  601,   87,   87,   88,   88,
1.115719 + /*   730 */    88,   88,  424,   86,   86,   86,   86,   85,   85,   84,
1.115720 + /*   740 */    84,   84,   83,  330,  306,  424,  311,  424,  585,   54,
1.115721 + /*   750 */   424,  516,  517,  590,  614,  112,  424,  584,  424,  572,
1.115722 + /*   760 */   424,  195,  424,  571,  424,   67,  424,  614,   94,  614,
1.115723 + /*   770 */    98,  424,  614,   97,  264,  606,  606,  195,  614,   46,
1.115724 + /*   780 */   614,   96,  614,   30,  614,   49,  614,  115,  614,  114,
1.115725 + /*   790 */   418,  229,  388,  614,  113,  306,   89,   90,   80,  600,
1.115726 + /*   800 */   599,  601,  601,   87,   87,   88,   88,   88,   88,  424,
1.115727 + /*   810 */    86,   86,   86,   86,   85,   85,   84,   84,   84,   83,
1.115728 + /*   820 */   330,  119,  424,  590,  110,  372,  606,  606,  195,   53,
1.115729 + /*   830 */   250,  614,   29,  195,  472,  438,  729,  190,  302,  498,
1.115730 + /*   840 */    14,  523,  641,    2,  614,   43,  306,   89,   90,   80,
1.115731 + /*   850 */   600,  599,  601,  601,   87,   87,   88,   88,   88,   88,
1.115732 + /*   860 */   424,   86,   86,   86,   86,   85,   85,   84,   84,   84,
1.115733 + /*   870 */    83,  330,  424,  613,  964,  964,  354,  606,  606,  420,
1.115734 + /*   880 */   312,   64,  614,   42,  391,  355,  283,  437,  301,  255,
1.115735 + /*   890 */   414,  410,  495,  492,  614,   28,  471,  306,   89,   90,
1.115736 + /*   900 */    80,  600,  599,  601,  601,   87,   87,   88,   88,   88,
1.115737 + /*   910 */    88,  424,   86,   86,   86,   86,   85,   85,   84,   84,
1.115738 + /*   920 */    84,   83,  330,  424,  110,  110,  110,  110,  606,  606,
1.115739 + /*   930 */   110,  254,   13,  614,   41,  532,  531,  283,  481,  531,
1.115740 + /*   940 */   457,  284,  119,  561,  356,  614,   40,  284,  306,   89,
1.115741 + /*   950 */    78,   80,  600,  599,  601,  601,   87,   87,   88,   88,
1.115742 + /*   960 */    88,   88,  424,   86,   86,   86,   86,   85,   85,   84,
1.115743 + /*   970 */    84,   84,   83,  330,  110,  424,  341,  220,  555,  606,
1.115744 + /*   980 */   606,  351,  555,  318,  614,   95,  413,  255,   83,  330,
1.115745 + /*   990 */   284,  284,  255,  640,  333,  356,  255,  614,   39,  306,
1.115746 + /*  1000 */   356,   90,   80,  600,  599,  601,  601,   87,   87,   88,
1.115747 + /*  1010 */    88,   88,   88,  424,   86,   86,   86,   86,   85,   85,
1.115748 + /*  1020 */    84,   84,   84,   83,  330,  424,  317,  316,  141,  465,
1.115749 + /*  1030 */   606,  606,  219,  619,  463,  614,   10,  417,  462,  255,
1.115750 + /*  1040 */   189,  510,  553,  351,  207,  363,  161,  614,   38,  315,
1.115751 + /*  1050 */   218,  255,  255,   80,  600,  599,  601,  601,   87,   87,
1.115752 + /*  1060 */    88,   88,   88,   88,  424,   86,   86,   86,   86,   85,
1.115753 + /*  1070 */    85,   84,   84,   84,   83,  330,   76,  419,  255,    3,
1.115754 + /*  1080 */   878,  461,  424,  247,  331,  331,  614,   37,  217,   76,
1.115755 + /*  1090 */   419,  390,    3,  216,  215,  422,    4,  331,  331,  424,
1.115756 + /*  1100 */   547,   12,  424,  545,  614,   36,  424,  541,  422,  424,
1.115757 + /*  1110 */   540,  424,  214,  424,  408,  424,  539,  403,  605,  605,
1.115758 + /*  1120 */   237,  614,   25,  119,  614,   24,  588,  408,  614,   45,
1.115759 + /*  1130 */   118,  614,   35,  614,   34,  614,   33,  614,   23,  588,
1.115760 + /*  1140 */    60,  223,  603,  602,  513,  378,   73,   74,  140,  139,
1.115761 + /*  1150 */   424,  110,  265,   75,  426,  425,   59,  424,  610,   73,
1.115762 + /*  1160 */    74,  549,  402,  404,  424,  373,   75,  426,  425,  604,
1.115763 + /*  1170 */   138,  610,  614,   11,  392,   76,  419,  181,    3,  614,
1.115764 + /*  1180 */    32,  271,  369,  331,  331,  493,  614,   31,  149,  608,
1.115765 + /*  1190 */   608,  608,  607,   15,  422,  365,  614,    8,  137,  489,
1.115766 + /*  1200 */   136,  190,  608,  608,  608,  607,   15,  485,  176,  135,
1.115767 + /*  1210 */     7,  252,  477,  408,  174,  133,  175,  474,   57,   56,
1.115768 + /*  1220 */   132,  130,  119,   76,  419,  588,    3,  468,  245,  464,
1.115769 + /*  1230 */   171,  331,  331,  125,  123,  456,  447,  122,  446,  104,
1.115770 + /*  1240 */   336,  231,  422,  166,  154,   73,   74,  332,  116,  431,
1.115771 + /*  1250 */   121,  309,   75,  426,  425,  222,  106,  610,  308,  637,
1.115772 + /*  1260 */   204,  408,  629,  627,  628,    6,  200,  428,  427,  290,
1.115773 + /*  1270 */   203,  622,  201,  588,   62,   63,  289,   66,  419,  399,
1.115774 + /*  1280 */     3,  401,  288,   92,  143,  331,  331,  287,  608,  608,
1.115775 + /*  1290 */   608,  607,   15,   73,   74,  227,  422,  325,   69,  416,
1.115776 + /*  1300 */    75,  426,  425,  612,  412,  610,  192,   61,  569,  209,
1.115777 + /*  1310 */   396,  226,  278,  225,  383,  408,  527,  558,  276,  533,
1.115778 + /*  1320 */   552,  528,  321,  523,  370,  508,  180,  588,  494,  179,
1.115779 + /*  1330 */   366,  117,  253,  269,  522,  503,  608,  608,  608,  607,
1.115780 + /*  1340 */    15,  551,  502,   58,  274,  524,  178,   73,   74,  304,
1.115781 + /*  1350 */   501,  368,  303,  206,   75,  426,  425,  491,  360,  610,
1.115782 + /*  1360 */   213,  177,  483,  131,  345,  298,  297,  296,  202,  294,
1.115783 + /*  1370 */   480,  490,  466,  134,  172,  129,  444,  346,  470,  128,
1.115784 + /*  1380 */   314,  459,  103,  127,  126,  148,  124,  167,  443,  235,
1.115785 + /*  1390 */   608,  608,  608,  607,   15,  442,  439,  623,  234,  299,
1.115786 + /*  1400 */   145,  583,  291,  377,  581,  160,  119,  156,  270,  636,
1.115787 + /*  1410 */   971,  169,  279,  626,  520,  625,  473,  624,  170,  621,
1.115788 + /*  1420 */   618,  119,  168,   55,  409,  423,  537,  609,  286,  285,
1.115789 + /*  1430 */   405,  570,  560,  556,    5,   52,  458,  554,  147,  267,
1.115790 + /*  1440 */   519,  504,  518,  406,  262,  239,  260,  512,  343,  511,
1.115791 + /*  1450 */   258,  353,  565,  256,  224,  251,  359,  277,  275,  476,
1.115792 + /*  1460 */   475,  246,  352,  244,  467,  455,  236,  233,  232,  307,
1.115793 + /*  1470 */   441,  281,  205,  163,  397,  280,  535,  505,  330,  617,
1.115794 + /*  1480 */   971,  971,  971,  971,  367,  971,  971,  971,  971,  971,
1.115795 + /*  1490 */   971,  971,  971,  971,  971,  971,  338,
1.115796 +};
1.115797 +static const YYCODETYPE yy_lookahead[] = {
1.115798 + /*     0 */    19,   22,   22,   23,    1,   24,   26,   15,   27,   80,
1.115799 + /*    10 */    81,   82,   83,   84,   85,   86,   87,   88,   89,   90,
1.115800 + /*    20 */    91,   92,   93,   94,   95,  108,  109,  110,   27,   28,
1.115801 + /*    30 */    23,   50,   51,   80,   81,   82,   83,  122,   85,   86,
1.115802 + /*    40 */    87,   88,   89,   90,   91,   92,   93,   94,   95,   22,
1.115803 + /*    50 */    70,   23,   71,   72,   73,   74,   75,   76,   77,   78,
1.115804 + /*    60 */    79,   80,   81,   82,   83,  122,   85,   86,   87,   88,
1.115805 + /*    70 */    89,   90,   91,   92,   93,   94,   95,   19,   97,   91,
1.115806 + /*    80 */    92,   93,   94,   95,   26,   85,   86,   87,   88,   89,
1.115807 + /*    90 */    90,   91,   92,   93,   94,   95,   27,   28,   97,   98,
1.115808 + /*   100 */    99,  122,  211,  102,  103,  104,   79,   19,   50,   51,
1.115809 + /*   110 */    19,  122,   59,   55,  113,  224,  225,  226,   89,   90,
1.115810 + /*   120 */    91,   92,   93,   94,   95,   23,   27,   28,   26,   71,
1.115811 + /*   130 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
1.115812 + /*   140 */    82,   83,   51,   85,   86,   87,   88,   89,   90,   91,
1.115813 + /*   150 */    92,   93,   94,   95,   19,  132,  133,   58,   89,   90,
1.115814 + /*   160 */    21,  108,  109,  110,   27,   28,   97,   98,   33,  100,
1.115815 + /*   170 */     7,    8,  119,  120,   22,   19,  107,   42,  109,   27,
1.115816 + /*   180 */    28,   27,   28,   95,   28,   50,   51,   99,  100,  101,
1.115817 + /*   190 */   102,  103,  104,  105,   27,   28,   97,   98,  107,  152,
1.115818 + /*   200 */   112,  132,  133,  112,   65,   69,   71,   72,   73,   74,
1.115819 + /*   210 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   11,
1.115820 + /*   220 */    85,   86,   87,   88,   89,   90,   91,   92,   93,   94,
1.115821 + /*   230 */    95,   19,  101,   97,   97,   98,   24,  101,  122,  157,
1.115822 + /*   240 */    12,   99,  103,  112,  102,  103,  104,  152,   22,   97,
1.115823 + /*   250 */    98,   97,   98,   27,   28,  113,   27,   29,   91,  164,
1.115824 + /*   260 */   165,  124,   50,   51,   97,   98,  219,   59,  132,  133,
1.115825 + /*   270 */   134,   22,   23,   45,   66,   47,  212,  213,  124,  140,
1.115826 + /*   280 */   132,  133,   19,   71,   72,   73,   74,   75,   76,   77,
1.115827 + /*   290 */    78,   79,   80,   81,   82,   83,  152,   85,   86,   87,
1.115828 + /*   300 */    88,   89,   90,   91,   92,   93,   94,   95,  164,  165,
1.115829 + /*   310 */    27,   28,  230,   50,   51,  233,  108,  109,  110,   70,
1.115830 + /*   320 */    16,   59,   23,   97,   98,   26,   97,   22,   66,  185,
1.115831 + /*   330 */    12,  187,   27,   28,   71,   72,   73,   74,   75,   76,
1.115832 + /*   340 */    77,   78,   79,   80,   81,   82,   83,   29,   85,   86,
1.115833 + /*   350 */    87,   88,   89,   90,   91,   92,   93,   94,   95,   19,
1.115834 + /*   360 */    22,  148,  149,   45,   23,   47,   62,  154,   64,  156,
1.115835 + /*   370 */   108,  109,  110,   37,   69,   23,  163,   59,   26,   26,
1.115836 + /*   380 */    97,   98,  144,  145,  146,  147,  152,  200,   52,   23,
1.115837 + /*   390 */    50,   51,   26,   22,   89,   90,   60,  210,    7,    8,
1.115838 + /*   400 */     9,  138,   97,   22,   23,   26,  101,   26,  174,  175,
1.115839 + /*   410 */   197,   71,   72,   73,   74,   75,   76,   77,   78,   79,
1.115840 + /*   420 */    80,   81,   82,   83,   16,   85,   86,   87,   88,   89,
1.115841 + /*   430 */    90,   91,   92,   93,   94,   95,   19,  132,  133,  134,
1.115842 + /*   440 */    23,  152,  208,  209,  140,  152,  152,  111,  195,  196,
1.115843 + /*   450 */    98,   70,  163,  160,  152,   23,   22,  164,  165,  246,
1.115844 + /*   460 */   207,   27,  152,  174,  175,  171,  172,   50,   51,  137,
1.115845 + /*   470 */    62,  139,   64,  171,  172,  222,  124,   27,  138,   24,
1.115846 + /*   480 */   163,   89,   90,  130,  174,  175,  197,  163,   71,   72,
1.115847 + /*   490 */    73,   74,   75,   76,   77,   78,   79,   80,   81,   82,
1.115848 + /*   500 */    83,   22,   85,   86,   87,   88,   89,   90,   91,   92,
1.115849 + /*   510 */    93,   94,   95,   19,  197,  181,  182,   23,  208,  209,
1.115850 + /*   520 */   152,  197,   26,  189,  132,  133,  232,  224,  225,  226,
1.115851 + /*   530 */   152,   97,   91,   26,  232,  116,  212,  213,  152,  222,
1.115852 + /*   540 */   121,  152,  174,  175,   50,   51,  243,   97,   22,   23,
1.115853 + /*   550 */    22,  234,  174,  175,  177,   23,  239,  116,  163,  177,
1.115854 + /*   560 */   174,  175,  121,  174,  175,   71,   72,   73,   74,   75,
1.115855 + /*   570 */    76,   77,   78,   79,   80,   81,   82,   83,   24,   85,
1.115856 + /*   580 */    86,   87,   88,   89,   90,   91,   92,   93,   94,   95,
1.115857 + /*   590 */    19,   23,  197,   11,   23,  227,   70,  208,  220,  152,
1.115858 + /*   600 */    31,  224,  225,  226,   35,   98,  224,  225,  226,  108,
1.115859 + /*   610 */   109,  110,  115,  152,  117,  118,   27,  222,   49,  123,
1.115860 + /*   620 */    24,   50,   51,   27,    0,    1,    2,  224,  225,  226,
1.115861 + /*   630 */   166,  124,  168,  169,  239,  174,  175,  170,  171,  172,
1.115862 + /*   640 */    22,  194,   71,   72,   73,   74,   75,   76,   77,   78,
1.115863 + /*   650 */    79,   80,   81,   82,   83,  152,   85,   86,   87,   88,
1.115864 + /*   660 */    89,   90,   91,   92,   93,   94,   95,   19,   22,  208,
1.115865 + /*   670 */    24,   23,  195,  196,  170,  171,  172,  174,  175,  152,
1.115866 + /*   680 */    26,  152,  152,  152,  207,  152,   97,  152,   23,  152,
1.115867 + /*   690 */    51,  244,  152,   97,  152,  247,  248,   23,   50,   51,
1.115868 + /*   700 */    26,  174,  175,  174,  175,  174,  175,  174,  175,  174,
1.115869 + /*   710 */   175,  174,  175,   23,  174,  175,  174,  175,  188,   71,
1.115870 + /*   720 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
1.115871 + /*   730 */    82,   83,  152,   85,   86,   87,   88,   89,   90,   91,
1.115872 + /*   740 */    92,   93,   94,   95,   19,  152,  107,  152,   33,   24,
1.115873 + /*   750 */   152,  100,  101,   27,  174,  175,  152,   42,  152,   23,
1.115874 + /*   760 */   152,   26,  152,   23,  152,   26,  152,  174,  175,  174,
1.115875 + /*   770 */   175,  152,  174,  175,   23,   50,   51,   26,  174,  175,
1.115876 + /*   780 */   174,  175,  174,  175,  174,  175,  174,  175,  174,  175,
1.115877 + /*   790 */   163,  119,  120,  174,  175,   19,   71,   72,   73,   74,
1.115878 + /*   800 */    75,   76,   77,   78,   79,   80,   81,   82,   83,  152,
1.115879 + /*   810 */    85,   86,   87,   88,   89,   90,   91,   92,   93,   94,
1.115880 + /*   820 */    95,   66,  152,   97,  197,   23,   50,   51,   26,   53,
1.115881 + /*   830 */    23,  174,  175,   26,   23,   23,   23,   26,   26,   26,
1.115882 + /*   840 */    36,  106,  146,  147,  174,  175,   19,   71,   72,   73,
1.115883 + /*   850 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
1.115884 + /*   860 */   152,   85,   86,   87,   88,   89,   90,   91,   92,   93,
1.115885 + /*   870 */    94,   95,  152,  196,  119,  120,   19,   50,   51,  168,
1.115886 + /*   880 */   169,   26,  174,  175,  207,   28,  152,  249,  250,  152,
1.115887 + /*   890 */   163,  163,  163,  163,  174,  175,  163,   19,   71,   72,
1.115888 + /*   900 */    73,   74,   75,   76,   77,   78,   79,   80,   81,   82,
1.115889 + /*   910 */    83,  152,   85,   86,   87,   88,   89,   90,   91,   92,
1.115890 + /*   920 */    93,   94,   95,  152,  197,  197,  197,  197,   50,   51,
1.115891 + /*   930 */   197,  194,   36,  174,  175,  191,  192,  152,  191,  192,
1.115892 + /*   940 */   163,  152,   66,  124,  152,  174,  175,  152,   19,   71,
1.115893 + /*   950 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
1.115894 + /*   960 */    82,   83,  152,   85,   86,   87,   88,   89,   90,   91,
1.115895 + /*   970 */    92,   93,   94,   95,  197,  152,  100,  188,  152,   50,
1.115896 + /*   980 */    51,  152,  152,  188,  174,  175,  252,  152,   94,   95,
1.115897 + /*   990 */   152,  152,  152,    1,    2,  152,  152,  174,  175,   19,
1.115898 + /*  1000 */   152,   72,   73,   74,   75,   76,   77,   78,   79,   80,
1.115899 + /*  1010 */    81,   82,   83,  152,   85,   86,   87,   88,   89,   90,
1.115900 + /*  1020 */    91,   92,   93,   94,   95,  152,  188,  188,   22,  194,
1.115901 + /*  1030 */    50,   51,  240,  173,  194,  174,  175,  252,  194,  152,
1.115902 + /*  1040 */    36,  181,   28,  152,   23,  219,  122,  174,  175,  219,
1.115903 + /*  1050 */   221,  152,  152,   73,   74,   75,   76,   77,   78,   79,
1.115904 + /*  1060 */    80,   81,   82,   83,  152,   85,   86,   87,   88,   89,
1.115905 + /*  1070 */    90,   91,   92,   93,   94,   95,   19,   20,  152,   22,
1.115906 + /*  1080 */    23,  194,  152,  240,   27,   28,  174,  175,  240,   19,
1.115907 + /*  1090 */    20,   26,   22,  194,  194,   38,   22,   27,   28,  152,
1.115908 + /*  1100 */    23,   22,  152,  116,  174,  175,  152,   23,   38,  152,
1.115909 + /*  1110 */    23,  152,  221,  152,   57,  152,   23,  163,   50,   51,
1.115910 + /*  1120 */   194,  174,  175,   66,  174,  175,   69,   57,  174,  175,
1.115911 + /*  1130 */    40,  174,  175,  174,  175,  174,  175,  174,  175,   69,
1.115912 + /*  1140 */    22,   53,   74,   75,   30,   53,   89,   90,   22,   22,
1.115913 + /*  1150 */   152,  197,   23,   96,   97,   98,   22,  152,  101,   89,
1.115914 + /*  1160 */    90,   91,  208,  209,  152,   53,   96,   97,   98,  101,
1.115915 + /*  1170 */    22,  101,  174,  175,  152,   19,   20,  105,   22,  174,
1.115916 + /*  1180 */   175,  112,   19,   27,   28,   20,  174,  175,   24,  132,
1.115917 + /*  1190 */   133,  134,  135,  136,   38,   44,  174,  175,  107,   61,
1.115918 + /*  1200 */    54,   26,  132,  133,  134,  135,  136,   54,  107,   22,
1.115919 + /*  1210 */     5,  140,    1,   57,   36,  111,  122,   28,   79,   79,
1.115920 + /*  1220 */   131,  123,   66,   19,   20,   69,   22,    1,   16,   20,
1.115921 + /*  1230 */   125,   27,   28,  123,  111,  120,   23,  131,   23,   16,
1.115922 + /*  1240 */    68,  142,   38,   15,   22,   89,   90,    3,  167,    4,
1.115923 + /*  1250 */   248,  251,   96,   97,   98,  180,  180,  101,  251,  151,
1.115924 + /*  1260 */     6,   57,  151,   13,  151,   26,   25,  151,  161,  202,
1.115925 + /*  1270 */   153,  162,  153,   69,  130,  128,  203,   19,   20,  127,
1.115926 + /*  1280 */    22,  126,  204,  129,   22,   27,   28,  205,  132,  133,
1.115927 + /*  1290 */   134,  135,  136,   89,   90,  231,   38,   95,  137,  179,
1.115928 + /*  1300 */    96,   97,   98,  206,  179,  101,  122,  107,  159,  159,
1.115929 + /*  1310 */   125,  231,  216,  228,  107,   57,  184,  217,  216,  176,
1.115930 + /*  1320 */   217,  176,   48,  106,   18,  184,  158,   69,  159,  158,
1.115931 + /*  1330 */    46,   71,  237,  176,  176,  176,  132,  133,  134,  135,
1.115932 + /*  1340 */   136,  217,  176,  137,  216,  178,  158,   89,   90,  179,
1.115933 + /*  1350 */   176,  159,  179,  159,   96,   97,   98,  159,  159,  101,
1.115934 + /*  1360 */     5,  158,  202,   22,   18,   10,   11,   12,   13,   14,
1.115935 + /*  1370 */   190,  238,   17,  190,  158,  193,   41,  159,  202,  193,
1.115936 + /*  1380 */   159,  202,  245,  193,  193,  223,  190,   32,  159,   34,
1.115937 + /*  1390 */   132,  133,  134,  135,  136,  159,   39,  155,   43,  150,
1.115938 + /*  1400 */   223,  177,  201,  178,  177,  186,   66,  199,  177,  152,
1.115939 + /*  1410 */   253,   56,  215,  152,  182,  152,  202,  152,   63,  152,
1.115940 + /*  1420 */   152,   66,   67,  242,  229,  152,  174,  152,  152,  152,
1.115941 + /*  1430 */   152,  152,  152,  152,  199,  242,  202,  152,  198,  152,
1.115942 + /*  1440 */   152,  152,  183,  192,  152,  215,  152,  183,  215,  183,
1.115943 + /*  1450 */   152,  241,  214,  152,  211,  152,  152,  211,  211,  152,
1.115944 + /*  1460 */   152,  241,  152,  152,  152,  152,  152,  152,  152,  114,
1.115945 + /*  1470 */   152,  152,  235,  152,  152,  152,  174,  187,   95,  174,
1.115946 + /*  1480 */   253,  253,  253,  253,  236,  253,  253,  253,  253,  253,
1.115947 + /*  1490 */   253,  253,  253,  253,  253,  253,  141,
1.115948 +};
1.115949 +#define YY_SHIFT_USE_DFLT (-86)
1.115950 +#define YY_SHIFT_COUNT (429)
1.115951 +#define YY_SHIFT_MIN   (-85)
1.115952 +#define YY_SHIFT_MAX   (1383)
1.115953 +static const short yy_shift_ofst[] = {
1.115954 + /*     0 */   992, 1057, 1355, 1156, 1204, 1204,    1,  262,  -19,  135,
1.115955 + /*    10 */   135,  776, 1204, 1204, 1204, 1204,   69,   69,   53,  208,
1.115956 + /*    20 */   283,  755,   58,  725,  648,  571,  494,  417,  340,  263,
1.115957 + /*    30 */   212,  827,  827,  827,  827,  827,  827,  827,  827,  827,
1.115958 + /*    40 */   827,  827,  827,  827,  827,  827,  878,  827,  929,  980,
1.115959 + /*    50 */   980, 1070, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
1.115960 + /*    60 */  1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
1.115961 + /*    70 */  1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
1.115962 + /*    80 */  1258, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
1.115963 + /*    90 */  1204, 1204, 1204, 1204,  -71,  -47,  -47,  -47,  -47,  -47,
1.115964 + /*   100 */     0,   29,  -12,  283,  283,  139,   91,  392,  392,  894,
1.115965 + /*   110 */   672,  726, 1383,  -86,  -86,  -86,   88,  318,  318,   99,
1.115966 + /*   120 */   381,  -20,  283,  283,  283,  283,  283,  283,  283,  283,
1.115967 + /*   130 */   283,  283,  283,  283,  283,  283,  283,  283,  283,  283,
1.115968 + /*   140 */   283,  283,  283,  283,  624,  876,  726,  672, 1340, 1340,
1.115969 + /*   150 */  1340, 1340, 1340, 1340,  -86,  -86,  -86,  305,  136,  136,
1.115970 + /*   160 */   142,  167,  226,  154,  137,  152,  283,  283,  283,  283,
1.115971 + /*   170 */   283,  283,  283,  283,  283,  283,  283,  283,  283,  283,
1.115972 + /*   180 */   283,  283,  283,  336,  336,  336,  283,  283,  352,  283,
1.115973 + /*   190 */   283,  283,  283,  283,  228,  283,  283,  283,  283,  283,
1.115974 + /*   200 */   283,  283,  283,  283,  283,  501,  569,  596,  596,  596,
1.115975 + /*   210 */   507,  497,  441,  391,  353,  156,  156,  857,  353,  857,
1.115976 + /*   220 */   735,  813,  639,  715,  156,  332,  715,  715,  496,  419,
1.115977 + /*   230 */   646, 1357, 1184, 1184, 1335, 1335, 1184, 1341, 1260, 1144,
1.115978 + /*   240 */  1346, 1346, 1346, 1346, 1184, 1306, 1144, 1341, 1260, 1260,
1.115979 + /*   250 */  1144, 1184, 1306, 1206, 1284, 1184, 1184, 1306, 1184, 1306,
1.115980 + /*   260 */  1184, 1306, 1262, 1207, 1207, 1207, 1274, 1262, 1207, 1217,
1.115981 + /*   270 */  1207, 1274, 1207, 1207, 1185, 1200, 1185, 1200, 1185, 1200,
1.115982 + /*   280 */  1184, 1184, 1161, 1262, 1202, 1202, 1262, 1154, 1155, 1147,
1.115983 + /*   290 */  1152, 1144, 1241, 1239, 1250, 1250, 1254, 1254, 1254, 1254,
1.115984 + /*   300 */   -86,  -86,  -86,  -86,  -86,  -86, 1068,  304,  526,  249,
1.115985 + /*   310 */   408,  -83,  434,  812,   27,  811,  807,  802,  751,  589,
1.115986 + /*   320 */   651,  163,  131,  674,  366,  450,  299,  148,   23,  102,
1.115987 + /*   330 */   229,  -21, 1245, 1244, 1222, 1099, 1228, 1172, 1223, 1215,
1.115988 + /*   340 */  1213, 1115, 1106, 1123, 1110, 1209, 1105, 1212, 1226, 1098,
1.115989 + /*   350 */  1089, 1140, 1139, 1104, 1189, 1178, 1094, 1211, 1205, 1187,
1.115990 + /*   360 */  1101, 1071, 1153, 1175, 1146, 1138, 1151, 1091, 1164, 1165,
1.115991 + /*   370 */  1163, 1069, 1072, 1148, 1112, 1134, 1127, 1129, 1126, 1092,
1.115992 + /*   380 */  1114, 1118, 1088, 1090, 1093, 1087, 1084,  987, 1079, 1077,
1.115993 + /*   390 */  1074, 1065,  924, 1021, 1014, 1004, 1006,  819,  739,  896,
1.115994 + /*   400 */   855,  804,  739,  740,  736,  690,  654,  665,  618,  582,
1.115995 + /*   410 */   568,  528,  554,  379,  532,  479,  455,  379,  432,  371,
1.115996 + /*   420 */   341,   28,  338,  116,  -11,  -57,  -85,    7,   -8,    3,
1.115997 +};
1.115998 +#define YY_REDUCE_USE_DFLT (-110)
1.115999 +#define YY_REDUCE_COUNT (305)
1.116000 +#define YY_REDUCE_MIN   (-109)
1.116001 +#define YY_REDUCE_MAX   (1323)
1.116002 +static const short yy_reduce_ofst[] = {
1.116003 + /*     0 */   238,  954,  213,  289,  310,  234,  144,  317, -109,  382,
1.116004 + /*    10 */   377,  303,  461,  389,  378,  368,  302,  294,  253,  395,
1.116005 + /*    20 */   293,  324,  403,  403,  403,  403,  403,  403,  403,  403,
1.116006 + /*    30 */   403,  403,  403,  403,  403,  403,  403,  403,  403,  403,
1.116007 + /*    40 */   403,  403,  403,  403,  403,  403,  403,  403,  403,  403,
1.116008 + /*    50 */   403, 1022, 1012, 1005,  998,  963,  961,  959,  957,  950,
1.116009 + /*    60 */   947,  930,  912,  873,  861,  823,  810,  771,  759,  720,
1.116010 + /*    70 */   708,  670,  657,  619,  614,  612,  610,  608,  606,  604,
1.116011 + /*    80 */   598,  595,  593,  580,  542,  540,  537,  535,  533,  531,
1.116012 + /*    90 */   529,  527,  503,  386,  403,  403,  403,  403,  403,  403,
1.116013 + /*   100 */   403,  403,  403,   95,  447,   82,  334,  504,  467,  403,
1.116014 + /*   110 */   477,  464,  403,  403,  403,  403,  860,  747,  744,  785,
1.116015 + /*   120 */   638,  638,  926,  891,  900,  899,  887,  844,  840,  835,
1.116016 + /*   130 */   848,  830,  843,  829,  792,  839,  826,  737,  838,  795,
1.116017 + /*   140 */   789,   47,  734,  530,  696,  777,  711,  677,  733,  730,
1.116018 + /*   150 */   729,  728,  727,  627,  448,   64,  187, 1305, 1302, 1252,
1.116019 + /*   160 */  1290, 1273, 1323, 1322, 1321, 1319, 1318, 1316, 1315, 1314,
1.116020 + /*   170 */  1313, 1312, 1311, 1310, 1308, 1307, 1304, 1303, 1301, 1298,
1.116021 + /*   180 */  1294, 1292, 1289, 1266, 1264, 1259, 1288, 1287, 1238, 1285,
1.116022 + /*   190 */  1281, 1280, 1279, 1278, 1251, 1277, 1276, 1275, 1273, 1268,
1.116023 + /*   200 */  1267, 1265, 1263, 1261, 1257, 1248, 1237, 1247, 1246, 1243,
1.116024 + /*   210 */  1238, 1240, 1235, 1249, 1234, 1233, 1230, 1220, 1214, 1210,
1.116025 + /*   220 */  1225, 1219, 1232, 1231, 1197, 1195, 1227, 1224, 1201, 1208,
1.116026 + /*   230 */  1242, 1137, 1236, 1229, 1193, 1181, 1221, 1177, 1196, 1179,
1.116027 + /*   240 */  1191, 1190, 1186, 1182, 1218, 1216, 1176, 1162, 1183, 1180,
1.116028 + /*   250 */  1160, 1199, 1203, 1133, 1095, 1198, 1194, 1188, 1192, 1171,
1.116029 + /*   260 */  1169, 1168, 1173, 1174, 1166, 1159, 1141, 1170, 1158, 1167,
1.116030 + /*   270 */  1157, 1132, 1145, 1143, 1124, 1128, 1103, 1102, 1100, 1096,
1.116031 + /*   280 */  1150, 1149, 1085, 1125, 1080, 1064, 1120, 1097, 1082, 1078,
1.116032 + /*   290 */  1073, 1067, 1109, 1107, 1119, 1117, 1116, 1113, 1111, 1108,
1.116033 + /*   300 */  1007, 1000, 1002, 1076, 1075, 1081,
1.116034 +};
1.116035 +static const YYACTIONTYPE yy_default[] = {
1.116036 + /*     0 */   647,  964,  964,  964,  878,  878,  969,  964,  774,  802,
1.116037 + /*    10 */   802,  938,  969,  969,  969,  876,  969,  969,  969,  964,
1.116038 + /*    20 */   969,  778,  808,  969,  969,  969,  969,  969,  969,  969,
1.116039 + /*    30 */   969,  937,  939,  816,  815,  918,  789,  813,  806,  810,
1.116040 + /*    40 */   879,  872,  873,  871,  875,  880,  969,  809,  841,  856,
1.116041 + /*    50 */   840,  969,  969,  969,  969,  969,  969,  969,  969,  969,
1.116042 + /*    60 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
1.116043 + /*    70 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
1.116044 + /*    80 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
1.116045 + /*    90 */   969,  969,  969,  969,  850,  855,  862,  854,  851,  843,
1.116046 + /*   100 */   842,  844,  845,  969,  969,  673,  739,  969,  969,  846,
1.116047 + /*   110 */   969,  685,  847,  859,  858,  857,  680,  969,  969,  969,
1.116048 + /*   120 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
1.116049 + /*   130 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
1.116050 + /*   140 */   969,  969,  969,  969,  647,  964,  969,  969,  964,  964,
1.116051 + /*   150 */   964,  964,  964,  964,  956,  778,  768,  969,  969,  969,
1.116052 + /*   160 */   969,  969,  969,  969,  969,  969,  969,  944,  942,  969,
1.116053 + /*   170 */   891,  969,  969,  969,  969,  969,  969,  969,  969,  969,
1.116054 + /*   180 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
1.116055 + /*   190 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
1.116056 + /*   200 */   969,  969,  969,  969,  653,  969,  911,  774,  774,  774,
1.116057 + /*   210 */   776,  754,  766,  655,  812,  791,  791,  923,  812,  923,
1.116058 + /*   220 */   710,  733,  707,  802,  791,  874,  802,  802,  775,  766,
1.116059 + /*   230 */   969,  949,  782,  782,  941,  941,  782,  821,  743,  812,
1.116060 + /*   240 */   750,  750,  750,  750,  782,  670,  812,  821,  743,  743,
1.116061 + /*   250 */   812,  782,  670,  917,  915,  782,  782,  670,  782,  670,
1.116062 + /*   260 */   782,  670,  884,  741,  741,  741,  725,  884,  741,  710,
1.116063 + /*   270 */   741,  725,  741,  741,  795,  790,  795,  790,  795,  790,
1.116064 + /*   280 */   782,  782,  969,  884,  888,  888,  884,  807,  796,  805,
1.116065 + /*   290 */   803,  812,  676,  728,  663,  663,  652,  652,  652,  652,
1.116066 + /*   300 */   961,  961,  956,  712,  712,  695,  969,  969,  969,  969,
1.116067 + /*   310 */   969,  969,  687,  969,  893,  969,  969,  969,  969,  969,
1.116068 + /*   320 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
1.116069 + /*   330 */   969,  828,  969,  648,  951,  969,  969,  948,  969,  969,
1.116070 + /*   340 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
1.116071 + /*   350 */   969,  969,  969,  969,  969,  969,  921,  969,  969,  969,
1.116072 + /*   360 */   969,  969,  969,  914,  913,  969,  969,  969,  969,  969,
1.116073 + /*   370 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
1.116074 + /*   380 */   969,  969,  969,  969,  969,  969,  969,  757,  969,  969,
1.116075 + /*   390 */   969,  761,  969,  969,  969,  969,  969,  969,  804,  969,
1.116076 + /*   400 */   797,  969,  877,  969,  969,  969,  969,  969,  969,  969,
1.116077 + /*   410 */   969,  969,  969,  966,  969,  969,  969,  965,  969,  969,
1.116078 + /*   420 */   969,  969,  969,  830,  969,  829,  833,  969,  661,  969,
1.116079 + /*   430 */   644,  649,  960,  963,  962,  959,  958,  957,  952,  950,
1.116080 + /*   440 */   947,  946,  945,  943,  940,  936,  897,  895,  902,  901,
1.116081 + /*   450 */   900,  899,  898,  896,  894,  892,  818,  817,  814,  811,
1.116082 + /*   460 */   753,  935,  890,  752,  749,  748,  669,  953,  920,  929,
1.116083 + /*   470 */   928,  927,  822,  926,  925,  924,  922,  919,  906,  820,
1.116084 + /*   480 */   819,  744,  882,  881,  672,  910,  909,  908,  912,  916,
1.116085 + /*   490 */   907,  784,  751,  671,  668,  675,  679,  731,  732,  740,
1.116086 + /*   500 */   738,  737,  736,  735,  734,  730,  681,  686,  724,  709,
1.116087 + /*   510 */   708,  717,  716,  722,  721,  720,  719,  718,  715,  714,
1.116088 + /*   520 */   713,  706,  705,  711,  704,  727,  726,  723,  703,  747,
1.116089 + /*   530 */   746,  745,  742,  702,  701,  700,  833,  699,  698,  838,
1.116090 + /*   540 */   837,  866,  826,  755,  759,  758,  762,  763,  771,  770,
1.116091 + /*   550 */   769,  780,  781,  793,  792,  824,  823,  794,  779,  773,
1.116092 + /*   560 */   772,  788,  787,  786,  785,  777,  767,  799,  798,  868,
1.116093 + /*   570 */   783,  867,  865,  934,  933,  932,  931,  930,  870,  967,
1.116094 + /*   580 */   968,  887,  889,  886,  801,  800,  885,  869,  839,  836,
1.116095 + /*   590 */   690,  691,  905,  904,  903,  693,  692,  689,  688,  863,
1.116096 + /*   600 */   860,  852,  864,  861,  853,  849,  848,  834,  832,  831,
1.116097 + /*   610 */   827,  835,  760,  756,  825,  765,  764,  697,  696,  694,
1.116098 + /*   620 */   678,  677,  674,  667,  665,  664,  666,  662,  660,  659,
1.116099 + /*   630 */   658,  657,  656,  684,  683,  682,  654,  651,  650,  646,
1.116100 + /*   640 */   645,  643,
1.116101 +};
1.116102 +
1.116103 +/* The next table maps tokens into fallback tokens.  If a construct
1.116104 +** like the following:
1.116105 +** 
1.116106 +**      %fallback ID X Y Z.
1.116107 +**
1.116108 +** appears in the grammar, then ID becomes a fallback token for X, Y,
1.116109 +** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
1.116110 +** but it does not parse, the type of the token is changed to ID and
1.116111 +** the parse is retried before an error is thrown.
1.116112 +*/
1.116113 +#ifdef YYFALLBACK
1.116114 +static const YYCODETYPE yyFallback[] = {
1.116115 +    0,  /*          $ => nothing */
1.116116 +    0,  /*       SEMI => nothing */
1.116117 +   27,  /*    EXPLAIN => ID */
1.116118 +   27,  /*      QUERY => ID */
1.116119 +   27,  /*       PLAN => ID */
1.116120 +   27,  /*      BEGIN => ID */
1.116121 +    0,  /* TRANSACTION => nothing */
1.116122 +   27,  /*   DEFERRED => ID */
1.116123 +   27,  /*  IMMEDIATE => ID */
1.116124 +   27,  /*  EXCLUSIVE => ID */
1.116125 +    0,  /*     COMMIT => nothing */
1.116126 +   27,  /*        END => ID */
1.116127 +   27,  /*   ROLLBACK => ID */
1.116128 +   27,  /*  SAVEPOINT => ID */
1.116129 +   27,  /*    RELEASE => ID */
1.116130 +    0,  /*         TO => nothing */
1.116131 +    0,  /*      TABLE => nothing */
1.116132 +    0,  /*     CREATE => nothing */
1.116133 +   27,  /*         IF => ID */
1.116134 +    0,  /*        NOT => nothing */
1.116135 +    0,  /*     EXISTS => nothing */
1.116136 +   27,  /*       TEMP => ID */
1.116137 +    0,  /*         LP => nothing */
1.116138 +    0,  /*         RP => nothing */
1.116139 +    0,  /*         AS => nothing */
1.116140 +   27,  /*    WITHOUT => ID */
1.116141 +    0,  /*      COMMA => nothing */
1.116142 +    0,  /*         ID => nothing */
1.116143 +    0,  /*    INDEXED => nothing */
1.116144 +   27,  /*      ABORT => ID */
1.116145 +   27,  /*     ACTION => ID */
1.116146 +   27,  /*      AFTER => ID */
1.116147 +   27,  /*    ANALYZE => ID */
1.116148 +   27,  /*        ASC => ID */
1.116149 +   27,  /*     ATTACH => ID */
1.116150 +   27,  /*     BEFORE => ID */
1.116151 +   27,  /*         BY => ID */
1.116152 +   27,  /*    CASCADE => ID */
1.116153 +   27,  /*       CAST => ID */
1.116154 +   27,  /*   COLUMNKW => ID */
1.116155 +   27,  /*   CONFLICT => ID */
1.116156 +   27,  /*   DATABASE => ID */
1.116157 +   27,  /*       DESC => ID */
1.116158 +   27,  /*     DETACH => ID */
1.116159 +   27,  /*       EACH => ID */
1.116160 +   27,  /*       FAIL => ID */
1.116161 +   27,  /*        FOR => ID */
1.116162 +   27,  /*     IGNORE => ID */
1.116163 +   27,  /*  INITIALLY => ID */
1.116164 +   27,  /*    INSTEAD => ID */
1.116165 +   27,  /*    LIKE_KW => ID */
1.116166 +   27,  /*      MATCH => ID */
1.116167 +   27,  /*         NO => ID */
1.116168 +   27,  /*        KEY => ID */
1.116169 +   27,  /*         OF => ID */
1.116170 +   27,  /*     OFFSET => ID */
1.116171 +   27,  /*     PRAGMA => ID */
1.116172 +   27,  /*      RAISE => ID */
1.116173 +   27,  /*  RECURSIVE => ID */
1.116174 +   27,  /*    REPLACE => ID */
1.116175 +   27,  /*   RESTRICT => ID */
1.116176 +   27,  /*        ROW => ID */
1.116177 +   27,  /*    TRIGGER => ID */
1.116178 +   27,  /*     VACUUM => ID */
1.116179 +   27,  /*       VIEW => ID */
1.116180 +   27,  /*    VIRTUAL => ID */
1.116181 +   27,  /*       WITH => ID */
1.116182 +   27,  /*    REINDEX => ID */
1.116183 +   27,  /*     RENAME => ID */
1.116184 +   27,  /*   CTIME_KW => ID */
1.116185 +};
1.116186 +#endif /* YYFALLBACK */
1.116187 +
1.116188 +/* The following structure represents a single element of the
1.116189 +** parser's stack.  Information stored includes:
1.116190 +**
1.116191 +**   +  The state number for the parser at this level of the stack.
1.116192 +**
1.116193 +**   +  The value of the token stored at this level of the stack.
1.116194 +**      (In other words, the "major" token.)
1.116195 +**
1.116196 +**   +  The semantic value stored at this level of the stack.  This is
1.116197 +**      the information used by the action routines in the grammar.
1.116198 +**      It is sometimes called the "minor" token.
1.116199 +*/
1.116200 +struct yyStackEntry {
1.116201 +  YYACTIONTYPE stateno;  /* The state-number */
1.116202 +  YYCODETYPE major;      /* The major token value.  This is the code
1.116203 +                         ** number for the token at this stack level */
1.116204 +  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
1.116205 +                         ** is the value of the token  */
1.116206 +};
1.116207 +typedef struct yyStackEntry yyStackEntry;
1.116208 +
1.116209 +/* The state of the parser is completely contained in an instance of
1.116210 +** the following structure */
1.116211 +struct yyParser {
1.116212 +  int yyidx;                    /* Index of top element in stack */
1.116213 +#ifdef YYTRACKMAXSTACKDEPTH
1.116214 +  int yyidxMax;                 /* Maximum value of yyidx */
1.116215 +#endif
1.116216 +  int yyerrcnt;                 /* Shifts left before out of the error */
1.116217 +  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
1.116218 +#if YYSTACKDEPTH<=0
1.116219 +  int yystksz;                  /* Current side of the stack */
1.116220 +  yyStackEntry *yystack;        /* The parser's stack */
1.116221 +#else
1.116222 +  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
1.116223 +#endif
1.116224 +};
1.116225 +typedef struct yyParser yyParser;
1.116226 +
1.116227 +#ifndef NDEBUG
1.116228 +/* #include <stdio.h> */
1.116229 +static FILE *yyTraceFILE = 0;
1.116230 +static char *yyTracePrompt = 0;
1.116231 +#endif /* NDEBUG */
1.116232 +
1.116233 +#ifndef NDEBUG
1.116234 +/* 
1.116235 +** Turn parser tracing on by giving a stream to which to write the trace
1.116236 +** and a prompt to preface each trace message.  Tracing is turned off
1.116237 +** by making either argument NULL 
1.116238 +**
1.116239 +** Inputs:
1.116240 +** <ul>
1.116241 +** <li> A FILE* to which trace output should be written.
1.116242 +**      If NULL, then tracing is turned off.
1.116243 +** <li> A prefix string written at the beginning of every
1.116244 +**      line of trace output.  If NULL, then tracing is
1.116245 +**      turned off.
1.116246 +** </ul>
1.116247 +**
1.116248 +** Outputs:
1.116249 +** None.
1.116250 +*/
1.116251 +SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
1.116252 +  yyTraceFILE = TraceFILE;
1.116253 +  yyTracePrompt = zTracePrompt;
1.116254 +  if( yyTraceFILE==0 ) yyTracePrompt = 0;
1.116255 +  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
1.116256 +}
1.116257 +#endif /* NDEBUG */
1.116258 +
1.116259 +#ifndef NDEBUG
1.116260 +/* For tracing shifts, the names of all terminals and nonterminals
1.116261 +** are required.  The following table supplies these names */
1.116262 +static const char *const yyTokenName[] = { 
1.116263 +  "$",             "SEMI",          "EXPLAIN",       "QUERY",       
1.116264 +  "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
1.116265 +  "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
1.116266 +  "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
1.116267 +  "TABLE",         "CREATE",        "IF",            "NOT",         
1.116268 +  "EXISTS",        "TEMP",          "LP",            "RP",          
1.116269 +  "AS",            "WITHOUT",       "COMMA",         "ID",          
1.116270 +  "INDEXED",       "ABORT",         "ACTION",        "AFTER",       
1.116271 +  "ANALYZE",       "ASC",           "ATTACH",        "BEFORE",      
1.116272 +  "BY",            "CASCADE",       "CAST",          "COLUMNKW",    
1.116273 +  "CONFLICT",      "DATABASE",      "DESC",          "DETACH",      
1.116274 +  "EACH",          "FAIL",          "FOR",           "IGNORE",      
1.116275 +  "INITIALLY",     "INSTEAD",       "LIKE_KW",       "MATCH",       
1.116276 +  "NO",            "KEY",           "OF",            "OFFSET",      
1.116277 +  "PRAGMA",        "RAISE",         "RECURSIVE",     "REPLACE",     
1.116278 +  "RESTRICT",      "ROW",           "TRIGGER",       "VACUUM",      
1.116279 +  "VIEW",          "VIRTUAL",       "WITH",          "REINDEX",     
1.116280 +  "RENAME",        "CTIME_KW",      "ANY",           "OR",          
1.116281 +  "AND",           "IS",            "BETWEEN",       "IN",          
1.116282 +  "ISNULL",        "NOTNULL",       "NE",            "EQ",          
1.116283 +  "GT",            "LE",            "LT",            "GE",          
1.116284 +  "ESCAPE",        "BITAND",        "BITOR",         "LSHIFT",      
1.116285 +  "RSHIFT",        "PLUS",          "MINUS",         "STAR",        
1.116286 +  "SLASH",         "REM",           "CONCAT",        "COLLATE",     
1.116287 +  "BITNOT",        "STRING",        "JOIN_KW",       "CONSTRAINT",  
1.116288 +  "DEFAULT",       "NULL",          "PRIMARY",       "UNIQUE",      
1.116289 +  "CHECK",         "REFERENCES",    "AUTOINCR",      "ON",          
1.116290 +  "INSERT",        "DELETE",        "UPDATE",        "SET",         
1.116291 +  "DEFERRABLE",    "FOREIGN",       "DROP",          "UNION",       
1.116292 +  "ALL",           "EXCEPT",        "INTERSECT",     "SELECT",      
1.116293 +  "VALUES",        "DISTINCT",      "DOT",           "FROM",        
1.116294 +  "JOIN",          "USING",         "ORDER",         "GROUP",       
1.116295 +  "HAVING",        "LIMIT",         "WHERE",         "INTO",        
1.116296 +  "INTEGER",       "FLOAT",         "BLOB",          "VARIABLE",    
1.116297 +  "CASE",          "WHEN",          "THEN",          "ELSE",        
1.116298 +  "INDEX",         "ALTER",         "ADD",           "error",       
1.116299 +  "input",         "cmdlist",       "ecmd",          "explain",     
1.116300 +  "cmdx",          "cmd",           "transtype",     "trans_opt",   
1.116301 +  "nm",            "savepoint_opt",  "create_table",  "create_table_args",
1.116302 +  "createkw",      "temp",          "ifnotexists",   "dbnm",        
1.116303 +  "columnlist",    "conslist_opt",  "table_options",  "select",      
1.116304 +  "column",        "columnid",      "type",          "carglist",    
1.116305 +  "typetoken",     "typename",      "signed",        "plus_num",    
1.116306 +  "minus_num",     "ccons",         "term",          "expr",        
1.116307 +  "onconf",        "sortorder",     "autoinc",       "idxlist_opt", 
1.116308 +  "refargs",       "defer_subclause",  "refarg",        "refact",      
1.116309 +  "init_deferred_pred_opt",  "conslist",      "tconscomma",    "tcons",       
1.116310 +  "idxlist",       "defer_subclause_opt",  "orconf",        "resolvetype", 
1.116311 +  "raisetype",     "ifexists",      "fullname",      "selectnowith",
1.116312 +  "oneselect",     "with",          "multiselect_op",  "distinct",    
1.116313 +  "selcollist",    "from",          "where_opt",     "groupby_opt", 
1.116314 +  "having_opt",    "orderby_opt",   "limit_opt",     "values",      
1.116315 +  "nexprlist",     "exprlist",      "sclp",          "as",          
1.116316 +  "seltablist",    "stl_prefix",    "joinop",        "indexed_opt", 
1.116317 +  "on_opt",        "using_opt",     "joinop2",       "idlist",      
1.116318 +  "sortlist",      "setlist",       "insert_cmd",    "inscollist_opt",
1.116319 +  "likeop",        "between_op",    "in_op",         "case_operand",
1.116320 +  "case_exprlist",  "case_else",     "uniqueflag",    "collate",     
1.116321 +  "nmnum",         "trigger_decl",  "trigger_cmd_list",  "trigger_time",
1.116322 +  "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd", 
1.116323 +  "trnm",          "tridxby",       "database_kw_opt",  "key_opt",     
1.116324 +  "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist", 
1.116325 +  "vtabarg",       "vtabargtoken",  "lp",            "anylist",     
1.116326 +  "wqlist",      
1.116327 +};
1.116328 +#endif /* NDEBUG */
1.116329 +
1.116330 +#ifndef NDEBUG
1.116331 +/* For tracing reduce actions, the names of all rules are required.
1.116332 +*/
1.116333 +static const char *const yyRuleName[] = {
1.116334 + /*   0 */ "input ::= cmdlist",
1.116335 + /*   1 */ "cmdlist ::= cmdlist ecmd",
1.116336 + /*   2 */ "cmdlist ::= ecmd",
1.116337 + /*   3 */ "ecmd ::= SEMI",
1.116338 + /*   4 */ "ecmd ::= explain cmdx SEMI",
1.116339 + /*   5 */ "explain ::=",
1.116340 + /*   6 */ "explain ::= EXPLAIN",
1.116341 + /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
1.116342 + /*   8 */ "cmdx ::= cmd",
1.116343 + /*   9 */ "cmd ::= BEGIN transtype trans_opt",
1.116344 + /*  10 */ "trans_opt ::=",
1.116345 + /*  11 */ "trans_opt ::= TRANSACTION",
1.116346 + /*  12 */ "trans_opt ::= TRANSACTION nm",
1.116347 + /*  13 */ "transtype ::=",
1.116348 + /*  14 */ "transtype ::= DEFERRED",
1.116349 + /*  15 */ "transtype ::= IMMEDIATE",
1.116350 + /*  16 */ "transtype ::= EXCLUSIVE",
1.116351 + /*  17 */ "cmd ::= COMMIT trans_opt",
1.116352 + /*  18 */ "cmd ::= END trans_opt",
1.116353 + /*  19 */ "cmd ::= ROLLBACK trans_opt",
1.116354 + /*  20 */ "savepoint_opt ::= SAVEPOINT",
1.116355 + /*  21 */ "savepoint_opt ::=",
1.116356 + /*  22 */ "cmd ::= SAVEPOINT nm",
1.116357 + /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
1.116358 + /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
1.116359 + /*  25 */ "cmd ::= create_table create_table_args",
1.116360 + /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
1.116361 + /*  27 */ "createkw ::= CREATE",
1.116362 + /*  28 */ "ifnotexists ::=",
1.116363 + /*  29 */ "ifnotexists ::= IF NOT EXISTS",
1.116364 + /*  30 */ "temp ::= TEMP",
1.116365 + /*  31 */ "temp ::=",
1.116366 + /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
1.116367 + /*  33 */ "create_table_args ::= AS select",
1.116368 + /*  34 */ "table_options ::=",
1.116369 + /*  35 */ "table_options ::= WITHOUT nm",
1.116370 + /*  36 */ "columnlist ::= columnlist COMMA column",
1.116371 + /*  37 */ "columnlist ::= column",
1.116372 + /*  38 */ "column ::= columnid type carglist",
1.116373 + /*  39 */ "columnid ::= nm",
1.116374 + /*  40 */ "nm ::= ID|INDEXED",
1.116375 + /*  41 */ "nm ::= STRING",
1.116376 + /*  42 */ "nm ::= JOIN_KW",
1.116377 + /*  43 */ "type ::=",
1.116378 + /*  44 */ "type ::= typetoken",
1.116379 + /*  45 */ "typetoken ::= typename",
1.116380 + /*  46 */ "typetoken ::= typename LP signed RP",
1.116381 + /*  47 */ "typetoken ::= typename LP signed COMMA signed RP",
1.116382 + /*  48 */ "typename ::= ID|STRING",
1.116383 + /*  49 */ "typename ::= typename ID|STRING",
1.116384 + /*  50 */ "signed ::= plus_num",
1.116385 + /*  51 */ "signed ::= minus_num",
1.116386 + /*  52 */ "carglist ::= carglist ccons",
1.116387 + /*  53 */ "carglist ::=",
1.116388 + /*  54 */ "ccons ::= CONSTRAINT nm",
1.116389 + /*  55 */ "ccons ::= DEFAULT term",
1.116390 + /*  56 */ "ccons ::= DEFAULT LP expr RP",
1.116391 + /*  57 */ "ccons ::= DEFAULT PLUS term",
1.116392 + /*  58 */ "ccons ::= DEFAULT MINUS term",
1.116393 + /*  59 */ "ccons ::= DEFAULT ID|INDEXED",
1.116394 + /*  60 */ "ccons ::= NULL onconf",
1.116395 + /*  61 */ "ccons ::= NOT NULL onconf",
1.116396 + /*  62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
1.116397 + /*  63 */ "ccons ::= UNIQUE onconf",
1.116398 + /*  64 */ "ccons ::= CHECK LP expr RP",
1.116399 + /*  65 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
1.116400 + /*  66 */ "ccons ::= defer_subclause",
1.116401 + /*  67 */ "ccons ::= COLLATE ID|STRING",
1.116402 + /*  68 */ "autoinc ::=",
1.116403 + /*  69 */ "autoinc ::= AUTOINCR",
1.116404 + /*  70 */ "refargs ::=",
1.116405 + /*  71 */ "refargs ::= refargs refarg",
1.116406 + /*  72 */ "refarg ::= MATCH nm",
1.116407 + /*  73 */ "refarg ::= ON INSERT refact",
1.116408 + /*  74 */ "refarg ::= ON DELETE refact",
1.116409 + /*  75 */ "refarg ::= ON UPDATE refact",
1.116410 + /*  76 */ "refact ::= SET NULL",
1.116411 + /*  77 */ "refact ::= SET DEFAULT",
1.116412 + /*  78 */ "refact ::= CASCADE",
1.116413 + /*  79 */ "refact ::= RESTRICT",
1.116414 + /*  80 */ "refact ::= NO ACTION",
1.116415 + /*  81 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
1.116416 + /*  82 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
1.116417 + /*  83 */ "init_deferred_pred_opt ::=",
1.116418 + /*  84 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
1.116419 + /*  85 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
1.116420 + /*  86 */ "conslist_opt ::=",
1.116421 + /*  87 */ "conslist_opt ::= COMMA conslist",
1.116422 + /*  88 */ "conslist ::= conslist tconscomma tcons",
1.116423 + /*  89 */ "conslist ::= tcons",
1.116424 + /*  90 */ "tconscomma ::= COMMA",
1.116425 + /*  91 */ "tconscomma ::=",
1.116426 + /*  92 */ "tcons ::= CONSTRAINT nm",
1.116427 + /*  93 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
1.116428 + /*  94 */ "tcons ::= UNIQUE LP idxlist RP onconf",
1.116429 + /*  95 */ "tcons ::= CHECK LP expr RP onconf",
1.116430 + /*  96 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
1.116431 + /*  97 */ "defer_subclause_opt ::=",
1.116432 + /*  98 */ "defer_subclause_opt ::= defer_subclause",
1.116433 + /*  99 */ "onconf ::=",
1.116434 + /* 100 */ "onconf ::= ON CONFLICT resolvetype",
1.116435 + /* 101 */ "orconf ::=",
1.116436 + /* 102 */ "orconf ::= OR resolvetype",
1.116437 + /* 103 */ "resolvetype ::= raisetype",
1.116438 + /* 104 */ "resolvetype ::= IGNORE",
1.116439 + /* 105 */ "resolvetype ::= REPLACE",
1.116440 + /* 106 */ "cmd ::= DROP TABLE ifexists fullname",
1.116441 + /* 107 */ "ifexists ::= IF EXISTS",
1.116442 + /* 108 */ "ifexists ::=",
1.116443 + /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
1.116444 + /* 110 */ "cmd ::= DROP VIEW ifexists fullname",
1.116445 + /* 111 */ "cmd ::= select",
1.116446 + /* 112 */ "select ::= with selectnowith",
1.116447 + /* 113 */ "selectnowith ::= oneselect",
1.116448 + /* 114 */ "selectnowith ::= selectnowith multiselect_op oneselect",
1.116449 + /* 115 */ "multiselect_op ::= UNION",
1.116450 + /* 116 */ "multiselect_op ::= UNION ALL",
1.116451 + /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
1.116452 + /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
1.116453 + /* 119 */ "oneselect ::= values",
1.116454 + /* 120 */ "values ::= VALUES LP nexprlist RP",
1.116455 + /* 121 */ "values ::= values COMMA LP exprlist RP",
1.116456 + /* 122 */ "distinct ::= DISTINCT",
1.116457 + /* 123 */ "distinct ::= ALL",
1.116458 + /* 124 */ "distinct ::=",
1.116459 + /* 125 */ "sclp ::= selcollist COMMA",
1.116460 + /* 126 */ "sclp ::=",
1.116461 + /* 127 */ "selcollist ::= sclp expr as",
1.116462 + /* 128 */ "selcollist ::= sclp STAR",
1.116463 + /* 129 */ "selcollist ::= sclp nm DOT STAR",
1.116464 + /* 130 */ "as ::= AS nm",
1.116465 + /* 131 */ "as ::= ID|STRING",
1.116466 + /* 132 */ "as ::=",
1.116467 + /* 133 */ "from ::=",
1.116468 + /* 134 */ "from ::= FROM seltablist",
1.116469 + /* 135 */ "stl_prefix ::= seltablist joinop",
1.116470 + /* 136 */ "stl_prefix ::=",
1.116471 + /* 137 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
1.116472 + /* 138 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
1.116473 + /* 139 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
1.116474 + /* 140 */ "dbnm ::=",
1.116475 + /* 141 */ "dbnm ::= DOT nm",
1.116476 + /* 142 */ "fullname ::= nm dbnm",
1.116477 + /* 143 */ "joinop ::= COMMA|JOIN",
1.116478 + /* 144 */ "joinop ::= JOIN_KW JOIN",
1.116479 + /* 145 */ "joinop ::= JOIN_KW nm JOIN",
1.116480 + /* 146 */ "joinop ::= JOIN_KW nm nm JOIN",
1.116481 + /* 147 */ "on_opt ::= ON expr",
1.116482 + /* 148 */ "on_opt ::=",
1.116483 + /* 149 */ "indexed_opt ::=",
1.116484 + /* 150 */ "indexed_opt ::= INDEXED BY nm",
1.116485 + /* 151 */ "indexed_opt ::= NOT INDEXED",
1.116486 + /* 152 */ "using_opt ::= USING LP idlist RP",
1.116487 + /* 153 */ "using_opt ::=",
1.116488 + /* 154 */ "orderby_opt ::=",
1.116489 + /* 155 */ "orderby_opt ::= ORDER BY sortlist",
1.116490 + /* 156 */ "sortlist ::= sortlist COMMA expr sortorder",
1.116491 + /* 157 */ "sortlist ::= expr sortorder",
1.116492 + /* 158 */ "sortorder ::= ASC",
1.116493 + /* 159 */ "sortorder ::= DESC",
1.116494 + /* 160 */ "sortorder ::=",
1.116495 + /* 161 */ "groupby_opt ::=",
1.116496 + /* 162 */ "groupby_opt ::= GROUP BY nexprlist",
1.116497 + /* 163 */ "having_opt ::=",
1.116498 + /* 164 */ "having_opt ::= HAVING expr",
1.116499 + /* 165 */ "limit_opt ::=",
1.116500 + /* 166 */ "limit_opt ::= LIMIT expr",
1.116501 + /* 167 */ "limit_opt ::= LIMIT expr OFFSET expr",
1.116502 + /* 168 */ "limit_opt ::= LIMIT expr COMMA expr",
1.116503 + /* 169 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
1.116504 + /* 170 */ "where_opt ::=",
1.116505 + /* 171 */ "where_opt ::= WHERE expr",
1.116506 + /* 172 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
1.116507 + /* 173 */ "setlist ::= setlist COMMA nm EQ expr",
1.116508 + /* 174 */ "setlist ::= nm EQ expr",
1.116509 + /* 175 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt select",
1.116510 + /* 176 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
1.116511 + /* 177 */ "insert_cmd ::= INSERT orconf",
1.116512 + /* 178 */ "insert_cmd ::= REPLACE",
1.116513 + /* 179 */ "inscollist_opt ::=",
1.116514 + /* 180 */ "inscollist_opt ::= LP idlist RP",
1.116515 + /* 181 */ "idlist ::= idlist COMMA nm",
1.116516 + /* 182 */ "idlist ::= nm",
1.116517 + /* 183 */ "expr ::= term",
1.116518 + /* 184 */ "expr ::= LP expr RP",
1.116519 + /* 185 */ "term ::= NULL",
1.116520 + /* 186 */ "expr ::= ID|INDEXED",
1.116521 + /* 187 */ "expr ::= JOIN_KW",
1.116522 + /* 188 */ "expr ::= nm DOT nm",
1.116523 + /* 189 */ "expr ::= nm DOT nm DOT nm",
1.116524 + /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
1.116525 + /* 191 */ "term ::= STRING",
1.116526 + /* 192 */ "expr ::= VARIABLE",
1.116527 + /* 193 */ "expr ::= expr COLLATE ID|STRING",
1.116528 + /* 194 */ "expr ::= CAST LP expr AS typetoken RP",
1.116529 + /* 195 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
1.116530 + /* 196 */ "expr ::= ID|INDEXED LP STAR RP",
1.116531 + /* 197 */ "term ::= CTIME_KW",
1.116532 + /* 198 */ "expr ::= expr AND expr",
1.116533 + /* 199 */ "expr ::= expr OR expr",
1.116534 + /* 200 */ "expr ::= expr LT|GT|GE|LE expr",
1.116535 + /* 201 */ "expr ::= expr EQ|NE expr",
1.116536 + /* 202 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
1.116537 + /* 203 */ "expr ::= expr PLUS|MINUS expr",
1.116538 + /* 204 */ "expr ::= expr STAR|SLASH|REM expr",
1.116539 + /* 205 */ "expr ::= expr CONCAT expr",
1.116540 + /* 206 */ "likeop ::= LIKE_KW|MATCH",
1.116541 + /* 207 */ "likeop ::= NOT LIKE_KW|MATCH",
1.116542 + /* 208 */ "expr ::= expr likeop expr",
1.116543 + /* 209 */ "expr ::= expr likeop expr ESCAPE expr",
1.116544 + /* 210 */ "expr ::= expr ISNULL|NOTNULL",
1.116545 + /* 211 */ "expr ::= expr NOT NULL",
1.116546 + /* 212 */ "expr ::= expr IS expr",
1.116547 + /* 213 */ "expr ::= expr IS NOT expr",
1.116548 + /* 214 */ "expr ::= NOT expr",
1.116549 + /* 215 */ "expr ::= BITNOT expr",
1.116550 + /* 216 */ "expr ::= MINUS expr",
1.116551 + /* 217 */ "expr ::= PLUS expr",
1.116552 + /* 218 */ "between_op ::= BETWEEN",
1.116553 + /* 219 */ "between_op ::= NOT BETWEEN",
1.116554 + /* 220 */ "expr ::= expr between_op expr AND expr",
1.116555 + /* 221 */ "in_op ::= IN",
1.116556 + /* 222 */ "in_op ::= NOT IN",
1.116557 + /* 223 */ "expr ::= expr in_op LP exprlist RP",
1.116558 + /* 224 */ "expr ::= LP select RP",
1.116559 + /* 225 */ "expr ::= expr in_op LP select RP",
1.116560 + /* 226 */ "expr ::= expr in_op nm dbnm",
1.116561 + /* 227 */ "expr ::= EXISTS LP select RP",
1.116562 + /* 228 */ "expr ::= CASE case_operand case_exprlist case_else END",
1.116563 + /* 229 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
1.116564 + /* 230 */ "case_exprlist ::= WHEN expr THEN expr",
1.116565 + /* 231 */ "case_else ::= ELSE expr",
1.116566 + /* 232 */ "case_else ::=",
1.116567 + /* 233 */ "case_operand ::= expr",
1.116568 + /* 234 */ "case_operand ::=",
1.116569 + /* 235 */ "exprlist ::= nexprlist",
1.116570 + /* 236 */ "exprlist ::=",
1.116571 + /* 237 */ "nexprlist ::= nexprlist COMMA expr",
1.116572 + /* 238 */ "nexprlist ::= expr",
1.116573 + /* 239 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
1.116574 + /* 240 */ "uniqueflag ::= UNIQUE",
1.116575 + /* 241 */ "uniqueflag ::=",
1.116576 + /* 242 */ "idxlist_opt ::=",
1.116577 + /* 243 */ "idxlist_opt ::= LP idxlist RP",
1.116578 + /* 244 */ "idxlist ::= idxlist COMMA nm collate sortorder",
1.116579 + /* 245 */ "idxlist ::= nm collate sortorder",
1.116580 + /* 246 */ "collate ::=",
1.116581 + /* 247 */ "collate ::= COLLATE ID|STRING",
1.116582 + /* 248 */ "cmd ::= DROP INDEX ifexists fullname",
1.116583 + /* 249 */ "cmd ::= VACUUM",
1.116584 + /* 250 */ "cmd ::= VACUUM nm",
1.116585 + /* 251 */ "cmd ::= PRAGMA nm dbnm",
1.116586 + /* 252 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
1.116587 + /* 253 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
1.116588 + /* 254 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
1.116589 + /* 255 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
1.116590 + /* 256 */ "nmnum ::= plus_num",
1.116591 + /* 257 */ "nmnum ::= nm",
1.116592 + /* 258 */ "nmnum ::= ON",
1.116593 + /* 259 */ "nmnum ::= DELETE",
1.116594 + /* 260 */ "nmnum ::= DEFAULT",
1.116595 + /* 261 */ "plus_num ::= PLUS INTEGER|FLOAT",
1.116596 + /* 262 */ "plus_num ::= INTEGER|FLOAT",
1.116597 + /* 263 */ "minus_num ::= MINUS INTEGER|FLOAT",
1.116598 + /* 264 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
1.116599 + /* 265 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
1.116600 + /* 266 */ "trigger_time ::= BEFORE",
1.116601 + /* 267 */ "trigger_time ::= AFTER",
1.116602 + /* 268 */ "trigger_time ::= INSTEAD OF",
1.116603 + /* 269 */ "trigger_time ::=",
1.116604 + /* 270 */ "trigger_event ::= DELETE|INSERT",
1.116605 + /* 271 */ "trigger_event ::= UPDATE",
1.116606 + /* 272 */ "trigger_event ::= UPDATE OF idlist",
1.116607 + /* 273 */ "foreach_clause ::=",
1.116608 + /* 274 */ "foreach_clause ::= FOR EACH ROW",
1.116609 + /* 275 */ "when_clause ::=",
1.116610 + /* 276 */ "when_clause ::= WHEN expr",
1.116611 + /* 277 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
1.116612 + /* 278 */ "trigger_cmd_list ::= trigger_cmd SEMI",
1.116613 + /* 279 */ "trnm ::= nm",
1.116614 + /* 280 */ "trnm ::= nm DOT nm",
1.116615 + /* 281 */ "tridxby ::=",
1.116616 + /* 282 */ "tridxby ::= INDEXED BY nm",
1.116617 + /* 283 */ "tridxby ::= NOT INDEXED",
1.116618 + /* 284 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
1.116619 + /* 285 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
1.116620 + /* 286 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
1.116621 + /* 287 */ "trigger_cmd ::= select",
1.116622 + /* 288 */ "expr ::= RAISE LP IGNORE RP",
1.116623 + /* 289 */ "expr ::= RAISE LP raisetype COMMA nm RP",
1.116624 + /* 290 */ "raisetype ::= ROLLBACK",
1.116625 + /* 291 */ "raisetype ::= ABORT",
1.116626 + /* 292 */ "raisetype ::= FAIL",
1.116627 + /* 293 */ "cmd ::= DROP TRIGGER ifexists fullname",
1.116628 + /* 294 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
1.116629 + /* 295 */ "cmd ::= DETACH database_kw_opt expr",
1.116630 + /* 296 */ "key_opt ::=",
1.116631 + /* 297 */ "key_opt ::= KEY expr",
1.116632 + /* 298 */ "database_kw_opt ::= DATABASE",
1.116633 + /* 299 */ "database_kw_opt ::=",
1.116634 + /* 300 */ "cmd ::= REINDEX",
1.116635 + /* 301 */ "cmd ::= REINDEX nm dbnm",
1.116636 + /* 302 */ "cmd ::= ANALYZE",
1.116637 + /* 303 */ "cmd ::= ANALYZE nm dbnm",
1.116638 + /* 304 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
1.116639 + /* 305 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
1.116640 + /* 306 */ "add_column_fullname ::= fullname",
1.116641 + /* 307 */ "kwcolumn_opt ::=",
1.116642 + /* 308 */ "kwcolumn_opt ::= COLUMNKW",
1.116643 + /* 309 */ "cmd ::= create_vtab",
1.116644 + /* 310 */ "cmd ::= create_vtab LP vtabarglist RP",
1.116645 + /* 311 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
1.116646 + /* 312 */ "vtabarglist ::= vtabarg",
1.116647 + /* 313 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
1.116648 + /* 314 */ "vtabarg ::=",
1.116649 + /* 315 */ "vtabarg ::= vtabarg vtabargtoken",
1.116650 + /* 316 */ "vtabargtoken ::= ANY",
1.116651 + /* 317 */ "vtabargtoken ::= lp anylist RP",
1.116652 + /* 318 */ "lp ::= LP",
1.116653 + /* 319 */ "anylist ::=",
1.116654 + /* 320 */ "anylist ::= anylist LP anylist RP",
1.116655 + /* 321 */ "anylist ::= anylist ANY",
1.116656 + /* 322 */ "with ::=",
1.116657 + /* 323 */ "with ::= WITH wqlist",
1.116658 + /* 324 */ "with ::= WITH RECURSIVE wqlist",
1.116659 + /* 325 */ "wqlist ::= nm idxlist_opt AS LP select RP",
1.116660 + /* 326 */ "wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP",
1.116661 +};
1.116662 +#endif /* NDEBUG */
1.116663 +
1.116664 +
1.116665 +#if YYSTACKDEPTH<=0
1.116666 +/*
1.116667 +** Try to increase the size of the parser stack.
1.116668 +*/
1.116669 +static void yyGrowStack(yyParser *p){
1.116670 +  int newSize;
1.116671 +  yyStackEntry *pNew;
1.116672 +
1.116673 +  newSize = p->yystksz*2 + 100;
1.116674 +  pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
1.116675 +  if( pNew ){
1.116676 +    p->yystack = pNew;
1.116677 +    p->yystksz = newSize;
1.116678 +#ifndef NDEBUG
1.116679 +    if( yyTraceFILE ){
1.116680 +      fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
1.116681 +              yyTracePrompt, p->yystksz);
1.116682 +    }
1.116683 +#endif
1.116684 +  }
1.116685 +}
1.116686 +#endif
1.116687 +
1.116688 +/* 
1.116689 +** This function allocates a new parser.
1.116690 +** The only argument is a pointer to a function which works like
1.116691 +** malloc.
1.116692 +**
1.116693 +** Inputs:
1.116694 +** A pointer to the function used to allocate memory.
1.116695 +**
1.116696 +** Outputs:
1.116697 +** A pointer to a parser.  This pointer is used in subsequent calls
1.116698 +** to sqlite3Parser and sqlite3ParserFree.
1.116699 +*/
1.116700 +SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
1.116701 +  yyParser *pParser;
1.116702 +  pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
1.116703 +  if( pParser ){
1.116704 +    pParser->yyidx = -1;
1.116705 +#ifdef YYTRACKMAXSTACKDEPTH
1.116706 +    pParser->yyidxMax = 0;
1.116707 +#endif
1.116708 +#if YYSTACKDEPTH<=0
1.116709 +    pParser->yystack = NULL;
1.116710 +    pParser->yystksz = 0;
1.116711 +    yyGrowStack(pParser);
1.116712 +#endif
1.116713 +  }
1.116714 +  return pParser;
1.116715 +}
1.116716 +
1.116717 +/* The following function deletes the value associated with a
1.116718 +** symbol.  The symbol can be either a terminal or nonterminal.
1.116719 +** "yymajor" is the symbol code, and "yypminor" is a pointer to
1.116720 +** the value.
1.116721 +*/
1.116722 +static void yy_destructor(
1.116723 +  yyParser *yypParser,    /* The parser */
1.116724 +  YYCODETYPE yymajor,     /* Type code for object to destroy */
1.116725 +  YYMINORTYPE *yypminor   /* The object to be destroyed */
1.116726 +){
1.116727 +  sqlite3ParserARG_FETCH;
1.116728 +  switch( yymajor ){
1.116729 +    /* Here is inserted the actions which take place when a
1.116730 +    ** terminal or non-terminal is destroyed.  This can happen
1.116731 +    ** when the symbol is popped from the stack during a
1.116732 +    ** reduce or during error processing or when a parser is 
1.116733 +    ** being destroyed before it is finished parsing.
1.116734 +    **
1.116735 +    ** Note: during a reduce, the only symbols destroyed are those
1.116736 +    ** which appear on the RHS of the rule, but which are not used
1.116737 +    ** inside the C code.
1.116738 +    */
1.116739 +    case 163: /* select */
1.116740 +    case 195: /* selectnowith */
1.116741 +    case 196: /* oneselect */
1.116742 +    case 207: /* values */
1.116743 +{
1.116744 +sqlite3SelectDelete(pParse->db, (yypminor->yy3));
1.116745 +}
1.116746 +      break;
1.116747 +    case 174: /* term */
1.116748 +    case 175: /* expr */
1.116749 +{
1.116750 +sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
1.116751 +}
1.116752 +      break;
1.116753 +    case 179: /* idxlist_opt */
1.116754 +    case 188: /* idxlist */
1.116755 +    case 200: /* selcollist */
1.116756 +    case 203: /* groupby_opt */
1.116757 +    case 205: /* orderby_opt */
1.116758 +    case 208: /* nexprlist */
1.116759 +    case 209: /* exprlist */
1.116760 +    case 210: /* sclp */
1.116761 +    case 220: /* sortlist */
1.116762 +    case 221: /* setlist */
1.116763 +    case 228: /* case_exprlist */
1.116764 +{
1.116765 +sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
1.116766 +}
1.116767 +      break;
1.116768 +    case 194: /* fullname */
1.116769 +    case 201: /* from */
1.116770 +    case 212: /* seltablist */
1.116771 +    case 213: /* stl_prefix */
1.116772 +{
1.116773 +sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
1.116774 +}
1.116775 +      break;
1.116776 +    case 197: /* with */
1.116777 +    case 252: /* wqlist */
1.116778 +{
1.116779 +sqlite3WithDelete(pParse->db, (yypminor->yy59));
1.116780 +}
1.116781 +      break;
1.116782 +    case 202: /* where_opt */
1.116783 +    case 204: /* having_opt */
1.116784 +    case 216: /* on_opt */
1.116785 +    case 227: /* case_operand */
1.116786 +    case 229: /* case_else */
1.116787 +    case 238: /* when_clause */
1.116788 +    case 243: /* key_opt */
1.116789 +{
1.116790 +sqlite3ExprDelete(pParse->db, (yypminor->yy132));
1.116791 +}
1.116792 +      break;
1.116793 +    case 217: /* using_opt */
1.116794 +    case 219: /* idlist */
1.116795 +    case 223: /* inscollist_opt */
1.116796 +{
1.116797 +sqlite3IdListDelete(pParse->db, (yypminor->yy408));
1.116798 +}
1.116799 +      break;
1.116800 +    case 234: /* trigger_cmd_list */
1.116801 +    case 239: /* trigger_cmd */
1.116802 +{
1.116803 +sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
1.116804 +}
1.116805 +      break;
1.116806 +    case 236: /* trigger_event */
1.116807 +{
1.116808 +sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
1.116809 +}
1.116810 +      break;
1.116811 +    default:  break;   /* If no destructor action specified: do nothing */
1.116812 +  }
1.116813 +}
1.116814 +
1.116815 +/*
1.116816 +** Pop the parser's stack once.
1.116817 +**
1.116818 +** If there is a destructor routine associated with the token which
1.116819 +** is popped from the stack, then call it.
1.116820 +**
1.116821 +** Return the major token number for the symbol popped.
1.116822 +*/
1.116823 +static int yy_pop_parser_stack(yyParser *pParser){
1.116824 +  YYCODETYPE yymajor;
1.116825 +  yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
1.116826 +
1.116827 +  /* There is no mechanism by which the parser stack can be popped below
1.116828 +  ** empty in SQLite.  */
1.116829 +  if( NEVER(pParser->yyidx<0) ) return 0;
1.116830 +#ifndef NDEBUG
1.116831 +  if( yyTraceFILE && pParser->yyidx>=0 ){
1.116832 +    fprintf(yyTraceFILE,"%sPopping %s\n",
1.116833 +      yyTracePrompt,
1.116834 +      yyTokenName[yytos->major]);
1.116835 +  }
1.116836 +#endif
1.116837 +  yymajor = yytos->major;
1.116838 +  yy_destructor(pParser, yymajor, &yytos->minor);
1.116839 +  pParser->yyidx--;
1.116840 +  return yymajor;
1.116841 +}
1.116842 +
1.116843 +/* 
1.116844 +** Deallocate and destroy a parser.  Destructors are all called for
1.116845 +** all stack elements before shutting the parser down.
1.116846 +**
1.116847 +** Inputs:
1.116848 +** <ul>
1.116849 +** <li>  A pointer to the parser.  This should be a pointer
1.116850 +**       obtained from sqlite3ParserAlloc.
1.116851 +** <li>  A pointer to a function used to reclaim memory obtained
1.116852 +**       from malloc.
1.116853 +** </ul>
1.116854 +*/
1.116855 +SQLITE_PRIVATE void sqlite3ParserFree(
1.116856 +  void *p,                    /* The parser to be deleted */
1.116857 +  void (*freeProc)(void*)     /* Function used to reclaim memory */
1.116858 +){
1.116859 +  yyParser *pParser = (yyParser*)p;
1.116860 +  /* In SQLite, we never try to destroy a parser that was not successfully
1.116861 +  ** created in the first place. */
1.116862 +  if( NEVER(pParser==0) ) return;
1.116863 +  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
1.116864 +#if YYSTACKDEPTH<=0
1.116865 +  free(pParser->yystack);
1.116866 +#endif
1.116867 +  (*freeProc)((void*)pParser);
1.116868 +}
1.116869 +
1.116870 +/*
1.116871 +** Return the peak depth of the stack for a parser.
1.116872 +*/
1.116873 +#ifdef YYTRACKMAXSTACKDEPTH
1.116874 +SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
1.116875 +  yyParser *pParser = (yyParser*)p;
1.116876 +  return pParser->yyidxMax;
1.116877 +}
1.116878 +#endif
1.116879 +
1.116880 +/*
1.116881 +** Find the appropriate action for a parser given the terminal
1.116882 +** look-ahead token iLookAhead.
1.116883 +**
1.116884 +** If the look-ahead token is YYNOCODE, then check to see if the action is
1.116885 +** independent of the look-ahead.  If it is, return the action, otherwise
1.116886 +** return YY_NO_ACTION.
1.116887 +*/
1.116888 +static int yy_find_shift_action(
1.116889 +  yyParser *pParser,        /* The parser */
1.116890 +  YYCODETYPE iLookAhead     /* The look-ahead token */
1.116891 +){
1.116892 +  int i;
1.116893 +  int stateno = pParser->yystack[pParser->yyidx].stateno;
1.116894 + 
1.116895 +  if( stateno>YY_SHIFT_COUNT
1.116896 +   || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
1.116897 +    return yy_default[stateno];
1.116898 +  }
1.116899 +  assert( iLookAhead!=YYNOCODE );
1.116900 +  i += iLookAhead;
1.116901 +  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
1.116902 +    if( iLookAhead>0 ){
1.116903 +#ifdef YYFALLBACK
1.116904 +      YYCODETYPE iFallback;            /* Fallback token */
1.116905 +      if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
1.116906 +             && (iFallback = yyFallback[iLookAhead])!=0 ){
1.116907 +#ifndef NDEBUG
1.116908 +        if( yyTraceFILE ){
1.116909 +          fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
1.116910 +             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
1.116911 +        }
1.116912 +#endif
1.116913 +        return yy_find_shift_action(pParser, iFallback);
1.116914 +      }
1.116915 +#endif
1.116916 +#ifdef YYWILDCARD
1.116917 +      {
1.116918 +        int j = i - iLookAhead + YYWILDCARD;
1.116919 +        if( 
1.116920 +#if YY_SHIFT_MIN+YYWILDCARD<0
1.116921 +          j>=0 &&
1.116922 +#endif
1.116923 +#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
1.116924 +          j<YY_ACTTAB_COUNT &&
1.116925 +#endif
1.116926 +          yy_lookahead[j]==YYWILDCARD
1.116927 +        ){
1.116928 +#ifndef NDEBUG
1.116929 +          if( yyTraceFILE ){
1.116930 +            fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
1.116931 +               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
1.116932 +          }
1.116933 +#endif /* NDEBUG */
1.116934 +          return yy_action[j];
1.116935 +        }
1.116936 +      }
1.116937 +#endif /* YYWILDCARD */
1.116938 +    }
1.116939 +    return yy_default[stateno];
1.116940 +  }else{
1.116941 +    return yy_action[i];
1.116942 +  }
1.116943 +}
1.116944 +
1.116945 +/*
1.116946 +** Find the appropriate action for a parser given the non-terminal
1.116947 +** look-ahead token iLookAhead.
1.116948 +**
1.116949 +** If the look-ahead token is YYNOCODE, then check to see if the action is
1.116950 +** independent of the look-ahead.  If it is, return the action, otherwise
1.116951 +** return YY_NO_ACTION.
1.116952 +*/
1.116953 +static int yy_find_reduce_action(
1.116954 +  int stateno,              /* Current state number */
1.116955 +  YYCODETYPE iLookAhead     /* The look-ahead token */
1.116956 +){
1.116957 +  int i;
1.116958 +#ifdef YYERRORSYMBOL
1.116959 +  if( stateno>YY_REDUCE_COUNT ){
1.116960 +    return yy_default[stateno];
1.116961 +  }
1.116962 +#else
1.116963 +  assert( stateno<=YY_REDUCE_COUNT );
1.116964 +#endif
1.116965 +  i = yy_reduce_ofst[stateno];
1.116966 +  assert( i!=YY_REDUCE_USE_DFLT );
1.116967 +  assert( iLookAhead!=YYNOCODE );
1.116968 +  i += iLookAhead;
1.116969 +#ifdef YYERRORSYMBOL
1.116970 +  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
1.116971 +    return yy_default[stateno];
1.116972 +  }
1.116973 +#else
1.116974 +  assert( i>=0 && i<YY_ACTTAB_COUNT );
1.116975 +  assert( yy_lookahead[i]==iLookAhead );
1.116976 +#endif
1.116977 +  return yy_action[i];
1.116978 +}
1.116979 +
1.116980 +/*
1.116981 +** The following routine is called if the stack overflows.
1.116982 +*/
1.116983 +static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
1.116984 +   sqlite3ParserARG_FETCH;
1.116985 +   yypParser->yyidx--;
1.116986 +#ifndef NDEBUG
1.116987 +   if( yyTraceFILE ){
1.116988 +     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
1.116989 +   }
1.116990 +#endif
1.116991 +   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
1.116992 +   /* Here code is inserted which will execute if the parser
1.116993 +   ** stack every overflows */
1.116994 +
1.116995 +  UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
1.116996 +  sqlite3ErrorMsg(pParse, "parser stack overflow");
1.116997 +   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
1.116998 +}
1.116999 +
1.117000 +/*
1.117001 +** Perform a shift action.
1.117002 +*/
1.117003 +static void yy_shift(
1.117004 +  yyParser *yypParser,          /* The parser to be shifted */
1.117005 +  int yyNewState,               /* The new state to shift in */
1.117006 +  int yyMajor,                  /* The major token to shift in */
1.117007 +  YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
1.117008 +){
1.117009 +  yyStackEntry *yytos;
1.117010 +  yypParser->yyidx++;
1.117011 +#ifdef YYTRACKMAXSTACKDEPTH
1.117012 +  if( yypParser->yyidx>yypParser->yyidxMax ){
1.117013 +    yypParser->yyidxMax = yypParser->yyidx;
1.117014 +  }
1.117015 +#endif
1.117016 +#if YYSTACKDEPTH>0 
1.117017 +  if( yypParser->yyidx>=YYSTACKDEPTH ){
1.117018 +    yyStackOverflow(yypParser, yypMinor);
1.117019 +    return;
1.117020 +  }
1.117021 +#else
1.117022 +  if( yypParser->yyidx>=yypParser->yystksz ){
1.117023 +    yyGrowStack(yypParser);
1.117024 +    if( yypParser->yyidx>=yypParser->yystksz ){
1.117025 +      yyStackOverflow(yypParser, yypMinor);
1.117026 +      return;
1.117027 +    }
1.117028 +  }
1.117029 +#endif
1.117030 +  yytos = &yypParser->yystack[yypParser->yyidx];
1.117031 +  yytos->stateno = (YYACTIONTYPE)yyNewState;
1.117032 +  yytos->major = (YYCODETYPE)yyMajor;
1.117033 +  yytos->minor = *yypMinor;
1.117034 +#ifndef NDEBUG
1.117035 +  if( yyTraceFILE && yypParser->yyidx>0 ){
1.117036 +    int i;
1.117037 +    fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
1.117038 +    fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
1.117039 +    for(i=1; i<=yypParser->yyidx; i++)
1.117040 +      fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
1.117041 +    fprintf(yyTraceFILE,"\n");
1.117042 +  }
1.117043 +#endif
1.117044 +}
1.117045 +
1.117046 +/* The following table contains information about every rule that
1.117047 +** is used during the reduce.
1.117048 +*/
1.117049 +static const struct {
1.117050 +  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
1.117051 +  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
1.117052 +} yyRuleInfo[] = {
1.117053 +  { 144, 1 },
1.117054 +  { 145, 2 },
1.117055 +  { 145, 1 },
1.117056 +  { 146, 1 },
1.117057 +  { 146, 3 },
1.117058 +  { 147, 0 },
1.117059 +  { 147, 1 },
1.117060 +  { 147, 3 },
1.117061 +  { 148, 1 },
1.117062 +  { 149, 3 },
1.117063 +  { 151, 0 },
1.117064 +  { 151, 1 },
1.117065 +  { 151, 2 },
1.117066 +  { 150, 0 },
1.117067 +  { 150, 1 },
1.117068 +  { 150, 1 },
1.117069 +  { 150, 1 },
1.117070 +  { 149, 2 },
1.117071 +  { 149, 2 },
1.117072 +  { 149, 2 },
1.117073 +  { 153, 1 },
1.117074 +  { 153, 0 },
1.117075 +  { 149, 2 },
1.117076 +  { 149, 3 },
1.117077 +  { 149, 5 },
1.117078 +  { 149, 2 },
1.117079 +  { 154, 6 },
1.117080 +  { 156, 1 },
1.117081 +  { 158, 0 },
1.117082 +  { 158, 3 },
1.117083 +  { 157, 1 },
1.117084 +  { 157, 0 },
1.117085 +  { 155, 5 },
1.117086 +  { 155, 2 },
1.117087 +  { 162, 0 },
1.117088 +  { 162, 2 },
1.117089 +  { 160, 3 },
1.117090 +  { 160, 1 },
1.117091 +  { 164, 3 },
1.117092 +  { 165, 1 },
1.117093 +  { 152, 1 },
1.117094 +  { 152, 1 },
1.117095 +  { 152, 1 },
1.117096 +  { 166, 0 },
1.117097 +  { 166, 1 },
1.117098 +  { 168, 1 },
1.117099 +  { 168, 4 },
1.117100 +  { 168, 6 },
1.117101 +  { 169, 1 },
1.117102 +  { 169, 2 },
1.117103 +  { 170, 1 },
1.117104 +  { 170, 1 },
1.117105 +  { 167, 2 },
1.117106 +  { 167, 0 },
1.117107 +  { 173, 2 },
1.117108 +  { 173, 2 },
1.117109 +  { 173, 4 },
1.117110 +  { 173, 3 },
1.117111 +  { 173, 3 },
1.117112 +  { 173, 2 },
1.117113 +  { 173, 2 },
1.117114 +  { 173, 3 },
1.117115 +  { 173, 5 },
1.117116 +  { 173, 2 },
1.117117 +  { 173, 4 },
1.117118 +  { 173, 4 },
1.117119 +  { 173, 1 },
1.117120 +  { 173, 2 },
1.117121 +  { 178, 0 },
1.117122 +  { 178, 1 },
1.117123 +  { 180, 0 },
1.117124 +  { 180, 2 },
1.117125 +  { 182, 2 },
1.117126 +  { 182, 3 },
1.117127 +  { 182, 3 },
1.117128 +  { 182, 3 },
1.117129 +  { 183, 2 },
1.117130 +  { 183, 2 },
1.117131 +  { 183, 1 },
1.117132 +  { 183, 1 },
1.117133 +  { 183, 2 },
1.117134 +  { 181, 3 },
1.117135 +  { 181, 2 },
1.117136 +  { 184, 0 },
1.117137 +  { 184, 2 },
1.117138 +  { 184, 2 },
1.117139 +  { 161, 0 },
1.117140 +  { 161, 2 },
1.117141 +  { 185, 3 },
1.117142 +  { 185, 1 },
1.117143 +  { 186, 1 },
1.117144 +  { 186, 0 },
1.117145 +  { 187, 2 },
1.117146 +  { 187, 7 },
1.117147 +  { 187, 5 },
1.117148 +  { 187, 5 },
1.117149 +  { 187, 10 },
1.117150 +  { 189, 0 },
1.117151 +  { 189, 1 },
1.117152 +  { 176, 0 },
1.117153 +  { 176, 3 },
1.117154 +  { 190, 0 },
1.117155 +  { 190, 2 },
1.117156 +  { 191, 1 },
1.117157 +  { 191, 1 },
1.117158 +  { 191, 1 },
1.117159 +  { 149, 4 },
1.117160 +  { 193, 2 },
1.117161 +  { 193, 0 },
1.117162 +  { 149, 8 },
1.117163 +  { 149, 4 },
1.117164 +  { 149, 1 },
1.117165 +  { 163, 2 },
1.117166 +  { 195, 1 },
1.117167 +  { 195, 3 },
1.117168 +  { 198, 1 },
1.117169 +  { 198, 2 },
1.117170 +  { 198, 1 },
1.117171 +  { 196, 9 },
1.117172 +  { 196, 1 },
1.117173 +  { 207, 4 },
1.117174 +  { 207, 5 },
1.117175 +  { 199, 1 },
1.117176 +  { 199, 1 },
1.117177 +  { 199, 0 },
1.117178 +  { 210, 2 },
1.117179 +  { 210, 0 },
1.117180 +  { 200, 3 },
1.117181 +  { 200, 2 },
1.117182 +  { 200, 4 },
1.117183 +  { 211, 2 },
1.117184 +  { 211, 1 },
1.117185 +  { 211, 0 },
1.117186 +  { 201, 0 },
1.117187 +  { 201, 2 },
1.117188 +  { 213, 2 },
1.117189 +  { 213, 0 },
1.117190 +  { 212, 7 },
1.117191 +  { 212, 7 },
1.117192 +  { 212, 7 },
1.117193 +  { 159, 0 },
1.117194 +  { 159, 2 },
1.117195 +  { 194, 2 },
1.117196 +  { 214, 1 },
1.117197 +  { 214, 2 },
1.117198 +  { 214, 3 },
1.117199 +  { 214, 4 },
1.117200 +  { 216, 2 },
1.117201 +  { 216, 0 },
1.117202 +  { 215, 0 },
1.117203 +  { 215, 3 },
1.117204 +  { 215, 2 },
1.117205 +  { 217, 4 },
1.117206 +  { 217, 0 },
1.117207 +  { 205, 0 },
1.117208 +  { 205, 3 },
1.117209 +  { 220, 4 },
1.117210 +  { 220, 2 },
1.117211 +  { 177, 1 },
1.117212 +  { 177, 1 },
1.117213 +  { 177, 0 },
1.117214 +  { 203, 0 },
1.117215 +  { 203, 3 },
1.117216 +  { 204, 0 },
1.117217 +  { 204, 2 },
1.117218 +  { 206, 0 },
1.117219 +  { 206, 2 },
1.117220 +  { 206, 4 },
1.117221 +  { 206, 4 },
1.117222 +  { 149, 6 },
1.117223 +  { 202, 0 },
1.117224 +  { 202, 2 },
1.117225 +  { 149, 8 },
1.117226 +  { 221, 5 },
1.117227 +  { 221, 3 },
1.117228 +  { 149, 6 },
1.117229 +  { 149, 7 },
1.117230 +  { 222, 2 },
1.117231 +  { 222, 1 },
1.117232 +  { 223, 0 },
1.117233 +  { 223, 3 },
1.117234 +  { 219, 3 },
1.117235 +  { 219, 1 },
1.117236 +  { 175, 1 },
1.117237 +  { 175, 3 },
1.117238 +  { 174, 1 },
1.117239 +  { 175, 1 },
1.117240 +  { 175, 1 },
1.117241 +  { 175, 3 },
1.117242 +  { 175, 5 },
1.117243 +  { 174, 1 },
1.117244 +  { 174, 1 },
1.117245 +  { 175, 1 },
1.117246 +  { 175, 3 },
1.117247 +  { 175, 6 },
1.117248 +  { 175, 5 },
1.117249 +  { 175, 4 },
1.117250 +  { 174, 1 },
1.117251 +  { 175, 3 },
1.117252 +  { 175, 3 },
1.117253 +  { 175, 3 },
1.117254 +  { 175, 3 },
1.117255 +  { 175, 3 },
1.117256 +  { 175, 3 },
1.117257 +  { 175, 3 },
1.117258 +  { 175, 3 },
1.117259 +  { 224, 1 },
1.117260 +  { 224, 2 },
1.117261 +  { 175, 3 },
1.117262 +  { 175, 5 },
1.117263 +  { 175, 2 },
1.117264 +  { 175, 3 },
1.117265 +  { 175, 3 },
1.117266 +  { 175, 4 },
1.117267 +  { 175, 2 },
1.117268 +  { 175, 2 },
1.117269 +  { 175, 2 },
1.117270 +  { 175, 2 },
1.117271 +  { 225, 1 },
1.117272 +  { 225, 2 },
1.117273 +  { 175, 5 },
1.117274 +  { 226, 1 },
1.117275 +  { 226, 2 },
1.117276 +  { 175, 5 },
1.117277 +  { 175, 3 },
1.117278 +  { 175, 5 },
1.117279 +  { 175, 4 },
1.117280 +  { 175, 4 },
1.117281 +  { 175, 5 },
1.117282 +  { 228, 5 },
1.117283 +  { 228, 4 },
1.117284 +  { 229, 2 },
1.117285 +  { 229, 0 },
1.117286 +  { 227, 1 },
1.117287 +  { 227, 0 },
1.117288 +  { 209, 1 },
1.117289 +  { 209, 0 },
1.117290 +  { 208, 3 },
1.117291 +  { 208, 1 },
1.117292 +  { 149, 12 },
1.117293 +  { 230, 1 },
1.117294 +  { 230, 0 },
1.117295 +  { 179, 0 },
1.117296 +  { 179, 3 },
1.117297 +  { 188, 5 },
1.117298 +  { 188, 3 },
1.117299 +  { 231, 0 },
1.117300 +  { 231, 2 },
1.117301 +  { 149, 4 },
1.117302 +  { 149, 1 },
1.117303 +  { 149, 2 },
1.117304 +  { 149, 3 },
1.117305 +  { 149, 5 },
1.117306 +  { 149, 6 },
1.117307 +  { 149, 5 },
1.117308 +  { 149, 6 },
1.117309 +  { 232, 1 },
1.117310 +  { 232, 1 },
1.117311 +  { 232, 1 },
1.117312 +  { 232, 1 },
1.117313 +  { 232, 1 },
1.117314 +  { 171, 2 },
1.117315 +  { 171, 1 },
1.117316 +  { 172, 2 },
1.117317 +  { 149, 5 },
1.117318 +  { 233, 11 },
1.117319 +  { 235, 1 },
1.117320 +  { 235, 1 },
1.117321 +  { 235, 2 },
1.117322 +  { 235, 0 },
1.117323 +  { 236, 1 },
1.117324 +  { 236, 1 },
1.117325 +  { 236, 3 },
1.117326 +  { 237, 0 },
1.117327 +  { 237, 3 },
1.117328 +  { 238, 0 },
1.117329 +  { 238, 2 },
1.117330 +  { 234, 3 },
1.117331 +  { 234, 2 },
1.117332 +  { 240, 1 },
1.117333 +  { 240, 3 },
1.117334 +  { 241, 0 },
1.117335 +  { 241, 3 },
1.117336 +  { 241, 2 },
1.117337 +  { 239, 7 },
1.117338 +  { 239, 5 },
1.117339 +  { 239, 5 },
1.117340 +  { 239, 1 },
1.117341 +  { 175, 4 },
1.117342 +  { 175, 6 },
1.117343 +  { 192, 1 },
1.117344 +  { 192, 1 },
1.117345 +  { 192, 1 },
1.117346 +  { 149, 4 },
1.117347 +  { 149, 6 },
1.117348 +  { 149, 3 },
1.117349 +  { 243, 0 },
1.117350 +  { 243, 2 },
1.117351 +  { 242, 1 },
1.117352 +  { 242, 0 },
1.117353 +  { 149, 1 },
1.117354 +  { 149, 3 },
1.117355 +  { 149, 1 },
1.117356 +  { 149, 3 },
1.117357 +  { 149, 6 },
1.117358 +  { 149, 6 },
1.117359 +  { 244, 1 },
1.117360 +  { 245, 0 },
1.117361 +  { 245, 1 },
1.117362 +  { 149, 1 },
1.117363 +  { 149, 4 },
1.117364 +  { 246, 8 },
1.117365 +  { 247, 1 },
1.117366 +  { 247, 3 },
1.117367 +  { 248, 0 },
1.117368 +  { 248, 2 },
1.117369 +  { 249, 1 },
1.117370 +  { 249, 3 },
1.117371 +  { 250, 1 },
1.117372 +  { 251, 0 },
1.117373 +  { 251, 4 },
1.117374 +  { 251, 2 },
1.117375 +  { 197, 0 },
1.117376 +  { 197, 2 },
1.117377 +  { 197, 3 },
1.117378 +  { 252, 6 },
1.117379 +  { 252, 8 },
1.117380 +};
1.117381 +
1.117382 +static void yy_accept(yyParser*);  /* Forward Declaration */
1.117383 +
1.117384 +/*
1.117385 +** Perform a reduce action and the shift that must immediately
1.117386 +** follow the reduce.
1.117387 +*/
1.117388 +static void yy_reduce(
1.117389 +  yyParser *yypParser,         /* The parser */
1.117390 +  int yyruleno                 /* Number of the rule by which to reduce */
1.117391 +){
1.117392 +  int yygoto;                     /* The next state */
1.117393 +  int yyact;                      /* The next action */
1.117394 +  YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
1.117395 +  yyStackEntry *yymsp;            /* The top of the parser's stack */
1.117396 +  int yysize;                     /* Amount to pop the stack */
1.117397 +  sqlite3ParserARG_FETCH;
1.117398 +  yymsp = &yypParser->yystack[yypParser->yyidx];
1.117399 +#ifndef NDEBUG
1.117400 +  if( yyTraceFILE && yyruleno>=0 
1.117401 +        && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
1.117402 +    fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
1.117403 +      yyRuleName[yyruleno]);
1.117404 +  }
1.117405 +#endif /* NDEBUG */
1.117406 +
1.117407 +  /* Silence complaints from purify about yygotominor being uninitialized
1.117408 +  ** in some cases when it is copied into the stack after the following
1.117409 +  ** switch.  yygotominor is uninitialized when a rule reduces that does
1.117410 +  ** not set the value of its left-hand side nonterminal.  Leaving the
1.117411 +  ** value of the nonterminal uninitialized is utterly harmless as long
1.117412 +  ** as the value is never used.  So really the only thing this code
1.117413 +  ** accomplishes is to quieten purify.  
1.117414 +  **
1.117415 +  ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
1.117416 +  ** without this code, their parser segfaults.  I'm not sure what there
1.117417 +  ** parser is doing to make this happen.  This is the second bug report
1.117418 +  ** from wireshark this week.  Clearly they are stressing Lemon in ways
1.117419 +  ** that it has not been previously stressed...  (SQLite ticket #2172)
1.117420 +  */
1.117421 +  /*memset(&yygotominor, 0, sizeof(yygotominor));*/
1.117422 +  yygotominor = yyzerominor;
1.117423 +
1.117424 +
1.117425 +  switch( yyruleno ){
1.117426 +  /* Beginning here are the reduction cases.  A typical example
1.117427 +  ** follows:
1.117428 +  **   case 0:
1.117429 +  **  #line <lineno> <grammarfile>
1.117430 +  **     { ... }           // User supplied code
1.117431 +  **  #line <lineno> <thisfile>
1.117432 +  **     break;
1.117433 +  */
1.117434 +      case 5: /* explain ::= */
1.117435 +{ sqlite3BeginParse(pParse, 0); }
1.117436 +        break;
1.117437 +      case 6: /* explain ::= EXPLAIN */
1.117438 +{ sqlite3BeginParse(pParse, 1); }
1.117439 +        break;
1.117440 +      case 7: /* explain ::= EXPLAIN QUERY PLAN */
1.117441 +{ sqlite3BeginParse(pParse, 2); }
1.117442 +        break;
1.117443 +      case 8: /* cmdx ::= cmd */
1.117444 +{ sqlite3FinishCoding(pParse); }
1.117445 +        break;
1.117446 +      case 9: /* cmd ::= BEGIN transtype trans_opt */
1.117447 +{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
1.117448 +        break;
1.117449 +      case 13: /* transtype ::= */
1.117450 +{yygotominor.yy328 = TK_DEFERRED;}
1.117451 +        break;
1.117452 +      case 14: /* transtype ::= DEFERRED */
1.117453 +      case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
1.117454 +      case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
1.117455 +      case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
1.117456 +      case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
1.117457 +{yygotominor.yy328 = yymsp[0].major;}
1.117458 +        break;
1.117459 +      case 17: /* cmd ::= COMMIT trans_opt */
1.117460 +      case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
1.117461 +{sqlite3CommitTransaction(pParse);}
1.117462 +        break;
1.117463 +      case 19: /* cmd ::= ROLLBACK trans_opt */
1.117464 +{sqlite3RollbackTransaction(pParse);}
1.117465 +        break;
1.117466 +      case 22: /* cmd ::= SAVEPOINT nm */
1.117467 +{
1.117468 +  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
1.117469 +}
1.117470 +        break;
1.117471 +      case 23: /* cmd ::= RELEASE savepoint_opt nm */
1.117472 +{
1.117473 +  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
1.117474 +}
1.117475 +        break;
1.117476 +      case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
1.117477 +{
1.117478 +  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
1.117479 +}
1.117480 +        break;
1.117481 +      case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
1.117482 +{
1.117483 +   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
1.117484 +}
1.117485 +        break;
1.117486 +      case 27: /* createkw ::= CREATE */
1.117487 +{
1.117488 +  pParse->db->lookaside.bEnabled = 0;
1.117489 +  yygotominor.yy0 = yymsp[0].minor.yy0;
1.117490 +}
1.117491 +        break;
1.117492 +      case 28: /* ifnotexists ::= */
1.117493 +      case 31: /* temp ::= */ yytestcase(yyruleno==31);
1.117494 +      case 68: /* autoinc ::= */ yytestcase(yyruleno==68);
1.117495 +      case 81: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==81);
1.117496 +      case 83: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==83);
1.117497 +      case 85: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==85);
1.117498 +      case 97: /* defer_subclause_opt ::= */ yytestcase(yyruleno==97);
1.117499 +      case 108: /* ifexists ::= */ yytestcase(yyruleno==108);
1.117500 +      case 218: /* between_op ::= BETWEEN */ yytestcase(yyruleno==218);
1.117501 +      case 221: /* in_op ::= IN */ yytestcase(yyruleno==221);
1.117502 +{yygotominor.yy328 = 0;}
1.117503 +        break;
1.117504 +      case 29: /* ifnotexists ::= IF NOT EXISTS */
1.117505 +      case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
1.117506 +      case 69: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==69);
1.117507 +      case 84: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==84);
1.117508 +      case 107: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==107);
1.117509 +      case 219: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==219);
1.117510 +      case 222: /* in_op ::= NOT IN */ yytestcase(yyruleno==222);
1.117511 +{yygotominor.yy328 = 1;}
1.117512 +        break;
1.117513 +      case 32: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
1.117514 +{
1.117515 +  sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy186,0);
1.117516 +}
1.117517 +        break;
1.117518 +      case 33: /* create_table_args ::= AS select */
1.117519 +{
1.117520 +  sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy3);
1.117521 +  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
1.117522 +}
1.117523 +        break;
1.117524 +      case 34: /* table_options ::= */
1.117525 +{yygotominor.yy186 = 0;}
1.117526 +        break;
1.117527 +      case 35: /* table_options ::= WITHOUT nm */
1.117528 +{
1.117529 +  if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
1.117530 +    yygotominor.yy186 = TF_WithoutRowid;
1.117531 +  }else{
1.117532 +    yygotominor.yy186 = 0;
1.117533 +    sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
1.117534 +  }
1.117535 +}
1.117536 +        break;
1.117537 +      case 38: /* column ::= columnid type carglist */
1.117538 +{
1.117539 +  yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
1.117540 +  yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
1.117541 +}
1.117542 +        break;
1.117543 +      case 39: /* columnid ::= nm */
1.117544 +{
1.117545 +  sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
1.117546 +  yygotominor.yy0 = yymsp[0].minor.yy0;
1.117547 +  pParse->constraintName.n = 0;
1.117548 +}
1.117549 +        break;
1.117550 +      case 40: /* nm ::= ID|INDEXED */
1.117551 +      case 41: /* nm ::= STRING */ yytestcase(yyruleno==41);
1.117552 +      case 42: /* nm ::= JOIN_KW */ yytestcase(yyruleno==42);
1.117553 +      case 45: /* typetoken ::= typename */ yytestcase(yyruleno==45);
1.117554 +      case 48: /* typename ::= ID|STRING */ yytestcase(yyruleno==48);
1.117555 +      case 130: /* as ::= AS nm */ yytestcase(yyruleno==130);
1.117556 +      case 131: /* as ::= ID|STRING */ yytestcase(yyruleno==131);
1.117557 +      case 141: /* dbnm ::= DOT nm */ yytestcase(yyruleno==141);
1.117558 +      case 150: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==150);
1.117559 +      case 247: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==247);
1.117560 +      case 256: /* nmnum ::= plus_num */ yytestcase(yyruleno==256);
1.117561 +      case 257: /* nmnum ::= nm */ yytestcase(yyruleno==257);
1.117562 +      case 258: /* nmnum ::= ON */ yytestcase(yyruleno==258);
1.117563 +      case 259: /* nmnum ::= DELETE */ yytestcase(yyruleno==259);
1.117564 +      case 260: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==260);
1.117565 +      case 261: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==261);
1.117566 +      case 262: /* plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==262);
1.117567 +      case 263: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==263);
1.117568 +      case 279: /* trnm ::= nm */ yytestcase(yyruleno==279);
1.117569 +{yygotominor.yy0 = yymsp[0].minor.yy0;}
1.117570 +        break;
1.117571 +      case 44: /* type ::= typetoken */
1.117572 +{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
1.117573 +        break;
1.117574 +      case 46: /* typetoken ::= typename LP signed RP */
1.117575 +{
1.117576 +  yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
1.117577 +  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
1.117578 +}
1.117579 +        break;
1.117580 +      case 47: /* typetoken ::= typename LP signed COMMA signed RP */
1.117581 +{
1.117582 +  yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
1.117583 +  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
1.117584 +}
1.117585 +        break;
1.117586 +      case 49: /* typename ::= typename ID|STRING */
1.117587 +{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);}
1.117588 +        break;
1.117589 +      case 54: /* ccons ::= CONSTRAINT nm */
1.117590 +      case 92: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==92);
1.117591 +{pParse->constraintName = yymsp[0].minor.yy0;}
1.117592 +        break;
1.117593 +      case 55: /* ccons ::= DEFAULT term */
1.117594 +      case 57: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==57);
1.117595 +{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
1.117596 +        break;
1.117597 +      case 56: /* ccons ::= DEFAULT LP expr RP */
1.117598 +{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
1.117599 +        break;
1.117600 +      case 58: /* ccons ::= DEFAULT MINUS term */
1.117601 +{
1.117602 +  ExprSpan v;
1.117603 +  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
1.117604 +  v.zStart = yymsp[-1].minor.yy0.z;
1.117605 +  v.zEnd = yymsp[0].minor.yy346.zEnd;
1.117606 +  sqlite3AddDefaultValue(pParse,&v);
1.117607 +}
1.117608 +        break;
1.117609 +      case 59: /* ccons ::= DEFAULT ID|INDEXED */
1.117610 +{
1.117611 +  ExprSpan v;
1.117612 +  spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
1.117613 +  sqlite3AddDefaultValue(pParse,&v);
1.117614 +}
1.117615 +        break;
1.117616 +      case 61: /* ccons ::= NOT NULL onconf */
1.117617 +{sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
1.117618 +        break;
1.117619 +      case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
1.117620 +{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
1.117621 +        break;
1.117622 +      case 63: /* ccons ::= UNIQUE onconf */
1.117623 +{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
1.117624 +        break;
1.117625 +      case 64: /* ccons ::= CHECK LP expr RP */
1.117626 +{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
1.117627 +        break;
1.117628 +      case 65: /* ccons ::= REFERENCES nm idxlist_opt refargs */
1.117629 +{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
1.117630 +        break;
1.117631 +      case 66: /* ccons ::= defer_subclause */
1.117632 +{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
1.117633 +        break;
1.117634 +      case 67: /* ccons ::= COLLATE ID|STRING */
1.117635 +{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
1.117636 +        break;
1.117637 +      case 70: /* refargs ::= */
1.117638 +{ yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
1.117639 +        break;
1.117640 +      case 71: /* refargs ::= refargs refarg */
1.117641 +{ yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
1.117642 +        break;
1.117643 +      case 72: /* refarg ::= MATCH nm */
1.117644 +      case 73: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==73);
1.117645 +{ yygotominor.yy429.value = 0;     yygotominor.yy429.mask = 0x000000; }
1.117646 +        break;
1.117647 +      case 74: /* refarg ::= ON DELETE refact */
1.117648 +{ yygotominor.yy429.value = yymsp[0].minor.yy328;     yygotominor.yy429.mask = 0x0000ff; }
1.117649 +        break;
1.117650 +      case 75: /* refarg ::= ON UPDATE refact */
1.117651 +{ yygotominor.yy429.value = yymsp[0].minor.yy328<<8;  yygotominor.yy429.mask = 0x00ff00; }
1.117652 +        break;
1.117653 +      case 76: /* refact ::= SET NULL */
1.117654 +{ yygotominor.yy328 = OE_SetNull;  /* EV: R-33326-45252 */}
1.117655 +        break;
1.117656 +      case 77: /* refact ::= SET DEFAULT */
1.117657 +{ yygotominor.yy328 = OE_SetDflt;  /* EV: R-33326-45252 */}
1.117658 +        break;
1.117659 +      case 78: /* refact ::= CASCADE */
1.117660 +{ yygotominor.yy328 = OE_Cascade;  /* EV: R-33326-45252 */}
1.117661 +        break;
1.117662 +      case 79: /* refact ::= RESTRICT */
1.117663 +{ yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
1.117664 +        break;
1.117665 +      case 80: /* refact ::= NO ACTION */
1.117666 +{ yygotominor.yy328 = OE_None;     /* EV: R-33326-45252 */}
1.117667 +        break;
1.117668 +      case 82: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
1.117669 +      case 98: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==98);
1.117670 +      case 100: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==100);
1.117671 +      case 103: /* resolvetype ::= raisetype */ yytestcase(yyruleno==103);
1.117672 +{yygotominor.yy328 = yymsp[0].minor.yy328;}
1.117673 +        break;
1.117674 +      case 86: /* conslist_opt ::= */
1.117675 +{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
1.117676 +        break;
1.117677 +      case 87: /* conslist_opt ::= COMMA conslist */
1.117678 +{yygotominor.yy0 = yymsp[-1].minor.yy0;}
1.117679 +        break;
1.117680 +      case 90: /* tconscomma ::= COMMA */
1.117681 +{pParse->constraintName.n = 0;}
1.117682 +        break;
1.117683 +      case 93: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
1.117684 +{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
1.117685 +        break;
1.117686 +      case 94: /* tcons ::= UNIQUE LP idxlist RP onconf */
1.117687 +{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
1.117688 +        break;
1.117689 +      case 95: /* tcons ::= CHECK LP expr RP onconf */
1.117690 +{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
1.117691 +        break;
1.117692 +      case 96: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
1.117693 +{
1.117694 +    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
1.117695 +    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
1.117696 +}
1.117697 +        break;
1.117698 +      case 99: /* onconf ::= */
1.117699 +{yygotominor.yy328 = OE_Default;}
1.117700 +        break;
1.117701 +      case 101: /* orconf ::= */
1.117702 +{yygotominor.yy186 = OE_Default;}
1.117703 +        break;
1.117704 +      case 102: /* orconf ::= OR resolvetype */
1.117705 +{yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
1.117706 +        break;
1.117707 +      case 104: /* resolvetype ::= IGNORE */
1.117708 +{yygotominor.yy328 = OE_Ignore;}
1.117709 +        break;
1.117710 +      case 105: /* resolvetype ::= REPLACE */
1.117711 +{yygotominor.yy328 = OE_Replace;}
1.117712 +        break;
1.117713 +      case 106: /* cmd ::= DROP TABLE ifexists fullname */
1.117714 +{
1.117715 +  sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
1.117716 +}
1.117717 +        break;
1.117718 +      case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
1.117719 +{
1.117720 +  sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy3, yymsp[-6].minor.yy328, yymsp[-4].minor.yy328);
1.117721 +}
1.117722 +        break;
1.117723 +      case 110: /* cmd ::= DROP VIEW ifexists fullname */
1.117724 +{
1.117725 +  sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
1.117726 +}
1.117727 +        break;
1.117728 +      case 111: /* cmd ::= select */
1.117729 +{
1.117730 +  SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
1.117731 +  sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
1.117732 +  sqlite3ExplainBegin(pParse->pVdbe);
1.117733 +  sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy3);
1.117734 +  sqlite3ExplainFinish(pParse->pVdbe);
1.117735 +  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
1.117736 +}
1.117737 +        break;
1.117738 +      case 112: /* select ::= with selectnowith */
1.117739 +{
1.117740 +  Select *p = yymsp[0].minor.yy3, *pNext, *pLoop;
1.117741 +  if( p ){
1.117742 +    int cnt = 0, mxSelect;
1.117743 +    p->pWith = yymsp[-1].minor.yy59;
1.117744 +    if( p->pPrior ){
1.117745 +      pNext = 0;
1.117746 +      for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
1.117747 +        pLoop->pNext = pNext;
1.117748 +        pLoop->selFlags |= SF_Compound;
1.117749 +      }
1.117750 +      mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
1.117751 +      if( mxSelect && cnt>mxSelect ){
1.117752 +        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
1.117753 +      }
1.117754 +    }
1.117755 +  }else{
1.117756 +    sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy59);
1.117757 +  }
1.117758 +  yygotominor.yy3 = p;
1.117759 +}
1.117760 +        break;
1.117761 +      case 113: /* selectnowith ::= oneselect */
1.117762 +      case 119: /* oneselect ::= values */ yytestcase(yyruleno==119);
1.117763 +{yygotominor.yy3 = yymsp[0].minor.yy3;}
1.117764 +        break;
1.117765 +      case 114: /* selectnowith ::= selectnowith multiselect_op oneselect */
1.117766 +{
1.117767 +  Select *pRhs = yymsp[0].minor.yy3;
1.117768 +  if( pRhs && pRhs->pPrior ){
1.117769 +    SrcList *pFrom;
1.117770 +    Token x;
1.117771 +    x.n = 0;
1.117772 +    pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
1.117773 +    pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
1.117774 +  }
1.117775 +  if( pRhs ){
1.117776 +    pRhs->op = (u8)yymsp[-1].minor.yy328;
1.117777 +    pRhs->pPrior = yymsp[-2].minor.yy3;
1.117778 +    if( yymsp[-1].minor.yy328!=TK_ALL ) pParse->hasCompound = 1;
1.117779 +  }else{
1.117780 +    sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
1.117781 +  }
1.117782 +  yygotominor.yy3 = pRhs;
1.117783 +}
1.117784 +        break;
1.117785 +      case 116: /* multiselect_op ::= UNION ALL */
1.117786 +{yygotominor.yy328 = TK_ALL;}
1.117787 +        break;
1.117788 +      case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
1.117789 +{
1.117790 +  yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy14,yymsp[-5].minor.yy65,yymsp[-4].minor.yy132,yymsp[-3].minor.yy14,yymsp[-2].minor.yy132,yymsp[-1].minor.yy14,yymsp[-7].minor.yy381,yymsp[0].minor.yy476.pLimit,yymsp[0].minor.yy476.pOffset);
1.117791 +}
1.117792 +        break;
1.117793 +      case 120: /* values ::= VALUES LP nexprlist RP */
1.117794 +{
1.117795 +  yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
1.117796 +}
1.117797 +        break;
1.117798 +      case 121: /* values ::= values COMMA LP exprlist RP */
1.117799 +{
1.117800 +  Select *pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
1.117801 +  if( pRight ){
1.117802 +    pRight->op = TK_ALL;
1.117803 +    pRight->pPrior = yymsp[-4].minor.yy3;
1.117804 +    yygotominor.yy3 = pRight;
1.117805 +  }else{
1.117806 +    yygotominor.yy3 = yymsp[-4].minor.yy3;
1.117807 +  }
1.117808 +}
1.117809 +        break;
1.117810 +      case 122: /* distinct ::= DISTINCT */
1.117811 +{yygotominor.yy381 = SF_Distinct;}
1.117812 +        break;
1.117813 +      case 123: /* distinct ::= ALL */
1.117814 +      case 124: /* distinct ::= */ yytestcase(yyruleno==124);
1.117815 +{yygotominor.yy381 = 0;}
1.117816 +        break;
1.117817 +      case 125: /* sclp ::= selcollist COMMA */
1.117818 +      case 243: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==243);
1.117819 +{yygotominor.yy14 = yymsp[-1].minor.yy14;}
1.117820 +        break;
1.117821 +      case 126: /* sclp ::= */
1.117822 +      case 154: /* orderby_opt ::= */ yytestcase(yyruleno==154);
1.117823 +      case 161: /* groupby_opt ::= */ yytestcase(yyruleno==161);
1.117824 +      case 236: /* exprlist ::= */ yytestcase(yyruleno==236);
1.117825 +      case 242: /* idxlist_opt ::= */ yytestcase(yyruleno==242);
1.117826 +{yygotominor.yy14 = 0;}
1.117827 +        break;
1.117828 +      case 127: /* selcollist ::= sclp expr as */
1.117829 +{
1.117830 +   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
1.117831 +   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
1.117832 +   sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
1.117833 +}
1.117834 +        break;
1.117835 +      case 128: /* selcollist ::= sclp STAR */
1.117836 +{
1.117837 +  Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
1.117838 +  yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
1.117839 +}
1.117840 +        break;
1.117841 +      case 129: /* selcollist ::= sclp nm DOT STAR */
1.117842 +{
1.117843 +  Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
1.117844 +  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
1.117845 +  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
1.117846 +  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
1.117847 +}
1.117848 +        break;
1.117849 +      case 132: /* as ::= */
1.117850 +{yygotominor.yy0.n = 0;}
1.117851 +        break;
1.117852 +      case 133: /* from ::= */
1.117853 +{yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
1.117854 +        break;
1.117855 +      case 134: /* from ::= FROM seltablist */
1.117856 +{
1.117857 +  yygotominor.yy65 = yymsp[0].minor.yy65;
1.117858 +  sqlite3SrcListShiftJoinType(yygotominor.yy65);
1.117859 +}
1.117860 +        break;
1.117861 +      case 135: /* stl_prefix ::= seltablist joinop */
1.117862 +{
1.117863 +   yygotominor.yy65 = yymsp[-1].minor.yy65;
1.117864 +   if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
1.117865 +}
1.117866 +        break;
1.117867 +      case 136: /* stl_prefix ::= */
1.117868 +{yygotominor.yy65 = 0;}
1.117869 +        break;
1.117870 +      case 137: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
1.117871 +{
1.117872 +  yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
1.117873 +  sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
1.117874 +}
1.117875 +        break;
1.117876 +      case 138: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
1.117877 +{
1.117878 +    yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy3,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
1.117879 +  }
1.117880 +        break;
1.117881 +      case 139: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
1.117882 +{
1.117883 +    if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
1.117884 +      yygotominor.yy65 = yymsp[-4].minor.yy65;
1.117885 +    }else if( yymsp[-4].minor.yy65->nSrc==1 ){
1.117886 +      yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
1.117887 +      if( yygotominor.yy65 ){
1.117888 +        struct SrcList_item *pNew = &yygotominor.yy65->a[yygotominor.yy65->nSrc-1];
1.117889 +        struct SrcList_item *pOld = yymsp[-4].minor.yy65->a;
1.117890 +        pNew->zName = pOld->zName;
1.117891 +        pNew->zDatabase = pOld->zDatabase;
1.117892 +        pNew->pSelect = pOld->pSelect;
1.117893 +        pOld->zName = pOld->zDatabase = 0;
1.117894 +        pOld->pSelect = 0;
1.117895 +      }
1.117896 +      sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy65);
1.117897 +    }else{
1.117898 +      Select *pSubquery;
1.117899 +      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
1.117900 +      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,SF_NestedFrom,0,0);
1.117901 +      yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
1.117902 +    }
1.117903 +  }
1.117904 +        break;
1.117905 +      case 140: /* dbnm ::= */
1.117906 +      case 149: /* indexed_opt ::= */ yytestcase(yyruleno==149);
1.117907 +{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
1.117908 +        break;
1.117909 +      case 142: /* fullname ::= nm dbnm */
1.117910 +{yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
1.117911 +        break;
1.117912 +      case 143: /* joinop ::= COMMA|JOIN */
1.117913 +{ yygotominor.yy328 = JT_INNER; }
1.117914 +        break;
1.117915 +      case 144: /* joinop ::= JOIN_KW JOIN */
1.117916 +{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
1.117917 +        break;
1.117918 +      case 145: /* joinop ::= JOIN_KW nm JOIN */
1.117919 +{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
1.117920 +        break;
1.117921 +      case 146: /* joinop ::= JOIN_KW nm nm JOIN */
1.117922 +{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
1.117923 +        break;
1.117924 +      case 147: /* on_opt ::= ON expr */
1.117925 +      case 164: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==164);
1.117926 +      case 171: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==171);
1.117927 +      case 231: /* case_else ::= ELSE expr */ yytestcase(yyruleno==231);
1.117928 +      case 233: /* case_operand ::= expr */ yytestcase(yyruleno==233);
1.117929 +{yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
1.117930 +        break;
1.117931 +      case 148: /* on_opt ::= */
1.117932 +      case 163: /* having_opt ::= */ yytestcase(yyruleno==163);
1.117933 +      case 170: /* where_opt ::= */ yytestcase(yyruleno==170);
1.117934 +      case 232: /* case_else ::= */ yytestcase(yyruleno==232);
1.117935 +      case 234: /* case_operand ::= */ yytestcase(yyruleno==234);
1.117936 +{yygotominor.yy132 = 0;}
1.117937 +        break;
1.117938 +      case 151: /* indexed_opt ::= NOT INDEXED */
1.117939 +{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
1.117940 +        break;
1.117941 +      case 152: /* using_opt ::= USING LP idlist RP */
1.117942 +      case 180: /* inscollist_opt ::= LP idlist RP */ yytestcase(yyruleno==180);
1.117943 +{yygotominor.yy408 = yymsp[-1].minor.yy408;}
1.117944 +        break;
1.117945 +      case 153: /* using_opt ::= */
1.117946 +      case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
1.117947 +{yygotominor.yy408 = 0;}
1.117948 +        break;
1.117949 +      case 155: /* orderby_opt ::= ORDER BY sortlist */
1.117950 +      case 162: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==162);
1.117951 +      case 235: /* exprlist ::= nexprlist */ yytestcase(yyruleno==235);
1.117952 +{yygotominor.yy14 = yymsp[0].minor.yy14;}
1.117953 +        break;
1.117954 +      case 156: /* sortlist ::= sortlist COMMA expr sortorder */
1.117955 +{
1.117956 +  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy346.pExpr);
1.117957 +  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
1.117958 +}
1.117959 +        break;
1.117960 +      case 157: /* sortlist ::= expr sortorder */
1.117961 +{
1.117962 +  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy346.pExpr);
1.117963 +  if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
1.117964 +}
1.117965 +        break;
1.117966 +      case 158: /* sortorder ::= ASC */
1.117967 +      case 160: /* sortorder ::= */ yytestcase(yyruleno==160);
1.117968 +{yygotominor.yy328 = SQLITE_SO_ASC;}
1.117969 +        break;
1.117970 +      case 159: /* sortorder ::= DESC */
1.117971 +{yygotominor.yy328 = SQLITE_SO_DESC;}
1.117972 +        break;
1.117973 +      case 165: /* limit_opt ::= */
1.117974 +{yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
1.117975 +        break;
1.117976 +      case 166: /* limit_opt ::= LIMIT expr */
1.117977 +{yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
1.117978 +        break;
1.117979 +      case 167: /* limit_opt ::= LIMIT expr OFFSET expr */
1.117980 +{yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
1.117981 +        break;
1.117982 +      case 168: /* limit_opt ::= LIMIT expr COMMA expr */
1.117983 +{yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
1.117984 +        break;
1.117985 +      case 169: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
1.117986 +{
1.117987 +  sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
1.117988 +  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
1.117989 +  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
1.117990 +}
1.117991 +        break;
1.117992 +      case 172: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
1.117993 +{
1.117994 +  sqlite3WithPush(pParse, yymsp[-7].minor.yy59, 1);
1.117995 +  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
1.117996 +  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list"); 
1.117997 +  sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
1.117998 +}
1.117999 +        break;
1.118000 +      case 173: /* setlist ::= setlist COMMA nm EQ expr */
1.118001 +{
1.118002 +  yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
1.118003 +  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
1.118004 +}
1.118005 +        break;
1.118006 +      case 174: /* setlist ::= nm EQ expr */
1.118007 +{
1.118008 +  yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
1.118009 +  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
1.118010 +}
1.118011 +        break;
1.118012 +      case 175: /* cmd ::= with insert_cmd INTO fullname inscollist_opt select */
1.118013 +{
1.118014 +  sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
1.118015 +  sqlite3Insert(pParse, yymsp[-2].minor.yy65, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);
1.118016 +}
1.118017 +        break;
1.118018 +      case 176: /* cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
1.118019 +{
1.118020 +  sqlite3WithPush(pParse, yymsp[-6].minor.yy59, 1);
1.118021 +  sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);
1.118022 +}
1.118023 +        break;
1.118024 +      case 177: /* insert_cmd ::= INSERT orconf */
1.118025 +{yygotominor.yy186 = yymsp[0].minor.yy186;}
1.118026 +        break;
1.118027 +      case 178: /* insert_cmd ::= REPLACE */
1.118028 +{yygotominor.yy186 = OE_Replace;}
1.118029 +        break;
1.118030 +      case 181: /* idlist ::= idlist COMMA nm */
1.118031 +{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
1.118032 +        break;
1.118033 +      case 182: /* idlist ::= nm */
1.118034 +{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
1.118035 +        break;
1.118036 +      case 183: /* expr ::= term */
1.118037 +{yygotominor.yy346 = yymsp[0].minor.yy346;}
1.118038 +        break;
1.118039 +      case 184: /* expr ::= LP expr RP */
1.118040 +{yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
1.118041 +        break;
1.118042 +      case 185: /* term ::= NULL */
1.118043 +      case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
1.118044 +      case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
1.118045 +{spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
1.118046 +        break;
1.118047 +      case 186: /* expr ::= ID|INDEXED */
1.118048 +      case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
1.118049 +{spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
1.118050 +        break;
1.118051 +      case 188: /* expr ::= nm DOT nm */
1.118052 +{
1.118053 +  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
1.118054 +  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
1.118055 +  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
1.118056 +  spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
1.118057 +}
1.118058 +        break;
1.118059 +      case 189: /* expr ::= nm DOT nm DOT nm */
1.118060 +{
1.118061 +  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
1.118062 +  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
1.118063 +  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
1.118064 +  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
1.118065 +  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
1.118066 +  spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
1.118067 +}
1.118068 +        break;
1.118069 +      case 192: /* expr ::= VARIABLE */
1.118070 +{
1.118071 +  if( yymsp[0].minor.yy0.n>=2 && yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1]) ){
1.118072 +    /* When doing a nested parse, one can include terms in an expression
1.118073 +    ** that look like this:   #1 #2 ...  These terms refer to registers
1.118074 +    ** in the virtual machine.  #N is the N-th register. */
1.118075 +    if( pParse->nested==0 ){
1.118076 +      sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
1.118077 +      yygotominor.yy346.pExpr = 0;
1.118078 +    }else{
1.118079 +      yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
1.118080 +      if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
1.118081 +    }
1.118082 +  }else{
1.118083 +    spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
1.118084 +    sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
1.118085 +  }
1.118086 +  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
1.118087 +}
1.118088 +        break;
1.118089 +      case 193: /* expr ::= expr COLLATE ID|STRING */
1.118090 +{
1.118091 +  yygotominor.yy346.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0);
1.118092 +  yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
1.118093 +  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
1.118094 +}
1.118095 +        break;
1.118096 +      case 194: /* expr ::= CAST LP expr AS typetoken RP */
1.118097 +{
1.118098 +  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
1.118099 +  spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
1.118100 +}
1.118101 +        break;
1.118102 +      case 195: /* expr ::= ID|INDEXED LP distinct exprlist RP */
1.118103 +{
1.118104 +  if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
1.118105 +    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
1.118106 +  }
1.118107 +  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
1.118108 +  spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
1.118109 +  if( yymsp[-2].minor.yy381 && yygotominor.yy346.pExpr ){
1.118110 +    yygotominor.yy346.pExpr->flags |= EP_Distinct;
1.118111 +  }
1.118112 +}
1.118113 +        break;
1.118114 +      case 196: /* expr ::= ID|INDEXED LP STAR RP */
1.118115 +{
1.118116 +  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
1.118117 +  spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
1.118118 +}
1.118119 +        break;
1.118120 +      case 197: /* term ::= CTIME_KW */
1.118121 +{
1.118122 +  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
1.118123 +  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
1.118124 +}
1.118125 +        break;
1.118126 +      case 198: /* expr ::= expr AND expr */
1.118127 +      case 199: /* expr ::= expr OR expr */ yytestcase(yyruleno==199);
1.118128 +      case 200: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==200);
1.118129 +      case 201: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==201);
1.118130 +      case 202: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==202);
1.118131 +      case 203: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==203);
1.118132 +      case 204: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==204);
1.118133 +      case 205: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==205);
1.118134 +{spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
1.118135 +        break;
1.118136 +      case 206: /* likeop ::= LIKE_KW|MATCH */
1.118137 +{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 0;}
1.118138 +        break;
1.118139 +      case 207: /* likeop ::= NOT LIKE_KW|MATCH */
1.118140 +{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 1;}
1.118141 +        break;
1.118142 +      case 208: /* expr ::= expr likeop expr */
1.118143 +{
1.118144 +  ExprList *pList;
1.118145 +  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy346.pExpr);
1.118146 +  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy346.pExpr);
1.118147 +  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy96.eOperator);
1.118148 +  if( yymsp[-1].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
1.118149 +  yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
1.118150 +  yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
1.118151 +  if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
1.118152 +}
1.118153 +        break;
1.118154 +      case 209: /* expr ::= expr likeop expr ESCAPE expr */
1.118155 +{
1.118156 +  ExprList *pList;
1.118157 +  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
1.118158 +  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy346.pExpr);
1.118159 +  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
1.118160 +  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy96.eOperator);
1.118161 +  if( yymsp[-3].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
1.118162 +  yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
1.118163 +  yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
1.118164 +  if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
1.118165 +}
1.118166 +        break;
1.118167 +      case 210: /* expr ::= expr ISNULL|NOTNULL */
1.118168 +{spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
1.118169 +        break;
1.118170 +      case 211: /* expr ::= expr NOT NULL */
1.118171 +{spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
1.118172 +        break;
1.118173 +      case 212: /* expr ::= expr IS expr */
1.118174 +{
1.118175 +  spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
1.118176 +  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
1.118177 +}
1.118178 +        break;
1.118179 +      case 213: /* expr ::= expr IS NOT expr */
1.118180 +{
1.118181 +  spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
1.118182 +  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
1.118183 +}
1.118184 +        break;
1.118185 +      case 214: /* expr ::= NOT expr */
1.118186 +      case 215: /* expr ::= BITNOT expr */ yytestcase(yyruleno==215);
1.118187 +{spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
1.118188 +        break;
1.118189 +      case 216: /* expr ::= MINUS expr */
1.118190 +{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
1.118191 +        break;
1.118192 +      case 217: /* expr ::= PLUS expr */
1.118193 +{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
1.118194 +        break;
1.118195 +      case 220: /* expr ::= expr between_op expr AND expr */
1.118196 +{
1.118197 +  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
1.118198 +  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
1.118199 +  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
1.118200 +  if( yygotominor.yy346.pExpr ){
1.118201 +    yygotominor.yy346.pExpr->x.pList = pList;
1.118202 +  }else{
1.118203 +    sqlite3ExprListDelete(pParse->db, pList);
1.118204 +  } 
1.118205 +  if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
1.118206 +  yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
1.118207 +  yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
1.118208 +}
1.118209 +        break;
1.118210 +      case 223: /* expr ::= expr in_op LP exprlist RP */
1.118211 +{
1.118212 +    if( yymsp[-1].minor.yy14==0 ){
1.118213 +      /* Expressions of the form
1.118214 +      **
1.118215 +      **      expr1 IN ()
1.118216 +      **      expr1 NOT IN ()
1.118217 +      **
1.118218 +      ** simplify to constants 0 (false) and 1 (true), respectively,
1.118219 +      ** regardless of the value of expr1.
1.118220 +      */
1.118221 +      yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy328]);
1.118222 +      sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy346.pExpr);
1.118223 +    }else{
1.118224 +      yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
1.118225 +      if( yygotominor.yy346.pExpr ){
1.118226 +        yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
1.118227 +        sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
1.118228 +      }else{
1.118229 +        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
1.118230 +      }
1.118231 +      if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
1.118232 +    }
1.118233 +    yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
1.118234 +    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
1.118235 +  }
1.118236 +        break;
1.118237 +      case 224: /* expr ::= LP select RP */
1.118238 +{
1.118239 +    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
1.118240 +    if( yygotominor.yy346.pExpr ){
1.118241 +      yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
1.118242 +      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
1.118243 +      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
1.118244 +    }else{
1.118245 +      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
1.118246 +    }
1.118247 +    yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
1.118248 +    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
1.118249 +  }
1.118250 +        break;
1.118251 +      case 225: /* expr ::= expr in_op LP select RP */
1.118252 +{
1.118253 +    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
1.118254 +    if( yygotominor.yy346.pExpr ){
1.118255 +      yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
1.118256 +      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
1.118257 +      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
1.118258 +    }else{
1.118259 +      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
1.118260 +    }
1.118261 +    if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
1.118262 +    yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
1.118263 +    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
1.118264 +  }
1.118265 +        break;
1.118266 +      case 226: /* expr ::= expr in_op nm dbnm */
1.118267 +{
1.118268 +    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
1.118269 +    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
1.118270 +    if( yygotominor.yy346.pExpr ){
1.118271 +      yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
1.118272 +      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
1.118273 +      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
1.118274 +    }else{
1.118275 +      sqlite3SrcListDelete(pParse->db, pSrc);
1.118276 +    }
1.118277 +    if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
1.118278 +    yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
1.118279 +    yygotominor.yy346.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];
1.118280 +  }
1.118281 +        break;
1.118282 +      case 227: /* expr ::= EXISTS LP select RP */
1.118283 +{
1.118284 +    Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
1.118285 +    if( p ){
1.118286 +      p->x.pSelect = yymsp[-1].minor.yy3;
1.118287 +      ExprSetProperty(p, EP_xIsSelect);
1.118288 +      sqlite3ExprSetHeight(pParse, p);
1.118289 +    }else{
1.118290 +      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
1.118291 +    }
1.118292 +    yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
1.118293 +    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
1.118294 +  }
1.118295 +        break;
1.118296 +      case 228: /* expr ::= CASE case_operand case_exprlist case_else END */
1.118297 +{
1.118298 +  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, 0, 0);
1.118299 +  if( yygotominor.yy346.pExpr ){
1.118300 +    yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy132 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[-1].minor.yy132) : yymsp[-2].minor.yy14;
1.118301 +    sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
1.118302 +  }else{
1.118303 +    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
1.118304 +    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy132);
1.118305 +  }
1.118306 +  yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
1.118307 +  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
1.118308 +}
1.118309 +        break;
1.118310 +      case 229: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
1.118311 +{
1.118312 +  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
1.118313 +  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
1.118314 +}
1.118315 +        break;
1.118316 +      case 230: /* case_exprlist ::= WHEN expr THEN expr */
1.118317 +{
1.118318 +  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
1.118319 +  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
1.118320 +}
1.118321 +        break;
1.118322 +      case 237: /* nexprlist ::= nexprlist COMMA expr */
1.118323 +{yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
1.118324 +        break;
1.118325 +      case 238: /* nexprlist ::= expr */
1.118326 +{yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
1.118327 +        break;
1.118328 +      case 239: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
1.118329 +{
1.118330 +  sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, 
1.118331 +                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy14, yymsp[-10].minor.yy328,
1.118332 +                      &yymsp[-11].minor.yy0, yymsp[0].minor.yy132, SQLITE_SO_ASC, yymsp[-8].minor.yy328);
1.118333 +}
1.118334 +        break;
1.118335 +      case 240: /* uniqueflag ::= UNIQUE */
1.118336 +      case 291: /* raisetype ::= ABORT */ yytestcase(yyruleno==291);
1.118337 +{yygotominor.yy328 = OE_Abort;}
1.118338 +        break;
1.118339 +      case 241: /* uniqueflag ::= */
1.118340 +{yygotominor.yy328 = OE_None;}
1.118341 +        break;
1.118342 +      case 244: /* idxlist ::= idxlist COMMA nm collate sortorder */
1.118343 +{
1.118344 +  Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
1.118345 +  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
1.118346 +  sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
1.118347 +  sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
1.118348 +  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
1.118349 +}
1.118350 +        break;
1.118351 +      case 245: /* idxlist ::= nm collate sortorder */
1.118352 +{
1.118353 +  Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
1.118354 +  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
1.118355 +  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
1.118356 +  sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
1.118357 +  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
1.118358 +}
1.118359 +        break;
1.118360 +      case 246: /* collate ::= */
1.118361 +{yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
1.118362 +        break;
1.118363 +      case 248: /* cmd ::= DROP INDEX ifexists fullname */
1.118364 +{sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
1.118365 +        break;
1.118366 +      case 249: /* cmd ::= VACUUM */
1.118367 +      case 250: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==250);
1.118368 +{sqlite3Vacuum(pParse);}
1.118369 +        break;
1.118370 +      case 251: /* cmd ::= PRAGMA nm dbnm */
1.118371 +{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
1.118372 +        break;
1.118373 +      case 252: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
1.118374 +{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
1.118375 +        break;
1.118376 +      case 253: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
1.118377 +{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
1.118378 +        break;
1.118379 +      case 254: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
1.118380 +{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
1.118381 +        break;
1.118382 +      case 255: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
1.118383 +{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
1.118384 +        break;
1.118385 +      case 264: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
1.118386 +{
1.118387 +  Token all;
1.118388 +  all.z = yymsp[-3].minor.yy0.z;
1.118389 +  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
1.118390 +  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
1.118391 +}
1.118392 +        break;
1.118393 +      case 265: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
1.118394 +{
1.118395 +  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy328, yymsp[-4].minor.yy378.a, yymsp[-4].minor.yy378.b, yymsp[-2].minor.yy65, yymsp[0].minor.yy132, yymsp[-10].minor.yy328, yymsp[-8].minor.yy328);
1.118396 +  yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
1.118397 +}
1.118398 +        break;
1.118399 +      case 266: /* trigger_time ::= BEFORE */
1.118400 +      case 269: /* trigger_time ::= */ yytestcase(yyruleno==269);
1.118401 +{ yygotominor.yy328 = TK_BEFORE; }
1.118402 +        break;
1.118403 +      case 267: /* trigger_time ::= AFTER */
1.118404 +{ yygotominor.yy328 = TK_AFTER;  }
1.118405 +        break;
1.118406 +      case 268: /* trigger_time ::= INSTEAD OF */
1.118407 +{ yygotominor.yy328 = TK_INSTEAD;}
1.118408 +        break;
1.118409 +      case 270: /* trigger_event ::= DELETE|INSERT */
1.118410 +      case 271: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==271);
1.118411 +{yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
1.118412 +        break;
1.118413 +      case 272: /* trigger_event ::= UPDATE OF idlist */
1.118414 +{yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
1.118415 +        break;
1.118416 +      case 275: /* when_clause ::= */
1.118417 +      case 296: /* key_opt ::= */ yytestcase(yyruleno==296);
1.118418 +{ yygotominor.yy132 = 0; }
1.118419 +        break;
1.118420 +      case 276: /* when_clause ::= WHEN expr */
1.118421 +      case 297: /* key_opt ::= KEY expr */ yytestcase(yyruleno==297);
1.118422 +{ yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
1.118423 +        break;
1.118424 +      case 277: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
1.118425 +{
1.118426 +  assert( yymsp[-2].minor.yy473!=0 );
1.118427 +  yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
1.118428 +  yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
1.118429 +  yygotominor.yy473 = yymsp[-2].minor.yy473;
1.118430 +}
1.118431 +        break;
1.118432 +      case 278: /* trigger_cmd_list ::= trigger_cmd SEMI */
1.118433 +{ 
1.118434 +  assert( yymsp[-1].minor.yy473!=0 );
1.118435 +  yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
1.118436 +  yygotominor.yy473 = yymsp[-1].minor.yy473;
1.118437 +}
1.118438 +        break;
1.118439 +      case 280: /* trnm ::= nm DOT nm */
1.118440 +{
1.118441 +  yygotominor.yy0 = yymsp[0].minor.yy0;
1.118442 +  sqlite3ErrorMsg(pParse, 
1.118443 +        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
1.118444 +        "statements within triggers");
1.118445 +}
1.118446 +        break;
1.118447 +      case 282: /* tridxby ::= INDEXED BY nm */
1.118448 +{
1.118449 +  sqlite3ErrorMsg(pParse,
1.118450 +        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
1.118451 +        "within triggers");
1.118452 +}
1.118453 +        break;
1.118454 +      case 283: /* tridxby ::= NOT INDEXED */
1.118455 +{
1.118456 +  sqlite3ErrorMsg(pParse,
1.118457 +        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
1.118458 +        "within triggers");
1.118459 +}
1.118460 +        break;
1.118461 +      case 284: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
1.118462 +{ yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
1.118463 +        break;
1.118464 +      case 285: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
1.118465 +{yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
1.118466 +        break;
1.118467 +      case 286: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
1.118468 +{yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
1.118469 +        break;
1.118470 +      case 287: /* trigger_cmd ::= select */
1.118471 +{yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
1.118472 +        break;
1.118473 +      case 288: /* expr ::= RAISE LP IGNORE RP */
1.118474 +{
1.118475 +  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
1.118476 +  if( yygotominor.yy346.pExpr ){
1.118477 +    yygotominor.yy346.pExpr->affinity = OE_Ignore;
1.118478 +  }
1.118479 +  yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
1.118480 +  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
1.118481 +}
1.118482 +        break;
1.118483 +      case 289: /* expr ::= RAISE LP raisetype COMMA nm RP */
1.118484 +{
1.118485 +  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
1.118486 +  if( yygotominor.yy346.pExpr ) {
1.118487 +    yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
1.118488 +  }
1.118489 +  yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
1.118490 +  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
1.118491 +}
1.118492 +        break;
1.118493 +      case 290: /* raisetype ::= ROLLBACK */
1.118494 +{yygotominor.yy328 = OE_Rollback;}
1.118495 +        break;
1.118496 +      case 292: /* raisetype ::= FAIL */
1.118497 +{yygotominor.yy328 = OE_Fail;}
1.118498 +        break;
1.118499 +      case 293: /* cmd ::= DROP TRIGGER ifexists fullname */
1.118500 +{
1.118501 +  sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
1.118502 +}
1.118503 +        break;
1.118504 +      case 294: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
1.118505 +{
1.118506 +  sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
1.118507 +}
1.118508 +        break;
1.118509 +      case 295: /* cmd ::= DETACH database_kw_opt expr */
1.118510 +{
1.118511 +  sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
1.118512 +}
1.118513 +        break;
1.118514 +      case 300: /* cmd ::= REINDEX */
1.118515 +{sqlite3Reindex(pParse, 0, 0);}
1.118516 +        break;
1.118517 +      case 301: /* cmd ::= REINDEX nm dbnm */
1.118518 +{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
1.118519 +        break;
1.118520 +      case 302: /* cmd ::= ANALYZE */
1.118521 +{sqlite3Analyze(pParse, 0, 0);}
1.118522 +        break;
1.118523 +      case 303: /* cmd ::= ANALYZE nm dbnm */
1.118524 +{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
1.118525 +        break;
1.118526 +      case 304: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
1.118527 +{
1.118528 +  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
1.118529 +}
1.118530 +        break;
1.118531 +      case 305: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
1.118532 +{
1.118533 +  sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
1.118534 +}
1.118535 +        break;
1.118536 +      case 306: /* add_column_fullname ::= fullname */
1.118537 +{
1.118538 +  pParse->db->lookaside.bEnabled = 0;
1.118539 +  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
1.118540 +}
1.118541 +        break;
1.118542 +      case 309: /* cmd ::= create_vtab */
1.118543 +{sqlite3VtabFinishParse(pParse,0);}
1.118544 +        break;
1.118545 +      case 310: /* cmd ::= create_vtab LP vtabarglist RP */
1.118546 +{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
1.118547 +        break;
1.118548 +      case 311: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
1.118549 +{
1.118550 +    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy328);
1.118551 +}
1.118552 +        break;
1.118553 +      case 314: /* vtabarg ::= */
1.118554 +{sqlite3VtabArgInit(pParse);}
1.118555 +        break;
1.118556 +      case 316: /* vtabargtoken ::= ANY */
1.118557 +      case 317: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==317);
1.118558 +      case 318: /* lp ::= LP */ yytestcase(yyruleno==318);
1.118559 +{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
1.118560 +        break;
1.118561 +      case 322: /* with ::= */
1.118562 +{yygotominor.yy59 = 0;}
1.118563 +        break;
1.118564 +      case 323: /* with ::= WITH wqlist */
1.118565 +      case 324: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==324);
1.118566 +{ yygotominor.yy59 = yymsp[0].minor.yy59; }
1.118567 +        break;
1.118568 +      case 325: /* wqlist ::= nm idxlist_opt AS LP select RP */
1.118569 +{
1.118570 +  yygotominor.yy59 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
1.118571 +}
1.118572 +        break;
1.118573 +      case 326: /* wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP */
1.118574 +{
1.118575 +  yygotominor.yy59 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy59, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
1.118576 +}
1.118577 +        break;
1.118578 +      default:
1.118579 +      /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
1.118580 +      /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
1.118581 +      /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
1.118582 +      /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
1.118583 +      /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
1.118584 +      /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
1.118585 +      /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
1.118586 +      /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
1.118587 +      /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
1.118588 +      /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
1.118589 +      /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
1.118590 +      /* (36) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==36);
1.118591 +      /* (37) columnlist ::= column */ yytestcase(yyruleno==37);
1.118592 +      /* (43) type ::= */ yytestcase(yyruleno==43);
1.118593 +      /* (50) signed ::= plus_num */ yytestcase(yyruleno==50);
1.118594 +      /* (51) signed ::= minus_num */ yytestcase(yyruleno==51);
1.118595 +      /* (52) carglist ::= carglist ccons */ yytestcase(yyruleno==52);
1.118596 +      /* (53) carglist ::= */ yytestcase(yyruleno==53);
1.118597 +      /* (60) ccons ::= NULL onconf */ yytestcase(yyruleno==60);
1.118598 +      /* (88) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==88);
1.118599 +      /* (89) conslist ::= tcons */ yytestcase(yyruleno==89);
1.118600 +      /* (91) tconscomma ::= */ yytestcase(yyruleno==91);
1.118601 +      /* (273) foreach_clause ::= */ yytestcase(yyruleno==273);
1.118602 +      /* (274) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==274);
1.118603 +      /* (281) tridxby ::= */ yytestcase(yyruleno==281);
1.118604 +      /* (298) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==298);
1.118605 +      /* (299) database_kw_opt ::= */ yytestcase(yyruleno==299);
1.118606 +      /* (307) kwcolumn_opt ::= */ yytestcase(yyruleno==307);
1.118607 +      /* (308) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==308);
1.118608 +      /* (312) vtabarglist ::= vtabarg */ yytestcase(yyruleno==312);
1.118609 +      /* (313) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==313);
1.118610 +      /* (315) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==315);
1.118611 +      /* (319) anylist ::= */ yytestcase(yyruleno==319);
1.118612 +      /* (320) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==320);
1.118613 +      /* (321) anylist ::= anylist ANY */ yytestcase(yyruleno==321);
1.118614 +        break;
1.118615 +  };
1.118616 +  assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
1.118617 +  yygoto = yyRuleInfo[yyruleno].lhs;
1.118618 +  yysize = yyRuleInfo[yyruleno].nrhs;
1.118619 +  yypParser->yyidx -= yysize;
1.118620 +  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
1.118621 +  if( yyact < YYNSTATE ){
1.118622 +#ifdef NDEBUG
1.118623 +    /* If we are not debugging and the reduce action popped at least
1.118624 +    ** one element off the stack, then we can push the new element back
1.118625 +    ** onto the stack here, and skip the stack overflow test in yy_shift().
1.118626 +    ** That gives a significant speed improvement. */
1.118627 +    if( yysize ){
1.118628 +      yypParser->yyidx++;
1.118629 +      yymsp -= yysize-1;
1.118630 +      yymsp->stateno = (YYACTIONTYPE)yyact;
1.118631 +      yymsp->major = (YYCODETYPE)yygoto;
1.118632 +      yymsp->minor = yygotominor;
1.118633 +    }else
1.118634 +#endif
1.118635 +    {
1.118636 +      yy_shift(yypParser,yyact,yygoto,&yygotominor);
1.118637 +    }
1.118638 +  }else{
1.118639 +    assert( yyact == YYNSTATE + YYNRULE + 1 );
1.118640 +    yy_accept(yypParser);
1.118641 +  }
1.118642 +}
1.118643 +
1.118644 +/*
1.118645 +** The following code executes when the parse fails
1.118646 +*/
1.118647 +#ifndef YYNOERRORRECOVERY
1.118648 +static void yy_parse_failed(
1.118649 +  yyParser *yypParser           /* The parser */
1.118650 +){
1.118651 +  sqlite3ParserARG_FETCH;
1.118652 +#ifndef NDEBUG
1.118653 +  if( yyTraceFILE ){
1.118654 +    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
1.118655 +  }
1.118656 +#endif
1.118657 +  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
1.118658 +  /* Here code is inserted which will be executed whenever the
1.118659 +  ** parser fails */
1.118660 +  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
1.118661 +}
1.118662 +#endif /* YYNOERRORRECOVERY */
1.118663 +
1.118664 +/*
1.118665 +** The following code executes when a syntax error first occurs.
1.118666 +*/
1.118667 +static void yy_syntax_error(
1.118668 +  yyParser *yypParser,           /* The parser */
1.118669 +  int yymajor,                   /* The major type of the error token */
1.118670 +  YYMINORTYPE yyminor            /* The minor type of the error token */
1.118671 +){
1.118672 +  sqlite3ParserARG_FETCH;
1.118673 +#define TOKEN (yyminor.yy0)
1.118674 +
1.118675 +  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
1.118676 +  assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
1.118677 +  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
1.118678 +  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
1.118679 +}
1.118680 +
1.118681 +/*
1.118682 +** The following is executed when the parser accepts
1.118683 +*/
1.118684 +static void yy_accept(
1.118685 +  yyParser *yypParser           /* The parser */
1.118686 +){
1.118687 +  sqlite3ParserARG_FETCH;
1.118688 +#ifndef NDEBUG
1.118689 +  if( yyTraceFILE ){
1.118690 +    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
1.118691 +  }
1.118692 +#endif
1.118693 +  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
1.118694 +  /* Here code is inserted which will be executed whenever the
1.118695 +  ** parser accepts */
1.118696 +  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
1.118697 +}
1.118698 +
1.118699 +/* The main parser program.
1.118700 +** The first argument is a pointer to a structure obtained from
1.118701 +** "sqlite3ParserAlloc" which describes the current state of the parser.
1.118702 +** The second argument is the major token number.  The third is
1.118703 +** the minor token.  The fourth optional argument is whatever the
1.118704 +** user wants (and specified in the grammar) and is available for
1.118705 +** use by the action routines.
1.118706 +**
1.118707 +** Inputs:
1.118708 +** <ul>
1.118709 +** <li> A pointer to the parser (an opaque structure.)
1.118710 +** <li> The major token number.
1.118711 +** <li> The minor token number.
1.118712 +** <li> An option argument of a grammar-specified type.
1.118713 +** </ul>
1.118714 +**
1.118715 +** Outputs:
1.118716 +** None.
1.118717 +*/
1.118718 +SQLITE_PRIVATE void sqlite3Parser(
1.118719 +  void *yyp,                   /* The parser */
1.118720 +  int yymajor,                 /* The major token code number */
1.118721 +  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
1.118722 +  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
1.118723 +){
1.118724 +  YYMINORTYPE yyminorunion;
1.118725 +  int yyact;            /* The parser action. */
1.118726 +#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
1.118727 +  int yyendofinput;     /* True if we are at the end of input */
1.118728 +#endif
1.118729 +#ifdef YYERRORSYMBOL
1.118730 +  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
1.118731 +#endif
1.118732 +  yyParser *yypParser;  /* The parser */
1.118733 +
1.118734 +  /* (re)initialize the parser, if necessary */
1.118735 +  yypParser = (yyParser*)yyp;
1.118736 +  if( yypParser->yyidx<0 ){
1.118737 +#if YYSTACKDEPTH<=0
1.118738 +    if( yypParser->yystksz <=0 ){
1.118739 +      /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
1.118740 +      yyminorunion = yyzerominor;
1.118741 +      yyStackOverflow(yypParser, &yyminorunion);
1.118742 +      return;
1.118743 +    }
1.118744 +#endif
1.118745 +    yypParser->yyidx = 0;
1.118746 +    yypParser->yyerrcnt = -1;
1.118747 +    yypParser->yystack[0].stateno = 0;
1.118748 +    yypParser->yystack[0].major = 0;
1.118749 +  }
1.118750 +  yyminorunion.yy0 = yyminor;
1.118751 +#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
1.118752 +  yyendofinput = (yymajor==0);
1.118753 +#endif
1.118754 +  sqlite3ParserARG_STORE;
1.118755 +
1.118756 +#ifndef NDEBUG
1.118757 +  if( yyTraceFILE ){
1.118758 +    fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
1.118759 +  }
1.118760 +#endif
1.118761 +
1.118762 +  do{
1.118763 +    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
1.118764 +    if( yyact<YYNSTATE ){
1.118765 +      yy_shift(yypParser,yyact,yymajor,&yyminorunion);
1.118766 +      yypParser->yyerrcnt--;
1.118767 +      yymajor = YYNOCODE;
1.118768 +    }else if( yyact < YYNSTATE + YYNRULE ){
1.118769 +      yy_reduce(yypParser,yyact-YYNSTATE);
1.118770 +    }else{
1.118771 +      assert( yyact == YY_ERROR_ACTION );
1.118772 +#ifdef YYERRORSYMBOL
1.118773 +      int yymx;
1.118774 +#endif
1.118775 +#ifndef NDEBUG
1.118776 +      if( yyTraceFILE ){
1.118777 +        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
1.118778 +      }
1.118779 +#endif
1.118780 +#ifdef YYERRORSYMBOL
1.118781 +      /* A syntax error has occurred.
1.118782 +      ** The response to an error depends upon whether or not the
1.118783 +      ** grammar defines an error token "ERROR".  
1.118784 +      **
1.118785 +      ** This is what we do if the grammar does define ERROR:
1.118786 +      **
1.118787 +      **  * Call the %syntax_error function.
1.118788 +      **
1.118789 +      **  * Begin popping the stack until we enter a state where
1.118790 +      **    it is legal to shift the error symbol, then shift
1.118791 +      **    the error symbol.
1.118792 +      **
1.118793 +      **  * Set the error count to three.
1.118794 +      **
1.118795 +      **  * Begin accepting and shifting new tokens.  No new error
1.118796 +      **    processing will occur until three tokens have been
1.118797 +      **    shifted successfully.
1.118798 +      **
1.118799 +      */
1.118800 +      if( yypParser->yyerrcnt<0 ){
1.118801 +        yy_syntax_error(yypParser,yymajor,yyminorunion);
1.118802 +      }
1.118803 +      yymx = yypParser->yystack[yypParser->yyidx].major;
1.118804 +      if( yymx==YYERRORSYMBOL || yyerrorhit ){
1.118805 +#ifndef NDEBUG
1.118806 +        if( yyTraceFILE ){
1.118807 +          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
1.118808 +             yyTracePrompt,yyTokenName[yymajor]);
1.118809 +        }
1.118810 +#endif
1.118811 +        yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
1.118812 +        yymajor = YYNOCODE;
1.118813 +      }else{
1.118814 +         while(
1.118815 +          yypParser->yyidx >= 0 &&
1.118816 +          yymx != YYERRORSYMBOL &&
1.118817 +          (yyact = yy_find_reduce_action(
1.118818 +                        yypParser->yystack[yypParser->yyidx].stateno,
1.118819 +                        YYERRORSYMBOL)) >= YYNSTATE
1.118820 +        ){
1.118821 +          yy_pop_parser_stack(yypParser);
1.118822 +        }
1.118823 +        if( yypParser->yyidx < 0 || yymajor==0 ){
1.118824 +          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
1.118825 +          yy_parse_failed(yypParser);
1.118826 +          yymajor = YYNOCODE;
1.118827 +        }else if( yymx!=YYERRORSYMBOL ){
1.118828 +          YYMINORTYPE u2;
1.118829 +          u2.YYERRSYMDT = 0;
1.118830 +          yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
1.118831 +        }
1.118832 +      }
1.118833 +      yypParser->yyerrcnt = 3;
1.118834 +      yyerrorhit = 1;
1.118835 +#elif defined(YYNOERRORRECOVERY)
1.118836 +      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
1.118837 +      ** do any kind of error recovery.  Instead, simply invoke the syntax
1.118838 +      ** error routine and continue going as if nothing had happened.
1.118839 +      **
1.118840 +      ** Applications can set this macro (for example inside %include) if
1.118841 +      ** they intend to abandon the parse upon the first syntax error seen.
1.118842 +      */
1.118843 +      yy_syntax_error(yypParser,yymajor,yyminorunion);
1.118844 +      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
1.118845 +      yymajor = YYNOCODE;
1.118846 +      
1.118847 +#else  /* YYERRORSYMBOL is not defined */
1.118848 +      /* This is what we do if the grammar does not define ERROR:
1.118849 +      **
1.118850 +      **  * Report an error message, and throw away the input token.
1.118851 +      **
1.118852 +      **  * If the input token is $, then fail the parse.
1.118853 +      **
1.118854 +      ** As before, subsequent error messages are suppressed until
1.118855 +      ** three input tokens have been successfully shifted.
1.118856 +      */
1.118857 +      if( yypParser->yyerrcnt<=0 ){
1.118858 +        yy_syntax_error(yypParser,yymajor,yyminorunion);
1.118859 +      }
1.118860 +      yypParser->yyerrcnt = 3;
1.118861 +      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
1.118862 +      if( yyendofinput ){
1.118863 +        yy_parse_failed(yypParser);
1.118864 +      }
1.118865 +      yymajor = YYNOCODE;
1.118866 +#endif
1.118867 +    }
1.118868 +  }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
1.118869 +  return;
1.118870 +}
1.118871 +
1.118872 +/************** End of parse.c ***********************************************/
1.118873 +/************** Begin file tokenize.c ****************************************/
1.118874 +/*
1.118875 +** 2001 September 15
1.118876 +**
1.118877 +** The author disclaims copyright to this source code.  In place of
1.118878 +** a legal notice, here is a blessing:
1.118879 +**
1.118880 +**    May you do good and not evil.
1.118881 +**    May you find forgiveness for yourself and forgive others.
1.118882 +**    May you share freely, never taking more than you give.
1.118883 +**
1.118884 +*************************************************************************
1.118885 +** An tokenizer for SQL
1.118886 +**
1.118887 +** This file contains C code that splits an SQL input string up into
1.118888 +** individual tokens and sends those tokens one-by-one over to the
1.118889 +** parser for analysis.
1.118890 +*/
1.118891 +/* #include <stdlib.h> */
1.118892 +
1.118893 +/*
1.118894 +** The charMap() macro maps alphabetic characters into their
1.118895 +** lower-case ASCII equivalent.  On ASCII machines, this is just
1.118896 +** an upper-to-lower case map.  On EBCDIC machines we also need
1.118897 +** to adjust the encoding.  Only alphabetic characters and underscores
1.118898 +** need to be translated.
1.118899 +*/
1.118900 +#ifdef SQLITE_ASCII
1.118901 +# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
1.118902 +#endif
1.118903 +#ifdef SQLITE_EBCDIC
1.118904 +# define charMap(X) ebcdicToAscii[(unsigned char)X]
1.118905 +const unsigned char ebcdicToAscii[] = {
1.118906 +/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
1.118907 +   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
1.118908 +   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
1.118909 +   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
1.118910 +   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
1.118911 +   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
1.118912 +   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
1.118913 +   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
1.118914 +   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
1.118915 +   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
1.118916 +   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
1.118917 +   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
1.118918 +   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
1.118919 +   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
1.118920 +   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
1.118921 +   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
1.118922 +   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
1.118923 +};
1.118924 +#endif
1.118925 +
1.118926 +/*
1.118927 +** The sqlite3KeywordCode function looks up an identifier to determine if
1.118928 +** it is a keyword.  If it is a keyword, the token code of that keyword is 
1.118929 +** returned.  If the input is not a keyword, TK_ID is returned.
1.118930 +**
1.118931 +** The implementation of this routine was generated by a program,
1.118932 +** mkkeywordhash.h, located in the tool subdirectory of the distribution.
1.118933 +** The output of the mkkeywordhash.c program is written into a file
1.118934 +** named keywordhash.h and then included into this source file by
1.118935 +** the #include below.
1.118936 +*/
1.118937 +/************** Include keywordhash.h in the middle of tokenize.c ************/
1.118938 +/************** Begin file keywordhash.h *************************************/
1.118939 +/***** This file contains automatically generated code ******
1.118940 +**
1.118941 +** The code in this file has been automatically generated by
1.118942 +**
1.118943 +**   sqlite/tool/mkkeywordhash.c
1.118944 +**
1.118945 +** The code in this file implements a function that determines whether
1.118946 +** or not a given identifier is really an SQL keyword.  The same thing
1.118947 +** might be implemented more directly using a hand-written hash table.
1.118948 +** But by using this automatically generated code, the size of the code
1.118949 +** is substantially reduced.  This is important for embedded applications
1.118950 +** on platforms with limited memory.
1.118951 +*/
1.118952 +/* Hash score: 182 */
1.118953 +static int keywordCode(const char *z, int n){
1.118954 +  /* zText[] encodes 834 bytes of keywords in 554 bytes */
1.118955 +  /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
1.118956 +  /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
1.118957 +  /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
1.118958 +  /*   UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE         */
1.118959 +  /*   BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH     */
1.118960 +  /*   IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN     */
1.118961 +  /*   WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT         */
1.118962 +  /*   CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL        */
1.118963 +  /*   FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING        */
1.118964 +  /*   VACUUMVIEWINITIALLY                                                */
1.118965 +  static const char zText[553] = {
1.118966 +    'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
1.118967 +    'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
1.118968 +    'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
1.118969 +    'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
1.118970 +    'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
1.118971 +    'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
1.118972 +    'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
1.118973 +    'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
1.118974 +    'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
1.118975 +    'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
1.118976 +    'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
1.118977 +    'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
1.118978 +    'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
1.118979 +    'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
1.118980 +    'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
1.118981 +    'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
1.118982 +    'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
1.118983 +    'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
1.118984 +    'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
1.118985 +    'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
1.118986 +    'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
1.118987 +    'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
1.118988 +    'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
1.118989 +    'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
1.118990 +    'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
1.118991 +    'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
1.118992 +    'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
1.118993 +    'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
1.118994 +    'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
1.118995 +    'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
1.118996 +    'V','I','E','W','I','N','I','T','I','A','L','L','Y',
1.118997 +  };
1.118998 +  static const unsigned char aHash[127] = {
1.118999 +      76, 105, 117,  74,   0,  45,   0,   0,  82,   0,  77,   0,   0,
1.119000 +      42,  12,  78,  15,   0, 116,  85,  54, 112,   0,  19,   0,   0,
1.119001 +     121,   0, 119, 115,   0,  22,  93,   0,   9,   0,   0,  70,  71,
1.119002 +       0,  69,   6,   0,  48,  90, 102,   0, 118, 101,   0,   0,  44,
1.119003 +       0, 103,  24,   0,  17,   0, 122,  53,  23,   0,   5, 110,  25,
1.119004 +      96,   0,   0, 124, 106,  60, 123,  57,  28,  55,   0,  91,   0,
1.119005 +     100,  26,   0,  99,   0,   0,   0,  95,  92,  97,  88, 109,  14,
1.119006 +      39, 108,   0,  81,   0,  18,  89, 111,  32,   0, 120,  80, 113,
1.119007 +      62,  46,  84,   0,   0,  94,  40,  59, 114,   0,  36,   0,   0,
1.119008 +      29,   0,  86,  63,  64,   0,  20,  61,   0,  56,
1.119009 +  };
1.119010 +  static const unsigned char aNext[124] = {
1.119011 +       0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
1.119012 +       0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
1.119013 +       0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
1.119014 +       0,   0,   0,   0,  33,   0,  21,   0,   0,   0,   0,   0,  50,
1.119015 +       0,  43,   3,  47,   0,   0,   0,   0,  30,   0,  58,   0,  38,
1.119016 +       0,   0,   0,   1,  66,   0,   0,  67,   0,  41,   0,   0,   0,
1.119017 +       0,   0,   0,  49,  65,   0,   0,   0,   0,  31,  52,  16,  34,
1.119018 +      10,   0,   0,   0,   0,   0,   0,   0,  11,  72,  79,   0,   8,
1.119019 +       0, 104,  98,   0, 107,   0,  87,   0,  75,  51,   0,  27,  37,
1.119020 +      73,  83,   0,  35,  68,   0,   0,
1.119021 +  };
1.119022 +  static const unsigned char aLen[124] = {
1.119023 +       7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
1.119024 +       7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
1.119025 +      11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
1.119026 +       4,   6,   2,   3,   9,   4,   2,   6,   5,   7,   4,   5,   7,
1.119027 +       6,   6,   5,   6,   5,   5,   9,   7,   7,   3,   2,   4,   4,
1.119028 +       7,   3,   6,   4,   7,   6,  12,   6,   9,   4,   6,   5,   4,
1.119029 +       7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
1.119030 +      13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
1.119031 +       2,   4,   4,   4,   4,   4,   2,   2,   6,   5,   8,   5,   8,
1.119032 +       3,   5,   5,   6,   4,   9,   3,
1.119033 +  };
1.119034 +  static const unsigned short int aOffset[124] = {
1.119035 +       0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
1.119036 +      36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
1.119037 +      86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
1.119038 +     159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
1.119039 +     199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
1.119040 +     250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
1.119041 +     320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
1.119042 +     387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
1.119043 +     460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
1.119044 +     521, 524, 529, 534, 540, 544, 549,
1.119045 +  };
1.119046 +  static const unsigned char aCode[124] = {
1.119047 +    TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
1.119048 +    TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
1.119049 +    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
1.119050 +    TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
1.119051 +    TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
1.119052 +    TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
1.119053 +    TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
1.119054 +    TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
1.119055 +    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
1.119056 +    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_WITHOUT,    TK_WITH,       
1.119057 +    TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,     TK_HAVING,     TK_GROUP,      
1.119058 +    TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RECURSIVE,  TK_BETWEEN,    
1.119059 +    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       TK_LIKE_KW,    
1.119060 +    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       TK_COLLATE,    
1.119061 +    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  TK_JOIN,       
1.119062 +    TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,     
1.119063 +    TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      TK_WHEN,       
1.119064 +    TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    TK_AND,        
1.119065 +    TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         TK_CAST,       
1.119066 +    TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,   
1.119067 +    TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   TK_IS,         
1.119068 +    TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    TK_LIKE_KW,    
1.119069 +    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      TK_RESTRICT,   
1.119070 +    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        TK_UNION,      TK_USING,      
1.119071 +    TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  TK_ALL,        
1.119072 +  };
1.119073 +  int h, i;
1.119074 +  if( n<2 ) return TK_ID;
1.119075 +  h = ((charMap(z[0])*4) ^
1.119076 +      (charMap(z[n-1])*3) ^
1.119077 +      n) % 127;
1.119078 +  for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
1.119079 +    if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
1.119080 +      testcase( i==0 ); /* REINDEX */
1.119081 +      testcase( i==1 ); /* INDEXED */
1.119082 +      testcase( i==2 ); /* INDEX */
1.119083 +      testcase( i==3 ); /* DESC */
1.119084 +      testcase( i==4 ); /* ESCAPE */
1.119085 +      testcase( i==5 ); /* EACH */
1.119086 +      testcase( i==6 ); /* CHECK */
1.119087 +      testcase( i==7 ); /* KEY */
1.119088 +      testcase( i==8 ); /* BEFORE */
1.119089 +      testcase( i==9 ); /* FOREIGN */
1.119090 +      testcase( i==10 ); /* FOR */
1.119091 +      testcase( i==11 ); /* IGNORE */
1.119092 +      testcase( i==12 ); /* REGEXP */
1.119093 +      testcase( i==13 ); /* EXPLAIN */
1.119094 +      testcase( i==14 ); /* INSTEAD */
1.119095 +      testcase( i==15 ); /* ADD */
1.119096 +      testcase( i==16 ); /* DATABASE */
1.119097 +      testcase( i==17 ); /* AS */
1.119098 +      testcase( i==18 ); /* SELECT */
1.119099 +      testcase( i==19 ); /* TABLE */
1.119100 +      testcase( i==20 ); /* LEFT */
1.119101 +      testcase( i==21 ); /* THEN */
1.119102 +      testcase( i==22 ); /* END */
1.119103 +      testcase( i==23 ); /* DEFERRABLE */
1.119104 +      testcase( i==24 ); /* ELSE */
1.119105 +      testcase( i==25 ); /* EXCEPT */
1.119106 +      testcase( i==26 ); /* TRANSACTION */
1.119107 +      testcase( i==27 ); /* ACTION */
1.119108 +      testcase( i==28 ); /* ON */
1.119109 +      testcase( i==29 ); /* NATURAL */
1.119110 +      testcase( i==30 ); /* ALTER */
1.119111 +      testcase( i==31 ); /* RAISE */
1.119112 +      testcase( i==32 ); /* EXCLUSIVE */
1.119113 +      testcase( i==33 ); /* EXISTS */
1.119114 +      testcase( i==34 ); /* SAVEPOINT */
1.119115 +      testcase( i==35 ); /* INTERSECT */
1.119116 +      testcase( i==36 ); /* TRIGGER */
1.119117 +      testcase( i==37 ); /* REFERENCES */
1.119118 +      testcase( i==38 ); /* CONSTRAINT */
1.119119 +      testcase( i==39 ); /* INTO */
1.119120 +      testcase( i==40 ); /* OFFSET */
1.119121 +      testcase( i==41 ); /* OF */
1.119122 +      testcase( i==42 ); /* SET */
1.119123 +      testcase( i==43 ); /* TEMPORARY */
1.119124 +      testcase( i==44 ); /* TEMP */
1.119125 +      testcase( i==45 ); /* OR */
1.119126 +      testcase( i==46 ); /* UNIQUE */
1.119127 +      testcase( i==47 ); /* QUERY */
1.119128 +      testcase( i==48 ); /* WITHOUT */
1.119129 +      testcase( i==49 ); /* WITH */
1.119130 +      testcase( i==50 ); /* OUTER */
1.119131 +      testcase( i==51 ); /* RELEASE */
1.119132 +      testcase( i==52 ); /* ATTACH */
1.119133 +      testcase( i==53 ); /* HAVING */
1.119134 +      testcase( i==54 ); /* GROUP */
1.119135 +      testcase( i==55 ); /* UPDATE */
1.119136 +      testcase( i==56 ); /* BEGIN */
1.119137 +      testcase( i==57 ); /* INNER */
1.119138 +      testcase( i==58 ); /* RECURSIVE */
1.119139 +      testcase( i==59 ); /* BETWEEN */
1.119140 +      testcase( i==60 ); /* NOTNULL */
1.119141 +      testcase( i==61 ); /* NOT */
1.119142 +      testcase( i==62 ); /* NO */
1.119143 +      testcase( i==63 ); /* NULL */
1.119144 +      testcase( i==64 ); /* LIKE */
1.119145 +      testcase( i==65 ); /* CASCADE */
1.119146 +      testcase( i==66 ); /* ASC */
1.119147 +      testcase( i==67 ); /* DELETE */
1.119148 +      testcase( i==68 ); /* CASE */
1.119149 +      testcase( i==69 ); /* COLLATE */
1.119150 +      testcase( i==70 ); /* CREATE */
1.119151 +      testcase( i==71 ); /* CURRENT_DATE */
1.119152 +      testcase( i==72 ); /* DETACH */
1.119153 +      testcase( i==73 ); /* IMMEDIATE */
1.119154 +      testcase( i==74 ); /* JOIN */
1.119155 +      testcase( i==75 ); /* INSERT */
1.119156 +      testcase( i==76 ); /* MATCH */
1.119157 +      testcase( i==77 ); /* PLAN */
1.119158 +      testcase( i==78 ); /* ANALYZE */
1.119159 +      testcase( i==79 ); /* PRAGMA */
1.119160 +      testcase( i==80 ); /* ABORT */
1.119161 +      testcase( i==81 ); /* VALUES */
1.119162 +      testcase( i==82 ); /* VIRTUAL */
1.119163 +      testcase( i==83 ); /* LIMIT */
1.119164 +      testcase( i==84 ); /* WHEN */
1.119165 +      testcase( i==85 ); /* WHERE */
1.119166 +      testcase( i==86 ); /* RENAME */
1.119167 +      testcase( i==87 ); /* AFTER */
1.119168 +      testcase( i==88 ); /* REPLACE */
1.119169 +      testcase( i==89 ); /* AND */
1.119170 +      testcase( i==90 ); /* DEFAULT */
1.119171 +      testcase( i==91 ); /* AUTOINCREMENT */
1.119172 +      testcase( i==92 ); /* TO */
1.119173 +      testcase( i==93 ); /* IN */
1.119174 +      testcase( i==94 ); /* CAST */
1.119175 +      testcase( i==95 ); /* COLUMN */
1.119176 +      testcase( i==96 ); /* COMMIT */
1.119177 +      testcase( i==97 ); /* CONFLICT */
1.119178 +      testcase( i==98 ); /* CROSS */
1.119179 +      testcase( i==99 ); /* CURRENT_TIMESTAMP */
1.119180 +      testcase( i==100 ); /* CURRENT_TIME */
1.119181 +      testcase( i==101 ); /* PRIMARY */
1.119182 +      testcase( i==102 ); /* DEFERRED */
1.119183 +      testcase( i==103 ); /* DISTINCT */
1.119184 +      testcase( i==104 ); /* IS */
1.119185 +      testcase( i==105 ); /* DROP */
1.119186 +      testcase( i==106 ); /* FAIL */
1.119187 +      testcase( i==107 ); /* FROM */
1.119188 +      testcase( i==108 ); /* FULL */
1.119189 +      testcase( i==109 ); /* GLOB */
1.119190 +      testcase( i==110 ); /* BY */
1.119191 +      testcase( i==111 ); /* IF */
1.119192 +      testcase( i==112 ); /* ISNULL */
1.119193 +      testcase( i==113 ); /* ORDER */
1.119194 +      testcase( i==114 ); /* RESTRICT */
1.119195 +      testcase( i==115 ); /* RIGHT */
1.119196 +      testcase( i==116 ); /* ROLLBACK */
1.119197 +      testcase( i==117 ); /* ROW */
1.119198 +      testcase( i==118 ); /* UNION */
1.119199 +      testcase( i==119 ); /* USING */
1.119200 +      testcase( i==120 ); /* VACUUM */
1.119201 +      testcase( i==121 ); /* VIEW */
1.119202 +      testcase( i==122 ); /* INITIALLY */
1.119203 +      testcase( i==123 ); /* ALL */
1.119204 +      return aCode[i];
1.119205 +    }
1.119206 +  }
1.119207 +  return TK_ID;
1.119208 +}
1.119209 +SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
1.119210 +  return keywordCode((char*)z, n);
1.119211 +}
1.119212 +#define SQLITE_N_KEYWORD 124
1.119213 +
1.119214 +/************** End of keywordhash.h *****************************************/
1.119215 +/************** Continuing where we left off in tokenize.c *******************/
1.119216 +
1.119217 +
1.119218 +/*
1.119219 +** If X is a character that can be used in an identifier then
1.119220 +** IdChar(X) will be true.  Otherwise it is false.
1.119221 +**
1.119222 +** For ASCII, any character with the high-order bit set is
1.119223 +** allowed in an identifier.  For 7-bit characters, 
1.119224 +** sqlite3IsIdChar[X] must be 1.
1.119225 +**
1.119226 +** For EBCDIC, the rules are more complex but have the same
1.119227 +** end result.
1.119228 +**
1.119229 +** Ticket #1066.  the SQL standard does not allow '$' in the
1.119230 +** middle of identfiers.  But many SQL implementations do. 
1.119231 +** SQLite will allow '$' in identifiers for compatibility.
1.119232 +** But the feature is undocumented.
1.119233 +*/
1.119234 +#ifdef SQLITE_ASCII
1.119235 +#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
1.119236 +#endif
1.119237 +#ifdef SQLITE_EBCDIC
1.119238 +SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
1.119239 +/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
1.119240 +    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
1.119241 +    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
1.119242 +    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
1.119243 +    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
1.119244 +    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
1.119245 +    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
1.119246 +    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
1.119247 +    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
1.119248 +    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
1.119249 +    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
1.119250 +    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
1.119251 +    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
1.119252 +};
1.119253 +#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
1.119254 +#endif
1.119255 +
1.119256 +
1.119257 +/*
1.119258 +** Return the length of the token that begins at z[0]. 
1.119259 +** Store the token type in *tokenType before returning.
1.119260 +*/
1.119261 +SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
1.119262 +  int i, c;
1.119263 +  switch( *z ){
1.119264 +    case ' ': case '\t': case '\n': case '\f': case '\r': {
1.119265 +      testcase( z[0]==' ' );
1.119266 +      testcase( z[0]=='\t' );
1.119267 +      testcase( z[0]=='\n' );
1.119268 +      testcase( z[0]=='\f' );
1.119269 +      testcase( z[0]=='\r' );
1.119270 +      for(i=1; sqlite3Isspace(z[i]); i++){}
1.119271 +      *tokenType = TK_SPACE;
1.119272 +      return i;
1.119273 +    }
1.119274 +    case '-': {
1.119275 +      if( z[1]=='-' ){
1.119276 +        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
1.119277 +        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
1.119278 +        return i;
1.119279 +      }
1.119280 +      *tokenType = TK_MINUS;
1.119281 +      return 1;
1.119282 +    }
1.119283 +    case '(': {
1.119284 +      *tokenType = TK_LP;
1.119285 +      return 1;
1.119286 +    }
1.119287 +    case ')': {
1.119288 +      *tokenType = TK_RP;
1.119289 +      return 1;
1.119290 +    }
1.119291 +    case ';': {
1.119292 +      *tokenType = TK_SEMI;
1.119293 +      return 1;
1.119294 +    }
1.119295 +    case '+': {
1.119296 +      *tokenType = TK_PLUS;
1.119297 +      return 1;
1.119298 +    }
1.119299 +    case '*': {
1.119300 +      *tokenType = TK_STAR;
1.119301 +      return 1;
1.119302 +    }
1.119303 +    case '/': {
1.119304 +      if( z[1]!='*' || z[2]==0 ){
1.119305 +        *tokenType = TK_SLASH;
1.119306 +        return 1;
1.119307 +      }
1.119308 +      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
1.119309 +      if( c ) i++;
1.119310 +      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
1.119311 +      return i;
1.119312 +    }
1.119313 +    case '%': {
1.119314 +      *tokenType = TK_REM;
1.119315 +      return 1;
1.119316 +    }
1.119317 +    case '=': {
1.119318 +      *tokenType = TK_EQ;
1.119319 +      return 1 + (z[1]=='=');
1.119320 +    }
1.119321 +    case '<': {
1.119322 +      if( (c=z[1])=='=' ){
1.119323 +        *tokenType = TK_LE;
1.119324 +        return 2;
1.119325 +      }else if( c=='>' ){
1.119326 +        *tokenType = TK_NE;
1.119327 +        return 2;
1.119328 +      }else if( c=='<' ){
1.119329 +        *tokenType = TK_LSHIFT;
1.119330 +        return 2;
1.119331 +      }else{
1.119332 +        *tokenType = TK_LT;
1.119333 +        return 1;
1.119334 +      }
1.119335 +    }
1.119336 +    case '>': {
1.119337 +      if( (c=z[1])=='=' ){
1.119338 +        *tokenType = TK_GE;
1.119339 +        return 2;
1.119340 +      }else if( c=='>' ){
1.119341 +        *tokenType = TK_RSHIFT;
1.119342 +        return 2;
1.119343 +      }else{
1.119344 +        *tokenType = TK_GT;
1.119345 +        return 1;
1.119346 +      }
1.119347 +    }
1.119348 +    case '!': {
1.119349 +      if( z[1]!='=' ){
1.119350 +        *tokenType = TK_ILLEGAL;
1.119351 +        return 2;
1.119352 +      }else{
1.119353 +        *tokenType = TK_NE;
1.119354 +        return 2;
1.119355 +      }
1.119356 +    }
1.119357 +    case '|': {
1.119358 +      if( z[1]!='|' ){
1.119359 +        *tokenType = TK_BITOR;
1.119360 +        return 1;
1.119361 +      }else{
1.119362 +        *tokenType = TK_CONCAT;
1.119363 +        return 2;
1.119364 +      }
1.119365 +    }
1.119366 +    case ',': {
1.119367 +      *tokenType = TK_COMMA;
1.119368 +      return 1;
1.119369 +    }
1.119370 +    case '&': {
1.119371 +      *tokenType = TK_BITAND;
1.119372 +      return 1;
1.119373 +    }
1.119374 +    case '~': {
1.119375 +      *tokenType = TK_BITNOT;
1.119376 +      return 1;
1.119377 +    }
1.119378 +    case '`':
1.119379 +    case '\'':
1.119380 +    case '"': {
1.119381 +      int delim = z[0];
1.119382 +      testcase( delim=='`' );
1.119383 +      testcase( delim=='\'' );
1.119384 +      testcase( delim=='"' );
1.119385 +      for(i=1; (c=z[i])!=0; i++){
1.119386 +        if( c==delim ){
1.119387 +          if( z[i+1]==delim ){
1.119388 +            i++;
1.119389 +          }else{
1.119390 +            break;
1.119391 +          }
1.119392 +        }
1.119393 +      }
1.119394 +      if( c=='\'' ){
1.119395 +        *tokenType = TK_STRING;
1.119396 +        return i+1;
1.119397 +      }else if( c!=0 ){
1.119398 +        *tokenType = TK_ID;
1.119399 +        return i+1;
1.119400 +      }else{
1.119401 +        *tokenType = TK_ILLEGAL;
1.119402 +        return i;
1.119403 +      }
1.119404 +    }
1.119405 +    case '.': {
1.119406 +#ifndef SQLITE_OMIT_FLOATING_POINT
1.119407 +      if( !sqlite3Isdigit(z[1]) )
1.119408 +#endif
1.119409 +      {
1.119410 +        *tokenType = TK_DOT;
1.119411 +        return 1;
1.119412 +      }
1.119413 +      /* If the next character is a digit, this is a floating point
1.119414 +      ** number that begins with ".".  Fall thru into the next case */
1.119415 +    }
1.119416 +    case '0': case '1': case '2': case '3': case '4':
1.119417 +    case '5': case '6': case '7': case '8': case '9': {
1.119418 +      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
1.119419 +      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
1.119420 +      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
1.119421 +      testcase( z[0]=='9' );
1.119422 +      *tokenType = TK_INTEGER;
1.119423 +      for(i=0; sqlite3Isdigit(z[i]); i++){}
1.119424 +#ifndef SQLITE_OMIT_FLOATING_POINT
1.119425 +      if( z[i]=='.' ){
1.119426 +        i++;
1.119427 +        while( sqlite3Isdigit(z[i]) ){ i++; }
1.119428 +        *tokenType = TK_FLOAT;
1.119429 +      }
1.119430 +      if( (z[i]=='e' || z[i]=='E') &&
1.119431 +           ( sqlite3Isdigit(z[i+1]) 
1.119432 +            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
1.119433 +           )
1.119434 +      ){
1.119435 +        i += 2;
1.119436 +        while( sqlite3Isdigit(z[i]) ){ i++; }
1.119437 +        *tokenType = TK_FLOAT;
1.119438 +      }
1.119439 +#endif
1.119440 +      while( IdChar(z[i]) ){
1.119441 +        *tokenType = TK_ILLEGAL;
1.119442 +        i++;
1.119443 +      }
1.119444 +      return i;
1.119445 +    }
1.119446 +    case '[': {
1.119447 +      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
1.119448 +      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
1.119449 +      return i;
1.119450 +    }
1.119451 +    case '?': {
1.119452 +      *tokenType = TK_VARIABLE;
1.119453 +      for(i=1; sqlite3Isdigit(z[i]); i++){}
1.119454 +      return i;
1.119455 +    }
1.119456 +#ifndef SQLITE_OMIT_TCL_VARIABLE
1.119457 +    case '$':
1.119458 +#endif
1.119459 +    case '@':  /* For compatibility with MS SQL Server */
1.119460 +    case '#':
1.119461 +    case ':': {
1.119462 +      int n = 0;
1.119463 +      testcase( z[0]=='$' );  testcase( z[0]=='@' );
1.119464 +      testcase( z[0]==':' );  testcase( z[0]=='#' );
1.119465 +      *tokenType = TK_VARIABLE;
1.119466 +      for(i=1; (c=z[i])!=0; i++){
1.119467 +        if( IdChar(c) ){
1.119468 +          n++;
1.119469 +#ifndef SQLITE_OMIT_TCL_VARIABLE
1.119470 +        }else if( c=='(' && n>0 ){
1.119471 +          do{
1.119472 +            i++;
1.119473 +          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
1.119474 +          if( c==')' ){
1.119475 +            i++;
1.119476 +          }else{
1.119477 +            *tokenType = TK_ILLEGAL;
1.119478 +          }
1.119479 +          break;
1.119480 +        }else if( c==':' && z[i+1]==':' ){
1.119481 +          i++;
1.119482 +#endif
1.119483 +        }else{
1.119484 +          break;
1.119485 +        }
1.119486 +      }
1.119487 +      if( n==0 ) *tokenType = TK_ILLEGAL;
1.119488 +      return i;
1.119489 +    }
1.119490 +#ifndef SQLITE_OMIT_BLOB_LITERAL
1.119491 +    case 'x': case 'X': {
1.119492 +      testcase( z[0]=='x' ); testcase( z[0]=='X' );
1.119493 +      if( z[1]=='\'' ){
1.119494 +        *tokenType = TK_BLOB;
1.119495 +        for(i=2; sqlite3Isxdigit(z[i]); i++){}
1.119496 +        if( z[i]!='\'' || i%2 ){
1.119497 +          *tokenType = TK_ILLEGAL;
1.119498 +          while( z[i] && z[i]!='\'' ){ i++; }
1.119499 +        }
1.119500 +        if( z[i] ) i++;
1.119501 +        return i;
1.119502 +      }
1.119503 +      /* Otherwise fall through to the next case */
1.119504 +    }
1.119505 +#endif
1.119506 +    default: {
1.119507 +      if( !IdChar(*z) ){
1.119508 +        break;
1.119509 +      }
1.119510 +      for(i=1; IdChar(z[i]); i++){}
1.119511 +      *tokenType = keywordCode((char*)z, i);
1.119512 +      return i;
1.119513 +    }
1.119514 +  }
1.119515 +  *tokenType = TK_ILLEGAL;
1.119516 +  return 1;
1.119517 +}
1.119518 +
1.119519 +/*
1.119520 +** Run the parser on the given SQL string.  The parser structure is
1.119521 +** passed in.  An SQLITE_ status code is returned.  If an error occurs
1.119522 +** then an and attempt is made to write an error message into 
1.119523 +** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
1.119524 +** error message.
1.119525 +*/
1.119526 +SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
1.119527 +  int nErr = 0;                   /* Number of errors encountered */
1.119528 +  int i;                          /* Loop counter */
1.119529 +  void *pEngine;                  /* The LEMON-generated LALR(1) parser */
1.119530 +  int tokenType;                  /* type of the next token */
1.119531 +  int lastTokenParsed = -1;       /* type of the previous token */
1.119532 +  u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
1.119533 +  sqlite3 *db = pParse->db;       /* The database connection */
1.119534 +  int mxSqlLen;                   /* Max length of an SQL string */
1.119535 +
1.119536 +
1.119537 +  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
1.119538 +  if( db->nVdbeActive==0 ){
1.119539 +    db->u1.isInterrupted = 0;
1.119540 +  }
1.119541 +  pParse->rc = SQLITE_OK;
1.119542 +  pParse->zTail = zSql;
1.119543 +  i = 0;
1.119544 +  assert( pzErrMsg!=0 );
1.119545 +  pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
1.119546 +  if( pEngine==0 ){
1.119547 +    db->mallocFailed = 1;
1.119548 +    return SQLITE_NOMEM;
1.119549 +  }
1.119550 +  assert( pParse->pNewTable==0 );
1.119551 +  assert( pParse->pNewTrigger==0 );
1.119552 +  assert( pParse->nVar==0 );
1.119553 +  assert( pParse->nzVar==0 );
1.119554 +  assert( pParse->azVar==0 );
1.119555 +  enableLookaside = db->lookaside.bEnabled;
1.119556 +  if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
1.119557 +  while( !db->mallocFailed && zSql[i]!=0 ){
1.119558 +    assert( i>=0 );
1.119559 +    pParse->sLastToken.z = &zSql[i];
1.119560 +    pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
1.119561 +    i += pParse->sLastToken.n;
1.119562 +    if( i>mxSqlLen ){
1.119563 +      pParse->rc = SQLITE_TOOBIG;
1.119564 +      break;
1.119565 +    }
1.119566 +    switch( tokenType ){
1.119567 +      case TK_SPACE: {
1.119568 +        if( db->u1.isInterrupted ){
1.119569 +          sqlite3ErrorMsg(pParse, "interrupt");
1.119570 +          pParse->rc = SQLITE_INTERRUPT;
1.119571 +          goto abort_parse;
1.119572 +        }
1.119573 +        break;
1.119574 +      }
1.119575 +      case TK_ILLEGAL: {
1.119576 +        sqlite3DbFree(db, *pzErrMsg);
1.119577 +        *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
1.119578 +                        &pParse->sLastToken);
1.119579 +        nErr++;
1.119580 +        goto abort_parse;
1.119581 +      }
1.119582 +      case TK_SEMI: {
1.119583 +        pParse->zTail = &zSql[i];
1.119584 +        /* Fall thru into the default case */
1.119585 +      }
1.119586 +      default: {
1.119587 +        sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
1.119588 +        lastTokenParsed = tokenType;
1.119589 +        if( pParse->rc!=SQLITE_OK ){
1.119590 +          goto abort_parse;
1.119591 +        }
1.119592 +        break;
1.119593 +      }
1.119594 +    }
1.119595 +  }
1.119596 +abort_parse:
1.119597 +  if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
1.119598 +    if( lastTokenParsed!=TK_SEMI ){
1.119599 +      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
1.119600 +      pParse->zTail = &zSql[i];
1.119601 +    }
1.119602 +    sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
1.119603 +  }
1.119604 +#ifdef YYTRACKMAXSTACKDEPTH
1.119605 +  sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
1.119606 +      sqlite3ParserStackPeak(pEngine)
1.119607 +  );
1.119608 +#endif /* YYDEBUG */
1.119609 +  sqlite3ParserFree(pEngine, sqlite3_free);
1.119610 +  db->lookaside.bEnabled = enableLookaside;
1.119611 +  if( db->mallocFailed ){
1.119612 +    pParse->rc = SQLITE_NOMEM;
1.119613 +  }
1.119614 +  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
1.119615 +    sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
1.119616 +  }
1.119617 +  assert( pzErrMsg!=0 );
1.119618 +  if( pParse->zErrMsg ){
1.119619 +    *pzErrMsg = pParse->zErrMsg;
1.119620 +    sqlite3_log(pParse->rc, "%s", *pzErrMsg);
1.119621 +    pParse->zErrMsg = 0;
1.119622 +    nErr++;
1.119623 +  }
1.119624 +  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
1.119625 +    sqlite3VdbeDelete(pParse->pVdbe);
1.119626 +    pParse->pVdbe = 0;
1.119627 +  }
1.119628 +#ifndef SQLITE_OMIT_SHARED_CACHE
1.119629 +  if( pParse->nested==0 ){
1.119630 +    sqlite3DbFree(db, pParse->aTableLock);
1.119631 +    pParse->aTableLock = 0;
1.119632 +    pParse->nTableLock = 0;
1.119633 +  }
1.119634 +#endif
1.119635 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.119636 +  sqlite3_free(pParse->apVtabLock);
1.119637 +#endif
1.119638 +
1.119639 +  if( !IN_DECLARE_VTAB ){
1.119640 +    /* If the pParse->declareVtab flag is set, do not delete any table 
1.119641 +    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
1.119642 +    ** will take responsibility for freeing the Table structure.
1.119643 +    */
1.119644 +    sqlite3DeleteTable(db, pParse->pNewTable);
1.119645 +  }
1.119646 +
1.119647 +  if( pParse->bFreeWith ) sqlite3WithDelete(db, pParse->pWith);
1.119648 +  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1.119649 +  for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
1.119650 +  sqlite3DbFree(db, pParse->azVar);
1.119651 +  while( pParse->pAinc ){
1.119652 +    AutoincInfo *p = pParse->pAinc;
1.119653 +    pParse->pAinc = p->pNext;
1.119654 +    sqlite3DbFree(db, p);
1.119655 +  }
1.119656 +  while( pParse->pZombieTab ){
1.119657 +    Table *p = pParse->pZombieTab;
1.119658 +    pParse->pZombieTab = p->pNextZombie;
1.119659 +    sqlite3DeleteTable(db, p);
1.119660 +  }
1.119661 +  if( nErr>0 && pParse->rc==SQLITE_OK ){
1.119662 +    pParse->rc = SQLITE_ERROR;
1.119663 +  }
1.119664 +  return nErr;
1.119665 +}
1.119666 +
1.119667 +/************** End of tokenize.c ********************************************/
1.119668 +/************** Begin file complete.c ****************************************/
1.119669 +/*
1.119670 +** 2001 September 15
1.119671 +**
1.119672 +** The author disclaims copyright to this source code.  In place of
1.119673 +** a legal notice, here is a blessing:
1.119674 +**
1.119675 +**    May you do good and not evil.
1.119676 +**    May you find forgiveness for yourself and forgive others.
1.119677 +**    May you share freely, never taking more than you give.
1.119678 +**
1.119679 +*************************************************************************
1.119680 +** An tokenizer for SQL
1.119681 +**
1.119682 +** This file contains C code that implements the sqlite3_complete() API.
1.119683 +** This code used to be part of the tokenizer.c source file.  But by
1.119684 +** separating it out, the code will be automatically omitted from
1.119685 +** static links that do not use it.
1.119686 +*/
1.119687 +#ifndef SQLITE_OMIT_COMPLETE
1.119688 +
1.119689 +/*
1.119690 +** This is defined in tokenize.c.  We just have to import the definition.
1.119691 +*/
1.119692 +#ifndef SQLITE_AMALGAMATION
1.119693 +#ifdef SQLITE_ASCII
1.119694 +#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
1.119695 +#endif
1.119696 +#ifdef SQLITE_EBCDIC
1.119697 +SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
1.119698 +#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
1.119699 +#endif
1.119700 +#endif /* SQLITE_AMALGAMATION */
1.119701 +
1.119702 +
1.119703 +/*
1.119704 +** Token types used by the sqlite3_complete() routine.  See the header
1.119705 +** comments on that procedure for additional information.
1.119706 +*/
1.119707 +#define tkSEMI    0
1.119708 +#define tkWS      1
1.119709 +#define tkOTHER   2
1.119710 +#ifndef SQLITE_OMIT_TRIGGER
1.119711 +#define tkEXPLAIN 3
1.119712 +#define tkCREATE  4
1.119713 +#define tkTEMP    5
1.119714 +#define tkTRIGGER 6
1.119715 +#define tkEND     7
1.119716 +#endif
1.119717 +
1.119718 +/*
1.119719 +** Return TRUE if the given SQL string ends in a semicolon.
1.119720 +**
1.119721 +** Special handling is require for CREATE TRIGGER statements.
1.119722 +** Whenever the CREATE TRIGGER keywords are seen, the statement
1.119723 +** must end with ";END;".
1.119724 +**
1.119725 +** This implementation uses a state machine with 8 states:
1.119726 +**
1.119727 +**   (0) INVALID   We have not yet seen a non-whitespace character.
1.119728 +**
1.119729 +**   (1) START     At the beginning or end of an SQL statement.  This routine
1.119730 +**                 returns 1 if it ends in the START state and 0 if it ends
1.119731 +**                 in any other state.
1.119732 +**
1.119733 +**   (2) NORMAL    We are in the middle of statement which ends with a single
1.119734 +**                 semicolon.
1.119735 +**
1.119736 +**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
1.119737 +**                 a statement.
1.119738 +**
1.119739 +**   (4) CREATE    The keyword CREATE has been seen at the beginning of a
1.119740 +**                 statement, possibly preceeded by EXPLAIN and/or followed by
1.119741 +**                 TEMP or TEMPORARY
1.119742 +**
1.119743 +**   (5) TRIGGER   We are in the middle of a trigger definition that must be
1.119744 +**                 ended by a semicolon, the keyword END, and another semicolon.
1.119745 +**
1.119746 +**   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
1.119747 +**                 the end of a trigger definition.
1.119748 +**
1.119749 +**   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
1.119750 +**                 of a trigger difinition.
1.119751 +**
1.119752 +** Transitions between states above are determined by tokens extracted
1.119753 +** from the input.  The following tokens are significant:
1.119754 +**
1.119755 +**   (0) tkSEMI      A semicolon.
1.119756 +**   (1) tkWS        Whitespace.
1.119757 +**   (2) tkOTHER     Any other SQL token.
1.119758 +**   (3) tkEXPLAIN   The "explain" keyword.
1.119759 +**   (4) tkCREATE    The "create" keyword.
1.119760 +**   (5) tkTEMP      The "temp" or "temporary" keyword.
1.119761 +**   (6) tkTRIGGER   The "trigger" keyword.
1.119762 +**   (7) tkEND       The "end" keyword.
1.119763 +**
1.119764 +** Whitespace never causes a state transition and is always ignored.
1.119765 +** This means that a SQL string of all whitespace is invalid.
1.119766 +**
1.119767 +** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
1.119768 +** to recognize the end of a trigger can be omitted.  All we have to do
1.119769 +** is look for a semicolon that is not part of an string or comment.
1.119770 +*/
1.119771 +SQLITE_API int sqlite3_complete(const char *zSql){
1.119772 +  u8 state = 0;   /* Current state, using numbers defined in header comment */
1.119773 +  u8 token;       /* Value of the next token */
1.119774 +
1.119775 +#ifndef SQLITE_OMIT_TRIGGER
1.119776 +  /* A complex statement machine used to detect the end of a CREATE TRIGGER
1.119777 +  ** statement.  This is the normal case.
1.119778 +  */
1.119779 +  static const u8 trans[8][8] = {
1.119780 +                     /* Token:                                                */
1.119781 +     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
1.119782 +     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
1.119783 +     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
1.119784 +     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
1.119785 +     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
1.119786 +     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
1.119787 +     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
1.119788 +     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
1.119789 +     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
1.119790 +  };
1.119791 +#else
1.119792 +  /* If triggers are not supported by this compile then the statement machine
1.119793 +  ** used to detect the end of a statement is much simplier
1.119794 +  */
1.119795 +  static const u8 trans[3][3] = {
1.119796 +                     /* Token:           */
1.119797 +     /* State:       **  SEMI  WS  OTHER */
1.119798 +     /* 0 INVALID: */ {    1,  0,     2, },
1.119799 +     /* 1   START: */ {    1,  1,     2, },
1.119800 +     /* 2  NORMAL: */ {    1,  2,     2, },
1.119801 +  };
1.119802 +#endif /* SQLITE_OMIT_TRIGGER */
1.119803 +
1.119804 +  while( *zSql ){
1.119805 +    switch( *zSql ){
1.119806 +      case ';': {  /* A semicolon */
1.119807 +        token = tkSEMI;
1.119808 +        break;
1.119809 +      }
1.119810 +      case ' ':
1.119811 +      case '\r':
1.119812 +      case '\t':
1.119813 +      case '\n':
1.119814 +      case '\f': {  /* White space is ignored */
1.119815 +        token = tkWS;
1.119816 +        break;
1.119817 +      }
1.119818 +      case '/': {   /* C-style comments */
1.119819 +        if( zSql[1]!='*' ){
1.119820 +          token = tkOTHER;
1.119821 +          break;
1.119822 +        }
1.119823 +        zSql += 2;
1.119824 +        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
1.119825 +        if( zSql[0]==0 ) return 0;
1.119826 +        zSql++;
1.119827 +        token = tkWS;
1.119828 +        break;
1.119829 +      }
1.119830 +      case '-': {   /* SQL-style comments from "--" to end of line */
1.119831 +        if( zSql[1]!='-' ){
1.119832 +          token = tkOTHER;
1.119833 +          break;
1.119834 +        }
1.119835 +        while( *zSql && *zSql!='\n' ){ zSql++; }
1.119836 +        if( *zSql==0 ) return state==1;
1.119837 +        token = tkWS;
1.119838 +        break;
1.119839 +      }
1.119840 +      case '[': {   /* Microsoft-style identifiers in [...] */
1.119841 +        zSql++;
1.119842 +        while( *zSql && *zSql!=']' ){ zSql++; }
1.119843 +        if( *zSql==0 ) return 0;
1.119844 +        token = tkOTHER;
1.119845 +        break;
1.119846 +      }
1.119847 +      case '`':     /* Grave-accent quoted symbols used by MySQL */
1.119848 +      case '"':     /* single- and double-quoted strings */
1.119849 +      case '\'': {
1.119850 +        int c = *zSql;
1.119851 +        zSql++;
1.119852 +        while( *zSql && *zSql!=c ){ zSql++; }
1.119853 +        if( *zSql==0 ) return 0;
1.119854 +        token = tkOTHER;
1.119855 +        break;
1.119856 +      }
1.119857 +      default: {
1.119858 +#ifdef SQLITE_EBCDIC
1.119859 +        unsigned char c;
1.119860 +#endif
1.119861 +        if( IdChar((u8)*zSql) ){
1.119862 +          /* Keywords and unquoted identifiers */
1.119863 +          int nId;
1.119864 +          for(nId=1; IdChar(zSql[nId]); nId++){}
1.119865 +#ifdef SQLITE_OMIT_TRIGGER
1.119866 +          token = tkOTHER;
1.119867 +#else
1.119868 +          switch( *zSql ){
1.119869 +            case 'c': case 'C': {
1.119870 +              if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
1.119871 +                token = tkCREATE;
1.119872 +              }else{
1.119873 +                token = tkOTHER;
1.119874 +              }
1.119875 +              break;
1.119876 +            }
1.119877 +            case 't': case 'T': {
1.119878 +              if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
1.119879 +                token = tkTRIGGER;
1.119880 +              }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
1.119881 +                token = tkTEMP;
1.119882 +              }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
1.119883 +                token = tkTEMP;
1.119884 +              }else{
1.119885 +                token = tkOTHER;
1.119886 +              }
1.119887 +              break;
1.119888 +            }
1.119889 +            case 'e':  case 'E': {
1.119890 +              if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
1.119891 +                token = tkEND;
1.119892 +              }else
1.119893 +#ifndef SQLITE_OMIT_EXPLAIN
1.119894 +              if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
1.119895 +                token = tkEXPLAIN;
1.119896 +              }else
1.119897 +#endif
1.119898 +              {
1.119899 +                token = tkOTHER;
1.119900 +              }
1.119901 +              break;
1.119902 +            }
1.119903 +            default: {
1.119904 +              token = tkOTHER;
1.119905 +              break;
1.119906 +            }
1.119907 +          }
1.119908 +#endif /* SQLITE_OMIT_TRIGGER */
1.119909 +          zSql += nId-1;
1.119910 +        }else{
1.119911 +          /* Operators and special symbols */
1.119912 +          token = tkOTHER;
1.119913 +        }
1.119914 +        break;
1.119915 +      }
1.119916 +    }
1.119917 +    state = trans[state][token];
1.119918 +    zSql++;
1.119919 +  }
1.119920 +  return state==1;
1.119921 +}
1.119922 +
1.119923 +#ifndef SQLITE_OMIT_UTF16
1.119924 +/*
1.119925 +** This routine is the same as the sqlite3_complete() routine described
1.119926 +** above, except that the parameter is required to be UTF-16 encoded, not
1.119927 +** UTF-8.
1.119928 +*/
1.119929 +SQLITE_API int sqlite3_complete16(const void *zSql){
1.119930 +  sqlite3_value *pVal;
1.119931 +  char const *zSql8;
1.119932 +  int rc = SQLITE_NOMEM;
1.119933 +
1.119934 +#ifndef SQLITE_OMIT_AUTOINIT
1.119935 +  rc = sqlite3_initialize();
1.119936 +  if( rc ) return rc;
1.119937 +#endif
1.119938 +  pVal = sqlite3ValueNew(0);
1.119939 +  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
1.119940 +  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
1.119941 +  if( zSql8 ){
1.119942 +    rc = sqlite3_complete(zSql8);
1.119943 +  }else{
1.119944 +    rc = SQLITE_NOMEM;
1.119945 +  }
1.119946 +  sqlite3ValueFree(pVal);
1.119947 +  return sqlite3ApiExit(0, rc);
1.119948 +}
1.119949 +#endif /* SQLITE_OMIT_UTF16 */
1.119950 +#endif /* SQLITE_OMIT_COMPLETE */
1.119951 +
1.119952 +/************** End of complete.c ********************************************/
1.119953 +/************** Begin file main.c ********************************************/
1.119954 +/*
1.119955 +** 2001 September 15
1.119956 +**
1.119957 +** The author disclaims copyright to this source code.  In place of
1.119958 +** a legal notice, here is a blessing:
1.119959 +**
1.119960 +**    May you do good and not evil.
1.119961 +**    May you find forgiveness for yourself and forgive others.
1.119962 +**    May you share freely, never taking more than you give.
1.119963 +**
1.119964 +*************************************************************************
1.119965 +** Main file for the SQLite library.  The routines in this file
1.119966 +** implement the programmer interface to the library.  Routines in
1.119967 +** other files are for internal use by SQLite and should not be
1.119968 +** accessed by users of the library.
1.119969 +*/
1.119970 +
1.119971 +#ifdef SQLITE_ENABLE_FTS3
1.119972 +/************** Include fts3.h in the middle of main.c ***********************/
1.119973 +/************** Begin file fts3.h ********************************************/
1.119974 +/*
1.119975 +** 2006 Oct 10
1.119976 +**
1.119977 +** The author disclaims copyright to this source code.  In place of
1.119978 +** a legal notice, here is a blessing:
1.119979 +**
1.119980 +**    May you do good and not evil.
1.119981 +**    May you find forgiveness for yourself and forgive others.
1.119982 +**    May you share freely, never taking more than you give.
1.119983 +**
1.119984 +******************************************************************************
1.119985 +**
1.119986 +** This header file is used by programs that want to link against the
1.119987 +** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
1.119988 +*/
1.119989 +
1.119990 +#if 0
1.119991 +extern "C" {
1.119992 +#endif  /* __cplusplus */
1.119993 +
1.119994 +SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
1.119995 +
1.119996 +#if 0
1.119997 +}  /* extern "C" */
1.119998 +#endif  /* __cplusplus */
1.119999 +
1.120000 +/************** End of fts3.h ************************************************/
1.120001 +/************** Continuing where we left off in main.c ***********************/
1.120002 +#endif
1.120003 +#ifdef SQLITE_ENABLE_RTREE
1.120004 +/************** Include rtree.h in the middle of main.c **********************/
1.120005 +/************** Begin file rtree.h *******************************************/
1.120006 +/*
1.120007 +** 2008 May 26
1.120008 +**
1.120009 +** The author disclaims copyright to this source code.  In place of
1.120010 +** a legal notice, here is a blessing:
1.120011 +**
1.120012 +**    May you do good and not evil.
1.120013 +**    May you find forgiveness for yourself and forgive others.
1.120014 +**    May you share freely, never taking more than you give.
1.120015 +**
1.120016 +******************************************************************************
1.120017 +**
1.120018 +** This header file is used by programs that want to link against the
1.120019 +** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
1.120020 +*/
1.120021 +
1.120022 +#if 0
1.120023 +extern "C" {
1.120024 +#endif  /* __cplusplus */
1.120025 +
1.120026 +SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
1.120027 +
1.120028 +#if 0
1.120029 +}  /* extern "C" */
1.120030 +#endif  /* __cplusplus */
1.120031 +
1.120032 +/************** End of rtree.h ***********************************************/
1.120033 +/************** Continuing where we left off in main.c ***********************/
1.120034 +#endif
1.120035 +#ifdef SQLITE_ENABLE_ICU
1.120036 +/************** Include sqliteicu.h in the middle of main.c ******************/
1.120037 +/************** Begin file sqliteicu.h ***************************************/
1.120038 +/*
1.120039 +** 2008 May 26
1.120040 +**
1.120041 +** The author disclaims copyright to this source code.  In place of
1.120042 +** a legal notice, here is a blessing:
1.120043 +**
1.120044 +**    May you do good and not evil.
1.120045 +**    May you find forgiveness for yourself and forgive others.
1.120046 +**    May you share freely, never taking more than you give.
1.120047 +**
1.120048 +******************************************************************************
1.120049 +**
1.120050 +** This header file is used by programs that want to link against the
1.120051 +** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
1.120052 +*/
1.120053 +
1.120054 +#if 0
1.120055 +extern "C" {
1.120056 +#endif  /* __cplusplus */
1.120057 +
1.120058 +SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
1.120059 +
1.120060 +#if 0
1.120061 +}  /* extern "C" */
1.120062 +#endif  /* __cplusplus */
1.120063 +
1.120064 +
1.120065 +/************** End of sqliteicu.h *******************************************/
1.120066 +/************** Continuing where we left off in main.c ***********************/
1.120067 +#endif
1.120068 +
1.120069 +#ifndef SQLITE_AMALGAMATION
1.120070 +/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
1.120071 +** contains the text of SQLITE_VERSION macro. 
1.120072 +*/
1.120073 +SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
1.120074 +#endif
1.120075 +
1.120076 +/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
1.120077 +** a pointer to the to the sqlite3_version[] string constant. 
1.120078 +*/
1.120079 +SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
1.120080 +
1.120081 +/* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
1.120082 +** pointer to a string constant whose value is the same as the
1.120083 +** SQLITE_SOURCE_ID C preprocessor macro. 
1.120084 +*/
1.120085 +SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
1.120086 +
1.120087 +/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
1.120088 +** returns an integer equal to SQLITE_VERSION_NUMBER.
1.120089 +*/
1.120090 +SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
1.120091 +
1.120092 +/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
1.120093 +** zero if and only if SQLite was compiled with mutexing code omitted due to
1.120094 +** the SQLITE_THREADSAFE compile-time option being set to 0.
1.120095 +*/
1.120096 +SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
1.120097 +
1.120098 +#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
1.120099 +/*
1.120100 +** If the following function pointer is not NULL and if
1.120101 +** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
1.120102 +** I/O active are written using this function.  These messages
1.120103 +** are intended for debugging activity only.
1.120104 +*/
1.120105 +SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
1.120106 +#endif
1.120107 +
1.120108 +/*
1.120109 +** If the following global variable points to a string which is the
1.120110 +** name of a directory, then that directory will be used to store
1.120111 +** temporary files.
1.120112 +**
1.120113 +** See also the "PRAGMA temp_store_directory" SQL command.
1.120114 +*/
1.120115 +SQLITE_API char *sqlite3_temp_directory = 0;
1.120116 +
1.120117 +/*
1.120118 +** If the following global variable points to a string which is the
1.120119 +** name of a directory, then that directory will be used to store
1.120120 +** all database files specified with a relative pathname.
1.120121 +**
1.120122 +** See also the "PRAGMA data_store_directory" SQL command.
1.120123 +*/
1.120124 +SQLITE_API char *sqlite3_data_directory = 0;
1.120125 +
1.120126 +/*
1.120127 +** Initialize SQLite.  
1.120128 +**
1.120129 +** This routine must be called to initialize the memory allocation,
1.120130 +** VFS, and mutex subsystems prior to doing any serious work with
1.120131 +** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
1.120132 +** this routine will be called automatically by key routines such as
1.120133 +** sqlite3_open().  
1.120134 +**
1.120135 +** This routine is a no-op except on its very first call for the process,
1.120136 +** or for the first call after a call to sqlite3_shutdown.
1.120137 +**
1.120138 +** The first thread to call this routine runs the initialization to
1.120139 +** completion.  If subsequent threads call this routine before the first
1.120140 +** thread has finished the initialization process, then the subsequent
1.120141 +** threads must block until the first thread finishes with the initialization.
1.120142 +**
1.120143 +** The first thread might call this routine recursively.  Recursive
1.120144 +** calls to this routine should not block, of course.  Otherwise the
1.120145 +** initialization process would never complete.
1.120146 +**
1.120147 +** Let X be the first thread to enter this routine.  Let Y be some other
1.120148 +** thread.  Then while the initial invocation of this routine by X is
1.120149 +** incomplete, it is required that:
1.120150 +**
1.120151 +**    *  Calls to this routine from Y must block until the outer-most
1.120152 +**       call by X completes.
1.120153 +**
1.120154 +**    *  Recursive calls to this routine from thread X return immediately
1.120155 +**       without blocking.
1.120156 +*/
1.120157 +SQLITE_API int sqlite3_initialize(void){
1.120158 +  MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
1.120159 +  int rc;                                      /* Result code */
1.120160 +#ifdef SQLITE_EXTRA_INIT
1.120161 +  int bRunExtraInit = 0;                       /* Extra initialization needed */
1.120162 +#endif
1.120163 +
1.120164 +#ifdef SQLITE_OMIT_WSD
1.120165 +  rc = sqlite3_wsd_init(4096, 24);
1.120166 +  if( rc!=SQLITE_OK ){
1.120167 +    return rc;
1.120168 +  }
1.120169 +#endif
1.120170 +
1.120171 +  /* If SQLite is already completely initialized, then this call
1.120172 +  ** to sqlite3_initialize() should be a no-op.  But the initialization
1.120173 +  ** must be complete.  So isInit must not be set until the very end
1.120174 +  ** of this routine.
1.120175 +  */
1.120176 +  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
1.120177 +
1.120178 +  /* Make sure the mutex subsystem is initialized.  If unable to 
1.120179 +  ** initialize the mutex subsystem, return early with the error.
1.120180 +  ** If the system is so sick that we are unable to allocate a mutex,
1.120181 +  ** there is not much SQLite is going to be able to do.
1.120182 +  **
1.120183 +  ** The mutex subsystem must take care of serializing its own
1.120184 +  ** initialization.
1.120185 +  */
1.120186 +  rc = sqlite3MutexInit();
1.120187 +  if( rc ) return rc;
1.120188 +
1.120189 +  /* Initialize the malloc() system and the recursive pInitMutex mutex.
1.120190 +  ** This operation is protected by the STATIC_MASTER mutex.  Note that
1.120191 +  ** MutexAlloc() is called for a static mutex prior to initializing the
1.120192 +  ** malloc subsystem - this implies that the allocation of a static
1.120193 +  ** mutex must not require support from the malloc subsystem.
1.120194 +  */
1.120195 +  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
1.120196 +  sqlite3_mutex_enter(pMaster);
1.120197 +  sqlite3GlobalConfig.isMutexInit = 1;
1.120198 +  if( !sqlite3GlobalConfig.isMallocInit ){
1.120199 +    rc = sqlite3MallocInit();
1.120200 +  }
1.120201 +  if( rc==SQLITE_OK ){
1.120202 +    sqlite3GlobalConfig.isMallocInit = 1;
1.120203 +    if( !sqlite3GlobalConfig.pInitMutex ){
1.120204 +      sqlite3GlobalConfig.pInitMutex =
1.120205 +           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
1.120206 +      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
1.120207 +        rc = SQLITE_NOMEM;
1.120208 +      }
1.120209 +    }
1.120210 +  }
1.120211 +  if( rc==SQLITE_OK ){
1.120212 +    sqlite3GlobalConfig.nRefInitMutex++;
1.120213 +  }
1.120214 +  sqlite3_mutex_leave(pMaster);
1.120215 +
1.120216 +  /* If rc is not SQLITE_OK at this point, then either the malloc
1.120217 +  ** subsystem could not be initialized or the system failed to allocate
1.120218 +  ** the pInitMutex mutex. Return an error in either case.  */
1.120219 +  if( rc!=SQLITE_OK ){
1.120220 +    return rc;
1.120221 +  }
1.120222 +
1.120223 +  /* Do the rest of the initialization under the recursive mutex so
1.120224 +  ** that we will be able to handle recursive calls into
1.120225 +  ** sqlite3_initialize().  The recursive calls normally come through
1.120226 +  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
1.120227 +  ** recursive calls might also be possible.
1.120228 +  **
1.120229 +  ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
1.120230 +  ** to the xInit method, so the xInit method need not be threadsafe.
1.120231 +  **
1.120232 +  ** The following mutex is what serializes access to the appdef pcache xInit
1.120233 +  ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
1.120234 +  ** call to sqlite3PcacheInitialize().
1.120235 +  */
1.120236 +  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
1.120237 +  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
1.120238 +    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
1.120239 +    sqlite3GlobalConfig.inProgress = 1;
1.120240 +    memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
1.120241 +    sqlite3RegisterGlobalFunctions();
1.120242 +    if( sqlite3GlobalConfig.isPCacheInit==0 ){
1.120243 +      rc = sqlite3PcacheInitialize();
1.120244 +    }
1.120245 +    if( rc==SQLITE_OK ){
1.120246 +      sqlite3GlobalConfig.isPCacheInit = 1;
1.120247 +      rc = sqlite3OsInit();
1.120248 +    }
1.120249 +    if( rc==SQLITE_OK ){
1.120250 +      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
1.120251 +          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
1.120252 +      sqlite3GlobalConfig.isInit = 1;
1.120253 +#ifdef SQLITE_EXTRA_INIT
1.120254 +      bRunExtraInit = 1;
1.120255 +#endif
1.120256 +    }
1.120257 +    sqlite3GlobalConfig.inProgress = 0;
1.120258 +  }
1.120259 +  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
1.120260 +
1.120261 +  /* Go back under the static mutex and clean up the recursive
1.120262 +  ** mutex to prevent a resource leak.
1.120263 +  */
1.120264 +  sqlite3_mutex_enter(pMaster);
1.120265 +  sqlite3GlobalConfig.nRefInitMutex--;
1.120266 +  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
1.120267 +    assert( sqlite3GlobalConfig.nRefInitMutex==0 );
1.120268 +    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
1.120269 +    sqlite3GlobalConfig.pInitMutex = 0;
1.120270 +  }
1.120271 +  sqlite3_mutex_leave(pMaster);
1.120272 +
1.120273 +  /* The following is just a sanity check to make sure SQLite has
1.120274 +  ** been compiled correctly.  It is important to run this code, but
1.120275 +  ** we don't want to run it too often and soak up CPU cycles for no
1.120276 +  ** reason.  So we run it once during initialization.
1.120277 +  */
1.120278 +#ifndef NDEBUG
1.120279 +#ifndef SQLITE_OMIT_FLOATING_POINT
1.120280 +  /* This section of code's only "output" is via assert() statements. */
1.120281 +  if ( rc==SQLITE_OK ){
1.120282 +    u64 x = (((u64)1)<<63)-1;
1.120283 +    double y;
1.120284 +    assert(sizeof(x)==8);
1.120285 +    assert(sizeof(x)==sizeof(y));
1.120286 +    memcpy(&y, &x, 8);
1.120287 +    assert( sqlite3IsNaN(y) );
1.120288 +  }
1.120289 +#endif
1.120290 +#endif
1.120291 +
1.120292 +  /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
1.120293 +  ** compile-time option.
1.120294 +  */
1.120295 +#ifdef SQLITE_EXTRA_INIT
1.120296 +  if( bRunExtraInit ){
1.120297 +    int SQLITE_EXTRA_INIT(const char*);
1.120298 +    rc = SQLITE_EXTRA_INIT(0);
1.120299 +  }
1.120300 +#endif
1.120301 +
1.120302 +  return rc;
1.120303 +}
1.120304 +
1.120305 +/*
1.120306 +** Undo the effects of sqlite3_initialize().  Must not be called while
1.120307 +** there are outstanding database connections or memory allocations or
1.120308 +** while any part of SQLite is otherwise in use in any thread.  This
1.120309 +** routine is not threadsafe.  But it is safe to invoke this routine
1.120310 +** on when SQLite is already shut down.  If SQLite is already shut down
1.120311 +** when this routine is invoked, then this routine is a harmless no-op.
1.120312 +*/
1.120313 +SQLITE_API int sqlite3_shutdown(void){
1.120314 +  if( sqlite3GlobalConfig.isInit ){
1.120315 +#ifdef SQLITE_EXTRA_SHUTDOWN
1.120316 +    void SQLITE_EXTRA_SHUTDOWN(void);
1.120317 +    SQLITE_EXTRA_SHUTDOWN();
1.120318 +#endif
1.120319 +    sqlite3_os_end();
1.120320 +    sqlite3_reset_auto_extension();
1.120321 +    sqlite3GlobalConfig.isInit = 0;
1.120322 +  }
1.120323 +  if( sqlite3GlobalConfig.isPCacheInit ){
1.120324 +    sqlite3PcacheShutdown();
1.120325 +    sqlite3GlobalConfig.isPCacheInit = 0;
1.120326 +  }
1.120327 +  if( sqlite3GlobalConfig.isMallocInit ){
1.120328 +    sqlite3MallocEnd();
1.120329 +    sqlite3GlobalConfig.isMallocInit = 0;
1.120330 +
1.120331 +#ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
1.120332 +    /* The heap subsystem has now been shutdown and these values are supposed
1.120333 +    ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
1.120334 +    ** which would rely on that heap subsystem; therefore, make sure these
1.120335 +    ** values cannot refer to heap memory that was just invalidated when the
1.120336 +    ** heap subsystem was shutdown.  This is only done if the current call to
1.120337 +    ** this function resulted in the heap subsystem actually being shutdown.
1.120338 +    */
1.120339 +    sqlite3_data_directory = 0;
1.120340 +    sqlite3_temp_directory = 0;
1.120341 +#endif
1.120342 +  }
1.120343 +  if( sqlite3GlobalConfig.isMutexInit ){
1.120344 +    sqlite3MutexEnd();
1.120345 +    sqlite3GlobalConfig.isMutexInit = 0;
1.120346 +  }
1.120347 +
1.120348 +  return SQLITE_OK;
1.120349 +}
1.120350 +
1.120351 +/*
1.120352 +** This API allows applications to modify the global configuration of
1.120353 +** the SQLite library at run-time.
1.120354 +**
1.120355 +** This routine should only be called when there are no outstanding
1.120356 +** database connections or memory allocations.  This routine is not
1.120357 +** threadsafe.  Failure to heed these warnings can lead to unpredictable
1.120358 +** behavior.
1.120359 +*/
1.120360 +SQLITE_API int sqlite3_config(int op, ...){
1.120361 +  va_list ap;
1.120362 +  int rc = SQLITE_OK;
1.120363 +
1.120364 +  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
1.120365 +  ** the SQLite library is in use. */
1.120366 +  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
1.120367 +
1.120368 +  va_start(ap, op);
1.120369 +  switch( op ){
1.120370 +
1.120371 +    /* Mutex configuration options are only available in a threadsafe
1.120372 +    ** compile. 
1.120373 +    */
1.120374 +#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
1.120375 +    case SQLITE_CONFIG_SINGLETHREAD: {
1.120376 +      /* Disable all mutexing */
1.120377 +      sqlite3GlobalConfig.bCoreMutex = 0;
1.120378 +      sqlite3GlobalConfig.bFullMutex = 0;
1.120379 +      break;
1.120380 +    }
1.120381 +    case SQLITE_CONFIG_MULTITHREAD: {
1.120382 +      /* Disable mutexing of database connections */
1.120383 +      /* Enable mutexing of core data structures */
1.120384 +      sqlite3GlobalConfig.bCoreMutex = 1;
1.120385 +      sqlite3GlobalConfig.bFullMutex = 0;
1.120386 +      break;
1.120387 +    }
1.120388 +    case SQLITE_CONFIG_SERIALIZED: {
1.120389 +      /* Enable all mutexing */
1.120390 +      sqlite3GlobalConfig.bCoreMutex = 1;
1.120391 +      sqlite3GlobalConfig.bFullMutex = 1;
1.120392 +      break;
1.120393 +    }
1.120394 +    case SQLITE_CONFIG_MUTEX: {
1.120395 +      /* Specify an alternative mutex implementation */
1.120396 +      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
1.120397 +      break;
1.120398 +    }
1.120399 +    case SQLITE_CONFIG_GETMUTEX: {
1.120400 +      /* Retrieve the current mutex implementation */
1.120401 +      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
1.120402 +      break;
1.120403 +    }
1.120404 +#endif
1.120405 +
1.120406 +
1.120407 +    case SQLITE_CONFIG_MALLOC: {
1.120408 +      /* Specify an alternative malloc implementation */
1.120409 +      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
1.120410 +      break;
1.120411 +    }
1.120412 +    case SQLITE_CONFIG_GETMALLOC: {
1.120413 +      /* Retrieve the current malloc() implementation */
1.120414 +      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
1.120415 +      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
1.120416 +      break;
1.120417 +    }
1.120418 +    case SQLITE_CONFIG_MEMSTATUS: {
1.120419 +      /* Enable or disable the malloc status collection */
1.120420 +      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
1.120421 +      break;
1.120422 +    }
1.120423 +    case SQLITE_CONFIG_SCRATCH: {
1.120424 +      /* Designate a buffer for scratch memory space */
1.120425 +      sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
1.120426 +      sqlite3GlobalConfig.szScratch = va_arg(ap, int);
1.120427 +      sqlite3GlobalConfig.nScratch = va_arg(ap, int);
1.120428 +      break;
1.120429 +    }
1.120430 +    case SQLITE_CONFIG_PAGECACHE: {
1.120431 +      /* Designate a buffer for page cache memory space */
1.120432 +      sqlite3GlobalConfig.pPage = va_arg(ap, void*);
1.120433 +      sqlite3GlobalConfig.szPage = va_arg(ap, int);
1.120434 +      sqlite3GlobalConfig.nPage = va_arg(ap, int);
1.120435 +      break;
1.120436 +    }
1.120437 +
1.120438 +    case SQLITE_CONFIG_PCACHE: {
1.120439 +      /* no-op */
1.120440 +      break;
1.120441 +    }
1.120442 +    case SQLITE_CONFIG_GETPCACHE: {
1.120443 +      /* now an error */
1.120444 +      rc = SQLITE_ERROR;
1.120445 +      break;
1.120446 +    }
1.120447 +
1.120448 +    case SQLITE_CONFIG_PCACHE2: {
1.120449 +      /* Specify an alternative page cache implementation */
1.120450 +      sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
1.120451 +      break;
1.120452 +    }
1.120453 +    case SQLITE_CONFIG_GETPCACHE2: {
1.120454 +      if( sqlite3GlobalConfig.pcache2.xInit==0 ){
1.120455 +        sqlite3PCacheSetDefault();
1.120456 +      }
1.120457 +      *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
1.120458 +      break;
1.120459 +    }
1.120460 +
1.120461 +#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
1.120462 +    case SQLITE_CONFIG_HEAP: {
1.120463 +      /* Designate a buffer for heap memory space */
1.120464 +      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
1.120465 +      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
1.120466 +      sqlite3GlobalConfig.mnReq = va_arg(ap, int);
1.120467 +
1.120468 +      if( sqlite3GlobalConfig.mnReq<1 ){
1.120469 +        sqlite3GlobalConfig.mnReq = 1;
1.120470 +      }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
1.120471 +        /* cap min request size at 2^12 */
1.120472 +        sqlite3GlobalConfig.mnReq = (1<<12);
1.120473 +      }
1.120474 +
1.120475 +      if( sqlite3GlobalConfig.pHeap==0 ){
1.120476 +        /* If the heap pointer is NULL, then restore the malloc implementation
1.120477 +        ** back to NULL pointers too.  This will cause the malloc to go
1.120478 +        ** back to its default implementation when sqlite3_initialize() is
1.120479 +        ** run.
1.120480 +        */
1.120481 +        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
1.120482 +      }else{
1.120483 +        /* The heap pointer is not NULL, then install one of the
1.120484 +        ** mem5.c/mem3.c methods.  The enclosing #if guarantees at
1.120485 +        ** least one of these methods is currently enabled.
1.120486 +        */
1.120487 +#ifdef SQLITE_ENABLE_MEMSYS3
1.120488 +        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
1.120489 +#endif
1.120490 +#ifdef SQLITE_ENABLE_MEMSYS5
1.120491 +        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
1.120492 +#endif
1.120493 +      }
1.120494 +      break;
1.120495 +    }
1.120496 +#endif
1.120497 +
1.120498 +    case SQLITE_CONFIG_LOOKASIDE: {
1.120499 +      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
1.120500 +      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
1.120501 +      break;
1.120502 +    }
1.120503 +    
1.120504 +    /* Record a pointer to the logger function and its first argument.
1.120505 +    ** The default is NULL.  Logging is disabled if the function pointer is
1.120506 +    ** NULL.
1.120507 +    */
1.120508 +    case SQLITE_CONFIG_LOG: {
1.120509 +      /* MSVC is picky about pulling func ptrs from va lists.
1.120510 +      ** http://support.microsoft.com/kb/47961
1.120511 +      ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
1.120512 +      */
1.120513 +      typedef void(*LOGFUNC_t)(void*,int,const char*);
1.120514 +      sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
1.120515 +      sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
1.120516 +      break;
1.120517 +    }
1.120518 +
1.120519 +    case SQLITE_CONFIG_URI: {
1.120520 +      sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
1.120521 +      break;
1.120522 +    }
1.120523 +
1.120524 +    case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
1.120525 +      sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
1.120526 +      break;
1.120527 +    }
1.120528 +
1.120529 +#ifdef SQLITE_ENABLE_SQLLOG
1.120530 +    case SQLITE_CONFIG_SQLLOG: {
1.120531 +      typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
1.120532 +      sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
1.120533 +      sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
1.120534 +      break;
1.120535 +    }
1.120536 +#endif
1.120537 +
1.120538 +    case SQLITE_CONFIG_MMAP_SIZE: {
1.120539 +      sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
1.120540 +      sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
1.120541 +      if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
1.120542 +        mxMmap = SQLITE_MAX_MMAP_SIZE;
1.120543 +      }
1.120544 +      sqlite3GlobalConfig.mxMmap = mxMmap;
1.120545 +      if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
1.120546 +      if( szMmap>mxMmap) szMmap = mxMmap;
1.120547 +      sqlite3GlobalConfig.szMmap = szMmap;
1.120548 +      break;
1.120549 +    }
1.120550 +
1.120551 +#if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC)
1.120552 +    case SQLITE_CONFIG_WIN32_HEAPSIZE: {
1.120553 +      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
1.120554 +      break;
1.120555 +    }
1.120556 +#endif
1.120557 +
1.120558 +    default: {
1.120559 +      rc = SQLITE_ERROR;
1.120560 +      break;
1.120561 +    }
1.120562 +  }
1.120563 +  va_end(ap);
1.120564 +  return rc;
1.120565 +}
1.120566 +
1.120567 +/*
1.120568 +** Set up the lookaside buffers for a database connection.
1.120569 +** Return SQLITE_OK on success.  
1.120570 +** If lookaside is already active, return SQLITE_BUSY.
1.120571 +**
1.120572 +** The sz parameter is the number of bytes in each lookaside slot.
1.120573 +** The cnt parameter is the number of slots.  If pStart is NULL the
1.120574 +** space for the lookaside memory is obtained from sqlite3_malloc().
1.120575 +** If pStart is not NULL then it is sz*cnt bytes of memory to use for
1.120576 +** the lookaside memory.
1.120577 +*/
1.120578 +static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
1.120579 +  void *pStart;
1.120580 +  if( db->lookaside.nOut ){
1.120581 +    return SQLITE_BUSY;
1.120582 +  }
1.120583 +  /* Free any existing lookaside buffer for this handle before
1.120584 +  ** allocating a new one so we don't have to have space for 
1.120585 +  ** both at the same time.
1.120586 +  */
1.120587 +  if( db->lookaside.bMalloced ){
1.120588 +    sqlite3_free(db->lookaside.pStart);
1.120589 +  }
1.120590 +  /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
1.120591 +  ** than a pointer to be useful.
1.120592 +  */
1.120593 +  sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
1.120594 +  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
1.120595 +  if( cnt<0 ) cnt = 0;
1.120596 +  if( sz==0 || cnt==0 ){
1.120597 +    sz = 0;
1.120598 +    pStart = 0;
1.120599 +  }else if( pBuf==0 ){
1.120600 +    sqlite3BeginBenignMalloc();
1.120601 +    pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
1.120602 +    sqlite3EndBenignMalloc();
1.120603 +    if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
1.120604 +  }else{
1.120605 +    pStart = pBuf;
1.120606 +  }
1.120607 +  db->lookaside.pStart = pStart;
1.120608 +  db->lookaside.pFree = 0;
1.120609 +  db->lookaside.sz = (u16)sz;
1.120610 +  if( pStart ){
1.120611 +    int i;
1.120612 +    LookasideSlot *p;
1.120613 +    assert( sz > (int)sizeof(LookasideSlot*) );
1.120614 +    p = (LookasideSlot*)pStart;
1.120615 +    for(i=cnt-1; i>=0; i--){
1.120616 +      p->pNext = db->lookaside.pFree;
1.120617 +      db->lookaside.pFree = p;
1.120618 +      p = (LookasideSlot*)&((u8*)p)[sz];
1.120619 +    }
1.120620 +    db->lookaside.pEnd = p;
1.120621 +    db->lookaside.bEnabled = 1;
1.120622 +    db->lookaside.bMalloced = pBuf==0 ?1:0;
1.120623 +  }else{
1.120624 +    db->lookaside.pStart = db;
1.120625 +    db->lookaside.pEnd = db;
1.120626 +    db->lookaside.bEnabled = 0;
1.120627 +    db->lookaside.bMalloced = 0;
1.120628 +  }
1.120629 +  return SQLITE_OK;
1.120630 +}
1.120631 +
1.120632 +/*
1.120633 +** Return the mutex associated with a database connection.
1.120634 +*/
1.120635 +SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
1.120636 +  return db->mutex;
1.120637 +}
1.120638 +
1.120639 +/*
1.120640 +** Free up as much memory as we can from the given database
1.120641 +** connection.
1.120642 +*/
1.120643 +SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
1.120644 +  int i;
1.120645 +  sqlite3_mutex_enter(db->mutex);
1.120646 +  sqlite3BtreeEnterAll(db);
1.120647 +  for(i=0; i<db->nDb; i++){
1.120648 +    Btree *pBt = db->aDb[i].pBt;
1.120649 +    if( pBt ){
1.120650 +      Pager *pPager = sqlite3BtreePager(pBt);
1.120651 +      sqlite3PagerShrink(pPager);
1.120652 +    }
1.120653 +  }
1.120654 +  sqlite3BtreeLeaveAll(db);
1.120655 +  sqlite3_mutex_leave(db->mutex);
1.120656 +  return SQLITE_OK;
1.120657 +}
1.120658 +
1.120659 +/*
1.120660 +** Configuration settings for an individual database connection
1.120661 +*/
1.120662 +SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
1.120663 +  va_list ap;
1.120664 +  int rc;
1.120665 +  va_start(ap, op);
1.120666 +  switch( op ){
1.120667 +    case SQLITE_DBCONFIG_LOOKASIDE: {
1.120668 +      void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
1.120669 +      int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
1.120670 +      int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
1.120671 +      rc = setupLookaside(db, pBuf, sz, cnt);
1.120672 +      break;
1.120673 +    }
1.120674 +    default: {
1.120675 +      static const struct {
1.120676 +        int op;      /* The opcode */
1.120677 +        u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
1.120678 +      } aFlagOp[] = {
1.120679 +        { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
1.120680 +        { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
1.120681 +      };
1.120682 +      unsigned int i;
1.120683 +      rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
1.120684 +      for(i=0; i<ArraySize(aFlagOp); i++){
1.120685 +        if( aFlagOp[i].op==op ){
1.120686 +          int onoff = va_arg(ap, int);
1.120687 +          int *pRes = va_arg(ap, int*);
1.120688 +          int oldFlags = db->flags;
1.120689 +          if( onoff>0 ){
1.120690 +            db->flags |= aFlagOp[i].mask;
1.120691 +          }else if( onoff==0 ){
1.120692 +            db->flags &= ~aFlagOp[i].mask;
1.120693 +          }
1.120694 +          if( oldFlags!=db->flags ){
1.120695 +            sqlite3ExpirePreparedStatements(db);
1.120696 +          }
1.120697 +          if( pRes ){
1.120698 +            *pRes = (db->flags & aFlagOp[i].mask)!=0;
1.120699 +          }
1.120700 +          rc = SQLITE_OK;
1.120701 +          break;
1.120702 +        }
1.120703 +      }
1.120704 +      break;
1.120705 +    }
1.120706 +  }
1.120707 +  va_end(ap);
1.120708 +  return rc;
1.120709 +}
1.120710 +
1.120711 +
1.120712 +/*
1.120713 +** Return true if the buffer z[0..n-1] contains all spaces.
1.120714 +*/
1.120715 +static int allSpaces(const char *z, int n){
1.120716 +  while( n>0 && z[n-1]==' ' ){ n--; }
1.120717 +  return n==0;
1.120718 +}
1.120719 +
1.120720 +/*
1.120721 +** This is the default collating function named "BINARY" which is always
1.120722 +** available.
1.120723 +**
1.120724 +** If the padFlag argument is not NULL then space padding at the end
1.120725 +** of strings is ignored.  This implements the RTRIM collation.
1.120726 +*/
1.120727 +static int binCollFunc(
1.120728 +  void *padFlag,
1.120729 +  int nKey1, const void *pKey1,
1.120730 +  int nKey2, const void *pKey2
1.120731 +){
1.120732 +  int rc, n;
1.120733 +  n = nKey1<nKey2 ? nKey1 : nKey2;
1.120734 +  rc = memcmp(pKey1, pKey2, n);
1.120735 +  if( rc==0 ){
1.120736 +    if( padFlag
1.120737 +     && allSpaces(((char*)pKey1)+n, nKey1-n)
1.120738 +     && allSpaces(((char*)pKey2)+n, nKey2-n)
1.120739 +    ){
1.120740 +      /* Leave rc unchanged at 0 */
1.120741 +    }else{
1.120742 +      rc = nKey1 - nKey2;
1.120743 +    }
1.120744 +  }
1.120745 +  return rc;
1.120746 +}
1.120747 +
1.120748 +/*
1.120749 +** Another built-in collating sequence: NOCASE. 
1.120750 +**
1.120751 +** This collating sequence is intended to be used for "case independent
1.120752 +** comparison". SQLite's knowledge of upper and lower case equivalents
1.120753 +** extends only to the 26 characters used in the English language.
1.120754 +**
1.120755 +** At the moment there is only a UTF-8 implementation.
1.120756 +*/
1.120757 +static int nocaseCollatingFunc(
1.120758 +  void *NotUsed,
1.120759 +  int nKey1, const void *pKey1,
1.120760 +  int nKey2, const void *pKey2
1.120761 +){
1.120762 +  int r = sqlite3StrNICmp(
1.120763 +      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
1.120764 +  UNUSED_PARAMETER(NotUsed);
1.120765 +  if( 0==r ){
1.120766 +    r = nKey1-nKey2;
1.120767 +  }
1.120768 +  return r;
1.120769 +}
1.120770 +
1.120771 +/*
1.120772 +** Return the ROWID of the most recent insert
1.120773 +*/
1.120774 +SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
1.120775 +  return db->lastRowid;
1.120776 +}
1.120777 +
1.120778 +/*
1.120779 +** Return the number of changes in the most recent call to sqlite3_exec().
1.120780 +*/
1.120781 +SQLITE_API int sqlite3_changes(sqlite3 *db){
1.120782 +  return db->nChange;
1.120783 +}
1.120784 +
1.120785 +/*
1.120786 +** Return the number of changes since the database handle was opened.
1.120787 +*/
1.120788 +SQLITE_API int sqlite3_total_changes(sqlite3 *db){
1.120789 +  return db->nTotalChange;
1.120790 +}
1.120791 +
1.120792 +/*
1.120793 +** Close all open savepoints. This function only manipulates fields of the
1.120794 +** database handle object, it does not close any savepoints that may be open
1.120795 +** at the b-tree/pager level.
1.120796 +*/
1.120797 +SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
1.120798 +  while( db->pSavepoint ){
1.120799 +    Savepoint *pTmp = db->pSavepoint;
1.120800 +    db->pSavepoint = pTmp->pNext;
1.120801 +    sqlite3DbFree(db, pTmp);
1.120802 +  }
1.120803 +  db->nSavepoint = 0;
1.120804 +  db->nStatement = 0;
1.120805 +  db->isTransactionSavepoint = 0;
1.120806 +}
1.120807 +
1.120808 +/*
1.120809 +** Invoke the destructor function associated with FuncDef p, if any. Except,
1.120810 +** if this is not the last copy of the function, do not invoke it. Multiple
1.120811 +** copies of a single function are created when create_function() is called
1.120812 +** with SQLITE_ANY as the encoding.
1.120813 +*/
1.120814 +static void functionDestroy(sqlite3 *db, FuncDef *p){
1.120815 +  FuncDestructor *pDestructor = p->pDestructor;
1.120816 +  if( pDestructor ){
1.120817 +    pDestructor->nRef--;
1.120818 +    if( pDestructor->nRef==0 ){
1.120819 +      pDestructor->xDestroy(pDestructor->pUserData);
1.120820 +      sqlite3DbFree(db, pDestructor);
1.120821 +    }
1.120822 +  }
1.120823 +}
1.120824 +
1.120825 +/*
1.120826 +** Disconnect all sqlite3_vtab objects that belong to database connection
1.120827 +** db. This is called when db is being closed.
1.120828 +*/
1.120829 +static void disconnectAllVtab(sqlite3 *db){
1.120830 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.120831 +  int i;
1.120832 +  sqlite3BtreeEnterAll(db);
1.120833 +  for(i=0; i<db->nDb; i++){
1.120834 +    Schema *pSchema = db->aDb[i].pSchema;
1.120835 +    if( db->aDb[i].pSchema ){
1.120836 +      HashElem *p;
1.120837 +      for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
1.120838 +        Table *pTab = (Table *)sqliteHashData(p);
1.120839 +        if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
1.120840 +      }
1.120841 +    }
1.120842 +  }
1.120843 +  sqlite3BtreeLeaveAll(db);
1.120844 +#else
1.120845 +  UNUSED_PARAMETER(db);
1.120846 +#endif
1.120847 +}
1.120848 +
1.120849 +/*
1.120850 +** Return TRUE if database connection db has unfinalized prepared
1.120851 +** statements or unfinished sqlite3_backup objects.  
1.120852 +*/
1.120853 +static int connectionIsBusy(sqlite3 *db){
1.120854 +  int j;
1.120855 +  assert( sqlite3_mutex_held(db->mutex) );
1.120856 +  if( db->pVdbe ) return 1;
1.120857 +  for(j=0; j<db->nDb; j++){
1.120858 +    Btree *pBt = db->aDb[j].pBt;
1.120859 +    if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
1.120860 +  }
1.120861 +  return 0;
1.120862 +}
1.120863 +
1.120864 +/*
1.120865 +** Close an existing SQLite database
1.120866 +*/
1.120867 +static int sqlite3Close(sqlite3 *db, int forceZombie){
1.120868 +  if( !db ){
1.120869 +    return SQLITE_OK;
1.120870 +  }
1.120871 +  if( !sqlite3SafetyCheckSickOrOk(db) ){
1.120872 +    return SQLITE_MISUSE_BKPT;
1.120873 +  }
1.120874 +  sqlite3_mutex_enter(db->mutex);
1.120875 +
1.120876 +  /* Force xDisconnect calls on all virtual tables */
1.120877 +  disconnectAllVtab(db);
1.120878 +
1.120879 +  /* If a transaction is open, the disconnectAllVtab() call above
1.120880 +  ** will not have called the xDisconnect() method on any virtual
1.120881 +  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
1.120882 +  ** call will do so. We need to do this before the check for active
1.120883 +  ** SQL statements below, as the v-table implementation may be storing
1.120884 +  ** some prepared statements internally.
1.120885 +  */
1.120886 +  sqlite3VtabRollback(db);
1.120887 +
1.120888 +  /* Legacy behavior (sqlite3_close() behavior) is to return
1.120889 +  ** SQLITE_BUSY if the connection can not be closed immediately.
1.120890 +  */
1.120891 +  if( !forceZombie && connectionIsBusy(db) ){
1.120892 +    sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
1.120893 +       "statements or unfinished backups");
1.120894 +    sqlite3_mutex_leave(db->mutex);
1.120895 +    return SQLITE_BUSY;
1.120896 +  }
1.120897 +
1.120898 +#ifdef SQLITE_ENABLE_SQLLOG
1.120899 +  if( sqlite3GlobalConfig.xSqllog ){
1.120900 +    /* Closing the handle. Fourth parameter is passed the value 2. */
1.120901 +    sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
1.120902 +  }
1.120903 +#endif
1.120904 +
1.120905 +  /* Convert the connection into a zombie and then close it.
1.120906 +  */
1.120907 +  db->magic = SQLITE_MAGIC_ZOMBIE;
1.120908 +  sqlite3LeaveMutexAndCloseZombie(db);
1.120909 +  return SQLITE_OK;
1.120910 +}
1.120911 +
1.120912 +/*
1.120913 +** Two variations on the public interface for closing a database
1.120914 +** connection. The sqlite3_close() version returns SQLITE_BUSY and
1.120915 +** leaves the connection option if there are unfinalized prepared
1.120916 +** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
1.120917 +** version forces the connection to become a zombie if there are
1.120918 +** unclosed resources, and arranges for deallocation when the last
1.120919 +** prepare statement or sqlite3_backup closes.
1.120920 +*/
1.120921 +SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
1.120922 +SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
1.120923 +
1.120924 +
1.120925 +/*
1.120926 +** Close the mutex on database connection db.
1.120927 +**
1.120928 +** Furthermore, if database connection db is a zombie (meaning that there
1.120929 +** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
1.120930 +** every sqlite3_stmt has now been finalized and every sqlite3_backup has
1.120931 +** finished, then free all resources.
1.120932 +*/
1.120933 +SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
1.120934 +  HashElem *i;                    /* Hash table iterator */
1.120935 +  int j;
1.120936 +
1.120937 +  /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
1.120938 +  ** or if the connection has not yet been closed by sqlite3_close_v2(),
1.120939 +  ** then just leave the mutex and return.
1.120940 +  */
1.120941 +  if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
1.120942 +    sqlite3_mutex_leave(db->mutex);
1.120943 +    return;
1.120944 +  }
1.120945 +
1.120946 +  /* If we reach this point, it means that the database connection has
1.120947 +  ** closed all sqlite3_stmt and sqlite3_backup objects and has been
1.120948 +  ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
1.120949 +  ** go ahead and free all resources.
1.120950 +  */
1.120951 +
1.120952 +  /* If a transaction is open, roll it back. This also ensures that if
1.120953 +  ** any database schemas have been modified by an uncommitted transaction
1.120954 +  ** they are reset. And that the required b-tree mutex is held to make
1.120955 +  ** the pager rollback and schema reset an atomic operation. */
1.120956 +  sqlite3RollbackAll(db, SQLITE_OK);
1.120957 +
1.120958 +  /* Free any outstanding Savepoint structures. */
1.120959 +  sqlite3CloseSavepoints(db);
1.120960 +
1.120961 +  /* Close all database connections */
1.120962 +  for(j=0; j<db->nDb; j++){
1.120963 +    struct Db *pDb = &db->aDb[j];
1.120964 +    if( pDb->pBt ){
1.120965 +      sqlite3BtreeClose(pDb->pBt);
1.120966 +      pDb->pBt = 0;
1.120967 +      if( j!=1 ){
1.120968 +        pDb->pSchema = 0;
1.120969 +      }
1.120970 +    }
1.120971 +  }
1.120972 +  /* Clear the TEMP schema separately and last */
1.120973 +  if( db->aDb[1].pSchema ){
1.120974 +    sqlite3SchemaClear(db->aDb[1].pSchema);
1.120975 +  }
1.120976 +  sqlite3VtabUnlockList(db);
1.120977 +
1.120978 +  /* Free up the array of auxiliary databases */
1.120979 +  sqlite3CollapseDatabaseArray(db);
1.120980 +  assert( db->nDb<=2 );
1.120981 +  assert( db->aDb==db->aDbStatic );
1.120982 +
1.120983 +  /* Tell the code in notify.c that the connection no longer holds any
1.120984 +  ** locks and does not require any further unlock-notify callbacks.
1.120985 +  */
1.120986 +  sqlite3ConnectionClosed(db);
1.120987 +
1.120988 +  for(j=0; j<ArraySize(db->aFunc.a); j++){
1.120989 +    FuncDef *pNext, *pHash, *p;
1.120990 +    for(p=db->aFunc.a[j]; p; p=pHash){
1.120991 +      pHash = p->pHash;
1.120992 +      while( p ){
1.120993 +        functionDestroy(db, p);
1.120994 +        pNext = p->pNext;
1.120995 +        sqlite3DbFree(db, p);
1.120996 +        p = pNext;
1.120997 +      }
1.120998 +    }
1.120999 +  }
1.121000 +  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
1.121001 +    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
1.121002 +    /* Invoke any destructors registered for collation sequence user data. */
1.121003 +    for(j=0; j<3; j++){
1.121004 +      if( pColl[j].xDel ){
1.121005 +        pColl[j].xDel(pColl[j].pUser);
1.121006 +      }
1.121007 +    }
1.121008 +    sqlite3DbFree(db, pColl);
1.121009 +  }
1.121010 +  sqlite3HashClear(&db->aCollSeq);
1.121011 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.121012 +  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
1.121013 +    Module *pMod = (Module *)sqliteHashData(i);
1.121014 +    if( pMod->xDestroy ){
1.121015 +      pMod->xDestroy(pMod->pAux);
1.121016 +    }
1.121017 +    sqlite3DbFree(db, pMod);
1.121018 +  }
1.121019 +  sqlite3HashClear(&db->aModule);
1.121020 +#endif
1.121021 +
1.121022 +  sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
1.121023 +  sqlite3ValueFree(db->pErr);
1.121024 +  sqlite3CloseExtensions(db);
1.121025 +
1.121026 +  db->magic = SQLITE_MAGIC_ERROR;
1.121027 +
1.121028 +  /* The temp-database schema is allocated differently from the other schema
1.121029 +  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
1.121030 +  ** So it needs to be freed here. Todo: Why not roll the temp schema into
1.121031 +  ** the same sqliteMalloc() as the one that allocates the database 
1.121032 +  ** structure?
1.121033 +  */
1.121034 +  sqlite3DbFree(db, db->aDb[1].pSchema);
1.121035 +  sqlite3_mutex_leave(db->mutex);
1.121036 +  db->magic = SQLITE_MAGIC_CLOSED;
1.121037 +  sqlite3_mutex_free(db->mutex);
1.121038 +  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
1.121039 +  if( db->lookaside.bMalloced ){
1.121040 +    sqlite3_free(db->lookaside.pStart);
1.121041 +  }
1.121042 +  sqlite3_free(db);
1.121043 +}
1.121044 +
1.121045 +/*
1.121046 +** Rollback all database files.  If tripCode is not SQLITE_OK, then
1.121047 +** any open cursors are invalidated ("tripped" - as in "tripping a circuit
1.121048 +** breaker") and made to return tripCode if there are any further
1.121049 +** attempts to use that cursor.
1.121050 +*/
1.121051 +SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
1.121052 +  int i;
1.121053 +  int inTrans = 0;
1.121054 +  assert( sqlite3_mutex_held(db->mutex) );
1.121055 +  sqlite3BeginBenignMalloc();
1.121056 +
1.121057 +  /* Obtain all b-tree mutexes before making any calls to BtreeRollback(). 
1.121058 +  ** This is important in case the transaction being rolled back has
1.121059 +  ** modified the database schema. If the b-tree mutexes are not taken
1.121060 +  ** here, then another shared-cache connection might sneak in between
1.121061 +  ** the database rollback and schema reset, which can cause false
1.121062 +  ** corruption reports in some cases.  */
1.121063 +  sqlite3BtreeEnterAll(db);
1.121064 +
1.121065 +  for(i=0; i<db->nDb; i++){
1.121066 +    Btree *p = db->aDb[i].pBt;
1.121067 +    if( p ){
1.121068 +      if( sqlite3BtreeIsInTrans(p) ){
1.121069 +        inTrans = 1;
1.121070 +      }
1.121071 +      sqlite3BtreeRollback(p, tripCode);
1.121072 +    }
1.121073 +  }
1.121074 +  sqlite3VtabRollback(db);
1.121075 +  sqlite3EndBenignMalloc();
1.121076 +
1.121077 +  if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
1.121078 +    sqlite3ExpirePreparedStatements(db);
1.121079 +    sqlite3ResetAllSchemasOfConnection(db);
1.121080 +  }
1.121081 +  sqlite3BtreeLeaveAll(db);
1.121082 +
1.121083 +  /* Any deferred constraint violations have now been resolved. */
1.121084 +  db->nDeferredCons = 0;
1.121085 +  db->nDeferredImmCons = 0;
1.121086 +  db->flags &= ~SQLITE_DeferFKs;
1.121087 +
1.121088 +  /* If one has been configured, invoke the rollback-hook callback */
1.121089 +  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
1.121090 +    db->xRollbackCallback(db->pRollbackArg);
1.121091 +  }
1.121092 +}
1.121093 +
1.121094 +/*
1.121095 +** Return a static string containing the name corresponding to the error code
1.121096 +** specified in the argument.
1.121097 +*/
1.121098 +#if defined(SQLITE_TEST)
1.121099 +SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
1.121100 +  const char *zName = 0;
1.121101 +  int i, origRc = rc;
1.121102 +  for(i=0; i<2 && zName==0; i++, rc &= 0xff){
1.121103 +    switch( rc ){
1.121104 +      case SQLITE_OK:                 zName = "SQLITE_OK";                break;
1.121105 +      case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
1.121106 +      case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
1.121107 +      case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
1.121108 +      case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
1.121109 +      case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
1.121110 +      case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
1.121111 +      case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
1.121112 +      case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
1.121113 +      case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
1.121114 +      case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
1.121115 +      case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
1.121116 +      case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
1.121117 +      case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
1.121118 +      case SQLITE_READONLY_CANTLOCK:  zName = "SQLITE_READONLY_CANTLOCK"; break;
1.121119 +      case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
1.121120 +      case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
1.121121 +      case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
1.121122 +      case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
1.121123 +      case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
1.121124 +      case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
1.121125 +      case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
1.121126 +      case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
1.121127 +      case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
1.121128 +      case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
1.121129 +      case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
1.121130 +      case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
1.121131 +      case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
1.121132 +      case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
1.121133 +      case SQLITE_IOERR_BLOCKED:      zName = "SQLITE_IOERR_BLOCKED";     break;
1.121134 +      case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
1.121135 +      case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
1.121136 +      case SQLITE_IOERR_CHECKRESERVEDLOCK:
1.121137 +                                zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
1.121138 +      case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
1.121139 +      case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
1.121140 +      case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
1.121141 +      case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
1.121142 +      case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
1.121143 +      case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
1.121144 +      case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
1.121145 +      case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
1.121146 +      case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
1.121147 +      case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
1.121148 +      case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
1.121149 +      case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
1.121150 +      case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
1.121151 +      case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
1.121152 +      case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
1.121153 +      case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
1.121154 +      case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
1.121155 +      case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
1.121156 +      case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
1.121157 +      case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
1.121158 +      case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
1.121159 +      case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
1.121160 +      case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
1.121161 +      case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
1.121162 +      case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
1.121163 +      case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
1.121164 +      case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
1.121165 +      case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
1.121166 +      case SQLITE_CONSTRAINT_FOREIGNKEY:
1.121167 +                                zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
1.121168 +      case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
1.121169 +      case SQLITE_CONSTRAINT_PRIMARYKEY:
1.121170 +                                zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
1.121171 +      case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
1.121172 +      case SQLITE_CONSTRAINT_COMMITHOOK:
1.121173 +                                zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
1.121174 +      case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
1.121175 +      case SQLITE_CONSTRAINT_FUNCTION:
1.121176 +                                zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
1.121177 +      case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
1.121178 +      case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
1.121179 +      case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
1.121180 +      case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
1.121181 +      case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
1.121182 +      case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
1.121183 +      case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
1.121184 +      case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
1.121185 +      case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
1.121186 +      case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
1.121187 +      case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
1.121188 +      case SQLITE_NOTICE_RECOVER_ROLLBACK:
1.121189 +                                zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
1.121190 +      case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
1.121191 +      case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
1.121192 +      case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
1.121193 +    }
1.121194 +  }
1.121195 +  if( zName==0 ){
1.121196 +    static char zBuf[50];
1.121197 +    sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
1.121198 +    zName = zBuf;
1.121199 +  }
1.121200 +  return zName;
1.121201 +}
1.121202 +#endif
1.121203 +
1.121204 +/*
1.121205 +** Return a static string that describes the kind of error specified in the
1.121206 +** argument.
1.121207 +*/
1.121208 +SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
1.121209 +  static const char* const aMsg[] = {
1.121210 +    /* SQLITE_OK          */ "not an error",
1.121211 +    /* SQLITE_ERROR       */ "SQL logic error or missing database",
1.121212 +    /* SQLITE_INTERNAL    */ 0,
1.121213 +    /* SQLITE_PERM        */ "access permission denied",
1.121214 +    /* SQLITE_ABORT       */ "callback requested query abort",
1.121215 +    /* SQLITE_BUSY        */ "database is locked",
1.121216 +    /* SQLITE_LOCKED      */ "database table is locked",
1.121217 +    /* SQLITE_NOMEM       */ "out of memory",
1.121218 +    /* SQLITE_READONLY    */ "attempt to write a readonly database",
1.121219 +    /* SQLITE_INTERRUPT   */ "interrupted",
1.121220 +    /* SQLITE_IOERR       */ "disk I/O error",
1.121221 +    /* SQLITE_CORRUPT     */ "database disk image is malformed",
1.121222 +    /* SQLITE_NOTFOUND    */ "unknown operation",
1.121223 +    /* SQLITE_FULL        */ "database or disk is full",
1.121224 +    /* SQLITE_CANTOPEN    */ "unable to open database file",
1.121225 +    /* SQLITE_PROTOCOL    */ "locking protocol",
1.121226 +    /* SQLITE_EMPTY       */ "table contains no data",
1.121227 +    /* SQLITE_SCHEMA      */ "database schema has changed",
1.121228 +    /* SQLITE_TOOBIG      */ "string or blob too big",
1.121229 +    /* SQLITE_CONSTRAINT  */ "constraint failed",
1.121230 +    /* SQLITE_MISMATCH    */ "datatype mismatch",
1.121231 +    /* SQLITE_MISUSE      */ "library routine called out of sequence",
1.121232 +    /* SQLITE_NOLFS       */ "large file support is disabled",
1.121233 +    /* SQLITE_AUTH        */ "authorization denied",
1.121234 +    /* SQLITE_FORMAT      */ "auxiliary database format error",
1.121235 +    /* SQLITE_RANGE       */ "bind or column index out of range",
1.121236 +    /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
1.121237 +  };
1.121238 +  const char *zErr = "unknown error";
1.121239 +  switch( rc ){
1.121240 +    case SQLITE_ABORT_ROLLBACK: {
1.121241 +      zErr = "abort due to ROLLBACK";
1.121242 +      break;
1.121243 +    }
1.121244 +    default: {
1.121245 +      rc &= 0xff;
1.121246 +      if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
1.121247 +        zErr = aMsg[rc];
1.121248 +      }
1.121249 +      break;
1.121250 +    }
1.121251 +  }
1.121252 +  return zErr;
1.121253 +}
1.121254 +
1.121255 +/*
1.121256 +** This routine implements a busy callback that sleeps and tries
1.121257 +** again until a timeout value is reached.  The timeout value is
1.121258 +** an integer number of milliseconds passed in as the first
1.121259 +** argument.
1.121260 +*/
1.121261 +static int sqliteDefaultBusyCallback(
1.121262 + void *ptr,               /* Database connection */
1.121263 + int count                /* Number of times table has been busy */
1.121264 +){
1.121265 +#if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
1.121266 +  static const u8 delays[] =
1.121267 +     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
1.121268 +  static const u8 totals[] =
1.121269 +     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
1.121270 +# define NDELAY ArraySize(delays)
1.121271 +  sqlite3 *db = (sqlite3 *)ptr;
1.121272 +  int timeout = db->busyTimeout;
1.121273 +  int delay, prior;
1.121274 +
1.121275 +  assert( count>=0 );
1.121276 +  if( count < NDELAY ){
1.121277 +    delay = delays[count];
1.121278 +    prior = totals[count];
1.121279 +  }else{
1.121280 +    delay = delays[NDELAY-1];
1.121281 +    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
1.121282 +  }
1.121283 +  if( prior + delay > timeout ){
1.121284 +    delay = timeout - prior;
1.121285 +    if( delay<=0 ) return 0;
1.121286 +  }
1.121287 +  sqlite3OsSleep(db->pVfs, delay*1000);
1.121288 +  return 1;
1.121289 +#else
1.121290 +  sqlite3 *db = (sqlite3 *)ptr;
1.121291 +  int timeout = ((sqlite3 *)ptr)->busyTimeout;
1.121292 +  if( (count+1)*1000 > timeout ){
1.121293 +    return 0;
1.121294 +  }
1.121295 +  sqlite3OsSleep(db->pVfs, 1000000);
1.121296 +  return 1;
1.121297 +#endif
1.121298 +}
1.121299 +
1.121300 +/*
1.121301 +** Invoke the given busy handler.
1.121302 +**
1.121303 +** This routine is called when an operation failed with a lock.
1.121304 +** If this routine returns non-zero, the lock is retried.  If it
1.121305 +** returns 0, the operation aborts with an SQLITE_BUSY error.
1.121306 +*/
1.121307 +SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
1.121308 +  int rc;
1.121309 +  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
1.121310 +  rc = p->xFunc(p->pArg, p->nBusy);
1.121311 +  if( rc==0 ){
1.121312 +    p->nBusy = -1;
1.121313 +  }else{
1.121314 +    p->nBusy++;
1.121315 +  }
1.121316 +  return rc; 
1.121317 +}
1.121318 +
1.121319 +/*
1.121320 +** This routine sets the busy callback for an Sqlite database to the
1.121321 +** given callback function with the given argument.
1.121322 +*/
1.121323 +SQLITE_API int sqlite3_busy_handler(
1.121324 +  sqlite3 *db,
1.121325 +  int (*xBusy)(void*,int),
1.121326 +  void *pArg
1.121327 +){
1.121328 +  sqlite3_mutex_enter(db->mutex);
1.121329 +  db->busyHandler.xFunc = xBusy;
1.121330 +  db->busyHandler.pArg = pArg;
1.121331 +  db->busyHandler.nBusy = 0;
1.121332 +  db->busyTimeout = 0;
1.121333 +  sqlite3_mutex_leave(db->mutex);
1.121334 +  return SQLITE_OK;
1.121335 +}
1.121336 +
1.121337 +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1.121338 +/*
1.121339 +** This routine sets the progress callback for an Sqlite database to the
1.121340 +** given callback function with the given argument. The progress callback will
1.121341 +** be invoked every nOps opcodes.
1.121342 +*/
1.121343 +SQLITE_API void sqlite3_progress_handler(
1.121344 +  sqlite3 *db, 
1.121345 +  int nOps,
1.121346 +  int (*xProgress)(void*), 
1.121347 +  void *pArg
1.121348 +){
1.121349 +  sqlite3_mutex_enter(db->mutex);
1.121350 +  if( nOps>0 ){
1.121351 +    db->xProgress = xProgress;
1.121352 +    db->nProgressOps = (unsigned)nOps;
1.121353 +    db->pProgressArg = pArg;
1.121354 +  }else{
1.121355 +    db->xProgress = 0;
1.121356 +    db->nProgressOps = 0;
1.121357 +    db->pProgressArg = 0;
1.121358 +  }
1.121359 +  sqlite3_mutex_leave(db->mutex);
1.121360 +}
1.121361 +#endif
1.121362 +
1.121363 +
1.121364 +/*
1.121365 +** This routine installs a default busy handler that waits for the
1.121366 +** specified number of milliseconds before returning 0.
1.121367 +*/
1.121368 +SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
1.121369 +  if( ms>0 ){
1.121370 +    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
1.121371 +    db->busyTimeout = ms;
1.121372 +  }else{
1.121373 +    sqlite3_busy_handler(db, 0, 0);
1.121374 +  }
1.121375 +  return SQLITE_OK;
1.121376 +}
1.121377 +
1.121378 +/*
1.121379 +** Cause any pending operation to stop at its earliest opportunity.
1.121380 +*/
1.121381 +SQLITE_API void sqlite3_interrupt(sqlite3 *db){
1.121382 +  db->u1.isInterrupted = 1;
1.121383 +}
1.121384 +
1.121385 +
1.121386 +/*
1.121387 +** This function is exactly the same as sqlite3_create_function(), except
1.121388 +** that it is designed to be called by internal code. The difference is
1.121389 +** that if a malloc() fails in sqlite3_create_function(), an error code
1.121390 +** is returned and the mallocFailed flag cleared. 
1.121391 +*/
1.121392 +SQLITE_PRIVATE int sqlite3CreateFunc(
1.121393 +  sqlite3 *db,
1.121394 +  const char *zFunctionName,
1.121395 +  int nArg,
1.121396 +  int enc,
1.121397 +  void *pUserData,
1.121398 +  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
1.121399 +  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
1.121400 +  void (*xFinal)(sqlite3_context*),
1.121401 +  FuncDestructor *pDestructor
1.121402 +){
1.121403 +  FuncDef *p;
1.121404 +  int nName;
1.121405 +  int extraFlags;
1.121406 +
1.121407 +  assert( sqlite3_mutex_held(db->mutex) );
1.121408 +  if( zFunctionName==0 ||
1.121409 +      (xFunc && (xFinal || xStep)) || 
1.121410 +      (!xFunc && (xFinal && !xStep)) ||
1.121411 +      (!xFunc && (!xFinal && xStep)) ||
1.121412 +      (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
1.121413 +      (255<(nName = sqlite3Strlen30( zFunctionName))) ){
1.121414 +    return SQLITE_MISUSE_BKPT;
1.121415 +  }
1.121416 +
1.121417 +  assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
1.121418 +  extraFlags = enc &  SQLITE_DETERMINISTIC;
1.121419 +  enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
1.121420 +  
1.121421 +#ifndef SQLITE_OMIT_UTF16
1.121422 +  /* If SQLITE_UTF16 is specified as the encoding type, transform this
1.121423 +  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
1.121424 +  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
1.121425 +  **
1.121426 +  ** If SQLITE_ANY is specified, add three versions of the function
1.121427 +  ** to the hash table.
1.121428 +  */
1.121429 +  if( enc==SQLITE_UTF16 ){
1.121430 +    enc = SQLITE_UTF16NATIVE;
1.121431 +  }else if( enc==SQLITE_ANY ){
1.121432 +    int rc;
1.121433 +    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
1.121434 +         pUserData, xFunc, xStep, xFinal, pDestructor);
1.121435 +    if( rc==SQLITE_OK ){
1.121436 +      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
1.121437 +          pUserData, xFunc, xStep, xFinal, pDestructor);
1.121438 +    }
1.121439 +    if( rc!=SQLITE_OK ){
1.121440 +      return rc;
1.121441 +    }
1.121442 +    enc = SQLITE_UTF16BE;
1.121443 +  }
1.121444 +#else
1.121445 +  enc = SQLITE_UTF8;
1.121446 +#endif
1.121447 +  
1.121448 +  /* Check if an existing function is being overridden or deleted. If so,
1.121449 +  ** and there are active VMs, then return SQLITE_BUSY. If a function
1.121450 +  ** is being overridden/deleted but there are no active VMs, allow the
1.121451 +  ** operation to continue but invalidate all precompiled statements.
1.121452 +  */
1.121453 +  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
1.121454 +  if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
1.121455 +    if( db->nVdbeActive ){
1.121456 +      sqlite3Error(db, SQLITE_BUSY, 
1.121457 +        "unable to delete/modify user-function due to active statements");
1.121458 +      assert( !db->mallocFailed );
1.121459 +      return SQLITE_BUSY;
1.121460 +    }else{
1.121461 +      sqlite3ExpirePreparedStatements(db);
1.121462 +    }
1.121463 +  }
1.121464 +
1.121465 +  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
1.121466 +  assert(p || db->mallocFailed);
1.121467 +  if( !p ){
1.121468 +    return SQLITE_NOMEM;
1.121469 +  }
1.121470 +
1.121471 +  /* If an older version of the function with a configured destructor is
1.121472 +  ** being replaced invoke the destructor function here. */
1.121473 +  functionDestroy(db, p);
1.121474 +
1.121475 +  if( pDestructor ){
1.121476 +    pDestructor->nRef++;
1.121477 +  }
1.121478 +  p->pDestructor = pDestructor;
1.121479 +  p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
1.121480 +  testcase( p->funcFlags & SQLITE_DETERMINISTIC );
1.121481 +  p->xFunc = xFunc;
1.121482 +  p->xStep = xStep;
1.121483 +  p->xFinalize = xFinal;
1.121484 +  p->pUserData = pUserData;
1.121485 +  p->nArg = (u16)nArg;
1.121486 +  return SQLITE_OK;
1.121487 +}
1.121488 +
1.121489 +/*
1.121490 +** Create new user functions.
1.121491 +*/
1.121492 +SQLITE_API int sqlite3_create_function(
1.121493 +  sqlite3 *db,
1.121494 +  const char *zFunc,
1.121495 +  int nArg,
1.121496 +  int enc,
1.121497 +  void *p,
1.121498 +  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
1.121499 +  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
1.121500 +  void (*xFinal)(sqlite3_context*)
1.121501 +){
1.121502 +  return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
1.121503 +                                    xFinal, 0);
1.121504 +}
1.121505 +
1.121506 +SQLITE_API int sqlite3_create_function_v2(
1.121507 +  sqlite3 *db,
1.121508 +  const char *zFunc,
1.121509 +  int nArg,
1.121510 +  int enc,
1.121511 +  void *p,
1.121512 +  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
1.121513 +  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
1.121514 +  void (*xFinal)(sqlite3_context*),
1.121515 +  void (*xDestroy)(void *)
1.121516 +){
1.121517 +  int rc = SQLITE_ERROR;
1.121518 +  FuncDestructor *pArg = 0;
1.121519 +  sqlite3_mutex_enter(db->mutex);
1.121520 +  if( xDestroy ){
1.121521 +    pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
1.121522 +    if( !pArg ){
1.121523 +      xDestroy(p);
1.121524 +      goto out;
1.121525 +    }
1.121526 +    pArg->xDestroy = xDestroy;
1.121527 +    pArg->pUserData = p;
1.121528 +  }
1.121529 +  rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
1.121530 +  if( pArg && pArg->nRef==0 ){
1.121531 +    assert( rc!=SQLITE_OK );
1.121532 +    xDestroy(p);
1.121533 +    sqlite3DbFree(db, pArg);
1.121534 +  }
1.121535 +
1.121536 + out:
1.121537 +  rc = sqlite3ApiExit(db, rc);
1.121538 +  sqlite3_mutex_leave(db->mutex);
1.121539 +  return rc;
1.121540 +}
1.121541 +
1.121542 +#ifndef SQLITE_OMIT_UTF16
1.121543 +SQLITE_API int sqlite3_create_function16(
1.121544 +  sqlite3 *db,
1.121545 +  const void *zFunctionName,
1.121546 +  int nArg,
1.121547 +  int eTextRep,
1.121548 +  void *p,
1.121549 +  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
1.121550 +  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
1.121551 +  void (*xFinal)(sqlite3_context*)
1.121552 +){
1.121553 +  int rc;
1.121554 +  char *zFunc8;
1.121555 +  sqlite3_mutex_enter(db->mutex);
1.121556 +  assert( !db->mallocFailed );
1.121557 +  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
1.121558 +  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
1.121559 +  sqlite3DbFree(db, zFunc8);
1.121560 +  rc = sqlite3ApiExit(db, rc);
1.121561 +  sqlite3_mutex_leave(db->mutex);
1.121562 +  return rc;
1.121563 +}
1.121564 +#endif
1.121565 +
1.121566 +
1.121567 +/*
1.121568 +** Declare that a function has been overloaded by a virtual table.
1.121569 +**
1.121570 +** If the function already exists as a regular global function, then
1.121571 +** this routine is a no-op.  If the function does not exist, then create
1.121572 +** a new one that always throws a run-time error.  
1.121573 +**
1.121574 +** When virtual tables intend to provide an overloaded function, they
1.121575 +** should call this routine to make sure the global function exists.
1.121576 +** A global function must exist in order for name resolution to work
1.121577 +** properly.
1.121578 +*/
1.121579 +SQLITE_API int sqlite3_overload_function(
1.121580 +  sqlite3 *db,
1.121581 +  const char *zName,
1.121582 +  int nArg
1.121583 +){
1.121584 +  int nName = sqlite3Strlen30(zName);
1.121585 +  int rc = SQLITE_OK;
1.121586 +  sqlite3_mutex_enter(db->mutex);
1.121587 +  if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
1.121588 +    rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
1.121589 +                           0, sqlite3InvalidFunction, 0, 0, 0);
1.121590 +  }
1.121591 +  rc = sqlite3ApiExit(db, rc);
1.121592 +  sqlite3_mutex_leave(db->mutex);
1.121593 +  return rc;
1.121594 +}
1.121595 +
1.121596 +#ifndef SQLITE_OMIT_TRACE
1.121597 +/*
1.121598 +** Register a trace function.  The pArg from the previously registered trace
1.121599 +** is returned.  
1.121600 +**
1.121601 +** A NULL trace function means that no tracing is executes.  A non-NULL
1.121602 +** trace is a pointer to a function that is invoked at the start of each
1.121603 +** SQL statement.
1.121604 +*/
1.121605 +SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
1.121606 +  void *pOld;
1.121607 +  sqlite3_mutex_enter(db->mutex);
1.121608 +  pOld = db->pTraceArg;
1.121609 +  db->xTrace = xTrace;
1.121610 +  db->pTraceArg = pArg;
1.121611 +  sqlite3_mutex_leave(db->mutex);
1.121612 +  return pOld;
1.121613 +}
1.121614 +/*
1.121615 +** Register a profile function.  The pArg from the previously registered 
1.121616 +** profile function is returned.  
1.121617 +**
1.121618 +** A NULL profile function means that no profiling is executes.  A non-NULL
1.121619 +** profile is a pointer to a function that is invoked at the conclusion of
1.121620 +** each SQL statement that is run.
1.121621 +*/
1.121622 +SQLITE_API void *sqlite3_profile(
1.121623 +  sqlite3 *db,
1.121624 +  void (*xProfile)(void*,const char*,sqlite_uint64),
1.121625 +  void *pArg
1.121626 +){
1.121627 +  void *pOld;
1.121628 +  sqlite3_mutex_enter(db->mutex);
1.121629 +  pOld = db->pProfileArg;
1.121630 +  db->xProfile = xProfile;
1.121631 +  db->pProfileArg = pArg;
1.121632 +  sqlite3_mutex_leave(db->mutex);
1.121633 +  return pOld;
1.121634 +}
1.121635 +#endif /* SQLITE_OMIT_TRACE */
1.121636 +
1.121637 +/*
1.121638 +** Register a function to be invoked when a transaction commits.
1.121639 +** If the invoked function returns non-zero, then the commit becomes a
1.121640 +** rollback.
1.121641 +*/
1.121642 +SQLITE_API void *sqlite3_commit_hook(
1.121643 +  sqlite3 *db,              /* Attach the hook to this database */
1.121644 +  int (*xCallback)(void*),  /* Function to invoke on each commit */
1.121645 +  void *pArg                /* Argument to the function */
1.121646 +){
1.121647 +  void *pOld;
1.121648 +  sqlite3_mutex_enter(db->mutex);
1.121649 +  pOld = db->pCommitArg;
1.121650 +  db->xCommitCallback = xCallback;
1.121651 +  db->pCommitArg = pArg;
1.121652 +  sqlite3_mutex_leave(db->mutex);
1.121653 +  return pOld;
1.121654 +}
1.121655 +
1.121656 +/*
1.121657 +** Register a callback to be invoked each time a row is updated,
1.121658 +** inserted or deleted using this database connection.
1.121659 +*/
1.121660 +SQLITE_API void *sqlite3_update_hook(
1.121661 +  sqlite3 *db,              /* Attach the hook to this database */
1.121662 +  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
1.121663 +  void *pArg                /* Argument to the function */
1.121664 +){
1.121665 +  void *pRet;
1.121666 +  sqlite3_mutex_enter(db->mutex);
1.121667 +  pRet = db->pUpdateArg;
1.121668 +  db->xUpdateCallback = xCallback;
1.121669 +  db->pUpdateArg = pArg;
1.121670 +  sqlite3_mutex_leave(db->mutex);
1.121671 +  return pRet;
1.121672 +}
1.121673 +
1.121674 +/*
1.121675 +** Register a callback to be invoked each time a transaction is rolled
1.121676 +** back by this database connection.
1.121677 +*/
1.121678 +SQLITE_API void *sqlite3_rollback_hook(
1.121679 +  sqlite3 *db,              /* Attach the hook to this database */
1.121680 +  void (*xCallback)(void*), /* Callback function */
1.121681 +  void *pArg                /* Argument to the function */
1.121682 +){
1.121683 +  void *pRet;
1.121684 +  sqlite3_mutex_enter(db->mutex);
1.121685 +  pRet = db->pRollbackArg;
1.121686 +  db->xRollbackCallback = xCallback;
1.121687 +  db->pRollbackArg = pArg;
1.121688 +  sqlite3_mutex_leave(db->mutex);
1.121689 +  return pRet;
1.121690 +}
1.121691 +
1.121692 +#ifndef SQLITE_OMIT_WAL
1.121693 +/*
1.121694 +** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
1.121695 +** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
1.121696 +** is greater than sqlite3.pWalArg cast to an integer (the value configured by
1.121697 +** wal_autocheckpoint()).
1.121698 +*/ 
1.121699 +SQLITE_PRIVATE int sqlite3WalDefaultHook(
1.121700 +  void *pClientData,     /* Argument */
1.121701 +  sqlite3 *db,           /* Connection */
1.121702 +  const char *zDb,       /* Database */
1.121703 +  int nFrame             /* Size of WAL */
1.121704 +){
1.121705 +  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
1.121706 +    sqlite3BeginBenignMalloc();
1.121707 +    sqlite3_wal_checkpoint(db, zDb);
1.121708 +    sqlite3EndBenignMalloc();
1.121709 +  }
1.121710 +  return SQLITE_OK;
1.121711 +}
1.121712 +#endif /* SQLITE_OMIT_WAL */
1.121713 +
1.121714 +/*
1.121715 +** Configure an sqlite3_wal_hook() callback to automatically checkpoint
1.121716 +** a database after committing a transaction if there are nFrame or
1.121717 +** more frames in the log file. Passing zero or a negative value as the
1.121718 +** nFrame parameter disables automatic checkpoints entirely.
1.121719 +**
1.121720 +** The callback registered by this function replaces any existing callback
1.121721 +** registered using sqlite3_wal_hook(). Likewise, registering a callback
1.121722 +** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
1.121723 +** configured by this function.
1.121724 +*/
1.121725 +SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
1.121726 +#ifdef SQLITE_OMIT_WAL
1.121727 +  UNUSED_PARAMETER(db);
1.121728 +  UNUSED_PARAMETER(nFrame);
1.121729 +#else
1.121730 +  if( nFrame>0 ){
1.121731 +    sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
1.121732 +  }else{
1.121733 +    sqlite3_wal_hook(db, 0, 0);
1.121734 +  }
1.121735 +#endif
1.121736 +  return SQLITE_OK;
1.121737 +}
1.121738 +
1.121739 +/*
1.121740 +** Register a callback to be invoked each time a transaction is written
1.121741 +** into the write-ahead-log by this database connection.
1.121742 +*/
1.121743 +SQLITE_API void *sqlite3_wal_hook(
1.121744 +  sqlite3 *db,                    /* Attach the hook to this db handle */
1.121745 +  int(*xCallback)(void *, sqlite3*, const char*, int),
1.121746 +  void *pArg                      /* First argument passed to xCallback() */
1.121747 +){
1.121748 +#ifndef SQLITE_OMIT_WAL
1.121749 +  void *pRet;
1.121750 +  sqlite3_mutex_enter(db->mutex);
1.121751 +  pRet = db->pWalArg;
1.121752 +  db->xWalCallback = xCallback;
1.121753 +  db->pWalArg = pArg;
1.121754 +  sqlite3_mutex_leave(db->mutex);
1.121755 +  return pRet;
1.121756 +#else
1.121757 +  return 0;
1.121758 +#endif
1.121759 +}
1.121760 +
1.121761 +/*
1.121762 +** Checkpoint database zDb.
1.121763 +*/
1.121764 +SQLITE_API int sqlite3_wal_checkpoint_v2(
1.121765 +  sqlite3 *db,                    /* Database handle */
1.121766 +  const char *zDb,                /* Name of attached database (or NULL) */
1.121767 +  int eMode,                      /* SQLITE_CHECKPOINT_* value */
1.121768 +  int *pnLog,                     /* OUT: Size of WAL log in frames */
1.121769 +  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
1.121770 +){
1.121771 +#ifdef SQLITE_OMIT_WAL
1.121772 +  return SQLITE_OK;
1.121773 +#else
1.121774 +  int rc;                         /* Return code */
1.121775 +  int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
1.121776 +
1.121777 +  /* Initialize the output variables to -1 in case an error occurs. */
1.121778 +  if( pnLog ) *pnLog = -1;
1.121779 +  if( pnCkpt ) *pnCkpt = -1;
1.121780 +
1.121781 +  assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
1.121782 +  assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
1.121783 +  assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
1.121784 +  if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
1.121785 +    return SQLITE_MISUSE;
1.121786 +  }
1.121787 +
1.121788 +  sqlite3_mutex_enter(db->mutex);
1.121789 +  if( zDb && zDb[0] ){
1.121790 +    iDb = sqlite3FindDbName(db, zDb);
1.121791 +  }
1.121792 +  if( iDb<0 ){
1.121793 +    rc = SQLITE_ERROR;
1.121794 +    sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
1.121795 +  }else{
1.121796 +    rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
1.121797 +    sqlite3Error(db, rc, 0);
1.121798 +  }
1.121799 +  rc = sqlite3ApiExit(db, rc);
1.121800 +  sqlite3_mutex_leave(db->mutex);
1.121801 +  return rc;
1.121802 +#endif
1.121803 +}
1.121804 +
1.121805 +
1.121806 +/*
1.121807 +** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
1.121808 +** to contains a zero-length string, all attached databases are 
1.121809 +** checkpointed.
1.121810 +*/
1.121811 +SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
1.121812 +  return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
1.121813 +}
1.121814 +
1.121815 +#ifndef SQLITE_OMIT_WAL
1.121816 +/*
1.121817 +** Run a checkpoint on database iDb. This is a no-op if database iDb is
1.121818 +** not currently open in WAL mode.
1.121819 +**
1.121820 +** If a transaction is open on the database being checkpointed, this 
1.121821 +** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
1.121822 +** an error occurs while running the checkpoint, an SQLite error code is 
1.121823 +** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
1.121824 +**
1.121825 +** The mutex on database handle db should be held by the caller. The mutex
1.121826 +** associated with the specific b-tree being checkpointed is taken by
1.121827 +** this function while the checkpoint is running.
1.121828 +**
1.121829 +** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
1.121830 +** checkpointed. If an error is encountered it is returned immediately -
1.121831 +** no attempt is made to checkpoint any remaining databases.
1.121832 +**
1.121833 +** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
1.121834 +*/
1.121835 +SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
1.121836 +  int rc = SQLITE_OK;             /* Return code */
1.121837 +  int i;                          /* Used to iterate through attached dbs */
1.121838 +  int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
1.121839 +
1.121840 +  assert( sqlite3_mutex_held(db->mutex) );
1.121841 +  assert( !pnLog || *pnLog==-1 );
1.121842 +  assert( !pnCkpt || *pnCkpt==-1 );
1.121843 +
1.121844 +  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
1.121845 +    if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
1.121846 +      rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
1.121847 +      pnLog = 0;
1.121848 +      pnCkpt = 0;
1.121849 +      if( rc==SQLITE_BUSY ){
1.121850 +        bBusy = 1;
1.121851 +        rc = SQLITE_OK;
1.121852 +      }
1.121853 +    }
1.121854 +  }
1.121855 +
1.121856 +  return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
1.121857 +}
1.121858 +#endif /* SQLITE_OMIT_WAL */
1.121859 +
1.121860 +/*
1.121861 +** This function returns true if main-memory should be used instead of
1.121862 +** a temporary file for transient pager files and statement journals.
1.121863 +** The value returned depends on the value of db->temp_store (runtime
1.121864 +** parameter) and the compile time value of SQLITE_TEMP_STORE. The
1.121865 +** following table describes the relationship between these two values
1.121866 +** and this functions return value.
1.121867 +**
1.121868 +**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
1.121869 +**   -----------------     --------------     ------------------------------
1.121870 +**   0                     any                file      (return 0)
1.121871 +**   1                     1                  file      (return 0)
1.121872 +**   1                     2                  memory    (return 1)
1.121873 +**   1                     0                  file      (return 0)
1.121874 +**   2                     1                  file      (return 0)
1.121875 +**   2                     2                  memory    (return 1)
1.121876 +**   2                     0                  memory    (return 1)
1.121877 +**   3                     any                memory    (return 1)
1.121878 +*/
1.121879 +SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
1.121880 +#if SQLITE_TEMP_STORE==1
1.121881 +  return ( db->temp_store==2 );
1.121882 +#endif
1.121883 +#if SQLITE_TEMP_STORE==2
1.121884 +  return ( db->temp_store!=1 );
1.121885 +#endif
1.121886 +#if SQLITE_TEMP_STORE==3
1.121887 +  return 1;
1.121888 +#endif
1.121889 +#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
1.121890 +  return 0;
1.121891 +#endif
1.121892 +}
1.121893 +
1.121894 +/*
1.121895 +** Return UTF-8 encoded English language explanation of the most recent
1.121896 +** error.
1.121897 +*/
1.121898 +SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
1.121899 +  const char *z;
1.121900 +  if( !db ){
1.121901 +    return sqlite3ErrStr(SQLITE_NOMEM);
1.121902 +  }
1.121903 +  if( !sqlite3SafetyCheckSickOrOk(db) ){
1.121904 +    return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
1.121905 +  }
1.121906 +  sqlite3_mutex_enter(db->mutex);
1.121907 +  if( db->mallocFailed ){
1.121908 +    z = sqlite3ErrStr(SQLITE_NOMEM);
1.121909 +  }else{
1.121910 +    testcase( db->pErr==0 );
1.121911 +    z = (char*)sqlite3_value_text(db->pErr);
1.121912 +    assert( !db->mallocFailed );
1.121913 +    if( z==0 ){
1.121914 +      z = sqlite3ErrStr(db->errCode);
1.121915 +    }
1.121916 +  }
1.121917 +  sqlite3_mutex_leave(db->mutex);
1.121918 +  return z;
1.121919 +}
1.121920 +
1.121921 +#ifndef SQLITE_OMIT_UTF16
1.121922 +/*
1.121923 +** Return UTF-16 encoded English language explanation of the most recent
1.121924 +** error.
1.121925 +*/
1.121926 +SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
1.121927 +  static const u16 outOfMem[] = {
1.121928 +    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
1.121929 +  };
1.121930 +  static const u16 misuse[] = {
1.121931 +    'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
1.121932 +    'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
1.121933 +    'c', 'a', 'l', 'l', 'e', 'd', ' ', 
1.121934 +    'o', 'u', 't', ' ', 
1.121935 +    'o', 'f', ' ', 
1.121936 +    's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
1.121937 +  };
1.121938 +
1.121939 +  const void *z;
1.121940 +  if( !db ){
1.121941 +    return (void *)outOfMem;
1.121942 +  }
1.121943 +  if( !sqlite3SafetyCheckSickOrOk(db) ){
1.121944 +    return (void *)misuse;
1.121945 +  }
1.121946 +  sqlite3_mutex_enter(db->mutex);
1.121947 +  if( db->mallocFailed ){
1.121948 +    z = (void *)outOfMem;
1.121949 +  }else{
1.121950 +    z = sqlite3_value_text16(db->pErr);
1.121951 +    if( z==0 ){
1.121952 +      sqlite3Error(db, db->errCode, sqlite3ErrStr(db->errCode));
1.121953 +      z = sqlite3_value_text16(db->pErr);
1.121954 +    }
1.121955 +    /* A malloc() may have failed within the call to sqlite3_value_text16()
1.121956 +    ** above. If this is the case, then the db->mallocFailed flag needs to
1.121957 +    ** be cleared before returning. Do this directly, instead of via
1.121958 +    ** sqlite3ApiExit(), to avoid setting the database handle error message.
1.121959 +    */
1.121960 +    db->mallocFailed = 0;
1.121961 +  }
1.121962 +  sqlite3_mutex_leave(db->mutex);
1.121963 +  return z;
1.121964 +}
1.121965 +#endif /* SQLITE_OMIT_UTF16 */
1.121966 +
1.121967 +/*
1.121968 +** Return the most recent error code generated by an SQLite routine. If NULL is
1.121969 +** passed to this function, we assume a malloc() failed during sqlite3_open().
1.121970 +*/
1.121971 +SQLITE_API int sqlite3_errcode(sqlite3 *db){
1.121972 +  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
1.121973 +    return SQLITE_MISUSE_BKPT;
1.121974 +  }
1.121975 +  if( !db || db->mallocFailed ){
1.121976 +    return SQLITE_NOMEM;
1.121977 +  }
1.121978 +  return db->errCode & db->errMask;
1.121979 +}
1.121980 +SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
1.121981 +  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
1.121982 +    return SQLITE_MISUSE_BKPT;
1.121983 +  }
1.121984 +  if( !db || db->mallocFailed ){
1.121985 +    return SQLITE_NOMEM;
1.121986 +  }
1.121987 +  return db->errCode;
1.121988 +}
1.121989 +
1.121990 +/*
1.121991 +** Return a string that describes the kind of error specified in the
1.121992 +** argument.  For now, this simply calls the internal sqlite3ErrStr()
1.121993 +** function.
1.121994 +*/
1.121995 +SQLITE_API const char *sqlite3_errstr(int rc){
1.121996 +  return sqlite3ErrStr(rc);
1.121997 +}
1.121998 +
1.121999 +/*
1.122000 +** Invalidate all cached KeyInfo objects for database connection "db"
1.122001 +*/
1.122002 +static void invalidateCachedKeyInfo(sqlite3 *db){
1.122003 +  Db *pDb;                    /* A single database */
1.122004 +  int iDb;                    /* The database index number */
1.122005 +  HashElem *k;                /* For looping over tables in pDb */
1.122006 +  Table *pTab;                /* A table in the database */
1.122007 +  Index *pIdx;                /* Each index */
1.122008 +
1.122009 +  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
1.122010 +    if( pDb->pBt==0 ) continue;
1.122011 +    sqlite3BtreeEnter(pDb->pBt);
1.122012 +    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
1.122013 +      pTab = (Table*)sqliteHashData(k);
1.122014 +      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1.122015 +        if( pIdx->pKeyInfo && pIdx->pKeyInfo->db==db ){
1.122016 +          sqlite3KeyInfoUnref(pIdx->pKeyInfo);
1.122017 +          pIdx->pKeyInfo = 0;
1.122018 +        }
1.122019 +      }
1.122020 +    }
1.122021 +    sqlite3BtreeLeave(pDb->pBt);
1.122022 +  }
1.122023 +}
1.122024 +
1.122025 +/*
1.122026 +** Create a new collating function for database "db".  The name is zName
1.122027 +** and the encoding is enc.
1.122028 +*/
1.122029 +static int createCollation(
1.122030 +  sqlite3* db,
1.122031 +  const char *zName, 
1.122032 +  u8 enc,
1.122033 +  void* pCtx,
1.122034 +  int(*xCompare)(void*,int,const void*,int,const void*),
1.122035 +  void(*xDel)(void*)
1.122036 +){
1.122037 +  CollSeq *pColl;
1.122038 +  int enc2;
1.122039 +  int nName = sqlite3Strlen30(zName);
1.122040 +  
1.122041 +  assert( sqlite3_mutex_held(db->mutex) );
1.122042 +
1.122043 +  /* If SQLITE_UTF16 is specified as the encoding type, transform this
1.122044 +  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
1.122045 +  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
1.122046 +  */
1.122047 +  enc2 = enc;
1.122048 +  testcase( enc2==SQLITE_UTF16 );
1.122049 +  testcase( enc2==SQLITE_UTF16_ALIGNED );
1.122050 +  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
1.122051 +    enc2 = SQLITE_UTF16NATIVE;
1.122052 +  }
1.122053 +  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
1.122054 +    return SQLITE_MISUSE_BKPT;
1.122055 +  }
1.122056 +
1.122057 +  /* Check if this call is removing or replacing an existing collation 
1.122058 +  ** sequence. If so, and there are active VMs, return busy. If there
1.122059 +  ** are no active VMs, invalidate any pre-compiled statements.
1.122060 +  */
1.122061 +  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
1.122062 +  if( pColl && pColl->xCmp ){
1.122063 +    if( db->nVdbeActive ){
1.122064 +      sqlite3Error(db, SQLITE_BUSY, 
1.122065 +        "unable to delete/modify collation sequence due to active statements");
1.122066 +      return SQLITE_BUSY;
1.122067 +    }
1.122068 +    sqlite3ExpirePreparedStatements(db);
1.122069 +    invalidateCachedKeyInfo(db);
1.122070 +
1.122071 +    /* If collation sequence pColl was created directly by a call to
1.122072 +    ** sqlite3_create_collation, and not generated by synthCollSeq(),
1.122073 +    ** then any copies made by synthCollSeq() need to be invalidated.
1.122074 +    ** Also, collation destructor - CollSeq.xDel() - function may need
1.122075 +    ** to be called.
1.122076 +    */ 
1.122077 +    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
1.122078 +      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
1.122079 +      int j;
1.122080 +      for(j=0; j<3; j++){
1.122081 +        CollSeq *p = &aColl[j];
1.122082 +        if( p->enc==pColl->enc ){
1.122083 +          if( p->xDel ){
1.122084 +            p->xDel(p->pUser);
1.122085 +          }
1.122086 +          p->xCmp = 0;
1.122087 +        }
1.122088 +      }
1.122089 +    }
1.122090 +  }
1.122091 +
1.122092 +  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
1.122093 +  if( pColl==0 ) return SQLITE_NOMEM;
1.122094 +  pColl->xCmp = xCompare;
1.122095 +  pColl->pUser = pCtx;
1.122096 +  pColl->xDel = xDel;
1.122097 +  pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
1.122098 +  sqlite3Error(db, SQLITE_OK, 0);
1.122099 +  return SQLITE_OK;
1.122100 +}
1.122101 +
1.122102 +
1.122103 +/*
1.122104 +** This array defines hard upper bounds on limit values.  The
1.122105 +** initializer must be kept in sync with the SQLITE_LIMIT_*
1.122106 +** #defines in sqlite3.h.
1.122107 +*/
1.122108 +static const int aHardLimit[] = {
1.122109 +  SQLITE_MAX_LENGTH,
1.122110 +  SQLITE_MAX_SQL_LENGTH,
1.122111 +  SQLITE_MAX_COLUMN,
1.122112 +  SQLITE_MAX_EXPR_DEPTH,
1.122113 +  SQLITE_MAX_COMPOUND_SELECT,
1.122114 +  SQLITE_MAX_VDBE_OP,
1.122115 +  SQLITE_MAX_FUNCTION_ARG,
1.122116 +  SQLITE_MAX_ATTACHED,
1.122117 +  SQLITE_MAX_LIKE_PATTERN_LENGTH,
1.122118 +  SQLITE_MAX_VARIABLE_NUMBER,
1.122119 +  SQLITE_MAX_TRIGGER_DEPTH,
1.122120 +};
1.122121 +
1.122122 +/*
1.122123 +** Make sure the hard limits are set to reasonable values
1.122124 +*/
1.122125 +#if SQLITE_MAX_LENGTH<100
1.122126 +# error SQLITE_MAX_LENGTH must be at least 100
1.122127 +#endif
1.122128 +#if SQLITE_MAX_SQL_LENGTH<100
1.122129 +# error SQLITE_MAX_SQL_LENGTH must be at least 100
1.122130 +#endif
1.122131 +#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
1.122132 +# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
1.122133 +#endif
1.122134 +#if SQLITE_MAX_COMPOUND_SELECT<2
1.122135 +# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
1.122136 +#endif
1.122137 +#if SQLITE_MAX_VDBE_OP<40
1.122138 +# error SQLITE_MAX_VDBE_OP must be at least 40
1.122139 +#endif
1.122140 +#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
1.122141 +# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
1.122142 +#endif
1.122143 +#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
1.122144 +# error SQLITE_MAX_ATTACHED must be between 0 and 62
1.122145 +#endif
1.122146 +#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
1.122147 +# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
1.122148 +#endif
1.122149 +#if SQLITE_MAX_COLUMN>32767
1.122150 +# error SQLITE_MAX_COLUMN must not exceed 32767
1.122151 +#endif
1.122152 +#if SQLITE_MAX_TRIGGER_DEPTH<1
1.122153 +# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
1.122154 +#endif
1.122155 +
1.122156 +
1.122157 +/*
1.122158 +** Change the value of a limit.  Report the old value.
1.122159 +** If an invalid limit index is supplied, report -1.
1.122160 +** Make no changes but still report the old value if the
1.122161 +** new limit is negative.
1.122162 +**
1.122163 +** A new lower limit does not shrink existing constructs.
1.122164 +** It merely prevents new constructs that exceed the limit
1.122165 +** from forming.
1.122166 +*/
1.122167 +SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
1.122168 +  int oldLimit;
1.122169 +
1.122170 +
1.122171 +  /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
1.122172 +  ** there is a hard upper bound set at compile-time by a C preprocessor
1.122173 +  ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
1.122174 +  ** "_MAX_".)
1.122175 +  */
1.122176 +  assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
1.122177 +  assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
1.122178 +  assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
1.122179 +  assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
1.122180 +  assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
1.122181 +  assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
1.122182 +  assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
1.122183 +  assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
1.122184 +  assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
1.122185 +                                               SQLITE_MAX_LIKE_PATTERN_LENGTH );
1.122186 +  assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
1.122187 +  assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
1.122188 +  assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
1.122189 +
1.122190 +
1.122191 +  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
1.122192 +    return -1;
1.122193 +  }
1.122194 +  oldLimit = db->aLimit[limitId];
1.122195 +  if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
1.122196 +    if( newLimit>aHardLimit[limitId] ){
1.122197 +      newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
1.122198 +    }
1.122199 +    db->aLimit[limitId] = newLimit;
1.122200 +  }
1.122201 +  return oldLimit;                     /* IMP: R-53341-35419 */
1.122202 +}
1.122203 +
1.122204 +/*
1.122205 +** This function is used to parse both URIs and non-URI filenames passed by the
1.122206 +** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
1.122207 +** URIs specified as part of ATTACH statements.
1.122208 +**
1.122209 +** The first argument to this function is the name of the VFS to use (or
1.122210 +** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
1.122211 +** query parameter. The second argument contains the URI (or non-URI filename)
1.122212 +** itself. When this function is called the *pFlags variable should contain
1.122213 +** the default flags to open the database handle with. The value stored in
1.122214 +** *pFlags may be updated before returning if the URI filename contains 
1.122215 +** "cache=xxx" or "mode=xxx" query parameters.
1.122216 +**
1.122217 +** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
1.122218 +** the VFS that should be used to open the database file. *pzFile is set to
1.122219 +** point to a buffer containing the name of the file to open. It is the 
1.122220 +** responsibility of the caller to eventually call sqlite3_free() to release
1.122221 +** this buffer.
1.122222 +**
1.122223 +** If an error occurs, then an SQLite error code is returned and *pzErrMsg
1.122224 +** may be set to point to a buffer containing an English language error 
1.122225 +** message. It is the responsibility of the caller to eventually release
1.122226 +** this buffer by calling sqlite3_free().
1.122227 +*/
1.122228 +SQLITE_PRIVATE int sqlite3ParseUri(
1.122229 +  const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
1.122230 +  const char *zUri,               /* Nul-terminated URI to parse */
1.122231 +  unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
1.122232 +  sqlite3_vfs **ppVfs,            /* OUT: VFS to use */ 
1.122233 +  char **pzFile,                  /* OUT: Filename component of URI */
1.122234 +  char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
1.122235 +){
1.122236 +  int rc = SQLITE_OK;
1.122237 +  unsigned int flags = *pFlags;
1.122238 +  const char *zVfs = zDefaultVfs;
1.122239 +  char *zFile;
1.122240 +  char c;
1.122241 +  int nUri = sqlite3Strlen30(zUri);
1.122242 +
1.122243 +  assert( *pzErrMsg==0 );
1.122244 +
1.122245 +  if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri) 
1.122246 +   && nUri>=5 && memcmp(zUri, "file:", 5)==0 
1.122247 +  ){
1.122248 +    char *zOpt;
1.122249 +    int eState;                   /* Parser state when parsing URI */
1.122250 +    int iIn;                      /* Input character index */
1.122251 +    int iOut = 0;                 /* Output character index */
1.122252 +    int nByte = nUri+2;           /* Bytes of space to allocate */
1.122253 +
1.122254 +    /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen 
1.122255 +    ** method that there may be extra parameters following the file-name.  */
1.122256 +    flags |= SQLITE_OPEN_URI;
1.122257 +
1.122258 +    for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
1.122259 +    zFile = sqlite3_malloc(nByte);
1.122260 +    if( !zFile ) return SQLITE_NOMEM;
1.122261 +
1.122262 +    iIn = 5;
1.122263 +#ifndef SQLITE_ALLOW_URI_AUTHORITY
1.122264 +    /* Discard the scheme and authority segments of the URI. */
1.122265 +    if( zUri[5]=='/' && zUri[6]=='/' ){
1.122266 +      iIn = 7;
1.122267 +      while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
1.122268 +      if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
1.122269 +        *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", 
1.122270 +            iIn-7, &zUri[7]);
1.122271 +        rc = SQLITE_ERROR;
1.122272 +        goto parse_uri_out;
1.122273 +      }
1.122274 +    }
1.122275 +#endif
1.122276 +
1.122277 +    /* Copy the filename and any query parameters into the zFile buffer. 
1.122278 +    ** Decode %HH escape codes along the way. 
1.122279 +    **
1.122280 +    ** Within this loop, variable eState may be set to 0, 1 or 2, depending
1.122281 +    ** on the parsing context. As follows:
1.122282 +    **
1.122283 +    **   0: Parsing file-name.
1.122284 +    **   1: Parsing name section of a name=value query parameter.
1.122285 +    **   2: Parsing value section of a name=value query parameter.
1.122286 +    */
1.122287 +    eState = 0;
1.122288 +    while( (c = zUri[iIn])!=0 && c!='#' ){
1.122289 +      iIn++;
1.122290 +      if( c=='%' 
1.122291 +       && sqlite3Isxdigit(zUri[iIn]) 
1.122292 +       && sqlite3Isxdigit(zUri[iIn+1]) 
1.122293 +      ){
1.122294 +        int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
1.122295 +        octet += sqlite3HexToInt(zUri[iIn++]);
1.122296 +
1.122297 +        assert( octet>=0 && octet<256 );
1.122298 +        if( octet==0 ){
1.122299 +          /* This branch is taken when "%00" appears within the URI. In this
1.122300 +          ** case we ignore all text in the remainder of the path, name or
1.122301 +          ** value currently being parsed. So ignore the current character
1.122302 +          ** and skip to the next "?", "=" or "&", as appropriate. */
1.122303 +          while( (c = zUri[iIn])!=0 && c!='#' 
1.122304 +              && (eState!=0 || c!='?')
1.122305 +              && (eState!=1 || (c!='=' && c!='&'))
1.122306 +              && (eState!=2 || c!='&')
1.122307 +          ){
1.122308 +            iIn++;
1.122309 +          }
1.122310 +          continue;
1.122311 +        }
1.122312 +        c = octet;
1.122313 +      }else if( eState==1 && (c=='&' || c=='=') ){
1.122314 +        if( zFile[iOut-1]==0 ){
1.122315 +          /* An empty option name. Ignore this option altogether. */
1.122316 +          while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
1.122317 +          continue;
1.122318 +        }
1.122319 +        if( c=='&' ){
1.122320 +          zFile[iOut++] = '\0';
1.122321 +        }else{
1.122322 +          eState = 2;
1.122323 +        }
1.122324 +        c = 0;
1.122325 +      }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
1.122326 +        c = 0;
1.122327 +        eState = 1;
1.122328 +      }
1.122329 +      zFile[iOut++] = c;
1.122330 +    }
1.122331 +    if( eState==1 ) zFile[iOut++] = '\0';
1.122332 +    zFile[iOut++] = '\0';
1.122333 +    zFile[iOut++] = '\0';
1.122334 +
1.122335 +    /* Check if there were any options specified that should be interpreted 
1.122336 +    ** here. Options that are interpreted here include "vfs" and those that
1.122337 +    ** correspond to flags that may be passed to the sqlite3_open_v2()
1.122338 +    ** method. */
1.122339 +    zOpt = &zFile[sqlite3Strlen30(zFile)+1];
1.122340 +    while( zOpt[0] ){
1.122341 +      int nOpt = sqlite3Strlen30(zOpt);
1.122342 +      char *zVal = &zOpt[nOpt+1];
1.122343 +      int nVal = sqlite3Strlen30(zVal);
1.122344 +
1.122345 +      if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
1.122346 +        zVfs = zVal;
1.122347 +      }else{
1.122348 +        struct OpenMode {
1.122349 +          const char *z;
1.122350 +          int mode;
1.122351 +        } *aMode = 0;
1.122352 +        char *zModeType = 0;
1.122353 +        int mask = 0;
1.122354 +        int limit = 0;
1.122355 +
1.122356 +        if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
1.122357 +          static struct OpenMode aCacheMode[] = {
1.122358 +            { "shared",  SQLITE_OPEN_SHAREDCACHE },
1.122359 +            { "private", SQLITE_OPEN_PRIVATECACHE },
1.122360 +            { 0, 0 }
1.122361 +          };
1.122362 +
1.122363 +          mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
1.122364 +          aMode = aCacheMode;
1.122365 +          limit = mask;
1.122366 +          zModeType = "cache";
1.122367 +        }
1.122368 +        if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
1.122369 +          static struct OpenMode aOpenMode[] = {
1.122370 +            { "ro",  SQLITE_OPEN_READONLY },
1.122371 +            { "rw",  SQLITE_OPEN_READWRITE }, 
1.122372 +            { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
1.122373 +            { "memory", SQLITE_OPEN_MEMORY },
1.122374 +            { 0, 0 }
1.122375 +          };
1.122376 +
1.122377 +          mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
1.122378 +                   | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
1.122379 +          aMode = aOpenMode;
1.122380 +          limit = mask & flags;
1.122381 +          zModeType = "access";
1.122382 +        }
1.122383 +
1.122384 +        if( aMode ){
1.122385 +          int i;
1.122386 +          int mode = 0;
1.122387 +          for(i=0; aMode[i].z; i++){
1.122388 +            const char *z = aMode[i].z;
1.122389 +            if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
1.122390 +              mode = aMode[i].mode;
1.122391 +              break;
1.122392 +            }
1.122393 +          }
1.122394 +          if( mode==0 ){
1.122395 +            *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
1.122396 +            rc = SQLITE_ERROR;
1.122397 +            goto parse_uri_out;
1.122398 +          }
1.122399 +          if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
1.122400 +            *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
1.122401 +                                        zModeType, zVal);
1.122402 +            rc = SQLITE_PERM;
1.122403 +            goto parse_uri_out;
1.122404 +          }
1.122405 +          flags = (flags & ~mask) | mode;
1.122406 +        }
1.122407 +      }
1.122408 +
1.122409 +      zOpt = &zVal[nVal+1];
1.122410 +    }
1.122411 +
1.122412 +  }else{
1.122413 +    zFile = sqlite3_malloc(nUri+2);
1.122414 +    if( !zFile ) return SQLITE_NOMEM;
1.122415 +    memcpy(zFile, zUri, nUri);
1.122416 +    zFile[nUri] = '\0';
1.122417 +    zFile[nUri+1] = '\0';
1.122418 +    flags &= ~SQLITE_OPEN_URI;
1.122419 +  }
1.122420 +
1.122421 +  *ppVfs = sqlite3_vfs_find(zVfs);
1.122422 +  if( *ppVfs==0 ){
1.122423 +    *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
1.122424 +    rc = SQLITE_ERROR;
1.122425 +  }
1.122426 + parse_uri_out:
1.122427 +  if( rc!=SQLITE_OK ){
1.122428 +    sqlite3_free(zFile);
1.122429 +    zFile = 0;
1.122430 +  }
1.122431 +  *pFlags = flags;
1.122432 +  *pzFile = zFile;
1.122433 +  return rc;
1.122434 +}
1.122435 +
1.122436 +
1.122437 +/*
1.122438 +** This routine does the work of opening a database on behalf of
1.122439 +** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
1.122440 +** is UTF-8 encoded.
1.122441 +*/
1.122442 +static int openDatabase(
1.122443 +  const char *zFilename, /* Database filename UTF-8 encoded */
1.122444 +  sqlite3 **ppDb,        /* OUT: Returned database handle */
1.122445 +  unsigned int flags,    /* Operational flags */
1.122446 +  const char *zVfs       /* Name of the VFS to use */
1.122447 +){
1.122448 +  sqlite3 *db;                    /* Store allocated handle here */
1.122449 +  int rc;                         /* Return code */
1.122450 +  int isThreadsafe;               /* True for threadsafe connections */
1.122451 +  char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
1.122452 +  char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
1.122453 +
1.122454 +  *ppDb = 0;
1.122455 +#ifndef SQLITE_OMIT_AUTOINIT
1.122456 +  rc = sqlite3_initialize();
1.122457 +  if( rc ) return rc;
1.122458 +#endif
1.122459 +
1.122460 +  /* Only allow sensible combinations of bits in the flags argument.  
1.122461 +  ** Throw an error if any non-sense combination is used.  If we
1.122462 +  ** do not block illegal combinations here, it could trigger
1.122463 +  ** assert() statements in deeper layers.  Sensible combinations
1.122464 +  ** are:
1.122465 +  **
1.122466 +  **  1:  SQLITE_OPEN_READONLY
1.122467 +  **  2:  SQLITE_OPEN_READWRITE
1.122468 +  **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
1.122469 +  */
1.122470 +  assert( SQLITE_OPEN_READONLY  == 0x01 );
1.122471 +  assert( SQLITE_OPEN_READWRITE == 0x02 );
1.122472 +  assert( SQLITE_OPEN_CREATE    == 0x04 );
1.122473 +  testcase( (1<<(flags&7))==0x02 ); /* READONLY */
1.122474 +  testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
1.122475 +  testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
1.122476 +  if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
1.122477 +
1.122478 +  if( sqlite3GlobalConfig.bCoreMutex==0 ){
1.122479 +    isThreadsafe = 0;
1.122480 +  }else if( flags & SQLITE_OPEN_NOMUTEX ){
1.122481 +    isThreadsafe = 0;
1.122482 +  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
1.122483 +    isThreadsafe = 1;
1.122484 +  }else{
1.122485 +    isThreadsafe = sqlite3GlobalConfig.bFullMutex;
1.122486 +  }
1.122487 +  if( flags & SQLITE_OPEN_PRIVATECACHE ){
1.122488 +    flags &= ~SQLITE_OPEN_SHAREDCACHE;
1.122489 +  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
1.122490 +    flags |= SQLITE_OPEN_SHAREDCACHE;
1.122491 +  }
1.122492 +
1.122493 +  /* Remove harmful bits from the flags parameter
1.122494 +  **
1.122495 +  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
1.122496 +  ** dealt with in the previous code block.  Besides these, the only
1.122497 +  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
1.122498 +  ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
1.122499 +  ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
1.122500 +  ** off all other flags.
1.122501 +  */
1.122502 +  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
1.122503 +               SQLITE_OPEN_EXCLUSIVE |
1.122504 +               SQLITE_OPEN_MAIN_DB |
1.122505 +               SQLITE_OPEN_TEMP_DB | 
1.122506 +               SQLITE_OPEN_TRANSIENT_DB | 
1.122507 +               SQLITE_OPEN_MAIN_JOURNAL | 
1.122508 +               SQLITE_OPEN_TEMP_JOURNAL | 
1.122509 +               SQLITE_OPEN_SUBJOURNAL | 
1.122510 +               SQLITE_OPEN_MASTER_JOURNAL |
1.122511 +               SQLITE_OPEN_NOMUTEX |
1.122512 +               SQLITE_OPEN_FULLMUTEX |
1.122513 +               SQLITE_OPEN_WAL
1.122514 +             );
1.122515 +
1.122516 +  /* Allocate the sqlite data structure */
1.122517 +  db = sqlite3MallocZero( sizeof(sqlite3) );
1.122518 +  if( db==0 ) goto opendb_out;
1.122519 +  if( isThreadsafe ){
1.122520 +    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
1.122521 +    if( db->mutex==0 ){
1.122522 +      sqlite3_free(db);
1.122523 +      db = 0;
1.122524 +      goto opendb_out;
1.122525 +    }
1.122526 +  }
1.122527 +  sqlite3_mutex_enter(db->mutex);
1.122528 +  db->errMask = 0xff;
1.122529 +  db->nDb = 2;
1.122530 +  db->magic = SQLITE_MAGIC_BUSY;
1.122531 +  db->aDb = db->aDbStatic;
1.122532 +
1.122533 +  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
1.122534 +  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
1.122535 +  db->autoCommit = 1;
1.122536 +  db->nextAutovac = -1;
1.122537 +  db->szMmap = sqlite3GlobalConfig.szMmap;
1.122538 +  db->nextPagesize = 0;
1.122539 +  db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
1.122540 +#if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
1.122541 +                 | SQLITE_AutoIndex
1.122542 +#endif
1.122543 +#if SQLITE_DEFAULT_FILE_FORMAT<4
1.122544 +                 | SQLITE_LegacyFileFmt
1.122545 +#endif
1.122546 +#ifdef SQLITE_ENABLE_LOAD_EXTENSION
1.122547 +                 | SQLITE_LoadExtension
1.122548 +#endif
1.122549 +#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
1.122550 +                 | SQLITE_RecTriggers
1.122551 +#endif
1.122552 +#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
1.122553 +                 | SQLITE_ForeignKeys
1.122554 +#endif
1.122555 +      ;
1.122556 +  sqlite3HashInit(&db->aCollSeq);
1.122557 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.122558 +  sqlite3HashInit(&db->aModule);
1.122559 +#endif
1.122560 +
1.122561 +  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
1.122562 +  ** and UTF-16, so add a version for each to avoid any unnecessary
1.122563 +  ** conversions. The only error that can occur here is a malloc() failure.
1.122564 +  */
1.122565 +  createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
1.122566 +  createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
1.122567 +  createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
1.122568 +  createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
1.122569 +  if( db->mallocFailed ){
1.122570 +    goto opendb_out;
1.122571 +  }
1.122572 +  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
1.122573 +  assert( db->pDfltColl!=0 );
1.122574 +
1.122575 +  /* Also add a UTF-8 case-insensitive collation sequence. */
1.122576 +  createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
1.122577 +
1.122578 +  /* Parse the filename/URI argument. */
1.122579 +  db->openFlags = flags;
1.122580 +  rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
1.122581 +  if( rc!=SQLITE_OK ){
1.122582 +    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
1.122583 +    sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
1.122584 +    sqlite3_free(zErrMsg);
1.122585 +    goto opendb_out;
1.122586 +  }
1.122587 +
1.122588 +  /* Open the backend database driver */
1.122589 +  rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
1.122590 +                        flags | SQLITE_OPEN_MAIN_DB);
1.122591 +  if( rc!=SQLITE_OK ){
1.122592 +    if( rc==SQLITE_IOERR_NOMEM ){
1.122593 +      rc = SQLITE_NOMEM;
1.122594 +    }
1.122595 +    sqlite3Error(db, rc, 0);
1.122596 +    goto opendb_out;
1.122597 +  }
1.122598 +  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
1.122599 +  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
1.122600 +
1.122601 +
1.122602 +  /* The default safety_level for the main database is 'full'; for the temp
1.122603 +  ** database it is 'NONE'. This matches the pager layer defaults.  
1.122604 +  */
1.122605 +  db->aDb[0].zName = "main";
1.122606 +  db->aDb[0].safety_level = 3;
1.122607 +  db->aDb[1].zName = "temp";
1.122608 +  db->aDb[1].safety_level = 1;
1.122609 +
1.122610 +  db->magic = SQLITE_MAGIC_OPEN;
1.122611 +  if( db->mallocFailed ){
1.122612 +    goto opendb_out;
1.122613 +  }
1.122614 +
1.122615 +  /* Register all built-in functions, but do not attempt to read the
1.122616 +  ** database schema yet. This is delayed until the first time the database
1.122617 +  ** is accessed.
1.122618 +  */
1.122619 +  sqlite3Error(db, SQLITE_OK, 0);
1.122620 +  sqlite3RegisterBuiltinFunctions(db);
1.122621 +
1.122622 +  /* Load automatic extensions - extensions that have been registered
1.122623 +  ** using the sqlite3_automatic_extension() API.
1.122624 +  */
1.122625 +  rc = sqlite3_errcode(db);
1.122626 +  if( rc==SQLITE_OK ){
1.122627 +    sqlite3AutoLoadExtensions(db);
1.122628 +    rc = sqlite3_errcode(db);
1.122629 +    if( rc!=SQLITE_OK ){
1.122630 +      goto opendb_out;
1.122631 +    }
1.122632 +  }
1.122633 +
1.122634 +#ifdef SQLITE_ENABLE_FTS1
1.122635 +  if( !db->mallocFailed ){
1.122636 +    extern int sqlite3Fts1Init(sqlite3*);
1.122637 +    rc = sqlite3Fts1Init(db);
1.122638 +  }
1.122639 +#endif
1.122640 +
1.122641 +#ifdef SQLITE_ENABLE_FTS2
1.122642 +  if( !db->mallocFailed && rc==SQLITE_OK ){
1.122643 +    extern int sqlite3Fts2Init(sqlite3*);
1.122644 +    rc = sqlite3Fts2Init(db);
1.122645 +  }
1.122646 +#endif
1.122647 +
1.122648 +#ifdef SQLITE_ENABLE_FTS3
1.122649 +  if( !db->mallocFailed && rc==SQLITE_OK ){
1.122650 +    rc = sqlite3Fts3Init(db);
1.122651 +  }
1.122652 +#endif
1.122653 +
1.122654 +#ifdef SQLITE_ENABLE_ICU
1.122655 +  if( !db->mallocFailed && rc==SQLITE_OK ){
1.122656 +    rc = sqlite3IcuInit(db);
1.122657 +  }
1.122658 +#endif
1.122659 +
1.122660 +#ifdef SQLITE_ENABLE_RTREE
1.122661 +  if( !db->mallocFailed && rc==SQLITE_OK){
1.122662 +    rc = sqlite3RtreeInit(db);
1.122663 +  }
1.122664 +#endif
1.122665 +
1.122666 +  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
1.122667 +  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
1.122668 +  ** mode.  Doing nothing at all also makes NORMAL the default.
1.122669 +  */
1.122670 +#ifdef SQLITE_DEFAULT_LOCKING_MODE
1.122671 +  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
1.122672 +  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
1.122673 +                          SQLITE_DEFAULT_LOCKING_MODE);
1.122674 +#endif
1.122675 +
1.122676 +  if( rc ) sqlite3Error(db, rc, 0);
1.122677 +
1.122678 +  /* Enable the lookaside-malloc subsystem */
1.122679 +  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
1.122680 +                        sqlite3GlobalConfig.nLookaside);
1.122681 +
1.122682 +  sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
1.122683 +
1.122684 +opendb_out:
1.122685 +  sqlite3_free(zOpen);
1.122686 +  if( db ){
1.122687 +    assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
1.122688 +    sqlite3_mutex_leave(db->mutex);
1.122689 +  }
1.122690 +  rc = sqlite3_errcode(db);
1.122691 +  assert( db!=0 || rc==SQLITE_NOMEM );
1.122692 +  if( rc==SQLITE_NOMEM ){
1.122693 +    sqlite3_close(db);
1.122694 +    db = 0;
1.122695 +  }else if( rc!=SQLITE_OK ){
1.122696 +    db->magic = SQLITE_MAGIC_SICK;
1.122697 +  }
1.122698 +  *ppDb = db;
1.122699 +#ifdef SQLITE_ENABLE_SQLLOG
1.122700 +  if( sqlite3GlobalConfig.xSqllog ){
1.122701 +    /* Opening a db handle. Fourth parameter is passed 0. */
1.122702 +    void *pArg = sqlite3GlobalConfig.pSqllogArg;
1.122703 +    sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
1.122704 +  }
1.122705 +#endif
1.122706 +  return sqlite3ApiExit(0, rc);
1.122707 +}
1.122708 +
1.122709 +/*
1.122710 +** Open a new database handle.
1.122711 +*/
1.122712 +SQLITE_API int sqlite3_open(
1.122713 +  const char *zFilename, 
1.122714 +  sqlite3 **ppDb 
1.122715 +){
1.122716 +  return openDatabase(zFilename, ppDb,
1.122717 +                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
1.122718 +}
1.122719 +SQLITE_API int sqlite3_open_v2(
1.122720 +  const char *filename,   /* Database filename (UTF-8) */
1.122721 +  sqlite3 **ppDb,         /* OUT: SQLite db handle */
1.122722 +  int flags,              /* Flags */
1.122723 +  const char *zVfs        /* Name of VFS module to use */
1.122724 +){
1.122725 +  return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
1.122726 +}
1.122727 +
1.122728 +#ifndef SQLITE_OMIT_UTF16
1.122729 +/*
1.122730 +** Open a new database handle.
1.122731 +*/
1.122732 +SQLITE_API int sqlite3_open16(
1.122733 +  const void *zFilename, 
1.122734 +  sqlite3 **ppDb
1.122735 +){
1.122736 +  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
1.122737 +  sqlite3_value *pVal;
1.122738 +  int rc;
1.122739 +
1.122740 +  assert( zFilename );
1.122741 +  assert( ppDb );
1.122742 +  *ppDb = 0;
1.122743 +#ifndef SQLITE_OMIT_AUTOINIT
1.122744 +  rc = sqlite3_initialize();
1.122745 +  if( rc ) return rc;
1.122746 +#endif
1.122747 +  pVal = sqlite3ValueNew(0);
1.122748 +  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
1.122749 +  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
1.122750 +  if( zFilename8 ){
1.122751 +    rc = openDatabase(zFilename8, ppDb,
1.122752 +                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
1.122753 +    assert( *ppDb || rc==SQLITE_NOMEM );
1.122754 +    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
1.122755 +      ENC(*ppDb) = SQLITE_UTF16NATIVE;
1.122756 +    }
1.122757 +  }else{
1.122758 +    rc = SQLITE_NOMEM;
1.122759 +  }
1.122760 +  sqlite3ValueFree(pVal);
1.122761 +
1.122762 +  return sqlite3ApiExit(0, rc);
1.122763 +}
1.122764 +#endif /* SQLITE_OMIT_UTF16 */
1.122765 +
1.122766 +/*
1.122767 +** Register a new collation sequence with the database handle db.
1.122768 +*/
1.122769 +SQLITE_API int sqlite3_create_collation(
1.122770 +  sqlite3* db, 
1.122771 +  const char *zName, 
1.122772 +  int enc, 
1.122773 +  void* pCtx,
1.122774 +  int(*xCompare)(void*,int,const void*,int,const void*)
1.122775 +){
1.122776 +  int rc;
1.122777 +  sqlite3_mutex_enter(db->mutex);
1.122778 +  assert( !db->mallocFailed );
1.122779 +  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
1.122780 +  rc = sqlite3ApiExit(db, rc);
1.122781 +  sqlite3_mutex_leave(db->mutex);
1.122782 +  return rc;
1.122783 +}
1.122784 +
1.122785 +/*
1.122786 +** Register a new collation sequence with the database handle db.
1.122787 +*/
1.122788 +SQLITE_API int sqlite3_create_collation_v2(
1.122789 +  sqlite3* db, 
1.122790 +  const char *zName, 
1.122791 +  int enc, 
1.122792 +  void* pCtx,
1.122793 +  int(*xCompare)(void*,int,const void*,int,const void*),
1.122794 +  void(*xDel)(void*)
1.122795 +){
1.122796 +  int rc;
1.122797 +  sqlite3_mutex_enter(db->mutex);
1.122798 +  assert( !db->mallocFailed );
1.122799 +  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
1.122800 +  rc = sqlite3ApiExit(db, rc);
1.122801 +  sqlite3_mutex_leave(db->mutex);
1.122802 +  return rc;
1.122803 +}
1.122804 +
1.122805 +#ifndef SQLITE_OMIT_UTF16
1.122806 +/*
1.122807 +** Register a new collation sequence with the database handle db.
1.122808 +*/
1.122809 +SQLITE_API int sqlite3_create_collation16(
1.122810 +  sqlite3* db, 
1.122811 +  const void *zName,
1.122812 +  int enc, 
1.122813 +  void* pCtx,
1.122814 +  int(*xCompare)(void*,int,const void*,int,const void*)
1.122815 +){
1.122816 +  int rc = SQLITE_OK;
1.122817 +  char *zName8;
1.122818 +  sqlite3_mutex_enter(db->mutex);
1.122819 +  assert( !db->mallocFailed );
1.122820 +  zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
1.122821 +  if( zName8 ){
1.122822 +    rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
1.122823 +    sqlite3DbFree(db, zName8);
1.122824 +  }
1.122825 +  rc = sqlite3ApiExit(db, rc);
1.122826 +  sqlite3_mutex_leave(db->mutex);
1.122827 +  return rc;
1.122828 +}
1.122829 +#endif /* SQLITE_OMIT_UTF16 */
1.122830 +
1.122831 +/*
1.122832 +** Register a collation sequence factory callback with the database handle
1.122833 +** db. Replace any previously installed collation sequence factory.
1.122834 +*/
1.122835 +SQLITE_API int sqlite3_collation_needed(
1.122836 +  sqlite3 *db, 
1.122837 +  void *pCollNeededArg, 
1.122838 +  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
1.122839 +){
1.122840 +  sqlite3_mutex_enter(db->mutex);
1.122841 +  db->xCollNeeded = xCollNeeded;
1.122842 +  db->xCollNeeded16 = 0;
1.122843 +  db->pCollNeededArg = pCollNeededArg;
1.122844 +  sqlite3_mutex_leave(db->mutex);
1.122845 +  return SQLITE_OK;
1.122846 +}
1.122847 +
1.122848 +#ifndef SQLITE_OMIT_UTF16
1.122849 +/*
1.122850 +** Register a collation sequence factory callback with the database handle
1.122851 +** db. Replace any previously installed collation sequence factory.
1.122852 +*/
1.122853 +SQLITE_API int sqlite3_collation_needed16(
1.122854 +  sqlite3 *db, 
1.122855 +  void *pCollNeededArg, 
1.122856 +  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
1.122857 +){
1.122858 +  sqlite3_mutex_enter(db->mutex);
1.122859 +  db->xCollNeeded = 0;
1.122860 +  db->xCollNeeded16 = xCollNeeded16;
1.122861 +  db->pCollNeededArg = pCollNeededArg;
1.122862 +  sqlite3_mutex_leave(db->mutex);
1.122863 +  return SQLITE_OK;
1.122864 +}
1.122865 +#endif /* SQLITE_OMIT_UTF16 */
1.122866 +
1.122867 +#ifndef SQLITE_OMIT_DEPRECATED
1.122868 +/*
1.122869 +** This function is now an anachronism. It used to be used to recover from a
1.122870 +** malloc() failure, but SQLite now does this automatically.
1.122871 +*/
1.122872 +SQLITE_API int sqlite3_global_recover(void){
1.122873 +  return SQLITE_OK;
1.122874 +}
1.122875 +#endif
1.122876 +
1.122877 +/*
1.122878 +** Test to see whether or not the database connection is in autocommit
1.122879 +** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
1.122880 +** by default.  Autocommit is disabled by a BEGIN statement and reenabled
1.122881 +** by the next COMMIT or ROLLBACK.
1.122882 +*/
1.122883 +SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
1.122884 +  return db->autoCommit;
1.122885 +}
1.122886 +
1.122887 +/*
1.122888 +** The following routines are subtitutes for constants SQLITE_CORRUPT,
1.122889 +** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
1.122890 +** constants.  They server two purposes:
1.122891 +**
1.122892 +**   1.  Serve as a convenient place to set a breakpoint in a debugger
1.122893 +**       to detect when version error conditions occurs.
1.122894 +**
1.122895 +**   2.  Invoke sqlite3_log() to provide the source code location where
1.122896 +**       a low-level error is first detected.
1.122897 +*/
1.122898 +SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
1.122899 +  testcase( sqlite3GlobalConfig.xLog!=0 );
1.122900 +  sqlite3_log(SQLITE_CORRUPT,
1.122901 +              "database corruption at line %d of [%.10s]",
1.122902 +              lineno, 20+sqlite3_sourceid());
1.122903 +  return SQLITE_CORRUPT;
1.122904 +}
1.122905 +SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
1.122906 +  testcase( sqlite3GlobalConfig.xLog!=0 );
1.122907 +  sqlite3_log(SQLITE_MISUSE, 
1.122908 +              "misuse at line %d of [%.10s]",
1.122909 +              lineno, 20+sqlite3_sourceid());
1.122910 +  return SQLITE_MISUSE;
1.122911 +}
1.122912 +SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
1.122913 +  testcase( sqlite3GlobalConfig.xLog!=0 );
1.122914 +  sqlite3_log(SQLITE_CANTOPEN, 
1.122915 +              "cannot open file at line %d of [%.10s]",
1.122916 +              lineno, 20+sqlite3_sourceid());
1.122917 +  return SQLITE_CANTOPEN;
1.122918 +}
1.122919 +
1.122920 +
1.122921 +#ifndef SQLITE_OMIT_DEPRECATED
1.122922 +/*
1.122923 +** This is a convenience routine that makes sure that all thread-specific
1.122924 +** data for this thread has been deallocated.
1.122925 +**
1.122926 +** SQLite no longer uses thread-specific data so this routine is now a
1.122927 +** no-op.  It is retained for historical compatibility.
1.122928 +*/
1.122929 +SQLITE_API void sqlite3_thread_cleanup(void){
1.122930 +}
1.122931 +#endif
1.122932 +
1.122933 +/*
1.122934 +** Return meta information about a specific column of a database table.
1.122935 +** See comment in sqlite3.h (sqlite.h.in) for details.
1.122936 +*/
1.122937 +#ifdef SQLITE_ENABLE_COLUMN_METADATA
1.122938 +SQLITE_API int sqlite3_table_column_metadata(
1.122939 +  sqlite3 *db,                /* Connection handle */
1.122940 +  const char *zDbName,        /* Database name or NULL */
1.122941 +  const char *zTableName,     /* Table name */
1.122942 +  const char *zColumnName,    /* Column name */
1.122943 +  char const **pzDataType,    /* OUTPUT: Declared data type */
1.122944 +  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
1.122945 +  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
1.122946 +  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
1.122947 +  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
1.122948 +){
1.122949 +  int rc;
1.122950 +  char *zErrMsg = 0;
1.122951 +  Table *pTab = 0;
1.122952 +  Column *pCol = 0;
1.122953 +  int iCol;
1.122954 +
1.122955 +  char const *zDataType = 0;
1.122956 +  char const *zCollSeq = 0;
1.122957 +  int notnull = 0;
1.122958 +  int primarykey = 0;
1.122959 +  int autoinc = 0;
1.122960 +
1.122961 +  /* Ensure the database schema has been loaded */
1.122962 +  sqlite3_mutex_enter(db->mutex);
1.122963 +  sqlite3BtreeEnterAll(db);
1.122964 +  rc = sqlite3Init(db, &zErrMsg);
1.122965 +  if( SQLITE_OK!=rc ){
1.122966 +    goto error_out;
1.122967 +  }
1.122968 +
1.122969 +  /* Locate the table in question */
1.122970 +  pTab = sqlite3FindTable(db, zTableName, zDbName);
1.122971 +  if( !pTab || pTab->pSelect ){
1.122972 +    pTab = 0;
1.122973 +    goto error_out;
1.122974 +  }
1.122975 +
1.122976 +  /* Find the column for which info is requested */
1.122977 +  if( sqlite3IsRowid(zColumnName) ){
1.122978 +    iCol = pTab->iPKey;
1.122979 +    if( iCol>=0 ){
1.122980 +      pCol = &pTab->aCol[iCol];
1.122981 +    }
1.122982 +  }else{
1.122983 +    for(iCol=0; iCol<pTab->nCol; iCol++){
1.122984 +      pCol = &pTab->aCol[iCol];
1.122985 +      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
1.122986 +        break;
1.122987 +      }
1.122988 +    }
1.122989 +    if( iCol==pTab->nCol ){
1.122990 +      pTab = 0;
1.122991 +      goto error_out;
1.122992 +    }
1.122993 +  }
1.122994 +
1.122995 +  /* The following block stores the meta information that will be returned
1.122996 +  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
1.122997 +  ** and autoinc. At this point there are two possibilities:
1.122998 +  ** 
1.122999 +  **     1. The specified column name was rowid", "oid" or "_rowid_" 
1.123000 +  **        and there is no explicitly declared IPK column. 
1.123001 +  **
1.123002 +  **     2. The table is not a view and the column name identified an 
1.123003 +  **        explicitly declared column. Copy meta information from *pCol.
1.123004 +  */ 
1.123005 +  if( pCol ){
1.123006 +    zDataType = pCol->zType;
1.123007 +    zCollSeq = pCol->zColl;
1.123008 +    notnull = pCol->notNull!=0;
1.123009 +    primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
1.123010 +    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
1.123011 +  }else{
1.123012 +    zDataType = "INTEGER";
1.123013 +    primarykey = 1;
1.123014 +  }
1.123015 +  if( !zCollSeq ){
1.123016 +    zCollSeq = "BINARY";
1.123017 +  }
1.123018 +
1.123019 +error_out:
1.123020 +  sqlite3BtreeLeaveAll(db);
1.123021 +
1.123022 +  /* Whether the function call succeeded or failed, set the output parameters
1.123023 +  ** to whatever their local counterparts contain. If an error did occur,
1.123024 +  ** this has the effect of zeroing all output parameters.
1.123025 +  */
1.123026 +  if( pzDataType ) *pzDataType = zDataType;
1.123027 +  if( pzCollSeq ) *pzCollSeq = zCollSeq;
1.123028 +  if( pNotNull ) *pNotNull = notnull;
1.123029 +  if( pPrimaryKey ) *pPrimaryKey = primarykey;
1.123030 +  if( pAutoinc ) *pAutoinc = autoinc;
1.123031 +
1.123032 +  if( SQLITE_OK==rc && !pTab ){
1.123033 +    sqlite3DbFree(db, zErrMsg);
1.123034 +    zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
1.123035 +        zColumnName);
1.123036 +    rc = SQLITE_ERROR;
1.123037 +  }
1.123038 +  sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
1.123039 +  sqlite3DbFree(db, zErrMsg);
1.123040 +  rc = sqlite3ApiExit(db, rc);
1.123041 +  sqlite3_mutex_leave(db->mutex);
1.123042 +  return rc;
1.123043 +}
1.123044 +#endif
1.123045 +
1.123046 +/*
1.123047 +** Sleep for a little while.  Return the amount of time slept.
1.123048 +*/
1.123049 +SQLITE_API int sqlite3_sleep(int ms){
1.123050 +  sqlite3_vfs *pVfs;
1.123051 +  int rc;
1.123052 +  pVfs = sqlite3_vfs_find(0);
1.123053 +  if( pVfs==0 ) return 0;
1.123054 +
1.123055 +  /* This function works in milliseconds, but the underlying OsSleep() 
1.123056 +  ** API uses microseconds. Hence the 1000's.
1.123057 +  */
1.123058 +  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
1.123059 +  return rc;
1.123060 +}
1.123061 +
1.123062 +/*
1.123063 +** Enable or disable the extended result codes.
1.123064 +*/
1.123065 +SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
1.123066 +  sqlite3_mutex_enter(db->mutex);
1.123067 +  db->errMask = onoff ? 0xffffffff : 0xff;
1.123068 +  sqlite3_mutex_leave(db->mutex);
1.123069 +  return SQLITE_OK;
1.123070 +}
1.123071 +
1.123072 +/*
1.123073 +** Invoke the xFileControl method on a particular database.
1.123074 +*/
1.123075 +SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
1.123076 +  int rc = SQLITE_ERROR;
1.123077 +  Btree *pBtree;
1.123078 +
1.123079 +  sqlite3_mutex_enter(db->mutex);
1.123080 +  pBtree = sqlite3DbNameToBtree(db, zDbName);
1.123081 +  if( pBtree ){
1.123082 +    Pager *pPager;
1.123083 +    sqlite3_file *fd;
1.123084 +    sqlite3BtreeEnter(pBtree);
1.123085 +    pPager = sqlite3BtreePager(pBtree);
1.123086 +    assert( pPager!=0 );
1.123087 +    fd = sqlite3PagerFile(pPager);
1.123088 +    assert( fd!=0 );
1.123089 +    if( op==SQLITE_FCNTL_FILE_POINTER ){
1.123090 +      *(sqlite3_file**)pArg = fd;
1.123091 +      rc = SQLITE_OK;
1.123092 +    }else if( fd->pMethods ){
1.123093 +      rc = sqlite3OsFileControl(fd, op, pArg);
1.123094 +    }else{
1.123095 +      rc = SQLITE_NOTFOUND;
1.123096 +    }
1.123097 +    sqlite3BtreeLeave(pBtree);
1.123098 +  }
1.123099 +  sqlite3_mutex_leave(db->mutex);
1.123100 +  return rc;   
1.123101 +}
1.123102 +
1.123103 +/*
1.123104 +** Interface to the testing logic.
1.123105 +*/
1.123106 +SQLITE_API int sqlite3_test_control(int op, ...){
1.123107 +  int rc = 0;
1.123108 +#ifndef SQLITE_OMIT_BUILTIN_TEST
1.123109 +  va_list ap;
1.123110 +  va_start(ap, op);
1.123111 +  switch( op ){
1.123112 +
1.123113 +    /*
1.123114 +    ** Save the current state of the PRNG.
1.123115 +    */
1.123116 +    case SQLITE_TESTCTRL_PRNG_SAVE: {
1.123117 +      sqlite3PrngSaveState();
1.123118 +      break;
1.123119 +    }
1.123120 +
1.123121 +    /*
1.123122 +    ** Restore the state of the PRNG to the last state saved using
1.123123 +    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
1.123124 +    ** this verb acts like PRNG_RESET.
1.123125 +    */
1.123126 +    case SQLITE_TESTCTRL_PRNG_RESTORE: {
1.123127 +      sqlite3PrngRestoreState();
1.123128 +      break;
1.123129 +    }
1.123130 +
1.123131 +    /*
1.123132 +    ** Reset the PRNG back to its uninitialized state.  The next call
1.123133 +    ** to sqlite3_randomness() will reseed the PRNG using a single call
1.123134 +    ** to the xRandomness method of the default VFS.
1.123135 +    */
1.123136 +    case SQLITE_TESTCTRL_PRNG_RESET: {
1.123137 +      sqlite3_randomness(0,0);
1.123138 +      break;
1.123139 +    }
1.123140 +
1.123141 +    /*
1.123142 +    **  sqlite3_test_control(BITVEC_TEST, size, program)
1.123143 +    **
1.123144 +    ** Run a test against a Bitvec object of size.  The program argument
1.123145 +    ** is an array of integers that defines the test.  Return -1 on a
1.123146 +    ** memory allocation error, 0 on success, or non-zero for an error.
1.123147 +    ** See the sqlite3BitvecBuiltinTest() for additional information.
1.123148 +    */
1.123149 +    case SQLITE_TESTCTRL_BITVEC_TEST: {
1.123150 +      int sz = va_arg(ap, int);
1.123151 +      int *aProg = va_arg(ap, int*);
1.123152 +      rc = sqlite3BitvecBuiltinTest(sz, aProg);
1.123153 +      break;
1.123154 +    }
1.123155 +
1.123156 +    /*
1.123157 +    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
1.123158 +    **
1.123159 +    ** Register hooks to call to indicate which malloc() failures 
1.123160 +    ** are benign.
1.123161 +    */
1.123162 +    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
1.123163 +      typedef void (*void_function)(void);
1.123164 +      void_function xBenignBegin;
1.123165 +      void_function xBenignEnd;
1.123166 +      xBenignBegin = va_arg(ap, void_function);
1.123167 +      xBenignEnd = va_arg(ap, void_function);
1.123168 +      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
1.123169 +      break;
1.123170 +    }
1.123171 +
1.123172 +    /*
1.123173 +    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
1.123174 +    **
1.123175 +    ** Set the PENDING byte to the value in the argument, if X>0.
1.123176 +    ** Make no changes if X==0.  Return the value of the pending byte
1.123177 +    ** as it existing before this routine was called.
1.123178 +    **
1.123179 +    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
1.123180 +    ** an incompatible database file format.  Changing the PENDING byte
1.123181 +    ** while any database connection is open results in undefined and
1.123182 +    ** dileterious behavior.
1.123183 +    */
1.123184 +    case SQLITE_TESTCTRL_PENDING_BYTE: {
1.123185 +      rc = PENDING_BYTE;
1.123186 +#ifndef SQLITE_OMIT_WSD
1.123187 +      {
1.123188 +        unsigned int newVal = va_arg(ap, unsigned int);
1.123189 +        if( newVal ) sqlite3PendingByte = newVal;
1.123190 +      }
1.123191 +#endif
1.123192 +      break;
1.123193 +    }
1.123194 +
1.123195 +    /*
1.123196 +    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
1.123197 +    **
1.123198 +    ** This action provides a run-time test to see whether or not
1.123199 +    ** assert() was enabled at compile-time.  If X is true and assert()
1.123200 +    ** is enabled, then the return value is true.  If X is true and
1.123201 +    ** assert() is disabled, then the return value is zero.  If X is
1.123202 +    ** false and assert() is enabled, then the assertion fires and the
1.123203 +    ** process aborts.  If X is false and assert() is disabled, then the
1.123204 +    ** return value is zero.
1.123205 +    */
1.123206 +    case SQLITE_TESTCTRL_ASSERT: {
1.123207 +      volatile int x = 0;
1.123208 +      assert( (x = va_arg(ap,int))!=0 );
1.123209 +      rc = x;
1.123210 +      break;
1.123211 +    }
1.123212 +
1.123213 +
1.123214 +    /*
1.123215 +    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
1.123216 +    **
1.123217 +    ** This action provides a run-time test to see how the ALWAYS and
1.123218 +    ** NEVER macros were defined at compile-time.
1.123219 +    **
1.123220 +    ** The return value is ALWAYS(X).  
1.123221 +    **
1.123222 +    ** The recommended test is X==2.  If the return value is 2, that means
1.123223 +    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
1.123224 +    ** default setting.  If the return value is 1, then ALWAYS() is either
1.123225 +    ** hard-coded to true or else it asserts if its argument is false.
1.123226 +    ** The first behavior (hard-coded to true) is the case if
1.123227 +    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
1.123228 +    ** behavior (assert if the argument to ALWAYS() is false) is the case if
1.123229 +    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
1.123230 +    **
1.123231 +    ** The run-time test procedure might look something like this:
1.123232 +    **
1.123233 +    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
1.123234 +    **      // ALWAYS() and NEVER() are no-op pass-through macros
1.123235 +    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
1.123236 +    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
1.123237 +    **    }else{
1.123238 +    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
1.123239 +    **    }
1.123240 +    */
1.123241 +    case SQLITE_TESTCTRL_ALWAYS: {
1.123242 +      int x = va_arg(ap,int);
1.123243 +      rc = ALWAYS(x);
1.123244 +      break;
1.123245 +    }
1.123246 +
1.123247 +    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
1.123248 +    **
1.123249 +    ** Set the nReserve size to N for the main database on the database
1.123250 +    ** connection db.
1.123251 +    */
1.123252 +    case SQLITE_TESTCTRL_RESERVE: {
1.123253 +      sqlite3 *db = va_arg(ap, sqlite3*);
1.123254 +      int x = va_arg(ap,int);
1.123255 +      sqlite3_mutex_enter(db->mutex);
1.123256 +      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
1.123257 +      sqlite3_mutex_leave(db->mutex);
1.123258 +      break;
1.123259 +    }
1.123260 +
1.123261 +    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
1.123262 +    **
1.123263 +    ** Enable or disable various optimizations for testing purposes.  The 
1.123264 +    ** argument N is a bitmask of optimizations to be disabled.  For normal
1.123265 +    ** operation N should be 0.  The idea is that a test program (like the
1.123266 +    ** SQL Logic Test or SLT test module) can run the same SQL multiple times
1.123267 +    ** with various optimizations disabled to verify that the same answer
1.123268 +    ** is obtained in every case.
1.123269 +    */
1.123270 +    case SQLITE_TESTCTRL_OPTIMIZATIONS: {
1.123271 +      sqlite3 *db = va_arg(ap, sqlite3*);
1.123272 +      db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
1.123273 +      break;
1.123274 +    }
1.123275 +
1.123276 +#ifdef SQLITE_N_KEYWORD
1.123277 +    /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
1.123278 +    **
1.123279 +    ** If zWord is a keyword recognized by the parser, then return the
1.123280 +    ** number of keywords.  Or if zWord is not a keyword, return 0.
1.123281 +    ** 
1.123282 +    ** This test feature is only available in the amalgamation since
1.123283 +    ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
1.123284 +    ** is built using separate source files.
1.123285 +    */
1.123286 +    case SQLITE_TESTCTRL_ISKEYWORD: {
1.123287 +      const char *zWord = va_arg(ap, const char*);
1.123288 +      int n = sqlite3Strlen30(zWord);
1.123289 +      rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
1.123290 +      break;
1.123291 +    }
1.123292 +#endif 
1.123293 +
1.123294 +    /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
1.123295 +    **
1.123296 +    ** Pass pFree into sqlite3ScratchFree(). 
1.123297 +    ** If sz>0 then allocate a scratch buffer into pNew.  
1.123298 +    */
1.123299 +    case SQLITE_TESTCTRL_SCRATCHMALLOC: {
1.123300 +      void *pFree, **ppNew;
1.123301 +      int sz;
1.123302 +      sz = va_arg(ap, int);
1.123303 +      ppNew = va_arg(ap, void**);
1.123304 +      pFree = va_arg(ap, void*);
1.123305 +      if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
1.123306 +      sqlite3ScratchFree(pFree);
1.123307 +      break;
1.123308 +    }
1.123309 +
1.123310 +    /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
1.123311 +    **
1.123312 +    ** If parameter onoff is non-zero, configure the wrappers so that all
1.123313 +    ** subsequent calls to localtime() and variants fail. If onoff is zero,
1.123314 +    ** undo this setting.
1.123315 +    */
1.123316 +    case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
1.123317 +      sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
1.123318 +      break;
1.123319 +    }
1.123320 +
1.123321 +#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
1.123322 +    /*   sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
1.123323 +    **                        sqlite3_stmt*,const char**);
1.123324 +    **
1.123325 +    ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
1.123326 +    ** a string that describes the optimized parse tree.  This test-control
1.123327 +    ** returns a pointer to that string.
1.123328 +    */
1.123329 +    case SQLITE_TESTCTRL_EXPLAIN_STMT: {
1.123330 +      sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
1.123331 +      const char **pzRet = va_arg(ap, const char**);
1.123332 +      *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
1.123333 +      break;
1.123334 +    }
1.123335 +#endif
1.123336 +
1.123337 +    /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
1.123338 +    **
1.123339 +    ** Set or clear a flag that indicates that the database file is always well-
1.123340 +    ** formed and never corrupt.  This flag is clear by default, indicating that
1.123341 +    ** database files might have arbitrary corruption.  Setting the flag during
1.123342 +    ** testing causes certain assert() statements in the code to be activated
1.123343 +    ** that demonstrat invariants on well-formed database files.
1.123344 +    */
1.123345 +    case SQLITE_TESTCTRL_NEVER_CORRUPT: {
1.123346 +      sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
1.123347 +      break;
1.123348 +    }
1.123349 +
1.123350 +
1.123351 +    /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
1.123352 +    **
1.123353 +    ** Set the VDBE coverage callback function to xCallback with context 
1.123354 +    ** pointer ptr.
1.123355 +    */
1.123356 +    case SQLITE_TESTCTRL_VDBE_COVERAGE: {
1.123357 +#ifdef SQLITE_VDBE_COVERAGE
1.123358 +      typedef void (*branch_callback)(void*,int,u8,u8);
1.123359 +      sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
1.123360 +      sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
1.123361 +#endif
1.123362 +      break;
1.123363 +    }
1.123364 +
1.123365 +  }
1.123366 +  va_end(ap);
1.123367 +#endif /* SQLITE_OMIT_BUILTIN_TEST */
1.123368 +  return rc;
1.123369 +}
1.123370 +
1.123371 +/*
1.123372 +** This is a utility routine, useful to VFS implementations, that checks
1.123373 +** to see if a database file was a URI that contained a specific query 
1.123374 +** parameter, and if so obtains the value of the query parameter.
1.123375 +**
1.123376 +** The zFilename argument is the filename pointer passed into the xOpen()
1.123377 +** method of a VFS implementation.  The zParam argument is the name of the
1.123378 +** query parameter we seek.  This routine returns the value of the zParam
1.123379 +** parameter if it exists.  If the parameter does not exist, this routine
1.123380 +** returns a NULL pointer.
1.123381 +*/
1.123382 +SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
1.123383 +  if( zFilename==0 ) return 0;
1.123384 +  zFilename += sqlite3Strlen30(zFilename) + 1;
1.123385 +  while( zFilename[0] ){
1.123386 +    int x = strcmp(zFilename, zParam);
1.123387 +    zFilename += sqlite3Strlen30(zFilename) + 1;
1.123388 +    if( x==0 ) return zFilename;
1.123389 +    zFilename += sqlite3Strlen30(zFilename) + 1;
1.123390 +  }
1.123391 +  return 0;
1.123392 +}
1.123393 +
1.123394 +/*
1.123395 +** Return a boolean value for a query parameter.
1.123396 +*/
1.123397 +SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
1.123398 +  const char *z = sqlite3_uri_parameter(zFilename, zParam);
1.123399 +  bDflt = bDflt!=0;
1.123400 +  return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
1.123401 +}
1.123402 +
1.123403 +/*
1.123404 +** Return a 64-bit integer value for a query parameter.
1.123405 +*/
1.123406 +SQLITE_API sqlite3_int64 sqlite3_uri_int64(
1.123407 +  const char *zFilename,    /* Filename as passed to xOpen */
1.123408 +  const char *zParam,       /* URI parameter sought */
1.123409 +  sqlite3_int64 bDflt       /* return if parameter is missing */
1.123410 +){
1.123411 +  const char *z = sqlite3_uri_parameter(zFilename, zParam);
1.123412 +  sqlite3_int64 v;
1.123413 +  if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
1.123414 +    bDflt = v;
1.123415 +  }
1.123416 +  return bDflt;
1.123417 +}
1.123418 +
1.123419 +/*
1.123420 +** Return the Btree pointer identified by zDbName.  Return NULL if not found.
1.123421 +*/
1.123422 +SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
1.123423 +  int i;
1.123424 +  for(i=0; i<db->nDb; i++){
1.123425 +    if( db->aDb[i].pBt
1.123426 +     && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
1.123427 +    ){
1.123428 +      return db->aDb[i].pBt;
1.123429 +    }
1.123430 +  }
1.123431 +  return 0;
1.123432 +}
1.123433 +
1.123434 +/*
1.123435 +** Return the filename of the database associated with a database
1.123436 +** connection.
1.123437 +*/
1.123438 +SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
1.123439 +  Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
1.123440 +  return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
1.123441 +}
1.123442 +
1.123443 +/*
1.123444 +** Return 1 if database is read-only or 0 if read/write.  Return -1 if
1.123445 +** no such database exists.
1.123446 +*/
1.123447 +SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
1.123448 +  Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
1.123449 +  return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
1.123450 +}
1.123451 +
1.123452 +/************** End of main.c ************************************************/
1.123453 +/************** Begin file notify.c ******************************************/
1.123454 +/*
1.123455 +** 2009 March 3
1.123456 +**
1.123457 +** The author disclaims copyright to this source code.  In place of
1.123458 +** a legal notice, here is a blessing:
1.123459 +**
1.123460 +**    May you do good and not evil.
1.123461 +**    May you find forgiveness for yourself and forgive others.
1.123462 +**    May you share freely, never taking more than you give.
1.123463 +**
1.123464 +*************************************************************************
1.123465 +**
1.123466 +** This file contains the implementation of the sqlite3_unlock_notify()
1.123467 +** API method and its associated functionality.
1.123468 +*/
1.123469 +
1.123470 +/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
1.123471 +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
1.123472 +
1.123473 +/*
1.123474 +** Public interfaces:
1.123475 +**
1.123476 +**   sqlite3ConnectionBlocked()
1.123477 +**   sqlite3ConnectionUnlocked()
1.123478 +**   sqlite3ConnectionClosed()
1.123479 +**   sqlite3_unlock_notify()
1.123480 +*/
1.123481 +
1.123482 +#define assertMutexHeld() \
1.123483 +  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
1.123484 +
1.123485 +/*
1.123486 +** Head of a linked list of all sqlite3 objects created by this process
1.123487 +** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
1.123488 +** is not NULL. This variable may only accessed while the STATIC_MASTER
1.123489 +** mutex is held.
1.123490 +*/
1.123491 +static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
1.123492 +
1.123493 +#ifndef NDEBUG
1.123494 +/*
1.123495 +** This function is a complex assert() that verifies the following 
1.123496 +** properties of the blocked connections list:
1.123497 +**
1.123498 +**   1) Each entry in the list has a non-NULL value for either 
1.123499 +**      pUnlockConnection or pBlockingConnection, or both.
1.123500 +**
1.123501 +**   2) All entries in the list that share a common value for 
1.123502 +**      xUnlockNotify are grouped together.
1.123503 +**
1.123504 +**   3) If the argument db is not NULL, then none of the entries in the
1.123505 +**      blocked connections list have pUnlockConnection or pBlockingConnection
1.123506 +**      set to db. This is used when closing connection db.
1.123507 +*/
1.123508 +static void checkListProperties(sqlite3 *db){
1.123509 +  sqlite3 *p;
1.123510 +  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
1.123511 +    int seen = 0;
1.123512 +    sqlite3 *p2;
1.123513 +
1.123514 +    /* Verify property (1) */
1.123515 +    assert( p->pUnlockConnection || p->pBlockingConnection );
1.123516 +
1.123517 +    /* Verify property (2) */
1.123518 +    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
1.123519 +      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
1.123520 +      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
1.123521 +      assert( db==0 || p->pUnlockConnection!=db );
1.123522 +      assert( db==0 || p->pBlockingConnection!=db );
1.123523 +    }
1.123524 +  }
1.123525 +}
1.123526 +#else
1.123527 +# define checkListProperties(x)
1.123528 +#endif
1.123529 +
1.123530 +/*
1.123531 +** Remove connection db from the blocked connections list. If connection
1.123532 +** db is not currently a part of the list, this function is a no-op.
1.123533 +*/
1.123534 +static void removeFromBlockedList(sqlite3 *db){
1.123535 +  sqlite3 **pp;
1.123536 +  assertMutexHeld();
1.123537 +  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
1.123538 +    if( *pp==db ){
1.123539 +      *pp = (*pp)->pNextBlocked;
1.123540 +      break;
1.123541 +    }
1.123542 +  }
1.123543 +}
1.123544 +
1.123545 +/*
1.123546 +** Add connection db to the blocked connections list. It is assumed
1.123547 +** that it is not already a part of the list.
1.123548 +*/
1.123549 +static void addToBlockedList(sqlite3 *db){
1.123550 +  sqlite3 **pp;
1.123551 +  assertMutexHeld();
1.123552 +  for(
1.123553 +    pp=&sqlite3BlockedList; 
1.123554 +    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
1.123555 +    pp=&(*pp)->pNextBlocked
1.123556 +  );
1.123557 +  db->pNextBlocked = *pp;
1.123558 +  *pp = db;
1.123559 +}
1.123560 +
1.123561 +/*
1.123562 +** Obtain the STATIC_MASTER mutex.
1.123563 +*/
1.123564 +static void enterMutex(void){
1.123565 +  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
1.123566 +  checkListProperties(0);
1.123567 +}
1.123568 +
1.123569 +/*
1.123570 +** Release the STATIC_MASTER mutex.
1.123571 +*/
1.123572 +static void leaveMutex(void){
1.123573 +  assertMutexHeld();
1.123574 +  checkListProperties(0);
1.123575 +  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
1.123576 +}
1.123577 +
1.123578 +/*
1.123579 +** Register an unlock-notify callback.
1.123580 +**
1.123581 +** This is called after connection "db" has attempted some operation
1.123582 +** but has received an SQLITE_LOCKED error because another connection
1.123583 +** (call it pOther) in the same process was busy using the same shared
1.123584 +** cache.  pOther is found by looking at db->pBlockingConnection.
1.123585 +**
1.123586 +** If there is no blocking connection, the callback is invoked immediately,
1.123587 +** before this routine returns.
1.123588 +**
1.123589 +** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
1.123590 +** a deadlock.
1.123591 +**
1.123592 +** Otherwise, make arrangements to invoke xNotify when pOther drops
1.123593 +** its locks.
1.123594 +**
1.123595 +** Each call to this routine overrides any prior callbacks registered
1.123596 +** on the same "db".  If xNotify==0 then any prior callbacks are immediately
1.123597 +** cancelled.
1.123598 +*/
1.123599 +SQLITE_API int sqlite3_unlock_notify(
1.123600 +  sqlite3 *db,
1.123601 +  void (*xNotify)(void **, int),
1.123602 +  void *pArg
1.123603 +){
1.123604 +  int rc = SQLITE_OK;
1.123605 +
1.123606 +  sqlite3_mutex_enter(db->mutex);
1.123607 +  enterMutex();
1.123608 +
1.123609 +  if( xNotify==0 ){
1.123610 +    removeFromBlockedList(db);
1.123611 +    db->pBlockingConnection = 0;
1.123612 +    db->pUnlockConnection = 0;
1.123613 +    db->xUnlockNotify = 0;
1.123614 +    db->pUnlockArg = 0;
1.123615 +  }else if( 0==db->pBlockingConnection ){
1.123616 +    /* The blocking transaction has been concluded. Or there never was a 
1.123617 +    ** blocking transaction. In either case, invoke the notify callback
1.123618 +    ** immediately. 
1.123619 +    */
1.123620 +    xNotify(&pArg, 1);
1.123621 +  }else{
1.123622 +    sqlite3 *p;
1.123623 +
1.123624 +    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
1.123625 +    if( p ){
1.123626 +      rc = SQLITE_LOCKED;              /* Deadlock detected. */
1.123627 +    }else{
1.123628 +      db->pUnlockConnection = db->pBlockingConnection;
1.123629 +      db->xUnlockNotify = xNotify;
1.123630 +      db->pUnlockArg = pArg;
1.123631 +      removeFromBlockedList(db);
1.123632 +      addToBlockedList(db);
1.123633 +    }
1.123634 +  }
1.123635 +
1.123636 +  leaveMutex();
1.123637 +  assert( !db->mallocFailed );
1.123638 +  sqlite3Error(db, rc, (rc?"database is deadlocked":0));
1.123639 +  sqlite3_mutex_leave(db->mutex);
1.123640 +  return rc;
1.123641 +}
1.123642 +
1.123643 +/*
1.123644 +** This function is called while stepping or preparing a statement 
1.123645 +** associated with connection db. The operation will return SQLITE_LOCKED
1.123646 +** to the user because it requires a lock that will not be available
1.123647 +** until connection pBlocker concludes its current transaction.
1.123648 +*/
1.123649 +SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
1.123650 +  enterMutex();
1.123651 +  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
1.123652 +    addToBlockedList(db);
1.123653 +  }
1.123654 +  db->pBlockingConnection = pBlocker;
1.123655 +  leaveMutex();
1.123656 +}
1.123657 +
1.123658 +/*
1.123659 +** This function is called when
1.123660 +** the transaction opened by database db has just finished. Locks held 
1.123661 +** by database connection db have been released.
1.123662 +**
1.123663 +** This function loops through each entry in the blocked connections
1.123664 +** list and does the following:
1.123665 +**
1.123666 +**   1) If the sqlite3.pBlockingConnection member of a list entry is
1.123667 +**      set to db, then set pBlockingConnection=0.
1.123668 +**
1.123669 +**   2) If the sqlite3.pUnlockConnection member of a list entry is
1.123670 +**      set to db, then invoke the configured unlock-notify callback and
1.123671 +**      set pUnlockConnection=0.
1.123672 +**
1.123673 +**   3) If the two steps above mean that pBlockingConnection==0 and
1.123674 +**      pUnlockConnection==0, remove the entry from the blocked connections
1.123675 +**      list.
1.123676 +*/
1.123677 +SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
1.123678 +  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
1.123679 +  int nArg = 0;                            /* Number of entries in aArg[] */
1.123680 +  sqlite3 **pp;                            /* Iterator variable */
1.123681 +  void **aArg;               /* Arguments to the unlock callback */
1.123682 +  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
1.123683 +  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
1.123684 +
1.123685 +  aArg = aStatic;
1.123686 +  enterMutex();         /* Enter STATIC_MASTER mutex */
1.123687 +
1.123688 +  /* This loop runs once for each entry in the blocked-connections list. */
1.123689 +  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
1.123690 +    sqlite3 *p = *pp;
1.123691 +
1.123692 +    /* Step 1. */
1.123693 +    if( p->pBlockingConnection==db ){
1.123694 +      p->pBlockingConnection = 0;
1.123695 +    }
1.123696 +
1.123697 +    /* Step 2. */
1.123698 +    if( p->pUnlockConnection==db ){
1.123699 +      assert( p->xUnlockNotify );
1.123700 +      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
1.123701 +        xUnlockNotify(aArg, nArg);
1.123702 +        nArg = 0;
1.123703 +      }
1.123704 +
1.123705 +      sqlite3BeginBenignMalloc();
1.123706 +      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
1.123707 +      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
1.123708 +      if( (!aDyn && nArg==(int)ArraySize(aStatic))
1.123709 +       || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
1.123710 +      ){
1.123711 +        /* The aArg[] array needs to grow. */
1.123712 +        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
1.123713 +        if( pNew ){
1.123714 +          memcpy(pNew, aArg, nArg*sizeof(void *));
1.123715 +          sqlite3_free(aDyn);
1.123716 +          aDyn = aArg = pNew;
1.123717 +        }else{
1.123718 +          /* This occurs when the array of context pointers that need to
1.123719 +          ** be passed to the unlock-notify callback is larger than the
1.123720 +          ** aStatic[] array allocated on the stack and the attempt to 
1.123721 +          ** allocate a larger array from the heap has failed.
1.123722 +          **
1.123723 +          ** This is a difficult situation to handle. Returning an error
1.123724 +          ** code to the caller is insufficient, as even if an error code
1.123725 +          ** is returned the transaction on connection db will still be
1.123726 +          ** closed and the unlock-notify callbacks on blocked connections
1.123727 +          ** will go unissued. This might cause the application to wait
1.123728 +          ** indefinitely for an unlock-notify callback that will never 
1.123729 +          ** arrive.
1.123730 +          **
1.123731 +          ** Instead, invoke the unlock-notify callback with the context
1.123732 +          ** array already accumulated. We can then clear the array and
1.123733 +          ** begin accumulating any further context pointers without 
1.123734 +          ** requiring any dynamic allocation. This is sub-optimal because
1.123735 +          ** it means that instead of one callback with a large array of
1.123736 +          ** context pointers the application will receive two or more
1.123737 +          ** callbacks with smaller arrays of context pointers, which will
1.123738 +          ** reduce the applications ability to prioritize multiple 
1.123739 +          ** connections. But it is the best that can be done under the
1.123740 +          ** circumstances.
1.123741 +          */
1.123742 +          xUnlockNotify(aArg, nArg);
1.123743 +          nArg = 0;
1.123744 +        }
1.123745 +      }
1.123746 +      sqlite3EndBenignMalloc();
1.123747 +
1.123748 +      aArg[nArg++] = p->pUnlockArg;
1.123749 +      xUnlockNotify = p->xUnlockNotify;
1.123750 +      p->pUnlockConnection = 0;
1.123751 +      p->xUnlockNotify = 0;
1.123752 +      p->pUnlockArg = 0;
1.123753 +    }
1.123754 +
1.123755 +    /* Step 3. */
1.123756 +    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
1.123757 +      /* Remove connection p from the blocked connections list. */
1.123758 +      *pp = p->pNextBlocked;
1.123759 +      p->pNextBlocked = 0;
1.123760 +    }else{
1.123761 +      pp = &p->pNextBlocked;
1.123762 +    }
1.123763 +  }
1.123764 +
1.123765 +  if( nArg!=0 ){
1.123766 +    xUnlockNotify(aArg, nArg);
1.123767 +  }
1.123768 +  sqlite3_free(aDyn);
1.123769 +  leaveMutex();         /* Leave STATIC_MASTER mutex */
1.123770 +}
1.123771 +
1.123772 +/*
1.123773 +** This is called when the database connection passed as an argument is 
1.123774 +** being closed. The connection is removed from the blocked list.
1.123775 +*/
1.123776 +SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
1.123777 +  sqlite3ConnectionUnlocked(db);
1.123778 +  enterMutex();
1.123779 +  removeFromBlockedList(db);
1.123780 +  checkListProperties(db);
1.123781 +  leaveMutex();
1.123782 +}
1.123783 +#endif
1.123784 +
1.123785 +/************** End of notify.c **********************************************/
1.123786 +/************** Begin file fts3.c ********************************************/
1.123787 +/*
1.123788 +** 2006 Oct 10
1.123789 +**
1.123790 +** The author disclaims copyright to this source code.  In place of
1.123791 +** a legal notice, here is a blessing:
1.123792 +**
1.123793 +**    May you do good and not evil.
1.123794 +**    May you find forgiveness for yourself and forgive others.
1.123795 +**    May you share freely, never taking more than you give.
1.123796 +**
1.123797 +******************************************************************************
1.123798 +**
1.123799 +** This is an SQLite module implementing full-text search.
1.123800 +*/
1.123801 +
1.123802 +/*
1.123803 +** The code in this file is only compiled if:
1.123804 +**
1.123805 +**     * The FTS3 module is being built as an extension
1.123806 +**       (in which case SQLITE_CORE is not defined), or
1.123807 +**
1.123808 +**     * The FTS3 module is being built into the core of
1.123809 +**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
1.123810 +*/
1.123811 +
1.123812 +/* The full-text index is stored in a series of b+tree (-like)
1.123813 +** structures called segments which map terms to doclists.  The
1.123814 +** structures are like b+trees in layout, but are constructed from the
1.123815 +** bottom up in optimal fashion and are not updatable.  Since trees
1.123816 +** are built from the bottom up, things will be described from the
1.123817 +** bottom up.
1.123818 +**
1.123819 +**
1.123820 +**** Varints ****
1.123821 +** The basic unit of encoding is a variable-length integer called a
1.123822 +** varint.  We encode variable-length integers in little-endian order
1.123823 +** using seven bits * per byte as follows:
1.123824 +**
1.123825 +** KEY:
1.123826 +**         A = 0xxxxxxx    7 bits of data and one flag bit
1.123827 +**         B = 1xxxxxxx    7 bits of data and one flag bit
1.123828 +**
1.123829 +**  7 bits - A
1.123830 +** 14 bits - BA
1.123831 +** 21 bits - BBA
1.123832 +** and so on.
1.123833 +**
1.123834 +** This is similar in concept to how sqlite encodes "varints" but
1.123835 +** the encoding is not the same.  SQLite varints are big-endian
1.123836 +** are are limited to 9 bytes in length whereas FTS3 varints are
1.123837 +** little-endian and can be up to 10 bytes in length (in theory).
1.123838 +**
1.123839 +** Example encodings:
1.123840 +**
1.123841 +**     1:    0x01
1.123842 +**   127:    0x7f
1.123843 +**   128:    0x81 0x00
1.123844 +**
1.123845 +**
1.123846 +**** Document lists ****
1.123847 +** A doclist (document list) holds a docid-sorted list of hits for a
1.123848 +** given term.  Doclists hold docids and associated token positions.
1.123849 +** A docid is the unique integer identifier for a single document.
1.123850 +** A position is the index of a word within the document.  The first 
1.123851 +** word of the document has a position of 0.
1.123852 +**
1.123853 +** FTS3 used to optionally store character offsets using a compile-time
1.123854 +** option.  But that functionality is no longer supported.
1.123855 +**
1.123856 +** A doclist is stored like this:
1.123857 +**
1.123858 +** array {
1.123859 +**   varint docid;          (delta from previous doclist)
1.123860 +**   array {                (position list for column 0)
1.123861 +**     varint position;     (2 more than the delta from previous position)
1.123862 +**   }
1.123863 +**   array {
1.123864 +**     varint POS_COLUMN;   (marks start of position list for new column)
1.123865 +**     varint column;       (index of new column)
1.123866 +**     array {
1.123867 +**       varint position;   (2 more than the delta from previous position)
1.123868 +**     }
1.123869 +**   }
1.123870 +**   varint POS_END;        (marks end of positions for this document.
1.123871 +** }
1.123872 +**
1.123873 +** Here, array { X } means zero or more occurrences of X, adjacent in
1.123874 +** memory.  A "position" is an index of a token in the token stream
1.123875 +** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
1.123876 +** in the same logical place as the position element, and act as sentinals
1.123877 +** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
1.123878 +** The positions numbers are not stored literally but rather as two more
1.123879 +** than the difference from the prior position, or the just the position plus
1.123880 +** 2 for the first position.  Example:
1.123881 +**
1.123882 +**   label:       A B C D E  F  G H   I  J K
1.123883 +**   value:     123 5 9 1 1 14 35 0 234 72 0
1.123884 +**
1.123885 +** The 123 value is the first docid.  For column zero in this document
1.123886 +** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
1.123887 +** at D signals the start of a new column; the 1 at E indicates that the
1.123888 +** new column is column number 1.  There are two positions at 12 and 45
1.123889 +** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
1.123890 +** 234 at I is the delta to next docid (357).  It has one position 70
1.123891 +** (72-2) and then terminates with the 0 at K.
1.123892 +**
1.123893 +** A "position-list" is the list of positions for multiple columns for
1.123894 +** a single docid.  A "column-list" is the set of positions for a single
1.123895 +** column.  Hence, a position-list consists of one or more column-lists,
1.123896 +** a document record consists of a docid followed by a position-list and
1.123897 +** a doclist consists of one or more document records.
1.123898 +**
1.123899 +** A bare doclist omits the position information, becoming an 
1.123900 +** array of varint-encoded docids.
1.123901 +**
1.123902 +**** Segment leaf nodes ****
1.123903 +** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
1.123904 +** nodes are written using LeafWriter, and read using LeafReader (to
1.123905 +** iterate through a single leaf node's data) and LeavesReader (to
1.123906 +** iterate through a segment's entire leaf layer).  Leaf nodes have
1.123907 +** the format:
1.123908 +**
1.123909 +** varint iHeight;             (height from leaf level, always 0)
1.123910 +** varint nTerm;               (length of first term)
1.123911 +** char pTerm[nTerm];          (content of first term)
1.123912 +** varint nDoclist;            (length of term's associated doclist)
1.123913 +** char pDoclist[nDoclist];    (content of doclist)
1.123914 +** array {
1.123915 +**                             (further terms are delta-encoded)
1.123916 +**   varint nPrefix;           (length of prefix shared with previous term)
1.123917 +**   varint nSuffix;           (length of unshared suffix)
1.123918 +**   char pTermSuffix[nSuffix];(unshared suffix of next term)
1.123919 +**   varint nDoclist;          (length of term's associated doclist)
1.123920 +**   char pDoclist[nDoclist];  (content of doclist)
1.123921 +** }
1.123922 +**
1.123923 +** Here, array { X } means zero or more occurrences of X, adjacent in
1.123924 +** memory.
1.123925 +**
1.123926 +** Leaf nodes are broken into blocks which are stored contiguously in
1.123927 +** the %_segments table in sorted order.  This means that when the end
1.123928 +** of a node is reached, the next term is in the node with the next
1.123929 +** greater node id.
1.123930 +**
1.123931 +** New data is spilled to a new leaf node when the current node
1.123932 +** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
1.123933 +** larger than STANDALONE_MIN (default 1024) is placed in a standalone
1.123934 +** node (a leaf node with a single term and doclist).  The goal of
1.123935 +** these settings is to pack together groups of small doclists while
1.123936 +** making it efficient to directly access large doclists.  The
1.123937 +** assumption is that large doclists represent terms which are more
1.123938 +** likely to be query targets.
1.123939 +**
1.123940 +** TODO(shess) It may be useful for blocking decisions to be more
1.123941 +** dynamic.  For instance, it may make more sense to have a 2.5k leaf
1.123942 +** node rather than splitting into 2k and .5k nodes.  My intuition is
1.123943 +** that this might extend through 2x or 4x the pagesize.
1.123944 +**
1.123945 +**
1.123946 +**** Segment interior nodes ****
1.123947 +** Segment interior nodes store blockids for subtree nodes and terms
1.123948 +** to describe what data is stored by the each subtree.  Interior
1.123949 +** nodes are written using InteriorWriter, and read using
1.123950 +** InteriorReader.  InteriorWriters are created as needed when
1.123951 +** SegmentWriter creates new leaf nodes, or when an interior node
1.123952 +** itself grows too big and must be split.  The format of interior
1.123953 +** nodes:
1.123954 +**
1.123955 +** varint iHeight;           (height from leaf level, always >0)
1.123956 +** varint iBlockid;          (block id of node's leftmost subtree)
1.123957 +** optional {
1.123958 +**   varint nTerm;           (length of first term)
1.123959 +**   char pTerm[nTerm];      (content of first term)
1.123960 +**   array {
1.123961 +**                                (further terms are delta-encoded)
1.123962 +**     varint nPrefix;            (length of shared prefix with previous term)
1.123963 +**     varint nSuffix;            (length of unshared suffix)
1.123964 +**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
1.123965 +**   }
1.123966 +** }
1.123967 +**
1.123968 +** Here, optional { X } means an optional element, while array { X }
1.123969 +** means zero or more occurrences of X, adjacent in memory.
1.123970 +**
1.123971 +** An interior node encodes n terms separating n+1 subtrees.  The
1.123972 +** subtree blocks are contiguous, so only the first subtree's blockid
1.123973 +** is encoded.  The subtree at iBlockid will contain all terms less
1.123974 +** than the first term encoded (or all terms if no term is encoded).
1.123975 +** Otherwise, for terms greater than or equal to pTerm[i] but less
1.123976 +** than pTerm[i+1], the subtree for that term will be rooted at
1.123977 +** iBlockid+i.  Interior nodes only store enough term data to
1.123978 +** distinguish adjacent children (if the rightmost term of the left
1.123979 +** child is "something", and the leftmost term of the right child is
1.123980 +** "wicked", only "w" is stored).
1.123981 +**
1.123982 +** New data is spilled to a new interior node at the same height when
1.123983 +** the current node exceeds INTERIOR_MAX bytes (default 2048).
1.123984 +** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
1.123985 +** interior nodes and making the tree too skinny.  The interior nodes
1.123986 +** at a given height are naturally tracked by interior nodes at
1.123987 +** height+1, and so on.
1.123988 +**
1.123989 +**
1.123990 +**** Segment directory ****
1.123991 +** The segment directory in table %_segdir stores meta-information for
1.123992 +** merging and deleting segments, and also the root node of the
1.123993 +** segment's tree.
1.123994 +**
1.123995 +** The root node is the top node of the segment's tree after encoding
1.123996 +** the entire segment, restricted to ROOT_MAX bytes (default 1024).
1.123997 +** This could be either a leaf node or an interior node.  If the top
1.123998 +** node requires more than ROOT_MAX bytes, it is flushed to %_segments
1.123999 +** and a new root interior node is generated (which should always fit
1.124000 +** within ROOT_MAX because it only needs space for 2 varints, the
1.124001 +** height and the blockid of the previous root).
1.124002 +**
1.124003 +** The meta-information in the segment directory is:
1.124004 +**   level               - segment level (see below)
1.124005 +**   idx                 - index within level
1.124006 +**                       - (level,idx uniquely identify a segment)
1.124007 +**   start_block         - first leaf node
1.124008 +**   leaves_end_block    - last leaf node
1.124009 +**   end_block           - last block (including interior nodes)
1.124010 +**   root                - contents of root node
1.124011 +**
1.124012 +** If the root node is a leaf node, then start_block,
1.124013 +** leaves_end_block, and end_block are all 0.
1.124014 +**
1.124015 +**
1.124016 +**** Segment merging ****
1.124017 +** To amortize update costs, segments are grouped into levels and
1.124018 +** merged in batches.  Each increase in level represents exponentially
1.124019 +** more documents.
1.124020 +**
1.124021 +** New documents (actually, document updates) are tokenized and
1.124022 +** written individually (using LeafWriter) to a level 0 segment, with
1.124023 +** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
1.124024 +** level 0 segments are merged into a single level 1 segment.  Level 1
1.124025 +** is populated like level 0, and eventually MERGE_COUNT level 1
1.124026 +** segments are merged to a single level 2 segment (representing
1.124027 +** MERGE_COUNT^2 updates), and so on.
1.124028 +**
1.124029 +** A segment merge traverses all segments at a given level in
1.124030 +** parallel, performing a straightforward sorted merge.  Since segment
1.124031 +** leaf nodes are written in to the %_segments table in order, this
1.124032 +** merge traverses the underlying sqlite disk structures efficiently.
1.124033 +** After the merge, all segment blocks from the merged level are
1.124034 +** deleted.
1.124035 +**
1.124036 +** MERGE_COUNT controls how often we merge segments.  16 seems to be
1.124037 +** somewhat of a sweet spot for insertion performance.  32 and 64 show
1.124038 +** very similar performance numbers to 16 on insertion, though they're
1.124039 +** a tiny bit slower (perhaps due to more overhead in merge-time
1.124040 +** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
1.124041 +** 16, 2 about 66% slower than 16.
1.124042 +**
1.124043 +** At query time, high MERGE_COUNT increases the number of segments
1.124044 +** which need to be scanned and merged.  For instance, with 100k docs
1.124045 +** inserted:
1.124046 +**
1.124047 +**    MERGE_COUNT   segments
1.124048 +**       16           25
1.124049 +**        8           12
1.124050 +**        4           10
1.124051 +**        2            6
1.124052 +**
1.124053 +** This appears to have only a moderate impact on queries for very
1.124054 +** frequent terms (which are somewhat dominated by segment merge
1.124055 +** costs), and infrequent and non-existent terms still seem to be fast
1.124056 +** even with many segments.
1.124057 +**
1.124058 +** TODO(shess) That said, it would be nice to have a better query-side
1.124059 +** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
1.124060 +** optimizations to things like doclist merging will swing the sweet
1.124061 +** spot around.
1.124062 +**
1.124063 +**
1.124064 +**
1.124065 +**** Handling of deletions and updates ****
1.124066 +** Since we're using a segmented structure, with no docid-oriented
1.124067 +** index into the term index, we clearly cannot simply update the term
1.124068 +** index when a document is deleted or updated.  For deletions, we
1.124069 +** write an empty doclist (varint(docid) varint(POS_END)), for updates
1.124070 +** we simply write the new doclist.  Segment merges overwrite older
1.124071 +** data for a particular docid with newer data, so deletes or updates
1.124072 +** will eventually overtake the earlier data and knock it out.  The
1.124073 +** query logic likewise merges doclists so that newer data knocks out
1.124074 +** older data.
1.124075 +*/
1.124076 +
1.124077 +/************** Include fts3Int.h in the middle of fts3.c ********************/
1.124078 +/************** Begin file fts3Int.h *****************************************/
1.124079 +/*
1.124080 +** 2009 Nov 12
1.124081 +**
1.124082 +** The author disclaims copyright to this source code.  In place of
1.124083 +** a legal notice, here is a blessing:
1.124084 +**
1.124085 +**    May you do good and not evil.
1.124086 +**    May you find forgiveness for yourself and forgive others.
1.124087 +**    May you share freely, never taking more than you give.
1.124088 +**
1.124089 +******************************************************************************
1.124090 +**
1.124091 +*/
1.124092 +#ifndef _FTSINT_H
1.124093 +#define _FTSINT_H
1.124094 +
1.124095 +#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
1.124096 +# define NDEBUG 1
1.124097 +#endif
1.124098 +
1.124099 +/*
1.124100 +** FTS4 is really an extension for FTS3.  It is enabled using the
1.124101 +** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
1.124102 +** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
1.124103 +*/
1.124104 +#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
1.124105 +# define SQLITE_ENABLE_FTS3
1.124106 +#endif
1.124107 +
1.124108 +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
1.124109 +
1.124110 +/* If not building as part of the core, include sqlite3ext.h. */
1.124111 +#ifndef SQLITE_CORE
1.124112 +SQLITE_EXTENSION_INIT3
1.124113 +#endif
1.124114 +
1.124115 +/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
1.124116 +/************** Begin file fts3_tokenizer.h **********************************/
1.124117 +/*
1.124118 +** 2006 July 10
1.124119 +**
1.124120 +** The author disclaims copyright to this source code.
1.124121 +**
1.124122 +*************************************************************************
1.124123 +** Defines the interface to tokenizers used by fulltext-search.  There
1.124124 +** are three basic components:
1.124125 +**
1.124126 +** sqlite3_tokenizer_module is a singleton defining the tokenizer
1.124127 +** interface functions.  This is essentially the class structure for
1.124128 +** tokenizers.
1.124129 +**
1.124130 +** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
1.124131 +** including customization information defined at creation time.
1.124132 +**
1.124133 +** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
1.124134 +** tokens from a particular input.
1.124135 +*/
1.124136 +#ifndef _FTS3_TOKENIZER_H_
1.124137 +#define _FTS3_TOKENIZER_H_
1.124138 +
1.124139 +/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
1.124140 +** If tokenizers are to be allowed to call sqlite3_*() functions, then
1.124141 +** we will need a way to register the API consistently.
1.124142 +*/
1.124143 +
1.124144 +/*
1.124145 +** Structures used by the tokenizer interface. When a new tokenizer
1.124146 +** implementation is registered, the caller provides a pointer to
1.124147 +** an sqlite3_tokenizer_module containing pointers to the callback
1.124148 +** functions that make up an implementation.
1.124149 +**
1.124150 +** When an fts3 table is created, it passes any arguments passed to
1.124151 +** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
1.124152 +** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
1.124153 +** implementation. The xCreate() function in turn returns an 
1.124154 +** sqlite3_tokenizer structure representing the specific tokenizer to
1.124155 +** be used for the fts3 table (customized by the tokenizer clause arguments).
1.124156 +**
1.124157 +** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
1.124158 +** method is called. It returns an sqlite3_tokenizer_cursor object
1.124159 +** that may be used to tokenize a specific input buffer based on
1.124160 +** the tokenization rules supplied by a specific sqlite3_tokenizer
1.124161 +** object.
1.124162 +*/
1.124163 +typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
1.124164 +typedef struct sqlite3_tokenizer sqlite3_tokenizer;
1.124165 +typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
1.124166 +
1.124167 +struct sqlite3_tokenizer_module {
1.124168 +
1.124169 +  /*
1.124170 +  ** Structure version. Should always be set to 0 or 1.
1.124171 +  */
1.124172 +  int iVersion;
1.124173 +
1.124174 +  /*
1.124175 +  ** Create a new tokenizer. The values in the argv[] array are the
1.124176 +  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
1.124177 +  ** TABLE statement that created the fts3 table. For example, if
1.124178 +  ** the following SQL is executed:
1.124179 +  **
1.124180 +  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
1.124181 +  **
1.124182 +  ** then argc is set to 2, and the argv[] array contains pointers
1.124183 +  ** to the strings "arg1" and "arg2".
1.124184 +  **
1.124185 +  ** This method should return either SQLITE_OK (0), or an SQLite error 
1.124186 +  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
1.124187 +  ** to point at the newly created tokenizer structure. The generic
1.124188 +  ** sqlite3_tokenizer.pModule variable should not be initialized by
1.124189 +  ** this callback. The caller will do so.
1.124190 +  */
1.124191 +  int (*xCreate)(
1.124192 +    int argc,                           /* Size of argv array */
1.124193 +    const char *const*argv,             /* Tokenizer argument strings */
1.124194 +    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
1.124195 +  );
1.124196 +
1.124197 +  /*
1.124198 +  ** Destroy an existing tokenizer. The fts3 module calls this method
1.124199 +  ** exactly once for each successful call to xCreate().
1.124200 +  */
1.124201 +  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
1.124202 +
1.124203 +  /*
1.124204 +  ** Create a tokenizer cursor to tokenize an input buffer. The caller
1.124205 +  ** is responsible for ensuring that the input buffer remains valid
1.124206 +  ** until the cursor is closed (using the xClose() method). 
1.124207 +  */
1.124208 +  int (*xOpen)(
1.124209 +    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
1.124210 +    const char *pInput, int nBytes,      /* Input buffer */
1.124211 +    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
1.124212 +  );
1.124213 +
1.124214 +  /*
1.124215 +  ** Destroy an existing tokenizer cursor. The fts3 module calls this 
1.124216 +  ** method exactly once for each successful call to xOpen().
1.124217 +  */
1.124218 +  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
1.124219 +
1.124220 +  /*
1.124221 +  ** Retrieve the next token from the tokenizer cursor pCursor. This
1.124222 +  ** method should either return SQLITE_OK and set the values of the
1.124223 +  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
1.124224 +  ** the end of the buffer has been reached, or an SQLite error code.
1.124225 +  **
1.124226 +  ** *ppToken should be set to point at a buffer containing the 
1.124227 +  ** normalized version of the token (i.e. after any case-folding and/or
1.124228 +  ** stemming has been performed). *pnBytes should be set to the length
1.124229 +  ** of this buffer in bytes. The input text that generated the token is
1.124230 +  ** identified by the byte offsets returned in *piStartOffset and
1.124231 +  ** *piEndOffset. *piStartOffset should be set to the index of the first
1.124232 +  ** byte of the token in the input buffer. *piEndOffset should be set
1.124233 +  ** to the index of the first byte just past the end of the token in
1.124234 +  ** the input buffer.
1.124235 +  **
1.124236 +  ** The buffer *ppToken is set to point at is managed by the tokenizer
1.124237 +  ** implementation. It is only required to be valid until the next call
1.124238 +  ** to xNext() or xClose(). 
1.124239 +  */
1.124240 +  /* TODO(shess) current implementation requires pInput to be
1.124241 +  ** nul-terminated.  This should either be fixed, or pInput/nBytes
1.124242 +  ** should be converted to zInput.
1.124243 +  */
1.124244 +  int (*xNext)(
1.124245 +    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
1.124246 +    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
1.124247 +    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
1.124248 +    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
1.124249 +    int *piPosition      /* OUT: Number of tokens returned before this one */
1.124250 +  );
1.124251 +
1.124252 +  /***********************************************************************
1.124253 +  ** Methods below this point are only available if iVersion>=1.
1.124254 +  */
1.124255 +
1.124256 +  /* 
1.124257 +  ** Configure the language id of a tokenizer cursor.
1.124258 +  */
1.124259 +  int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
1.124260 +};
1.124261 +
1.124262 +struct sqlite3_tokenizer {
1.124263 +  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
1.124264 +  /* Tokenizer implementations will typically add additional fields */
1.124265 +};
1.124266 +
1.124267 +struct sqlite3_tokenizer_cursor {
1.124268 +  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
1.124269 +  /* Tokenizer implementations will typically add additional fields */
1.124270 +};
1.124271 +
1.124272 +int fts3_global_term_cnt(int iTerm, int iCol);
1.124273 +int fts3_term_cnt(int iTerm, int iCol);
1.124274 +
1.124275 +
1.124276 +#endif /* _FTS3_TOKENIZER_H_ */
1.124277 +
1.124278 +/************** End of fts3_tokenizer.h **************************************/
1.124279 +/************** Continuing where we left off in fts3Int.h ********************/
1.124280 +/************** Include fts3_hash.h in the middle of fts3Int.h ***************/
1.124281 +/************** Begin file fts3_hash.h ***************************************/
1.124282 +/*
1.124283 +** 2001 September 22
1.124284 +**
1.124285 +** The author disclaims copyright to this source code.  In place of
1.124286 +** a legal notice, here is a blessing:
1.124287 +**
1.124288 +**    May you do good and not evil.
1.124289 +**    May you find forgiveness for yourself and forgive others.
1.124290 +**    May you share freely, never taking more than you give.
1.124291 +**
1.124292 +*************************************************************************
1.124293 +** This is the header file for the generic hash-table implementation
1.124294 +** used in SQLite.  We've modified it slightly to serve as a standalone
1.124295 +** hash table implementation for the full-text indexing module.
1.124296 +**
1.124297 +*/
1.124298 +#ifndef _FTS3_HASH_H_
1.124299 +#define _FTS3_HASH_H_
1.124300 +
1.124301 +/* Forward declarations of structures. */
1.124302 +typedef struct Fts3Hash Fts3Hash;
1.124303 +typedef struct Fts3HashElem Fts3HashElem;
1.124304 +
1.124305 +/* A complete hash table is an instance of the following structure.
1.124306 +** The internals of this structure are intended to be opaque -- client
1.124307 +** code should not attempt to access or modify the fields of this structure
1.124308 +** directly.  Change this structure only by using the routines below.
1.124309 +** However, many of the "procedures" and "functions" for modifying and
1.124310 +** accessing this structure are really macros, so we can't really make
1.124311 +** this structure opaque.
1.124312 +*/
1.124313 +struct Fts3Hash {
1.124314 +  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
1.124315 +  char copyKey;           /* True if copy of key made on insert */
1.124316 +  int count;              /* Number of entries in this table */
1.124317 +  Fts3HashElem *first;    /* The first element of the array */
1.124318 +  int htsize;             /* Number of buckets in the hash table */
1.124319 +  struct _fts3ht {        /* the hash table */
1.124320 +    int count;               /* Number of entries with this hash */
1.124321 +    Fts3HashElem *chain;     /* Pointer to first entry with this hash */
1.124322 +  } *ht;
1.124323 +};
1.124324 +
1.124325 +/* Each element in the hash table is an instance of the following 
1.124326 +** structure.  All elements are stored on a single doubly-linked list.
1.124327 +**
1.124328 +** Again, this structure is intended to be opaque, but it can't really
1.124329 +** be opaque because it is used by macros.
1.124330 +*/
1.124331 +struct Fts3HashElem {
1.124332 +  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
1.124333 +  void *data;                /* Data associated with this element */
1.124334 +  void *pKey; int nKey;      /* Key associated with this element */
1.124335 +};
1.124336 +
1.124337 +/*
1.124338 +** There are 2 different modes of operation for a hash table:
1.124339 +**
1.124340 +**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
1.124341 +**                           (including the null-terminator, if any).  Case
1.124342 +**                           is respected in comparisons.
1.124343 +**
1.124344 +**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
1.124345 +**                           memcmp() is used to compare keys.
1.124346 +**
1.124347 +** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
1.124348 +*/
1.124349 +#define FTS3_HASH_STRING    1
1.124350 +#define FTS3_HASH_BINARY    2
1.124351 +
1.124352 +/*
1.124353 +** Access routines.  To delete, insert a NULL pointer.
1.124354 +*/
1.124355 +SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
1.124356 +SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
1.124357 +SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
1.124358 +SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
1.124359 +SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
1.124360 +
1.124361 +/*
1.124362 +** Shorthand for the functions above
1.124363 +*/
1.124364 +#define fts3HashInit     sqlite3Fts3HashInit
1.124365 +#define fts3HashInsert   sqlite3Fts3HashInsert
1.124366 +#define fts3HashFind     sqlite3Fts3HashFind
1.124367 +#define fts3HashClear    sqlite3Fts3HashClear
1.124368 +#define fts3HashFindElem sqlite3Fts3HashFindElem
1.124369 +
1.124370 +/*
1.124371 +** Macros for looping over all elements of a hash table.  The idiom is
1.124372 +** like this:
1.124373 +**
1.124374 +**   Fts3Hash h;
1.124375 +**   Fts3HashElem *p;
1.124376 +**   ...
1.124377 +**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
1.124378 +**     SomeStructure *pData = fts3HashData(p);
1.124379 +**     // do something with pData
1.124380 +**   }
1.124381 +*/
1.124382 +#define fts3HashFirst(H)  ((H)->first)
1.124383 +#define fts3HashNext(E)   ((E)->next)
1.124384 +#define fts3HashData(E)   ((E)->data)
1.124385 +#define fts3HashKey(E)    ((E)->pKey)
1.124386 +#define fts3HashKeysize(E) ((E)->nKey)
1.124387 +
1.124388 +/*
1.124389 +** Number of entries in a hash table
1.124390 +*/
1.124391 +#define fts3HashCount(H)  ((H)->count)
1.124392 +
1.124393 +#endif /* _FTS3_HASH_H_ */
1.124394 +
1.124395 +/************** End of fts3_hash.h *******************************************/
1.124396 +/************** Continuing where we left off in fts3Int.h ********************/
1.124397 +
1.124398 +/*
1.124399 +** This constant determines the maximum depth of an FTS expression tree
1.124400 +** that the library will create and use. FTS uses recursion to perform 
1.124401 +** various operations on the query tree, so the disadvantage of a large
1.124402 +** limit is that it may allow very large queries to use large amounts
1.124403 +** of stack space (perhaps causing a stack overflow).
1.124404 +*/
1.124405 +#ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
1.124406 +# define SQLITE_FTS3_MAX_EXPR_DEPTH 12
1.124407 +#endif
1.124408 +
1.124409 +
1.124410 +/*
1.124411 +** This constant controls how often segments are merged. Once there are
1.124412 +** FTS3_MERGE_COUNT segments of level N, they are merged into a single
1.124413 +** segment of level N+1.
1.124414 +*/
1.124415 +#define FTS3_MERGE_COUNT 16
1.124416 +
1.124417 +/*
1.124418 +** This is the maximum amount of data (in bytes) to store in the 
1.124419 +** Fts3Table.pendingTerms hash table. Normally, the hash table is
1.124420 +** populated as documents are inserted/updated/deleted in a transaction
1.124421 +** and used to create a new segment when the transaction is committed.
1.124422 +** However if this limit is reached midway through a transaction, a new 
1.124423 +** segment is created and the hash table cleared immediately.
1.124424 +*/
1.124425 +#define FTS3_MAX_PENDING_DATA (1*1024*1024)
1.124426 +
1.124427 +/*
1.124428 +** Macro to return the number of elements in an array. SQLite has a
1.124429 +** similar macro called ArraySize(). Use a different name to avoid
1.124430 +** a collision when building an amalgamation with built-in FTS3.
1.124431 +*/
1.124432 +#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
1.124433 +
1.124434 +
1.124435 +#ifndef MIN
1.124436 +# define MIN(x,y) ((x)<(y)?(x):(y))
1.124437 +#endif
1.124438 +#ifndef MAX
1.124439 +# define MAX(x,y) ((x)>(y)?(x):(y))
1.124440 +#endif
1.124441 +
1.124442 +/*
1.124443 +** Maximum length of a varint encoded integer. The varint format is different
1.124444 +** from that used by SQLite, so the maximum length is 10, not 9.
1.124445 +*/
1.124446 +#define FTS3_VARINT_MAX 10
1.124447 +
1.124448 +/*
1.124449 +** FTS4 virtual tables may maintain multiple indexes - one index of all terms
1.124450 +** in the document set and zero or more prefix indexes. All indexes are stored
1.124451 +** as one or more b+-trees in the %_segments and %_segdir tables. 
1.124452 +**
1.124453 +** It is possible to determine which index a b+-tree belongs to based on the
1.124454 +** value stored in the "%_segdir.level" column. Given this value L, the index
1.124455 +** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
1.124456 +** level values between 0 and 1023 (inclusive) belong to index 0, all levels
1.124457 +** between 1024 and 2047 to index 1, and so on.
1.124458 +**
1.124459 +** It is considered impossible for an index to use more than 1024 levels. In 
1.124460 +** theory though this may happen, but only after at least 
1.124461 +** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
1.124462 +*/
1.124463 +#define FTS3_SEGDIR_MAXLEVEL      1024
1.124464 +#define FTS3_SEGDIR_MAXLEVEL_STR "1024"
1.124465 +
1.124466 +/*
1.124467 +** The testcase() macro is only used by the amalgamation.  If undefined,
1.124468 +** make it a no-op.
1.124469 +*/
1.124470 +#ifndef testcase
1.124471 +# define testcase(X)
1.124472 +#endif
1.124473 +
1.124474 +/*
1.124475 +** Terminator values for position-lists and column-lists.
1.124476 +*/
1.124477 +#define POS_COLUMN  (1)     /* Column-list terminator */
1.124478 +#define POS_END     (0)     /* Position-list terminator */ 
1.124479 +
1.124480 +/*
1.124481 +** This section provides definitions to allow the
1.124482 +** FTS3 extension to be compiled outside of the 
1.124483 +** amalgamation.
1.124484 +*/
1.124485 +#ifndef SQLITE_AMALGAMATION
1.124486 +/*
1.124487 +** Macros indicating that conditional expressions are always true or
1.124488 +** false.
1.124489 +*/
1.124490 +#ifdef SQLITE_COVERAGE_TEST
1.124491 +# define ALWAYS(x) (1)
1.124492 +# define NEVER(X)  (0)
1.124493 +#else
1.124494 +# define ALWAYS(x) (x)
1.124495 +# define NEVER(x)  (x)
1.124496 +#endif
1.124497 +
1.124498 +/*
1.124499 +** Internal types used by SQLite.
1.124500 +*/
1.124501 +typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
1.124502 +typedef short int i16;            /* 2-byte (or larger) signed integer */
1.124503 +typedef unsigned int u32;         /* 4-byte unsigned integer */
1.124504 +typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
1.124505 +typedef sqlite3_int64 i64;        /* 8-byte signed integer */
1.124506 +
1.124507 +/*
1.124508 +** Macro used to suppress compiler warnings for unused parameters.
1.124509 +*/
1.124510 +#define UNUSED_PARAMETER(x) (void)(x)
1.124511 +
1.124512 +/*
1.124513 +** Activate assert() only if SQLITE_TEST is enabled.
1.124514 +*/
1.124515 +#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
1.124516 +# define NDEBUG 1
1.124517 +#endif
1.124518 +
1.124519 +/*
1.124520 +** The TESTONLY macro is used to enclose variable declarations or
1.124521 +** other bits of code that are needed to support the arguments
1.124522 +** within testcase() and assert() macros.
1.124523 +*/
1.124524 +#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
1.124525 +# define TESTONLY(X)  X
1.124526 +#else
1.124527 +# define TESTONLY(X)
1.124528 +#endif
1.124529 +
1.124530 +#endif /* SQLITE_AMALGAMATION */
1.124531 +
1.124532 +#ifdef SQLITE_DEBUG
1.124533 +SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
1.124534 +# define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
1.124535 +#else
1.124536 +# define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
1.124537 +#endif
1.124538 +
1.124539 +typedef struct Fts3Table Fts3Table;
1.124540 +typedef struct Fts3Cursor Fts3Cursor;
1.124541 +typedef struct Fts3Expr Fts3Expr;
1.124542 +typedef struct Fts3Phrase Fts3Phrase;
1.124543 +typedef struct Fts3PhraseToken Fts3PhraseToken;
1.124544 +
1.124545 +typedef struct Fts3Doclist Fts3Doclist;
1.124546 +typedef struct Fts3SegFilter Fts3SegFilter;
1.124547 +typedef struct Fts3DeferredToken Fts3DeferredToken;
1.124548 +typedef struct Fts3SegReader Fts3SegReader;
1.124549 +typedef struct Fts3MultiSegReader Fts3MultiSegReader;
1.124550 +
1.124551 +/*
1.124552 +** A connection to a fulltext index is an instance of the following
1.124553 +** structure. The xCreate and xConnect methods create an instance
1.124554 +** of this structure and xDestroy and xDisconnect free that instance.
1.124555 +** All other methods receive a pointer to the structure as one of their
1.124556 +** arguments.
1.124557 +*/
1.124558 +struct Fts3Table {
1.124559 +  sqlite3_vtab base;              /* Base class used by SQLite core */
1.124560 +  sqlite3 *db;                    /* The database connection */
1.124561 +  const char *zDb;                /* logical database name */
1.124562 +  const char *zName;              /* virtual table name */
1.124563 +  int nColumn;                    /* number of named columns in virtual table */
1.124564 +  char **azColumn;                /* column names.  malloced */
1.124565 +  u8 *abNotindexed;               /* True for 'notindexed' columns */
1.124566 +  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
1.124567 +  char *zContentTbl;              /* content=xxx option, or NULL */
1.124568 +  char *zLanguageid;              /* languageid=xxx option, or NULL */
1.124569 +  u8 bAutoincrmerge;              /* True if automerge=1 */
1.124570 +  u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
1.124571 +
1.124572 +  /* Precompiled statements used by the implementation. Each of these 
1.124573 +  ** statements is run and reset within a single virtual table API call. 
1.124574 +  */
1.124575 +  sqlite3_stmt *aStmt[37];
1.124576 +
1.124577 +  char *zReadExprlist;
1.124578 +  char *zWriteExprlist;
1.124579 +
1.124580 +  int nNodeSize;                  /* Soft limit for node size */
1.124581 +  u8 bFts4;                       /* True for FTS4, false for FTS3 */
1.124582 +  u8 bHasStat;                    /* True if %_stat table exists */
1.124583 +  u8 bHasDocsize;                 /* True if %_docsize table exists */
1.124584 +  u8 bDescIdx;                    /* True if doclists are in reverse order */
1.124585 +  u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
1.124586 +  int nPgsz;                      /* Page size for host database */
1.124587 +  char *zSegmentsTbl;             /* Name of %_segments table */
1.124588 +  sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
1.124589 +
1.124590 +  /* 
1.124591 +  ** The following array of hash tables is used to buffer pending index 
1.124592 +  ** updates during transactions. All pending updates buffered at any one
1.124593 +  ** time must share a common language-id (see the FTS4 langid= feature).
1.124594 +  ** The current language id is stored in variable iPrevLangid.
1.124595 +  **
1.124596 +  ** A single FTS4 table may have multiple full-text indexes. For each index
1.124597 +  ** there is an entry in the aIndex[] array. Index 0 is an index of all the
1.124598 +  ** terms that appear in the document set. Each subsequent index in aIndex[]
1.124599 +  ** is an index of prefixes of a specific length.
1.124600 +  **
1.124601 +  ** Variable nPendingData contains an estimate the memory consumed by the 
1.124602 +  ** pending data structures, including hash table overhead, but not including
1.124603 +  ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
1.124604 +  ** tables are flushed to disk. Variable iPrevDocid is the docid of the most 
1.124605 +  ** recently inserted record.
1.124606 +  */
1.124607 +  int nIndex;                     /* Size of aIndex[] */
1.124608 +  struct Fts3Index {
1.124609 +    int nPrefix;                  /* Prefix length (0 for main terms index) */
1.124610 +    Fts3Hash hPending;            /* Pending terms table for this index */
1.124611 +  } *aIndex;
1.124612 +  int nMaxPendingData;            /* Max pending data before flush to disk */
1.124613 +  int nPendingData;               /* Current bytes of pending data */
1.124614 +  sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
1.124615 +  int iPrevLangid;                /* Langid of recently inserted document */
1.124616 +
1.124617 +#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
1.124618 +  /* State variables used for validating that the transaction control
1.124619 +  ** methods of the virtual table are called at appropriate times.  These
1.124620 +  ** values do not contribute to FTS functionality; they are used for
1.124621 +  ** verifying the operation of the SQLite core.
1.124622 +  */
1.124623 +  int inTransaction;     /* True after xBegin but before xCommit/xRollback */
1.124624 +  int mxSavepoint;       /* Largest valid xSavepoint integer */
1.124625 +#endif
1.124626 +
1.124627 +#ifdef SQLITE_TEST
1.124628 +  /* True to disable the incremental doclist optimization. This is controled
1.124629 +  ** by special insert command 'test-no-incr-doclist'.  */
1.124630 +  int bNoIncrDoclist;
1.124631 +#endif
1.124632 +};
1.124633 +
1.124634 +/*
1.124635 +** When the core wants to read from the virtual table, it creates a
1.124636 +** virtual table cursor (an instance of the following structure) using
1.124637 +** the xOpen method. Cursors are destroyed using the xClose method.
1.124638 +*/
1.124639 +struct Fts3Cursor {
1.124640 +  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
1.124641 +  i16 eSearch;                    /* Search strategy (see below) */
1.124642 +  u8 isEof;                       /* True if at End Of Results */
1.124643 +  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
1.124644 +  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
1.124645 +  Fts3Expr *pExpr;                /* Parsed MATCH query string */
1.124646 +  int iLangid;                    /* Language being queried for */
1.124647 +  int nPhrase;                    /* Number of matchable phrases in query */
1.124648 +  Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
1.124649 +  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
1.124650 +  char *pNextId;                  /* Pointer into the body of aDoclist */
1.124651 +  char *aDoclist;                 /* List of docids for full-text queries */
1.124652 +  int nDoclist;                   /* Size of buffer at aDoclist */
1.124653 +  u8 bDesc;                       /* True to sort in descending order */
1.124654 +  int eEvalmode;                  /* An FTS3_EVAL_XX constant */
1.124655 +  int nRowAvg;                    /* Average size of database rows, in pages */
1.124656 +  sqlite3_int64 nDoc;             /* Documents in table */
1.124657 +  i64 iMinDocid;                  /* Minimum docid to return */
1.124658 +  i64 iMaxDocid;                  /* Maximum docid to return */
1.124659 +  int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
1.124660 +  u32 *aMatchinfo;                /* Information about most recent match */
1.124661 +  int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
1.124662 +  char *zMatchinfo;               /* Matchinfo specification */
1.124663 +};
1.124664 +
1.124665 +#define FTS3_EVAL_FILTER    0
1.124666 +#define FTS3_EVAL_NEXT      1
1.124667 +#define FTS3_EVAL_MATCHINFO 2
1.124668 +
1.124669 +/*
1.124670 +** The Fts3Cursor.eSearch member is always set to one of the following.
1.124671 +** Actualy, Fts3Cursor.eSearch can be greater than or equal to
1.124672 +** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
1.124673 +** of the column to be searched.  For example, in
1.124674 +**
1.124675 +**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
1.124676 +**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
1.124677 +** 
1.124678 +** Because the LHS of the MATCH operator is 2nd column "b",
1.124679 +** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
1.124680 +** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
1.124681 +** indicating that all columns should be searched,
1.124682 +** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
1.124683 +*/
1.124684 +#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
1.124685 +#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
1.124686 +#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
1.124687 +
1.124688 +/*
1.124689 +** The lower 16-bits of the sqlite3_index_info.idxNum value set by
1.124690 +** the xBestIndex() method contains the Fts3Cursor.eSearch value described
1.124691 +** above. The upper 16-bits contain a combination of the following
1.124692 +** bits, used to describe extra constraints on full-text searches.
1.124693 +*/
1.124694 +#define FTS3_HAVE_LANGID    0x00010000      /* languageid=? */
1.124695 +#define FTS3_HAVE_DOCID_GE  0x00020000      /* docid>=? */
1.124696 +#define FTS3_HAVE_DOCID_LE  0x00040000      /* docid<=? */
1.124697 +
1.124698 +struct Fts3Doclist {
1.124699 +  char *aAll;                    /* Array containing doclist (or NULL) */
1.124700 +  int nAll;                      /* Size of a[] in bytes */
1.124701 +  char *pNextDocid;              /* Pointer to next docid */
1.124702 +
1.124703 +  sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
1.124704 +  int bFreeList;                 /* True if pList should be sqlite3_free()d */
1.124705 +  char *pList;                   /* Pointer to position list following iDocid */
1.124706 +  int nList;                     /* Length of position list */
1.124707 +};
1.124708 +
1.124709 +/*
1.124710 +** A "phrase" is a sequence of one or more tokens that must match in
1.124711 +** sequence.  A single token is the base case and the most common case.
1.124712 +** For a sequence of tokens contained in double-quotes (i.e. "one two three")
1.124713 +** nToken will be the number of tokens in the string.
1.124714 +*/
1.124715 +struct Fts3PhraseToken {
1.124716 +  char *z;                        /* Text of the token */
1.124717 +  int n;                          /* Number of bytes in buffer z */
1.124718 +  int isPrefix;                   /* True if token ends with a "*" character */
1.124719 +  int bFirst;                     /* True if token must appear at position 0 */
1.124720 +
1.124721 +  /* Variables above this point are populated when the expression is
1.124722 +  ** parsed (by code in fts3_expr.c). Below this point the variables are
1.124723 +  ** used when evaluating the expression. */
1.124724 +  Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
1.124725 +  Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
1.124726 +};
1.124727 +
1.124728 +struct Fts3Phrase {
1.124729 +  /* Cache of doclist for this phrase. */
1.124730 +  Fts3Doclist doclist;
1.124731 +  int bIncr;                 /* True if doclist is loaded incrementally */
1.124732 +  int iDoclistToken;
1.124733 +
1.124734 +  /* Variables below this point are populated by fts3_expr.c when parsing 
1.124735 +  ** a MATCH expression. Everything above is part of the evaluation phase. 
1.124736 +  */
1.124737 +  int nToken;                /* Number of tokens in the phrase */
1.124738 +  int iColumn;               /* Index of column this phrase must match */
1.124739 +  Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
1.124740 +};
1.124741 +
1.124742 +/*
1.124743 +** A tree of these objects forms the RHS of a MATCH operator.
1.124744 +**
1.124745 +** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist 
1.124746 +** points to a malloced buffer, size nDoclist bytes, containing the results 
1.124747 +** of this phrase query in FTS3 doclist format. As usual, the initial 
1.124748 +** "Length" field found in doclists stored on disk is omitted from this 
1.124749 +** buffer.
1.124750 +**
1.124751 +** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
1.124752 +** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
1.124753 +** where nCol is the number of columns in the queried FTS table. The array
1.124754 +** is populated as follows:
1.124755 +**
1.124756 +**   aMI[iCol*3 + 0] = Undefined
1.124757 +**   aMI[iCol*3 + 1] = Number of occurrences
1.124758 +**   aMI[iCol*3 + 2] = Number of rows containing at least one instance
1.124759 +**
1.124760 +** The aMI array is allocated using sqlite3_malloc(). It should be freed 
1.124761 +** when the expression node is.
1.124762 +*/
1.124763 +struct Fts3Expr {
1.124764 +  int eType;                 /* One of the FTSQUERY_XXX values defined below */
1.124765 +  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
1.124766 +  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
1.124767 +  Fts3Expr *pLeft;           /* Left operand */
1.124768 +  Fts3Expr *pRight;          /* Right operand */
1.124769 +  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
1.124770 +
1.124771 +  /* The following are used by the fts3_eval.c module. */
1.124772 +  sqlite3_int64 iDocid;      /* Current docid */
1.124773 +  u8 bEof;                   /* True this expression is at EOF already */
1.124774 +  u8 bStart;                 /* True if iDocid is valid */
1.124775 +  u8 bDeferred;              /* True if this expression is entirely deferred */
1.124776 +
1.124777 +  u32 *aMI;
1.124778 +};
1.124779 +
1.124780 +/*
1.124781 +** Candidate values for Fts3Query.eType. Note that the order of the first
1.124782 +** four values is in order of precedence when parsing expressions. For 
1.124783 +** example, the following:
1.124784 +**
1.124785 +**   "a OR b AND c NOT d NEAR e"
1.124786 +**
1.124787 +** is equivalent to:
1.124788 +**
1.124789 +**   "a OR (b AND (c NOT (d NEAR e)))"
1.124790 +*/
1.124791 +#define FTSQUERY_NEAR   1
1.124792 +#define FTSQUERY_NOT    2
1.124793 +#define FTSQUERY_AND    3
1.124794 +#define FTSQUERY_OR     4
1.124795 +#define FTSQUERY_PHRASE 5
1.124796 +
1.124797 +
1.124798 +/* fts3_write.c */
1.124799 +SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
1.124800 +SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
1.124801 +SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
1.124802 +SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
1.124803 +SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
1.124804 +  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
1.124805 +SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
1.124806 +  Fts3Table*,int,const char*,int,int,Fts3SegReader**);
1.124807 +SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
1.124808 +SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
1.124809 +SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
1.124810 +
1.124811 +SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
1.124812 +SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
1.124813 +
1.124814 +#ifndef SQLITE_DISABLE_FTS4_DEFERRED
1.124815 +SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
1.124816 +SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
1.124817 +SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
1.124818 +SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
1.124819 +SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
1.124820 +#else
1.124821 +# define sqlite3Fts3FreeDeferredTokens(x)
1.124822 +# define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
1.124823 +# define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
1.124824 +# define sqlite3Fts3FreeDeferredDoclists(x)
1.124825 +# define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
1.124826 +#endif
1.124827 +
1.124828 +SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
1.124829 +SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
1.124830 +
1.124831 +/* Special values interpreted by sqlite3SegReaderCursor() */
1.124832 +#define FTS3_SEGCURSOR_PENDING        -1
1.124833 +#define FTS3_SEGCURSOR_ALL            -2
1.124834 +
1.124835 +SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
1.124836 +SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
1.124837 +SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
1.124838 +
1.124839 +SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *, 
1.124840 +    int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
1.124841 +
1.124842 +/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
1.124843 +#define FTS3_SEGMENT_REQUIRE_POS   0x00000001
1.124844 +#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
1.124845 +#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
1.124846 +#define FTS3_SEGMENT_PREFIX        0x00000008
1.124847 +#define FTS3_SEGMENT_SCAN          0x00000010
1.124848 +#define FTS3_SEGMENT_FIRST         0x00000020
1.124849 +
1.124850 +/* Type passed as 4th argument to SegmentReaderIterate() */
1.124851 +struct Fts3SegFilter {
1.124852 +  const char *zTerm;
1.124853 +  int nTerm;
1.124854 +  int iCol;
1.124855 +  int flags;
1.124856 +};
1.124857 +
1.124858 +struct Fts3MultiSegReader {
1.124859 +  /* Used internally by sqlite3Fts3SegReaderXXX() calls */
1.124860 +  Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
1.124861 +  int nSegment;                   /* Size of apSegment array */
1.124862 +  int nAdvance;                   /* How many seg-readers to advance */
1.124863 +  Fts3SegFilter *pFilter;         /* Pointer to filter object */
1.124864 +  char *aBuffer;                  /* Buffer to merge doclists in */
1.124865 +  int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
1.124866 +
1.124867 +  int iColFilter;                 /* If >=0, filter for this column */
1.124868 +  int bRestart;
1.124869 +
1.124870 +  /* Used by fts3.c only. */
1.124871 +  int nCost;                      /* Cost of running iterator */
1.124872 +  int bLookup;                    /* True if a lookup of a single entry. */
1.124873 +
1.124874 +  /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
1.124875 +  char *zTerm;                    /* Pointer to term buffer */
1.124876 +  int nTerm;                      /* Size of zTerm in bytes */
1.124877 +  char *aDoclist;                 /* Pointer to doclist buffer */
1.124878 +  int nDoclist;                   /* Size of aDoclist[] in bytes */
1.124879 +};
1.124880 +
1.124881 +SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
1.124882 +
1.124883 +#define fts3GetVarint32(p, piVal) (                                           \
1.124884 +  (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
1.124885 +)
1.124886 +
1.124887 +/* fts3.c */
1.124888 +SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
1.124889 +SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
1.124890 +SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
1.124891 +SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
1.124892 +SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
1.124893 +SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
1.124894 +SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
1.124895 +SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
1.124896 +SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
1.124897 +
1.124898 +/* fts3_tokenizer.c */
1.124899 +SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
1.124900 +SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
1.124901 +SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, 
1.124902 +    sqlite3_tokenizer **, char **
1.124903 +);
1.124904 +SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
1.124905 +
1.124906 +/* fts3_snippet.c */
1.124907 +SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
1.124908 +SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
1.124909 +  const char *, const char *, int, int
1.124910 +);
1.124911 +SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
1.124912 +
1.124913 +/* fts3_expr.c */
1.124914 +SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
1.124915 +  char **, int, int, int, const char *, int, Fts3Expr **, char **
1.124916 +);
1.124917 +SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
1.124918 +#ifdef SQLITE_TEST
1.124919 +SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
1.124920 +SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
1.124921 +#endif
1.124922 +
1.124923 +SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
1.124924 +  sqlite3_tokenizer_cursor **
1.124925 +);
1.124926 +
1.124927 +/* fts3_aux.c */
1.124928 +SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
1.124929 +
1.124930 +SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
1.124931 +
1.124932 +SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
1.124933 +    Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
1.124934 +SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
1.124935 +    Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
1.124936 +SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); 
1.124937 +SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
1.124938 +SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
1.124939 +
1.124940 +/* fts3_tokenize_vtab.c */
1.124941 +SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
1.124942 +
1.124943 +/* fts3_unicode2.c (functions generated by parsing unicode text files) */
1.124944 +#ifdef SQLITE_ENABLE_FTS4_UNICODE61
1.124945 +SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
1.124946 +SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
1.124947 +SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
1.124948 +#endif
1.124949 +
1.124950 +#endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
1.124951 +#endif /* _FTSINT_H */
1.124952 +
1.124953 +/************** End of fts3Int.h *********************************************/
1.124954 +/************** Continuing where we left off in fts3.c ***********************/
1.124955 +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
1.124956 +
1.124957 +#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
1.124958 +# define SQLITE_CORE 1
1.124959 +#endif
1.124960 +
1.124961 +/* #include <assert.h> */
1.124962 +/* #include <stdlib.h> */
1.124963 +/* #include <stddef.h> */
1.124964 +/* #include <stdio.h> */
1.124965 +/* #include <string.h> */
1.124966 +/* #include <stdarg.h> */
1.124967 +
1.124968 +#ifndef SQLITE_CORE 
1.124969 +  SQLITE_EXTENSION_INIT1
1.124970 +#endif
1.124971 +
1.124972 +static int fts3EvalNext(Fts3Cursor *pCsr);
1.124973 +static int fts3EvalStart(Fts3Cursor *pCsr);
1.124974 +static int fts3TermSegReaderCursor(
1.124975 +    Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
1.124976 +
1.124977 +/* 
1.124978 +** Write a 64-bit variable-length integer to memory starting at p[0].
1.124979 +** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
1.124980 +** The number of bytes written is returned.
1.124981 +*/
1.124982 +SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
1.124983 +  unsigned char *q = (unsigned char *) p;
1.124984 +  sqlite_uint64 vu = v;
1.124985 +  do{
1.124986 +    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
1.124987 +    vu >>= 7;
1.124988 +  }while( vu!=0 );
1.124989 +  q[-1] &= 0x7f;  /* turn off high bit in final byte */
1.124990 +  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
1.124991 +  return (int) (q - (unsigned char *)p);
1.124992 +}
1.124993 +
1.124994 +#define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
1.124995 +  v = (v & mask1) | ( (*ptr++) << shift );                    \
1.124996 +  if( (v & mask2)==0 ){ var = v; return ret; }
1.124997 +#define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
1.124998 +  v = (*ptr++);                                               \
1.124999 +  if( (v & mask2)==0 ){ var = v; return ret; }
1.125000 +
1.125001 +/* 
1.125002 +** Read a 64-bit variable-length integer from memory starting at p[0].
1.125003 +** Return the number of bytes read, or 0 on error.
1.125004 +** The value is stored in *v.
1.125005 +*/
1.125006 +SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
1.125007 +  const char *pStart = p;
1.125008 +  u32 a;
1.125009 +  u64 b;
1.125010 +  int shift;
1.125011 +
1.125012 +  GETVARINT_INIT(a, p, 0,  0x00,     0x80, *v, 1);
1.125013 +  GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *v, 2);
1.125014 +  GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *v, 3);
1.125015 +  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
1.125016 +  b = (a & 0x0FFFFFFF );
1.125017 +
1.125018 +  for(shift=28; shift<=63; shift+=7){
1.125019 +    u64 c = *p++;
1.125020 +    b += (c&0x7F) << shift;
1.125021 +    if( (c & 0x80)==0 ) break;
1.125022 +  }
1.125023 +  *v = b;
1.125024 +  return (int)(p - pStart);
1.125025 +}
1.125026 +
1.125027 +/*
1.125028 +** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
1.125029 +** 32-bit integer before it is returned.
1.125030 +*/
1.125031 +SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
1.125032 +  u32 a;
1.125033 +
1.125034 +#ifndef fts3GetVarint32
1.125035 +  GETVARINT_INIT(a, p, 0,  0x00,     0x80, *pi, 1);
1.125036 +#else
1.125037 +  a = (*p++);
1.125038 +  assert( a & 0x80 );
1.125039 +#endif
1.125040 +
1.125041 +  GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *pi, 2);
1.125042 +  GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *pi, 3);
1.125043 +  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
1.125044 +  a = (a & 0x0FFFFFFF );
1.125045 +  *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
1.125046 +  return 5;
1.125047 +}
1.125048 +
1.125049 +/*
1.125050 +** Return the number of bytes required to encode v as a varint
1.125051 +*/
1.125052 +SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
1.125053 +  int i = 0;
1.125054 +  do{
1.125055 +    i++;
1.125056 +    v >>= 7;
1.125057 +  }while( v!=0 );
1.125058 +  return i;
1.125059 +}
1.125060 +
1.125061 +/*
1.125062 +** Convert an SQL-style quoted string into a normal string by removing
1.125063 +** the quote characters.  The conversion is done in-place.  If the
1.125064 +** input does not begin with a quote character, then this routine
1.125065 +** is a no-op.
1.125066 +**
1.125067 +** Examples:
1.125068 +**
1.125069 +**     "abc"   becomes   abc
1.125070 +**     'xyz'   becomes   xyz
1.125071 +**     [pqr]   becomes   pqr
1.125072 +**     `mno`   becomes   mno
1.125073 +**
1.125074 +*/
1.125075 +SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
1.125076 +  char quote;                     /* Quote character (if any ) */
1.125077 +
1.125078 +  quote = z[0];
1.125079 +  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
1.125080 +    int iIn = 1;                  /* Index of next byte to read from input */
1.125081 +    int iOut = 0;                 /* Index of next byte to write to output */
1.125082 +
1.125083 +    /* If the first byte was a '[', then the close-quote character is a ']' */
1.125084 +    if( quote=='[' ) quote = ']';  
1.125085 +
1.125086 +    while( ALWAYS(z[iIn]) ){
1.125087 +      if( z[iIn]==quote ){
1.125088 +        if( z[iIn+1]!=quote ) break;
1.125089 +        z[iOut++] = quote;
1.125090 +        iIn += 2;
1.125091 +      }else{
1.125092 +        z[iOut++] = z[iIn++];
1.125093 +      }
1.125094 +    }
1.125095 +    z[iOut] = '\0';
1.125096 +  }
1.125097 +}
1.125098 +
1.125099 +/*
1.125100 +** Read a single varint from the doclist at *pp and advance *pp to point
1.125101 +** to the first byte past the end of the varint.  Add the value of the varint
1.125102 +** to *pVal.
1.125103 +*/
1.125104 +static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
1.125105 +  sqlite3_int64 iVal;
1.125106 +  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
1.125107 +  *pVal += iVal;
1.125108 +}
1.125109 +
1.125110 +/*
1.125111 +** When this function is called, *pp points to the first byte following a
1.125112 +** varint that is part of a doclist (or position-list, or any other list
1.125113 +** of varints). This function moves *pp to point to the start of that varint,
1.125114 +** and sets *pVal by the varint value.
1.125115 +**
1.125116 +** Argument pStart points to the first byte of the doclist that the
1.125117 +** varint is part of.
1.125118 +*/
1.125119 +static void fts3GetReverseVarint(
1.125120 +  char **pp, 
1.125121 +  char *pStart, 
1.125122 +  sqlite3_int64 *pVal
1.125123 +){
1.125124 +  sqlite3_int64 iVal;
1.125125 +  char *p;
1.125126 +
1.125127 +  /* Pointer p now points at the first byte past the varint we are 
1.125128 +  ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
1.125129 +  ** clear on character p[-1]. */
1.125130 +  for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
1.125131 +  p++;
1.125132 +  *pp = p;
1.125133 +
1.125134 +  sqlite3Fts3GetVarint(p, &iVal);
1.125135 +  *pVal = iVal;
1.125136 +}
1.125137 +
1.125138 +/*
1.125139 +** The xDisconnect() virtual table method.
1.125140 +*/
1.125141 +static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
1.125142 +  Fts3Table *p = (Fts3Table *)pVtab;
1.125143 +  int i;
1.125144 +
1.125145 +  assert( p->nPendingData==0 );
1.125146 +  assert( p->pSegments==0 );
1.125147 +
1.125148 +  /* Free any prepared statements held */
1.125149 +  for(i=0; i<SizeofArray(p->aStmt); i++){
1.125150 +    sqlite3_finalize(p->aStmt[i]);
1.125151 +  }
1.125152 +  sqlite3_free(p->zSegmentsTbl);
1.125153 +  sqlite3_free(p->zReadExprlist);
1.125154 +  sqlite3_free(p->zWriteExprlist);
1.125155 +  sqlite3_free(p->zContentTbl);
1.125156 +  sqlite3_free(p->zLanguageid);
1.125157 +
1.125158 +  /* Invoke the tokenizer destructor to free the tokenizer. */
1.125159 +  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
1.125160 +
1.125161 +  sqlite3_free(p);
1.125162 +  return SQLITE_OK;
1.125163 +}
1.125164 +
1.125165 +/*
1.125166 +** Construct one or more SQL statements from the format string given
1.125167 +** and then evaluate those statements. The success code is written
1.125168 +** into *pRc.
1.125169 +**
1.125170 +** If *pRc is initially non-zero then this routine is a no-op.
1.125171 +*/
1.125172 +static void fts3DbExec(
1.125173 +  int *pRc,              /* Success code */
1.125174 +  sqlite3 *db,           /* Database in which to run SQL */
1.125175 +  const char *zFormat,   /* Format string for SQL */
1.125176 +  ...                    /* Arguments to the format string */
1.125177 +){
1.125178 +  va_list ap;
1.125179 +  char *zSql;
1.125180 +  if( *pRc ) return;
1.125181 +  va_start(ap, zFormat);
1.125182 +  zSql = sqlite3_vmprintf(zFormat, ap);
1.125183 +  va_end(ap);
1.125184 +  if( zSql==0 ){
1.125185 +    *pRc = SQLITE_NOMEM;
1.125186 +  }else{
1.125187 +    *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
1.125188 +    sqlite3_free(zSql);
1.125189 +  }
1.125190 +}
1.125191 +
1.125192 +/*
1.125193 +** The xDestroy() virtual table method.
1.125194 +*/
1.125195 +static int fts3DestroyMethod(sqlite3_vtab *pVtab){
1.125196 +  Fts3Table *p = (Fts3Table *)pVtab;
1.125197 +  int rc = SQLITE_OK;              /* Return code */
1.125198 +  const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
1.125199 +  sqlite3 *db = p->db;             /* Database handle */
1.125200 +
1.125201 +  /* Drop the shadow tables */
1.125202 +  if( p->zContentTbl==0 ){
1.125203 +    fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
1.125204 +  }
1.125205 +  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
1.125206 +  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
1.125207 +  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
1.125208 +  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
1.125209 +
1.125210 +  /* If everything has worked, invoke fts3DisconnectMethod() to free the
1.125211 +  ** memory associated with the Fts3Table structure and return SQLITE_OK.
1.125212 +  ** Otherwise, return an SQLite error code.
1.125213 +  */
1.125214 +  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
1.125215 +}
1.125216 +
1.125217 +
1.125218 +/*
1.125219 +** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
1.125220 +** passed as the first argument. This is done as part of the xConnect()
1.125221 +** and xCreate() methods.
1.125222 +**
1.125223 +** If *pRc is non-zero when this function is called, it is a no-op. 
1.125224 +** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
1.125225 +** before returning.
1.125226 +*/
1.125227 +static void fts3DeclareVtab(int *pRc, Fts3Table *p){
1.125228 +  if( *pRc==SQLITE_OK ){
1.125229 +    int i;                        /* Iterator variable */
1.125230 +    int rc;                       /* Return code */
1.125231 +    char *zSql;                   /* SQL statement passed to declare_vtab() */
1.125232 +    char *zCols;                  /* List of user defined columns */
1.125233 +    const char *zLanguageid;
1.125234 +
1.125235 +    zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
1.125236 +    sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
1.125237 +
1.125238 +    /* Create a list of user columns for the virtual table */
1.125239 +    zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
1.125240 +    for(i=1; zCols && i<p->nColumn; i++){
1.125241 +      zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
1.125242 +    }
1.125243 +
1.125244 +    /* Create the whole "CREATE TABLE" statement to pass to SQLite */
1.125245 +    zSql = sqlite3_mprintf(
1.125246 +        "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)", 
1.125247 +        zCols, p->zName, zLanguageid
1.125248 +    );
1.125249 +    if( !zCols || !zSql ){
1.125250 +      rc = SQLITE_NOMEM;
1.125251 +    }else{
1.125252 +      rc = sqlite3_declare_vtab(p->db, zSql);
1.125253 +    }
1.125254 +
1.125255 +    sqlite3_free(zSql);
1.125256 +    sqlite3_free(zCols);
1.125257 +    *pRc = rc;
1.125258 +  }
1.125259 +}
1.125260 +
1.125261 +/*
1.125262 +** Create the %_stat table if it does not already exist.
1.125263 +*/
1.125264 +SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
1.125265 +  fts3DbExec(pRc, p->db, 
1.125266 +      "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
1.125267 +          "(id INTEGER PRIMARY KEY, value BLOB);",
1.125268 +      p->zDb, p->zName
1.125269 +  );
1.125270 +  if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
1.125271 +}
1.125272 +
1.125273 +/*
1.125274 +** Create the backing store tables (%_content, %_segments and %_segdir)
1.125275 +** required by the FTS3 table passed as the only argument. This is done
1.125276 +** as part of the vtab xCreate() method.
1.125277 +**
1.125278 +** If the p->bHasDocsize boolean is true (indicating that this is an
1.125279 +** FTS4 table, not an FTS3 table) then also create the %_docsize and
1.125280 +** %_stat tables required by FTS4.
1.125281 +*/
1.125282 +static int fts3CreateTables(Fts3Table *p){
1.125283 +  int rc = SQLITE_OK;             /* Return code */
1.125284 +  int i;                          /* Iterator variable */
1.125285 +  sqlite3 *db = p->db;            /* The database connection */
1.125286 +
1.125287 +  if( p->zContentTbl==0 ){
1.125288 +    const char *zLanguageid = p->zLanguageid;
1.125289 +    char *zContentCols;           /* Columns of %_content table */
1.125290 +
1.125291 +    /* Create a list of user columns for the content table */
1.125292 +    zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
1.125293 +    for(i=0; zContentCols && i<p->nColumn; i++){
1.125294 +      char *z = p->azColumn[i];
1.125295 +      zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
1.125296 +    }
1.125297 +    if( zLanguageid && zContentCols ){
1.125298 +      zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
1.125299 +    }
1.125300 +    if( zContentCols==0 ) rc = SQLITE_NOMEM;
1.125301 +  
1.125302 +    /* Create the content table */
1.125303 +    fts3DbExec(&rc, db, 
1.125304 +       "CREATE TABLE %Q.'%q_content'(%s)",
1.125305 +       p->zDb, p->zName, zContentCols
1.125306 +    );
1.125307 +    sqlite3_free(zContentCols);
1.125308 +  }
1.125309 +
1.125310 +  /* Create other tables */
1.125311 +  fts3DbExec(&rc, db, 
1.125312 +      "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
1.125313 +      p->zDb, p->zName
1.125314 +  );
1.125315 +  fts3DbExec(&rc, db, 
1.125316 +      "CREATE TABLE %Q.'%q_segdir'("
1.125317 +        "level INTEGER,"
1.125318 +        "idx INTEGER,"
1.125319 +        "start_block INTEGER,"
1.125320 +        "leaves_end_block INTEGER,"
1.125321 +        "end_block INTEGER,"
1.125322 +        "root BLOB,"
1.125323 +        "PRIMARY KEY(level, idx)"
1.125324 +      ");",
1.125325 +      p->zDb, p->zName
1.125326 +  );
1.125327 +  if( p->bHasDocsize ){
1.125328 +    fts3DbExec(&rc, db, 
1.125329 +        "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
1.125330 +        p->zDb, p->zName
1.125331 +    );
1.125332 +  }
1.125333 +  assert( p->bHasStat==p->bFts4 );
1.125334 +  if( p->bHasStat ){
1.125335 +    sqlite3Fts3CreateStatTable(&rc, p);
1.125336 +  }
1.125337 +  return rc;
1.125338 +}
1.125339 +
1.125340 +/*
1.125341 +** Store the current database page-size in bytes in p->nPgsz.
1.125342 +**
1.125343 +** If *pRc is non-zero when this function is called, it is a no-op. 
1.125344 +** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
1.125345 +** before returning.
1.125346 +*/
1.125347 +static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
1.125348 +  if( *pRc==SQLITE_OK ){
1.125349 +    int rc;                       /* Return code */
1.125350 +    char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
1.125351 +    sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
1.125352 +  
1.125353 +    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
1.125354 +    if( !zSql ){
1.125355 +      rc = SQLITE_NOMEM;
1.125356 +    }else{
1.125357 +      rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
1.125358 +      if( rc==SQLITE_OK ){
1.125359 +        sqlite3_step(pStmt);
1.125360 +        p->nPgsz = sqlite3_column_int(pStmt, 0);
1.125361 +        rc = sqlite3_finalize(pStmt);
1.125362 +      }else if( rc==SQLITE_AUTH ){
1.125363 +        p->nPgsz = 1024;
1.125364 +        rc = SQLITE_OK;
1.125365 +      }
1.125366 +    }
1.125367 +    assert( p->nPgsz>0 || rc!=SQLITE_OK );
1.125368 +    sqlite3_free(zSql);
1.125369 +    *pRc = rc;
1.125370 +  }
1.125371 +}
1.125372 +
1.125373 +/*
1.125374 +** "Special" FTS4 arguments are column specifications of the following form:
1.125375 +**
1.125376 +**   <key> = <value>
1.125377 +**
1.125378 +** There may not be whitespace surrounding the "=" character. The <value> 
1.125379 +** term may be quoted, but the <key> may not.
1.125380 +*/
1.125381 +static int fts3IsSpecialColumn(
1.125382 +  const char *z, 
1.125383 +  int *pnKey,
1.125384 +  char **pzValue
1.125385 +){
1.125386 +  char *zValue;
1.125387 +  const char *zCsr = z;
1.125388 +
1.125389 +  while( *zCsr!='=' ){
1.125390 +    if( *zCsr=='\0' ) return 0;
1.125391 +    zCsr++;
1.125392 +  }
1.125393 +
1.125394 +  *pnKey = (int)(zCsr-z);
1.125395 +  zValue = sqlite3_mprintf("%s", &zCsr[1]);
1.125396 +  if( zValue ){
1.125397 +    sqlite3Fts3Dequote(zValue);
1.125398 +  }
1.125399 +  *pzValue = zValue;
1.125400 +  return 1;
1.125401 +}
1.125402 +
1.125403 +/*
1.125404 +** Append the output of a printf() style formatting to an existing string.
1.125405 +*/
1.125406 +static void fts3Appendf(
1.125407 +  int *pRc,                       /* IN/OUT: Error code */
1.125408 +  char **pz,                      /* IN/OUT: Pointer to string buffer */
1.125409 +  const char *zFormat,            /* Printf format string to append */
1.125410 +  ...                             /* Arguments for printf format string */
1.125411 +){
1.125412 +  if( *pRc==SQLITE_OK ){
1.125413 +    va_list ap;
1.125414 +    char *z;
1.125415 +    va_start(ap, zFormat);
1.125416 +    z = sqlite3_vmprintf(zFormat, ap);
1.125417 +    va_end(ap);
1.125418 +    if( z && *pz ){
1.125419 +      char *z2 = sqlite3_mprintf("%s%s", *pz, z);
1.125420 +      sqlite3_free(z);
1.125421 +      z = z2;
1.125422 +    }
1.125423 +    if( z==0 ) *pRc = SQLITE_NOMEM;
1.125424 +    sqlite3_free(*pz);
1.125425 +    *pz = z;
1.125426 +  }
1.125427 +}
1.125428 +
1.125429 +/*
1.125430 +** Return a copy of input string zInput enclosed in double-quotes (") and
1.125431 +** with all double quote characters escaped. For example:
1.125432 +**
1.125433 +**     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
1.125434 +**
1.125435 +** The pointer returned points to memory obtained from sqlite3_malloc(). It
1.125436 +** is the callers responsibility to call sqlite3_free() to release this
1.125437 +** memory.
1.125438 +*/
1.125439 +static char *fts3QuoteId(char const *zInput){
1.125440 +  int nRet;
1.125441 +  char *zRet;
1.125442 +  nRet = 2 + (int)strlen(zInput)*2 + 1;
1.125443 +  zRet = sqlite3_malloc(nRet);
1.125444 +  if( zRet ){
1.125445 +    int i;
1.125446 +    char *z = zRet;
1.125447 +    *(z++) = '"';
1.125448 +    for(i=0; zInput[i]; i++){
1.125449 +      if( zInput[i]=='"' ) *(z++) = '"';
1.125450 +      *(z++) = zInput[i];
1.125451 +    }
1.125452 +    *(z++) = '"';
1.125453 +    *(z++) = '\0';
1.125454 +  }
1.125455 +  return zRet;
1.125456 +}
1.125457 +
1.125458 +/*
1.125459 +** Return a list of comma separated SQL expressions and a FROM clause that 
1.125460 +** could be used in a SELECT statement such as the following:
1.125461 +**
1.125462 +**     SELECT <list of expressions> FROM %_content AS x ...
1.125463 +**
1.125464 +** to return the docid, followed by each column of text data in order
1.125465 +** from left to write. If parameter zFunc is not NULL, then instead of
1.125466 +** being returned directly each column of text data is passed to an SQL
1.125467 +** function named zFunc first. For example, if zFunc is "unzip" and the
1.125468 +** table has the three user-defined columns "a", "b", and "c", the following
1.125469 +** string is returned:
1.125470 +**
1.125471 +**     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
1.125472 +**
1.125473 +** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
1.125474 +** is the responsibility of the caller to eventually free it.
1.125475 +**
1.125476 +** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
1.125477 +** a NULL pointer is returned). Otherwise, if an OOM error is encountered
1.125478 +** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
1.125479 +** no error occurs, *pRc is left unmodified.
1.125480 +*/
1.125481 +static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
1.125482 +  char *zRet = 0;
1.125483 +  char *zFree = 0;
1.125484 +  char *zFunction;
1.125485 +  int i;
1.125486 +
1.125487 +  if( p->zContentTbl==0 ){
1.125488 +    if( !zFunc ){
1.125489 +      zFunction = "";
1.125490 +    }else{
1.125491 +      zFree = zFunction = fts3QuoteId(zFunc);
1.125492 +    }
1.125493 +    fts3Appendf(pRc, &zRet, "docid");
1.125494 +    for(i=0; i<p->nColumn; i++){
1.125495 +      fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
1.125496 +    }
1.125497 +    if( p->zLanguageid ){
1.125498 +      fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
1.125499 +    }
1.125500 +    sqlite3_free(zFree);
1.125501 +  }else{
1.125502 +    fts3Appendf(pRc, &zRet, "rowid");
1.125503 +    for(i=0; i<p->nColumn; i++){
1.125504 +      fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
1.125505 +    }
1.125506 +    if( p->zLanguageid ){
1.125507 +      fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
1.125508 +    }
1.125509 +  }
1.125510 +  fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x", 
1.125511 +      p->zDb,
1.125512 +      (p->zContentTbl ? p->zContentTbl : p->zName),
1.125513 +      (p->zContentTbl ? "" : "_content")
1.125514 +  );
1.125515 +  return zRet;
1.125516 +}
1.125517 +
1.125518 +/*
1.125519 +** Return a list of N comma separated question marks, where N is the number
1.125520 +** of columns in the %_content table (one for the docid plus one for each
1.125521 +** user-defined text column).
1.125522 +**
1.125523 +** If argument zFunc is not NULL, then all but the first question mark
1.125524 +** is preceded by zFunc and an open bracket, and followed by a closed
1.125525 +** bracket. For example, if zFunc is "zip" and the FTS3 table has three 
1.125526 +** user-defined text columns, the following string is returned:
1.125527 +**
1.125528 +**     "?, zip(?), zip(?), zip(?)"
1.125529 +**
1.125530 +** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
1.125531 +** is the responsibility of the caller to eventually free it.
1.125532 +**
1.125533 +** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
1.125534 +** a NULL pointer is returned). Otherwise, if an OOM error is encountered
1.125535 +** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
1.125536 +** no error occurs, *pRc is left unmodified.
1.125537 +*/
1.125538 +static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
1.125539 +  char *zRet = 0;
1.125540 +  char *zFree = 0;
1.125541 +  char *zFunction;
1.125542 +  int i;
1.125543 +
1.125544 +  if( !zFunc ){
1.125545 +    zFunction = "";
1.125546 +  }else{
1.125547 +    zFree = zFunction = fts3QuoteId(zFunc);
1.125548 +  }
1.125549 +  fts3Appendf(pRc, &zRet, "?");
1.125550 +  for(i=0; i<p->nColumn; i++){
1.125551 +    fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
1.125552 +  }
1.125553 +  if( p->zLanguageid ){
1.125554 +    fts3Appendf(pRc, &zRet, ", ?");
1.125555 +  }
1.125556 +  sqlite3_free(zFree);
1.125557 +  return zRet;
1.125558 +}
1.125559 +
1.125560 +/*
1.125561 +** This function interprets the string at (*pp) as a non-negative integer
1.125562 +** value. It reads the integer and sets *pnOut to the value read, then 
1.125563 +** sets *pp to point to the byte immediately following the last byte of
1.125564 +** the integer value.
1.125565 +**
1.125566 +** Only decimal digits ('0'..'9') may be part of an integer value. 
1.125567 +**
1.125568 +** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
1.125569 +** the output value undefined. Otherwise SQLITE_OK is returned.
1.125570 +**
1.125571 +** This function is used when parsing the "prefix=" FTS4 parameter.
1.125572 +*/
1.125573 +static int fts3GobbleInt(const char **pp, int *pnOut){
1.125574 +  const char *p;                  /* Iterator pointer */
1.125575 +  int nInt = 0;                   /* Output value */
1.125576 +
1.125577 +  for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
1.125578 +    nInt = nInt * 10 + (p[0] - '0');
1.125579 +  }
1.125580 +  if( p==*pp ) return SQLITE_ERROR;
1.125581 +  *pnOut = nInt;
1.125582 +  *pp = p;
1.125583 +  return SQLITE_OK;
1.125584 +}
1.125585 +
1.125586 +/*
1.125587 +** This function is called to allocate an array of Fts3Index structures
1.125588 +** representing the indexes maintained by the current FTS table. FTS tables
1.125589 +** always maintain the main "terms" index, but may also maintain one or
1.125590 +** more "prefix" indexes, depending on the value of the "prefix=" parameter
1.125591 +** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
1.125592 +**
1.125593 +** Argument zParam is passed the value of the "prefix=" option if one was
1.125594 +** specified, or NULL otherwise.
1.125595 +**
1.125596 +** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
1.125597 +** the allocated array. *pnIndex is set to the number of elements in the
1.125598 +** array. If an error does occur, an SQLite error code is returned.
1.125599 +**
1.125600 +** Regardless of whether or not an error is returned, it is the responsibility
1.125601 +** of the caller to call sqlite3_free() on the output array to free it.
1.125602 +*/
1.125603 +static int fts3PrefixParameter(
1.125604 +  const char *zParam,             /* ABC in prefix=ABC parameter to parse */
1.125605 +  int *pnIndex,                   /* OUT: size of *apIndex[] array */
1.125606 +  struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
1.125607 +){
1.125608 +  struct Fts3Index *aIndex;       /* Allocated array */
1.125609 +  int nIndex = 1;                 /* Number of entries in array */
1.125610 +
1.125611 +  if( zParam && zParam[0] ){
1.125612 +    const char *p;
1.125613 +    nIndex++;
1.125614 +    for(p=zParam; *p; p++){
1.125615 +      if( *p==',' ) nIndex++;
1.125616 +    }
1.125617 +  }
1.125618 +
1.125619 +  aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
1.125620 +  *apIndex = aIndex;
1.125621 +  *pnIndex = nIndex;
1.125622 +  if( !aIndex ){
1.125623 +    return SQLITE_NOMEM;
1.125624 +  }
1.125625 +
1.125626 +  memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
1.125627 +  if( zParam ){
1.125628 +    const char *p = zParam;
1.125629 +    int i;
1.125630 +    for(i=1; i<nIndex; i++){
1.125631 +      int nPrefix;
1.125632 +      if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
1.125633 +      aIndex[i].nPrefix = nPrefix;
1.125634 +      p++;
1.125635 +    }
1.125636 +  }
1.125637 +
1.125638 +  return SQLITE_OK;
1.125639 +}
1.125640 +
1.125641 +/*
1.125642 +** This function is called when initializing an FTS4 table that uses the
1.125643 +** content=xxx option. It determines the number of and names of the columns
1.125644 +** of the new FTS4 table.
1.125645 +**
1.125646 +** The third argument passed to this function is the value passed to the
1.125647 +** config=xxx option (i.e. "xxx"). This function queries the database for
1.125648 +** a table of that name. If found, the output variables are populated
1.125649 +** as follows:
1.125650 +**
1.125651 +**   *pnCol:   Set to the number of columns table xxx has,
1.125652 +**
1.125653 +**   *pnStr:   Set to the total amount of space required to store a copy
1.125654 +**             of each columns name, including the nul-terminator.
1.125655 +**
1.125656 +**   *pazCol:  Set to point to an array of *pnCol strings. Each string is
1.125657 +**             the name of the corresponding column in table xxx. The array
1.125658 +**             and its contents are allocated using a single allocation. It
1.125659 +**             is the responsibility of the caller to free this allocation
1.125660 +**             by eventually passing the *pazCol value to sqlite3_free().
1.125661 +**
1.125662 +** If the table cannot be found, an error code is returned and the output
1.125663 +** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
1.125664 +** returned (and the output variables are undefined).
1.125665 +*/
1.125666 +static int fts3ContentColumns(
1.125667 +  sqlite3 *db,                    /* Database handle */
1.125668 +  const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
1.125669 +  const char *zTbl,               /* Name of content table */
1.125670 +  const char ***pazCol,           /* OUT: Malloc'd array of column names */
1.125671 +  int *pnCol,                     /* OUT: Size of array *pazCol */
1.125672 +  int *pnStr                      /* OUT: Bytes of string content */
1.125673 +){
1.125674 +  int rc = SQLITE_OK;             /* Return code */
1.125675 +  char *zSql;                     /* "SELECT *" statement on zTbl */  
1.125676 +  sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
1.125677 +
1.125678 +  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
1.125679 +  if( !zSql ){
1.125680 +    rc = SQLITE_NOMEM;
1.125681 +  }else{
1.125682 +    rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
1.125683 +  }
1.125684 +  sqlite3_free(zSql);
1.125685 +
1.125686 +  if( rc==SQLITE_OK ){
1.125687 +    const char **azCol;           /* Output array */
1.125688 +    int nStr = 0;                 /* Size of all column names (incl. 0x00) */
1.125689 +    int nCol;                     /* Number of table columns */
1.125690 +    int i;                        /* Used to iterate through columns */
1.125691 +
1.125692 +    /* Loop through the returned columns. Set nStr to the number of bytes of
1.125693 +    ** space required to store a copy of each column name, including the
1.125694 +    ** nul-terminator byte.  */
1.125695 +    nCol = sqlite3_column_count(pStmt);
1.125696 +    for(i=0; i<nCol; i++){
1.125697 +      const char *zCol = sqlite3_column_name(pStmt, i);
1.125698 +      nStr += (int)strlen(zCol) + 1;
1.125699 +    }
1.125700 +
1.125701 +    /* Allocate and populate the array to return. */
1.125702 +    azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
1.125703 +    if( azCol==0 ){
1.125704 +      rc = SQLITE_NOMEM;
1.125705 +    }else{
1.125706 +      char *p = (char *)&azCol[nCol];
1.125707 +      for(i=0; i<nCol; i++){
1.125708 +        const char *zCol = sqlite3_column_name(pStmt, i);
1.125709 +        int n = (int)strlen(zCol)+1;
1.125710 +        memcpy(p, zCol, n);
1.125711 +        azCol[i] = p;
1.125712 +        p += n;
1.125713 +      }
1.125714 +    }
1.125715 +    sqlite3_finalize(pStmt);
1.125716 +
1.125717 +    /* Set the output variables. */
1.125718 +    *pnCol = nCol;
1.125719 +    *pnStr = nStr;
1.125720 +    *pazCol = azCol;
1.125721 +  }
1.125722 +
1.125723 +  return rc;
1.125724 +}
1.125725 +
1.125726 +/*
1.125727 +** This function is the implementation of both the xConnect and xCreate
1.125728 +** methods of the FTS3 virtual table.
1.125729 +**
1.125730 +** The argv[] array contains the following:
1.125731 +**
1.125732 +**   argv[0]   -> module name  ("fts3" or "fts4")
1.125733 +**   argv[1]   -> database name
1.125734 +**   argv[2]   -> table name
1.125735 +**   argv[...] -> "column name" and other module argument fields.
1.125736 +*/
1.125737 +static int fts3InitVtab(
1.125738 +  int isCreate,                   /* True for xCreate, false for xConnect */
1.125739 +  sqlite3 *db,                    /* The SQLite database connection */
1.125740 +  void *pAux,                     /* Hash table containing tokenizers */
1.125741 +  int argc,                       /* Number of elements in argv array */
1.125742 +  const char * const *argv,       /* xCreate/xConnect argument array */
1.125743 +  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
1.125744 +  char **pzErr                    /* Write any error message here */
1.125745 +){
1.125746 +  Fts3Hash *pHash = (Fts3Hash *)pAux;
1.125747 +  Fts3Table *p = 0;               /* Pointer to allocated vtab */
1.125748 +  int rc = SQLITE_OK;             /* Return code */
1.125749 +  int i;                          /* Iterator variable */
1.125750 +  int nByte;                      /* Size of allocation used for *p */
1.125751 +  int iCol;                       /* Column index */
1.125752 +  int nString = 0;                /* Bytes required to hold all column names */
1.125753 +  int nCol = 0;                   /* Number of columns in the FTS table */
1.125754 +  char *zCsr;                     /* Space for holding column names */
1.125755 +  int nDb;                        /* Bytes required to hold database name */
1.125756 +  int nName;                      /* Bytes required to hold table name */
1.125757 +  int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
1.125758 +  const char **aCol;              /* Array of column names */
1.125759 +  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
1.125760 +
1.125761 +  int nIndex;                     /* Size of aIndex[] array */
1.125762 +  struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
1.125763 +
1.125764 +  /* The results of parsing supported FTS4 key=value options: */
1.125765 +  int bNoDocsize = 0;             /* True to omit %_docsize table */
1.125766 +  int bDescIdx = 0;               /* True to store descending indexes */
1.125767 +  char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
1.125768 +  char *zCompress = 0;            /* compress=? parameter (or NULL) */
1.125769 +  char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
1.125770 +  char *zContent = 0;             /* content=? parameter (or NULL) */
1.125771 +  char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
1.125772 +  char **azNotindexed = 0;        /* The set of notindexed= columns */
1.125773 +  int nNotindexed = 0;            /* Size of azNotindexed[] array */
1.125774 +
1.125775 +  assert( strlen(argv[0])==4 );
1.125776 +  assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
1.125777 +       || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
1.125778 +  );
1.125779 +
1.125780 +  nDb = (int)strlen(argv[1]) + 1;
1.125781 +  nName = (int)strlen(argv[2]) + 1;
1.125782 +
1.125783 +  nByte = sizeof(const char *) * (argc-2);
1.125784 +  aCol = (const char **)sqlite3_malloc(nByte);
1.125785 +  if( aCol ){
1.125786 +    memset((void*)aCol, 0, nByte);
1.125787 +    azNotindexed = (char **)sqlite3_malloc(nByte);
1.125788 +  }
1.125789 +  if( azNotindexed ){
1.125790 +    memset(azNotindexed, 0, nByte);
1.125791 +  }
1.125792 +  if( !aCol || !azNotindexed ){
1.125793 +    rc = SQLITE_NOMEM;
1.125794 +    goto fts3_init_out;
1.125795 +  }
1.125796 +
1.125797 +  /* Loop through all of the arguments passed by the user to the FTS3/4
1.125798 +  ** module (i.e. all the column names and special arguments). This loop
1.125799 +  ** does the following:
1.125800 +  **
1.125801 +  **   + Figures out the number of columns the FTSX table will have, and
1.125802 +  **     the number of bytes of space that must be allocated to store copies
1.125803 +  **     of the column names.
1.125804 +  **
1.125805 +  **   + If there is a tokenizer specification included in the arguments,
1.125806 +  **     initializes the tokenizer pTokenizer.
1.125807 +  */
1.125808 +  for(i=3; rc==SQLITE_OK && i<argc; i++){
1.125809 +    char const *z = argv[i];
1.125810 +    int nKey;
1.125811 +    char *zVal;
1.125812 +
1.125813 +    /* Check if this is a tokenizer specification */
1.125814 +    if( !pTokenizer 
1.125815 +     && strlen(z)>8
1.125816 +     && 0==sqlite3_strnicmp(z, "tokenize", 8) 
1.125817 +     && 0==sqlite3Fts3IsIdChar(z[8])
1.125818 +    ){
1.125819 +      rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
1.125820 +    }
1.125821 +
1.125822 +    /* Check if it is an FTS4 special argument. */
1.125823 +    else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
1.125824 +      struct Fts4Option {
1.125825 +        const char *zOpt;
1.125826 +        int nOpt;
1.125827 +      } aFts4Opt[] = {
1.125828 +        { "matchinfo",   9 },     /* 0 -> MATCHINFO */
1.125829 +        { "prefix",      6 },     /* 1 -> PREFIX */
1.125830 +        { "compress",    8 },     /* 2 -> COMPRESS */
1.125831 +        { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
1.125832 +        { "order",       5 },     /* 4 -> ORDER */
1.125833 +        { "content",     7 },     /* 5 -> CONTENT */
1.125834 +        { "languageid", 10 },     /* 6 -> LANGUAGEID */
1.125835 +        { "notindexed", 10 }      /* 7 -> NOTINDEXED */
1.125836 +      };
1.125837 +
1.125838 +      int iOpt;
1.125839 +      if( !zVal ){
1.125840 +        rc = SQLITE_NOMEM;
1.125841 +      }else{
1.125842 +        for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
1.125843 +          struct Fts4Option *pOp = &aFts4Opt[iOpt];
1.125844 +          if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
1.125845 +            break;
1.125846 +          }
1.125847 +        }
1.125848 +        if( iOpt==SizeofArray(aFts4Opt) ){
1.125849 +          *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
1.125850 +          rc = SQLITE_ERROR;
1.125851 +        }else{
1.125852 +          switch( iOpt ){
1.125853 +            case 0:               /* MATCHINFO */
1.125854 +              if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
1.125855 +                *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
1.125856 +                rc = SQLITE_ERROR;
1.125857 +              }
1.125858 +              bNoDocsize = 1;
1.125859 +              break;
1.125860 +
1.125861 +            case 1:               /* PREFIX */
1.125862 +              sqlite3_free(zPrefix);
1.125863 +              zPrefix = zVal;
1.125864 +              zVal = 0;
1.125865 +              break;
1.125866 +
1.125867 +            case 2:               /* COMPRESS */
1.125868 +              sqlite3_free(zCompress);
1.125869 +              zCompress = zVal;
1.125870 +              zVal = 0;
1.125871 +              break;
1.125872 +
1.125873 +            case 3:               /* UNCOMPRESS */
1.125874 +              sqlite3_free(zUncompress);
1.125875 +              zUncompress = zVal;
1.125876 +              zVal = 0;
1.125877 +              break;
1.125878 +
1.125879 +            case 4:               /* ORDER */
1.125880 +              if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3)) 
1.125881 +               && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4)) 
1.125882 +              ){
1.125883 +                *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
1.125884 +                rc = SQLITE_ERROR;
1.125885 +              }
1.125886 +              bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
1.125887 +              break;
1.125888 +
1.125889 +            case 5:              /* CONTENT */
1.125890 +              sqlite3_free(zContent);
1.125891 +              zContent = zVal;
1.125892 +              zVal = 0;
1.125893 +              break;
1.125894 +
1.125895 +            case 6:              /* LANGUAGEID */
1.125896 +              assert( iOpt==6 );
1.125897 +              sqlite3_free(zLanguageid);
1.125898 +              zLanguageid = zVal;
1.125899 +              zVal = 0;
1.125900 +              break;
1.125901 +
1.125902 +            case 7:              /* NOTINDEXED */
1.125903 +              azNotindexed[nNotindexed++] = zVal;
1.125904 +              zVal = 0;
1.125905 +              break;
1.125906 +          }
1.125907 +        }
1.125908 +        sqlite3_free(zVal);
1.125909 +      }
1.125910 +    }
1.125911 +
1.125912 +    /* Otherwise, the argument is a column name. */
1.125913 +    else {
1.125914 +      nString += (int)(strlen(z) + 1);
1.125915 +      aCol[nCol++] = z;
1.125916 +    }
1.125917 +  }
1.125918 +
1.125919 +  /* If a content=xxx option was specified, the following:
1.125920 +  **
1.125921 +  **   1. Ignore any compress= and uncompress= options.
1.125922 +  **
1.125923 +  **   2. If no column names were specified as part of the CREATE VIRTUAL
1.125924 +  **      TABLE statement, use all columns from the content table.
1.125925 +  */
1.125926 +  if( rc==SQLITE_OK && zContent ){
1.125927 +    sqlite3_free(zCompress); 
1.125928 +    sqlite3_free(zUncompress); 
1.125929 +    zCompress = 0;
1.125930 +    zUncompress = 0;
1.125931 +    if( nCol==0 ){
1.125932 +      sqlite3_free((void*)aCol); 
1.125933 +      aCol = 0;
1.125934 +      rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
1.125935 +
1.125936 +      /* If a languageid= option was specified, remove the language id
1.125937 +      ** column from the aCol[] array. */ 
1.125938 +      if( rc==SQLITE_OK && zLanguageid ){
1.125939 +        int j;
1.125940 +        for(j=0; j<nCol; j++){
1.125941 +          if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
1.125942 +            int k;
1.125943 +            for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
1.125944 +            nCol--;
1.125945 +            break;
1.125946 +          }
1.125947 +        }
1.125948 +      }
1.125949 +    }
1.125950 +  }
1.125951 +  if( rc!=SQLITE_OK ) goto fts3_init_out;
1.125952 +
1.125953 +  if( nCol==0 ){
1.125954 +    assert( nString==0 );
1.125955 +    aCol[0] = "content";
1.125956 +    nString = 8;
1.125957 +    nCol = 1;
1.125958 +  }
1.125959 +
1.125960 +  if( pTokenizer==0 ){
1.125961 +    rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
1.125962 +    if( rc!=SQLITE_OK ) goto fts3_init_out;
1.125963 +  }
1.125964 +  assert( pTokenizer );
1.125965 +
1.125966 +  rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
1.125967 +  if( rc==SQLITE_ERROR ){
1.125968 +    assert( zPrefix );
1.125969 +    *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
1.125970 +  }
1.125971 +  if( rc!=SQLITE_OK ) goto fts3_init_out;
1.125972 +
1.125973 +  /* Allocate and populate the Fts3Table structure. */
1.125974 +  nByte = sizeof(Fts3Table) +                  /* Fts3Table */
1.125975 +          nCol * sizeof(char *) +              /* azColumn */
1.125976 +          nIndex * sizeof(struct Fts3Index) +  /* aIndex */
1.125977 +          nCol * sizeof(u8) +                  /* abNotindexed */
1.125978 +          nName +                              /* zName */
1.125979 +          nDb +                                /* zDb */
1.125980 +          nString;                             /* Space for azColumn strings */
1.125981 +  p = (Fts3Table*)sqlite3_malloc(nByte);
1.125982 +  if( p==0 ){
1.125983 +    rc = SQLITE_NOMEM;
1.125984 +    goto fts3_init_out;
1.125985 +  }
1.125986 +  memset(p, 0, nByte);
1.125987 +  p->db = db;
1.125988 +  p->nColumn = nCol;
1.125989 +  p->nPendingData = 0;
1.125990 +  p->azColumn = (char **)&p[1];
1.125991 +  p->pTokenizer = pTokenizer;
1.125992 +  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
1.125993 +  p->bHasDocsize = (isFts4 && bNoDocsize==0);
1.125994 +  p->bHasStat = isFts4;
1.125995 +  p->bFts4 = isFts4;
1.125996 +  p->bDescIdx = bDescIdx;
1.125997 +  p->bAutoincrmerge = 0xff;   /* 0xff means setting unknown */
1.125998 +  p->zContentTbl = zContent;
1.125999 +  p->zLanguageid = zLanguageid;
1.126000 +  zContent = 0;
1.126001 +  zLanguageid = 0;
1.126002 +  TESTONLY( p->inTransaction = -1 );
1.126003 +  TESTONLY( p->mxSavepoint = -1 );
1.126004 +
1.126005 +  p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
1.126006 +  memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
1.126007 +  p->nIndex = nIndex;
1.126008 +  for(i=0; i<nIndex; i++){
1.126009 +    fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
1.126010 +  }
1.126011 +  p->abNotindexed = (u8 *)&p->aIndex[nIndex];
1.126012 +
1.126013 +  /* Fill in the zName and zDb fields of the vtab structure. */
1.126014 +  zCsr = (char *)&p->abNotindexed[nCol];
1.126015 +  p->zName = zCsr;
1.126016 +  memcpy(zCsr, argv[2], nName);
1.126017 +  zCsr += nName;
1.126018 +  p->zDb = zCsr;
1.126019 +  memcpy(zCsr, argv[1], nDb);
1.126020 +  zCsr += nDb;
1.126021 +
1.126022 +  /* Fill in the azColumn array */
1.126023 +  for(iCol=0; iCol<nCol; iCol++){
1.126024 +    char *z; 
1.126025 +    int n = 0;
1.126026 +    z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
1.126027 +    memcpy(zCsr, z, n);
1.126028 +    zCsr[n] = '\0';
1.126029 +    sqlite3Fts3Dequote(zCsr);
1.126030 +    p->azColumn[iCol] = zCsr;
1.126031 +    zCsr += n+1;
1.126032 +    assert( zCsr <= &((char *)p)[nByte] );
1.126033 +  }
1.126034 +
1.126035 +  /* Fill in the abNotindexed array */
1.126036 +  for(iCol=0; iCol<nCol; iCol++){
1.126037 +    int n = (int)strlen(p->azColumn[iCol]);
1.126038 +    for(i=0; i<nNotindexed; i++){
1.126039 +      char *zNot = azNotindexed[i];
1.126040 +      if( zNot && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n) ){
1.126041 +        p->abNotindexed[iCol] = 1;
1.126042 +        sqlite3_free(zNot);
1.126043 +        azNotindexed[i] = 0;
1.126044 +      }
1.126045 +    }
1.126046 +  }
1.126047 +  for(i=0; i<nNotindexed; i++){
1.126048 +    if( azNotindexed[i] ){
1.126049 +      *pzErr = sqlite3_mprintf("no such column: %s", azNotindexed[i]);
1.126050 +      rc = SQLITE_ERROR;
1.126051 +    }
1.126052 +  }
1.126053 +
1.126054 +  if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
1.126055 +    char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
1.126056 +    rc = SQLITE_ERROR;
1.126057 +    *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
1.126058 +  }
1.126059 +  p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
1.126060 +  p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
1.126061 +  if( rc!=SQLITE_OK ) goto fts3_init_out;
1.126062 +
1.126063 +  /* If this is an xCreate call, create the underlying tables in the 
1.126064 +  ** database. TODO: For xConnect(), it could verify that said tables exist.
1.126065 +  */
1.126066 +  if( isCreate ){
1.126067 +    rc = fts3CreateTables(p);
1.126068 +  }
1.126069 +
1.126070 +  /* Check to see if a legacy fts3 table has been "upgraded" by the
1.126071 +  ** addition of a %_stat table so that it can use incremental merge.
1.126072 +  */
1.126073 +  if( !isFts4 && !isCreate ){
1.126074 +    int rc2 = SQLITE_OK;
1.126075 +    fts3DbExec(&rc2, db, "SELECT 1 FROM %Q.'%q_stat' WHERE id=2",
1.126076 +               p->zDb, p->zName);
1.126077 +    if( rc2==SQLITE_OK ) p->bHasStat = 1;
1.126078 +  }
1.126079 +
1.126080 +  /* Figure out the page-size for the database. This is required in order to
1.126081 +  ** estimate the cost of loading large doclists from the database.  */
1.126082 +  fts3DatabasePageSize(&rc, p);
1.126083 +  p->nNodeSize = p->nPgsz-35;
1.126084 +
1.126085 +  /* Declare the table schema to SQLite. */
1.126086 +  fts3DeclareVtab(&rc, p);
1.126087 +
1.126088 +fts3_init_out:
1.126089 +  sqlite3_free(zPrefix);
1.126090 +  sqlite3_free(aIndex);
1.126091 +  sqlite3_free(zCompress);
1.126092 +  sqlite3_free(zUncompress);
1.126093 +  sqlite3_free(zContent);
1.126094 +  sqlite3_free(zLanguageid);
1.126095 +  for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
1.126096 +  sqlite3_free((void *)aCol);
1.126097 +  sqlite3_free((void *)azNotindexed);
1.126098 +  if( rc!=SQLITE_OK ){
1.126099 +    if( p ){
1.126100 +      fts3DisconnectMethod((sqlite3_vtab *)p);
1.126101 +    }else if( pTokenizer ){
1.126102 +      pTokenizer->pModule->xDestroy(pTokenizer);
1.126103 +    }
1.126104 +  }else{
1.126105 +    assert( p->pSegments==0 );
1.126106 +    *ppVTab = &p->base;
1.126107 +  }
1.126108 +  return rc;
1.126109 +}
1.126110 +
1.126111 +/*
1.126112 +** The xConnect() and xCreate() methods for the virtual table. All the
1.126113 +** work is done in function fts3InitVtab().
1.126114 +*/
1.126115 +static int fts3ConnectMethod(
1.126116 +  sqlite3 *db,                    /* Database connection */
1.126117 +  void *pAux,                     /* Pointer to tokenizer hash table */
1.126118 +  int argc,                       /* Number of elements in argv array */
1.126119 +  const char * const *argv,       /* xCreate/xConnect argument array */
1.126120 +  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
1.126121 +  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
1.126122 +){
1.126123 +  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
1.126124 +}
1.126125 +static int fts3CreateMethod(
1.126126 +  sqlite3 *db,                    /* Database connection */
1.126127 +  void *pAux,                     /* Pointer to tokenizer hash table */
1.126128 +  int argc,                       /* Number of elements in argv array */
1.126129 +  const char * const *argv,       /* xCreate/xConnect argument array */
1.126130 +  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
1.126131 +  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
1.126132 +){
1.126133 +  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
1.126134 +}
1.126135 +
1.126136 +/*
1.126137 +** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
1.126138 +** extension is currently being used by a version of SQLite too old to
1.126139 +** support estimatedRows. In that case this function is a no-op.
1.126140 +*/
1.126141 +static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
1.126142 +#if SQLITE_VERSION_NUMBER>=3008002
1.126143 +  if( sqlite3_libversion_number()>=3008002 ){
1.126144 +    pIdxInfo->estimatedRows = nRow;
1.126145 +  }
1.126146 +#endif
1.126147 +}
1.126148 +
1.126149 +/* 
1.126150 +** Implementation of the xBestIndex method for FTS3 tables. There
1.126151 +** are three possible strategies, in order of preference:
1.126152 +**
1.126153 +**   1. Direct lookup by rowid or docid. 
1.126154 +**   2. Full-text search using a MATCH operator on a non-docid column.
1.126155 +**   3. Linear scan of %_content table.
1.126156 +*/
1.126157 +static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
1.126158 +  Fts3Table *p = (Fts3Table *)pVTab;
1.126159 +  int i;                          /* Iterator variable */
1.126160 +  int iCons = -1;                 /* Index of constraint to use */
1.126161 +
1.126162 +  int iLangidCons = -1;           /* Index of langid=x constraint, if present */
1.126163 +  int iDocidGe = -1;              /* Index of docid>=x constraint, if present */
1.126164 +  int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
1.126165 +  int iIdx;
1.126166 +
1.126167 +  /* By default use a full table scan. This is an expensive option,
1.126168 +  ** so search through the constraints to see if a more efficient 
1.126169 +  ** strategy is possible.
1.126170 +  */
1.126171 +  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
1.126172 +  pInfo->estimatedCost = 5000000;
1.126173 +  for(i=0; i<pInfo->nConstraint; i++){
1.126174 +    int bDocid;                 /* True if this constraint is on docid */
1.126175 +    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
1.126176 +    if( pCons->usable==0 ){
1.126177 +      if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
1.126178 +        /* There exists an unusable MATCH constraint. This means that if
1.126179 +        ** the planner does elect to use the results of this call as part
1.126180 +        ** of the overall query plan the user will see an "unable to use
1.126181 +        ** function MATCH in the requested context" error. To discourage
1.126182 +        ** this, return a very high cost here.  */
1.126183 +        pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
1.126184 +        pInfo->estimatedCost = 1e50;
1.126185 +        fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
1.126186 +        return SQLITE_OK;
1.126187 +      }
1.126188 +      continue;
1.126189 +    }
1.126190 +
1.126191 +    bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
1.126192 +
1.126193 +    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
1.126194 +    if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
1.126195 +      pInfo->idxNum = FTS3_DOCID_SEARCH;
1.126196 +      pInfo->estimatedCost = 1.0;
1.126197 +      iCons = i;
1.126198 +    }
1.126199 +
1.126200 +    /* A MATCH constraint. Use a full-text search.
1.126201 +    **
1.126202 +    ** If there is more than one MATCH constraint available, use the first
1.126203 +    ** one encountered. If there is both a MATCH constraint and a direct
1.126204 +    ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
1.126205 +    ** though the rowid/docid lookup is faster than a MATCH query, selecting
1.126206 +    ** it would lead to an "unable to use function MATCH in the requested 
1.126207 +    ** context" error.
1.126208 +    */
1.126209 +    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
1.126210 +     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
1.126211 +    ){
1.126212 +      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
1.126213 +      pInfo->estimatedCost = 2.0;
1.126214 +      iCons = i;
1.126215 +    }
1.126216 +
1.126217 +    /* Equality constraint on the langid column */
1.126218 +    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
1.126219 +     && pCons->iColumn==p->nColumn + 2
1.126220 +    ){
1.126221 +      iLangidCons = i;
1.126222 +    }
1.126223 +
1.126224 +    if( bDocid ){
1.126225 +      switch( pCons->op ){
1.126226 +        case SQLITE_INDEX_CONSTRAINT_GE:
1.126227 +        case SQLITE_INDEX_CONSTRAINT_GT:
1.126228 +          iDocidGe = i;
1.126229 +          break;
1.126230 +
1.126231 +        case SQLITE_INDEX_CONSTRAINT_LE:
1.126232 +        case SQLITE_INDEX_CONSTRAINT_LT:
1.126233 +          iDocidLe = i;
1.126234 +          break;
1.126235 +      }
1.126236 +    }
1.126237 +  }
1.126238 +
1.126239 +  iIdx = 1;
1.126240 +  if( iCons>=0 ){
1.126241 +    pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
1.126242 +    pInfo->aConstraintUsage[iCons].omit = 1;
1.126243 +  } 
1.126244 +  if( iLangidCons>=0 ){
1.126245 +    pInfo->idxNum |= FTS3_HAVE_LANGID;
1.126246 +    pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
1.126247 +  } 
1.126248 +  if( iDocidGe>=0 ){
1.126249 +    pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
1.126250 +    pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
1.126251 +  } 
1.126252 +  if( iDocidLe>=0 ){
1.126253 +    pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
1.126254 +    pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
1.126255 +  } 
1.126256 +
1.126257 +  /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
1.126258 +  ** docid) order. Both ascending and descending are possible. 
1.126259 +  */
1.126260 +  if( pInfo->nOrderBy==1 ){
1.126261 +    struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
1.126262 +    if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
1.126263 +      if( pOrder->desc ){
1.126264 +        pInfo->idxStr = "DESC";
1.126265 +      }else{
1.126266 +        pInfo->idxStr = "ASC";
1.126267 +      }
1.126268 +      pInfo->orderByConsumed = 1;
1.126269 +    }
1.126270 +  }
1.126271 +
1.126272 +  assert( p->pSegments==0 );
1.126273 +  return SQLITE_OK;
1.126274 +}
1.126275 +
1.126276 +/*
1.126277 +** Implementation of xOpen method.
1.126278 +*/
1.126279 +static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
1.126280 +  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
1.126281 +
1.126282 +  UNUSED_PARAMETER(pVTab);
1.126283 +
1.126284 +  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
1.126285 +  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
1.126286 +  ** if the allocation fails, return SQLITE_NOMEM.
1.126287 +  */
1.126288 +  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
1.126289 +  if( !pCsr ){
1.126290 +    return SQLITE_NOMEM;
1.126291 +  }
1.126292 +  memset(pCsr, 0, sizeof(Fts3Cursor));
1.126293 +  return SQLITE_OK;
1.126294 +}
1.126295 +
1.126296 +/*
1.126297 +** Close the cursor.  For additional information see the documentation
1.126298 +** on the xClose method of the virtual table interface.
1.126299 +*/
1.126300 +static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
1.126301 +  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
1.126302 +  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
1.126303 +  sqlite3_finalize(pCsr->pStmt);
1.126304 +  sqlite3Fts3ExprFree(pCsr->pExpr);
1.126305 +  sqlite3Fts3FreeDeferredTokens(pCsr);
1.126306 +  sqlite3_free(pCsr->aDoclist);
1.126307 +  sqlite3_free(pCsr->aMatchinfo);
1.126308 +  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
1.126309 +  sqlite3_free(pCsr);
1.126310 +  return SQLITE_OK;
1.126311 +}
1.126312 +
1.126313 +/*
1.126314 +** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
1.126315 +** compose and prepare an SQL statement of the form:
1.126316 +**
1.126317 +**    "SELECT <columns> FROM %_content WHERE rowid = ?"
1.126318 +**
1.126319 +** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
1.126320 +** it. If an error occurs, return an SQLite error code.
1.126321 +**
1.126322 +** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
1.126323 +*/
1.126324 +static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
1.126325 +  int rc = SQLITE_OK;
1.126326 +  if( pCsr->pStmt==0 ){
1.126327 +    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
1.126328 +    char *zSql;
1.126329 +    zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
1.126330 +    if( !zSql ) return SQLITE_NOMEM;
1.126331 +    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
1.126332 +    sqlite3_free(zSql);
1.126333 +  }
1.126334 +  *ppStmt = pCsr->pStmt;
1.126335 +  return rc;
1.126336 +}
1.126337 +
1.126338 +/*
1.126339 +** Position the pCsr->pStmt statement so that it is on the row
1.126340 +** of the %_content table that contains the last match.  Return
1.126341 +** SQLITE_OK on success.  
1.126342 +*/
1.126343 +static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
1.126344 +  int rc = SQLITE_OK;
1.126345 +  if( pCsr->isRequireSeek ){
1.126346 +    sqlite3_stmt *pStmt = 0;
1.126347 +
1.126348 +    rc = fts3CursorSeekStmt(pCsr, &pStmt);
1.126349 +    if( rc==SQLITE_OK ){
1.126350 +      sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
1.126351 +      pCsr->isRequireSeek = 0;
1.126352 +      if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
1.126353 +        return SQLITE_OK;
1.126354 +      }else{
1.126355 +        rc = sqlite3_reset(pCsr->pStmt);
1.126356 +        if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
1.126357 +          /* If no row was found and no error has occurred, then the %_content
1.126358 +          ** table is missing a row that is present in the full-text index.
1.126359 +          ** The data structures are corrupt.  */
1.126360 +          rc = FTS_CORRUPT_VTAB;
1.126361 +          pCsr->isEof = 1;
1.126362 +        }
1.126363 +      }
1.126364 +    }
1.126365 +  }
1.126366 +
1.126367 +  if( rc!=SQLITE_OK && pContext ){
1.126368 +    sqlite3_result_error_code(pContext, rc);
1.126369 +  }
1.126370 +  return rc;
1.126371 +}
1.126372 +
1.126373 +/*
1.126374 +** This function is used to process a single interior node when searching
1.126375 +** a b-tree for a term or term prefix. The node data is passed to this 
1.126376 +** function via the zNode/nNode parameters. The term to search for is
1.126377 +** passed in zTerm/nTerm.
1.126378 +**
1.126379 +** If piFirst is not NULL, then this function sets *piFirst to the blockid
1.126380 +** of the child node that heads the sub-tree that may contain the term.
1.126381 +**
1.126382 +** If piLast is not NULL, then *piLast is set to the right-most child node
1.126383 +** that heads a sub-tree that may contain a term for which zTerm/nTerm is
1.126384 +** a prefix.
1.126385 +**
1.126386 +** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
1.126387 +*/
1.126388 +static int fts3ScanInteriorNode(
1.126389 +  const char *zTerm,              /* Term to select leaves for */
1.126390 +  int nTerm,                      /* Size of term zTerm in bytes */
1.126391 +  const char *zNode,              /* Buffer containing segment interior node */
1.126392 +  int nNode,                      /* Size of buffer at zNode */
1.126393 +  sqlite3_int64 *piFirst,         /* OUT: Selected child node */
1.126394 +  sqlite3_int64 *piLast           /* OUT: Selected child node */
1.126395 +){
1.126396 +  int rc = SQLITE_OK;             /* Return code */
1.126397 +  const char *zCsr = zNode;       /* Cursor to iterate through node */
1.126398 +  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
1.126399 +  char *zBuffer = 0;              /* Buffer to load terms into */
1.126400 +  int nAlloc = 0;                 /* Size of allocated buffer */
1.126401 +  int isFirstTerm = 1;            /* True when processing first term on page */
1.126402 +  sqlite3_int64 iChild;           /* Block id of child node to descend to */
1.126403 +
1.126404 +  /* Skip over the 'height' varint that occurs at the start of every 
1.126405 +  ** interior node. Then load the blockid of the left-child of the b-tree
1.126406 +  ** node into variable iChild.  
1.126407 +  **
1.126408 +  ** Even if the data structure on disk is corrupted, this (reading two
1.126409 +  ** varints from the buffer) does not risk an overread. If zNode is a
1.126410 +  ** root node, then the buffer comes from a SELECT statement. SQLite does
1.126411 +  ** not make this guarantee explicitly, but in practice there are always
1.126412 +  ** either more than 20 bytes of allocated space following the nNode bytes of
1.126413 +  ** contents, or two zero bytes. Or, if the node is read from the %_segments
1.126414 +  ** table, then there are always 20 bytes of zeroed padding following the
1.126415 +  ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
1.126416 +  */
1.126417 +  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
1.126418 +  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
1.126419 +  if( zCsr>zEnd ){
1.126420 +    return FTS_CORRUPT_VTAB;
1.126421 +  }
1.126422 +  
1.126423 +  while( zCsr<zEnd && (piFirst || piLast) ){
1.126424 +    int cmp;                      /* memcmp() result */
1.126425 +    int nSuffix;                  /* Size of term suffix */
1.126426 +    int nPrefix = 0;              /* Size of term prefix */
1.126427 +    int nBuffer;                  /* Total term size */
1.126428 +  
1.126429 +    /* Load the next term on the node into zBuffer. Use realloc() to expand
1.126430 +    ** the size of zBuffer if required.  */
1.126431 +    if( !isFirstTerm ){
1.126432 +      zCsr += fts3GetVarint32(zCsr, &nPrefix);
1.126433 +    }
1.126434 +    isFirstTerm = 0;
1.126435 +    zCsr += fts3GetVarint32(zCsr, &nSuffix);
1.126436 +    
1.126437 +    if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
1.126438 +      rc = FTS_CORRUPT_VTAB;
1.126439 +      goto finish_scan;
1.126440 +    }
1.126441 +    if( nPrefix+nSuffix>nAlloc ){
1.126442 +      char *zNew;
1.126443 +      nAlloc = (nPrefix+nSuffix) * 2;
1.126444 +      zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
1.126445 +      if( !zNew ){
1.126446 +        rc = SQLITE_NOMEM;
1.126447 +        goto finish_scan;
1.126448 +      }
1.126449 +      zBuffer = zNew;
1.126450 +    }
1.126451 +    assert( zBuffer );
1.126452 +    memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
1.126453 +    nBuffer = nPrefix + nSuffix;
1.126454 +    zCsr += nSuffix;
1.126455 +
1.126456 +    /* Compare the term we are searching for with the term just loaded from
1.126457 +    ** the interior node. If the specified term is greater than or equal
1.126458 +    ** to the term from the interior node, then all terms on the sub-tree 
1.126459 +    ** headed by node iChild are smaller than zTerm. No need to search 
1.126460 +    ** iChild.
1.126461 +    **
1.126462 +    ** If the interior node term is larger than the specified term, then
1.126463 +    ** the tree headed by iChild may contain the specified term.
1.126464 +    */
1.126465 +    cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
1.126466 +    if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
1.126467 +      *piFirst = iChild;
1.126468 +      piFirst = 0;
1.126469 +    }
1.126470 +
1.126471 +    if( piLast && cmp<0 ){
1.126472 +      *piLast = iChild;
1.126473 +      piLast = 0;
1.126474 +    }
1.126475 +
1.126476 +    iChild++;
1.126477 +  };
1.126478 +
1.126479 +  if( piFirst ) *piFirst = iChild;
1.126480 +  if( piLast ) *piLast = iChild;
1.126481 +
1.126482 + finish_scan:
1.126483 +  sqlite3_free(zBuffer);
1.126484 +  return rc;
1.126485 +}
1.126486 +
1.126487 +
1.126488 +/*
1.126489 +** The buffer pointed to by argument zNode (size nNode bytes) contains an
1.126490 +** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
1.126491 +** contains a term. This function searches the sub-tree headed by the zNode
1.126492 +** node for the range of leaf nodes that may contain the specified term
1.126493 +** or terms for which the specified term is a prefix.
1.126494 +**
1.126495 +** If piLeaf is not NULL, then *piLeaf is set to the blockid of the 
1.126496 +** left-most leaf node in the tree that may contain the specified term.
1.126497 +** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
1.126498 +** right-most leaf node that may contain a term for which the specified
1.126499 +** term is a prefix.
1.126500 +**
1.126501 +** It is possible that the range of returned leaf nodes does not contain 
1.126502 +** the specified term or any terms for which it is a prefix. However, if the 
1.126503 +** segment does contain any such terms, they are stored within the identified
1.126504 +** range. Because this function only inspects interior segment nodes (and
1.126505 +** never loads leaf nodes into memory), it is not possible to be sure.
1.126506 +**
1.126507 +** If an error occurs, an error code other than SQLITE_OK is returned.
1.126508 +*/ 
1.126509 +static int fts3SelectLeaf(
1.126510 +  Fts3Table *p,                   /* Virtual table handle */
1.126511 +  const char *zTerm,              /* Term to select leaves for */
1.126512 +  int nTerm,                      /* Size of term zTerm in bytes */
1.126513 +  const char *zNode,              /* Buffer containing segment interior node */
1.126514 +  int nNode,                      /* Size of buffer at zNode */
1.126515 +  sqlite3_int64 *piLeaf,          /* Selected leaf node */
1.126516 +  sqlite3_int64 *piLeaf2          /* Selected leaf node */
1.126517 +){
1.126518 +  int rc;                         /* Return code */
1.126519 +  int iHeight;                    /* Height of this node in tree */
1.126520 +
1.126521 +  assert( piLeaf || piLeaf2 );
1.126522 +
1.126523 +  fts3GetVarint32(zNode, &iHeight);
1.126524 +  rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
1.126525 +  assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
1.126526 +
1.126527 +  if( rc==SQLITE_OK && iHeight>1 ){
1.126528 +    char *zBlob = 0;              /* Blob read from %_segments table */
1.126529 +    int nBlob;                    /* Size of zBlob in bytes */
1.126530 +
1.126531 +    if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
1.126532 +      rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
1.126533 +      if( rc==SQLITE_OK ){
1.126534 +        rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
1.126535 +      }
1.126536 +      sqlite3_free(zBlob);
1.126537 +      piLeaf = 0;
1.126538 +      zBlob = 0;
1.126539 +    }
1.126540 +
1.126541 +    if( rc==SQLITE_OK ){
1.126542 +      rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
1.126543 +    }
1.126544 +    if( rc==SQLITE_OK ){
1.126545 +      rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
1.126546 +    }
1.126547 +    sqlite3_free(zBlob);
1.126548 +  }
1.126549 +
1.126550 +  return rc;
1.126551 +}
1.126552 +
1.126553 +/*
1.126554 +** This function is used to create delta-encoded serialized lists of FTS3 
1.126555 +** varints. Each call to this function appends a single varint to a list.
1.126556 +*/
1.126557 +static void fts3PutDeltaVarint(
1.126558 +  char **pp,                      /* IN/OUT: Output pointer */
1.126559 +  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
1.126560 +  sqlite3_int64 iVal              /* Write this value to the list */
1.126561 +){
1.126562 +  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
1.126563 +  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
1.126564 +  *piPrev = iVal;
1.126565 +}
1.126566 +
1.126567 +/*
1.126568 +** When this function is called, *ppPoslist is assumed to point to the 
1.126569 +** start of a position-list. After it returns, *ppPoslist points to the
1.126570 +** first byte after the position-list.
1.126571 +**
1.126572 +** A position list is list of positions (delta encoded) and columns for 
1.126573 +** a single document record of a doclist.  So, in other words, this
1.126574 +** routine advances *ppPoslist so that it points to the next docid in
1.126575 +** the doclist, or to the first byte past the end of the doclist.
1.126576 +**
1.126577 +** If pp is not NULL, then the contents of the position list are copied
1.126578 +** to *pp. *pp is set to point to the first byte past the last byte copied
1.126579 +** before this function returns.
1.126580 +*/
1.126581 +static void fts3PoslistCopy(char **pp, char **ppPoslist){
1.126582 +  char *pEnd = *ppPoslist;
1.126583 +  char c = 0;
1.126584 +
1.126585 +  /* The end of a position list is marked by a zero encoded as an FTS3 
1.126586 +  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
1.126587 +  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
1.126588 +  ** of some other, multi-byte, value.
1.126589 +  **
1.126590 +  ** The following while-loop moves pEnd to point to the first byte that is not 
1.126591 +  ** immediately preceded by a byte with the 0x80 bit set. Then increments
1.126592 +  ** pEnd once more so that it points to the byte immediately following the
1.126593 +  ** last byte in the position-list.
1.126594 +  */
1.126595 +  while( *pEnd | c ){
1.126596 +    c = *pEnd++ & 0x80;
1.126597 +    testcase( c!=0 && (*pEnd)==0 );
1.126598 +  }
1.126599 +  pEnd++;  /* Advance past the POS_END terminator byte */
1.126600 +
1.126601 +  if( pp ){
1.126602 +    int n = (int)(pEnd - *ppPoslist);
1.126603 +    char *p = *pp;
1.126604 +    memcpy(p, *ppPoslist, n);
1.126605 +    p += n;
1.126606 +    *pp = p;
1.126607 +  }
1.126608 +  *ppPoslist = pEnd;
1.126609 +}
1.126610 +
1.126611 +/*
1.126612 +** When this function is called, *ppPoslist is assumed to point to the 
1.126613 +** start of a column-list. After it returns, *ppPoslist points to the
1.126614 +** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
1.126615 +**
1.126616 +** A column-list is list of delta-encoded positions for a single column
1.126617 +** within a single document within a doclist.
1.126618 +**
1.126619 +** The column-list is terminated either by a POS_COLUMN varint (1) or
1.126620 +** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
1.126621 +** the POS_COLUMN or POS_END that terminates the column-list.
1.126622 +**
1.126623 +** If pp is not NULL, then the contents of the column-list are copied
1.126624 +** to *pp. *pp is set to point to the first byte past the last byte copied
1.126625 +** before this function returns.  The POS_COLUMN or POS_END terminator
1.126626 +** is not copied into *pp.
1.126627 +*/
1.126628 +static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
1.126629 +  char *pEnd = *ppPoslist;
1.126630 +  char c = 0;
1.126631 +
1.126632 +  /* A column-list is terminated by either a 0x01 or 0x00 byte that is
1.126633 +  ** not part of a multi-byte varint.
1.126634 +  */
1.126635 +  while( 0xFE & (*pEnd | c) ){
1.126636 +    c = *pEnd++ & 0x80;
1.126637 +    testcase( c!=0 && ((*pEnd)&0xfe)==0 );
1.126638 +  }
1.126639 +  if( pp ){
1.126640 +    int n = (int)(pEnd - *ppPoslist);
1.126641 +    char *p = *pp;
1.126642 +    memcpy(p, *ppPoslist, n);
1.126643 +    p += n;
1.126644 +    *pp = p;
1.126645 +  }
1.126646 +  *ppPoslist = pEnd;
1.126647 +}
1.126648 +
1.126649 +/*
1.126650 +** Value used to signify the end of an position-list. This is safe because
1.126651 +** it is not possible to have a document with 2^31 terms.
1.126652 +*/
1.126653 +#define POSITION_LIST_END 0x7fffffff
1.126654 +
1.126655 +/*
1.126656 +** This function is used to help parse position-lists. When this function is
1.126657 +** called, *pp may point to the start of the next varint in the position-list
1.126658 +** being parsed, or it may point to 1 byte past the end of the position-list
1.126659 +** (in which case **pp will be a terminator bytes POS_END (0) or
1.126660 +** (1)).
1.126661 +**
1.126662 +** If *pp points past the end of the current position-list, set *pi to 
1.126663 +** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
1.126664 +** increment the current value of *pi by the value read, and set *pp to
1.126665 +** point to the next value before returning.
1.126666 +**
1.126667 +** Before calling this routine *pi must be initialized to the value of
1.126668 +** the previous position, or zero if we are reading the first position
1.126669 +** in the position-list.  Because positions are delta-encoded, the value
1.126670 +** of the previous position is needed in order to compute the value of
1.126671 +** the next position.
1.126672 +*/
1.126673 +static void fts3ReadNextPos(
1.126674 +  char **pp,                    /* IN/OUT: Pointer into position-list buffer */
1.126675 +  sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
1.126676 +){
1.126677 +  if( (**pp)&0xFE ){
1.126678 +    fts3GetDeltaVarint(pp, pi);
1.126679 +    *pi -= 2;
1.126680 +  }else{
1.126681 +    *pi = POSITION_LIST_END;
1.126682 +  }
1.126683 +}
1.126684 +
1.126685 +/*
1.126686 +** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
1.126687 +** the value of iCol encoded as a varint to *pp.   This will start a new
1.126688 +** column list.
1.126689 +**
1.126690 +** Set *pp to point to the byte just after the last byte written before 
1.126691 +** returning (do not modify it if iCol==0). Return the total number of bytes
1.126692 +** written (0 if iCol==0).
1.126693 +*/
1.126694 +static int fts3PutColNumber(char **pp, int iCol){
1.126695 +  int n = 0;                      /* Number of bytes written */
1.126696 +  if( iCol ){
1.126697 +    char *p = *pp;                /* Output pointer */
1.126698 +    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
1.126699 +    *p = 0x01;
1.126700 +    *pp = &p[n];
1.126701 +  }
1.126702 +  return n;
1.126703 +}
1.126704 +
1.126705 +/*
1.126706 +** Compute the union of two position lists.  The output written
1.126707 +** into *pp contains all positions of both *pp1 and *pp2 in sorted
1.126708 +** order and with any duplicates removed.  All pointers are
1.126709 +** updated appropriately.   The caller is responsible for insuring
1.126710 +** that there is enough space in *pp to hold the complete output.
1.126711 +*/
1.126712 +static void fts3PoslistMerge(
1.126713 +  char **pp,                      /* Output buffer */
1.126714 +  char **pp1,                     /* Left input list */
1.126715 +  char **pp2                      /* Right input list */
1.126716 +){
1.126717 +  char *p = *pp;
1.126718 +  char *p1 = *pp1;
1.126719 +  char *p2 = *pp2;
1.126720 +
1.126721 +  while( *p1 || *p2 ){
1.126722 +    int iCol1;         /* The current column index in pp1 */
1.126723 +    int iCol2;         /* The current column index in pp2 */
1.126724 +
1.126725 +    if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
1.126726 +    else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
1.126727 +    else iCol1 = 0;
1.126728 +
1.126729 +    if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
1.126730 +    else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
1.126731 +    else iCol2 = 0;
1.126732 +
1.126733 +    if( iCol1==iCol2 ){
1.126734 +      sqlite3_int64 i1 = 0;       /* Last position from pp1 */
1.126735 +      sqlite3_int64 i2 = 0;       /* Last position from pp2 */
1.126736 +      sqlite3_int64 iPrev = 0;
1.126737 +      int n = fts3PutColNumber(&p, iCol1);
1.126738 +      p1 += n;
1.126739 +      p2 += n;
1.126740 +
1.126741 +      /* At this point, both p1 and p2 point to the start of column-lists
1.126742 +      ** for the same column (the column with index iCol1 and iCol2).
1.126743 +      ** A column-list is a list of non-negative delta-encoded varints, each 
1.126744 +      ** incremented by 2 before being stored. Each list is terminated by a
1.126745 +      ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
1.126746 +      ** and writes the results to buffer p. p is left pointing to the byte
1.126747 +      ** after the list written. No terminator (POS_END or POS_COLUMN) is
1.126748 +      ** written to the output.
1.126749 +      */
1.126750 +      fts3GetDeltaVarint(&p1, &i1);
1.126751 +      fts3GetDeltaVarint(&p2, &i2);
1.126752 +      do {
1.126753 +        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
1.126754 +        iPrev -= 2;
1.126755 +        if( i1==i2 ){
1.126756 +          fts3ReadNextPos(&p1, &i1);
1.126757 +          fts3ReadNextPos(&p2, &i2);
1.126758 +        }else if( i1<i2 ){
1.126759 +          fts3ReadNextPos(&p1, &i1);
1.126760 +        }else{
1.126761 +          fts3ReadNextPos(&p2, &i2);
1.126762 +        }
1.126763 +      }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
1.126764 +    }else if( iCol1<iCol2 ){
1.126765 +      p1 += fts3PutColNumber(&p, iCol1);
1.126766 +      fts3ColumnlistCopy(&p, &p1);
1.126767 +    }else{
1.126768 +      p2 += fts3PutColNumber(&p, iCol2);
1.126769 +      fts3ColumnlistCopy(&p, &p2);
1.126770 +    }
1.126771 +  }
1.126772 +
1.126773 +  *p++ = POS_END;
1.126774 +  *pp = p;
1.126775 +  *pp1 = p1 + 1;
1.126776 +  *pp2 = p2 + 1;
1.126777 +}
1.126778 +
1.126779 +/*
1.126780 +** This function is used to merge two position lists into one. When it is
1.126781 +** called, *pp1 and *pp2 must both point to position lists. A position-list is
1.126782 +** the part of a doclist that follows each document id. For example, if a row
1.126783 +** contains:
1.126784 +**
1.126785 +**     'a b c'|'x y z'|'a b b a'
1.126786 +**
1.126787 +** Then the position list for this row for token 'b' would consist of:
1.126788 +**
1.126789 +**     0x02 0x01 0x02 0x03 0x03 0x00
1.126790 +**
1.126791 +** When this function returns, both *pp1 and *pp2 are left pointing to the
1.126792 +** byte following the 0x00 terminator of their respective position lists.
1.126793 +**
1.126794 +** If isSaveLeft is 0, an entry is added to the output position list for 
1.126795 +** each position in *pp2 for which there exists one or more positions in
1.126796 +** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
1.126797 +** when the *pp1 token appears before the *pp2 token, but not more than nToken
1.126798 +** slots before it.
1.126799 +**
1.126800 +** e.g. nToken==1 searches for adjacent positions.
1.126801 +*/
1.126802 +static int fts3PoslistPhraseMerge(
1.126803 +  char **pp,                      /* IN/OUT: Preallocated output buffer */
1.126804 +  int nToken,                     /* Maximum difference in token positions */
1.126805 +  int isSaveLeft,                 /* Save the left position */
1.126806 +  int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
1.126807 +  char **pp1,                     /* IN/OUT: Left input list */
1.126808 +  char **pp2                      /* IN/OUT: Right input list */
1.126809 +){
1.126810 +  char *p = *pp;
1.126811 +  char *p1 = *pp1;
1.126812 +  char *p2 = *pp2;
1.126813 +  int iCol1 = 0;
1.126814 +  int iCol2 = 0;
1.126815 +
1.126816 +  /* Never set both isSaveLeft and isExact for the same invocation. */
1.126817 +  assert( isSaveLeft==0 || isExact==0 );
1.126818 +
1.126819 +  assert( p!=0 && *p1!=0 && *p2!=0 );
1.126820 +  if( *p1==POS_COLUMN ){ 
1.126821 +    p1++;
1.126822 +    p1 += fts3GetVarint32(p1, &iCol1);
1.126823 +  }
1.126824 +  if( *p2==POS_COLUMN ){ 
1.126825 +    p2++;
1.126826 +    p2 += fts3GetVarint32(p2, &iCol2);
1.126827 +  }
1.126828 +
1.126829 +  while( 1 ){
1.126830 +    if( iCol1==iCol2 ){
1.126831 +      char *pSave = p;
1.126832 +      sqlite3_int64 iPrev = 0;
1.126833 +      sqlite3_int64 iPos1 = 0;
1.126834 +      sqlite3_int64 iPos2 = 0;
1.126835 +
1.126836 +      if( iCol1 ){
1.126837 +        *p++ = POS_COLUMN;
1.126838 +        p += sqlite3Fts3PutVarint(p, iCol1);
1.126839 +      }
1.126840 +
1.126841 +      assert( *p1!=POS_END && *p1!=POS_COLUMN );
1.126842 +      assert( *p2!=POS_END && *p2!=POS_COLUMN );
1.126843 +      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
1.126844 +      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
1.126845 +
1.126846 +      while( 1 ){
1.126847 +        if( iPos2==iPos1+nToken 
1.126848 +         || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) 
1.126849 +        ){
1.126850 +          sqlite3_int64 iSave;
1.126851 +          iSave = isSaveLeft ? iPos1 : iPos2;
1.126852 +          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
1.126853 +          pSave = 0;
1.126854 +          assert( p );
1.126855 +        }
1.126856 +        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
1.126857 +          if( (*p2&0xFE)==0 ) break;
1.126858 +          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
1.126859 +        }else{
1.126860 +          if( (*p1&0xFE)==0 ) break;
1.126861 +          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
1.126862 +        }
1.126863 +      }
1.126864 +
1.126865 +      if( pSave ){
1.126866 +        assert( pp && p );
1.126867 +        p = pSave;
1.126868 +      }
1.126869 +
1.126870 +      fts3ColumnlistCopy(0, &p1);
1.126871 +      fts3ColumnlistCopy(0, &p2);
1.126872 +      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
1.126873 +      if( 0==*p1 || 0==*p2 ) break;
1.126874 +
1.126875 +      p1++;
1.126876 +      p1 += fts3GetVarint32(p1, &iCol1);
1.126877 +      p2++;
1.126878 +      p2 += fts3GetVarint32(p2, &iCol2);
1.126879 +    }
1.126880 +
1.126881 +    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
1.126882 +    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
1.126883 +    ** end of the position list, or the 0x01 that precedes the next 
1.126884 +    ** column-number in the position list. 
1.126885 +    */
1.126886 +    else if( iCol1<iCol2 ){
1.126887 +      fts3ColumnlistCopy(0, &p1);
1.126888 +      if( 0==*p1 ) break;
1.126889 +      p1++;
1.126890 +      p1 += fts3GetVarint32(p1, &iCol1);
1.126891 +    }else{
1.126892 +      fts3ColumnlistCopy(0, &p2);
1.126893 +      if( 0==*p2 ) break;
1.126894 +      p2++;
1.126895 +      p2 += fts3GetVarint32(p2, &iCol2);
1.126896 +    }
1.126897 +  }
1.126898 +
1.126899 +  fts3PoslistCopy(0, &p2);
1.126900 +  fts3PoslistCopy(0, &p1);
1.126901 +  *pp1 = p1;
1.126902 +  *pp2 = p2;
1.126903 +  if( *pp==p ){
1.126904 +    return 0;
1.126905 +  }
1.126906 +  *p++ = 0x00;
1.126907 +  *pp = p;
1.126908 +  return 1;
1.126909 +}
1.126910 +
1.126911 +/*
1.126912 +** Merge two position-lists as required by the NEAR operator. The argument
1.126913 +** position lists correspond to the left and right phrases of an expression 
1.126914 +** like:
1.126915 +**
1.126916 +**     "phrase 1" NEAR "phrase number 2"
1.126917 +**
1.126918 +** Position list *pp1 corresponds to the left-hand side of the NEAR 
1.126919 +** expression and *pp2 to the right. As usual, the indexes in the position 
1.126920 +** lists are the offsets of the last token in each phrase (tokens "1" and "2" 
1.126921 +** in the example above).
1.126922 +**
1.126923 +** The output position list - written to *pp - is a copy of *pp2 with those
1.126924 +** entries that are not sufficiently NEAR entries in *pp1 removed.
1.126925 +*/
1.126926 +static int fts3PoslistNearMerge(
1.126927 +  char **pp,                      /* Output buffer */
1.126928 +  char *aTmp,                     /* Temporary buffer space */
1.126929 +  int nRight,                     /* Maximum difference in token positions */
1.126930 +  int nLeft,                      /* Maximum difference in token positions */
1.126931 +  char **pp1,                     /* IN/OUT: Left input list */
1.126932 +  char **pp2                      /* IN/OUT: Right input list */
1.126933 +){
1.126934 +  char *p1 = *pp1;
1.126935 +  char *p2 = *pp2;
1.126936 +
1.126937 +  char *pTmp1 = aTmp;
1.126938 +  char *pTmp2;
1.126939 +  char *aTmp2;
1.126940 +  int res = 1;
1.126941 +
1.126942 +  fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
1.126943 +  aTmp2 = pTmp2 = pTmp1;
1.126944 +  *pp1 = p1;
1.126945 +  *pp2 = p2;
1.126946 +  fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
1.126947 +  if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
1.126948 +    fts3PoslistMerge(pp, &aTmp, &aTmp2);
1.126949 +  }else if( pTmp1!=aTmp ){
1.126950 +    fts3PoslistCopy(pp, &aTmp);
1.126951 +  }else if( pTmp2!=aTmp2 ){
1.126952 +    fts3PoslistCopy(pp, &aTmp2);
1.126953 +  }else{
1.126954 +    res = 0;
1.126955 +  }
1.126956 +
1.126957 +  return res;
1.126958 +}
1.126959 +
1.126960 +/* 
1.126961 +** An instance of this function is used to merge together the (potentially
1.126962 +** large number of) doclists for each term that matches a prefix query.
1.126963 +** See function fts3TermSelectMerge() for details.
1.126964 +*/
1.126965 +typedef struct TermSelect TermSelect;
1.126966 +struct TermSelect {
1.126967 +  char *aaOutput[16];             /* Malloc'd output buffers */
1.126968 +  int anOutput[16];               /* Size each output buffer in bytes */
1.126969 +};
1.126970 +
1.126971 +/*
1.126972 +** This function is used to read a single varint from a buffer. Parameter
1.126973 +** pEnd points 1 byte past the end of the buffer. When this function is
1.126974 +** called, if *pp points to pEnd or greater, then the end of the buffer
1.126975 +** has been reached. In this case *pp is set to 0 and the function returns.
1.126976 +**
1.126977 +** If *pp does not point to or past pEnd, then a single varint is read
1.126978 +** from *pp. *pp is then set to point 1 byte past the end of the read varint.
1.126979 +**
1.126980 +** If bDescIdx is false, the value read is added to *pVal before returning.
1.126981 +** If it is true, the value read is subtracted from *pVal before this 
1.126982 +** function returns.
1.126983 +*/
1.126984 +static void fts3GetDeltaVarint3(
1.126985 +  char **pp,                      /* IN/OUT: Point to read varint from */
1.126986 +  char *pEnd,                     /* End of buffer */
1.126987 +  int bDescIdx,                   /* True if docids are descending */
1.126988 +  sqlite3_int64 *pVal             /* IN/OUT: Integer value */
1.126989 +){
1.126990 +  if( *pp>=pEnd ){
1.126991 +    *pp = 0;
1.126992 +  }else{
1.126993 +    sqlite3_int64 iVal;
1.126994 +    *pp += sqlite3Fts3GetVarint(*pp, &iVal);
1.126995 +    if( bDescIdx ){
1.126996 +      *pVal -= iVal;
1.126997 +    }else{
1.126998 +      *pVal += iVal;
1.126999 +    }
1.127000 +  }
1.127001 +}
1.127002 +
1.127003 +/*
1.127004 +** This function is used to write a single varint to a buffer. The varint
1.127005 +** is written to *pp. Before returning, *pp is set to point 1 byte past the
1.127006 +** end of the value written.
1.127007 +**
1.127008 +** If *pbFirst is zero when this function is called, the value written to
1.127009 +** the buffer is that of parameter iVal. 
1.127010 +**
1.127011 +** If *pbFirst is non-zero when this function is called, then the value 
1.127012 +** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
1.127013 +** (if bDescIdx is non-zero).
1.127014 +**
1.127015 +** Before returning, this function always sets *pbFirst to 1 and *piPrev
1.127016 +** to the value of parameter iVal.
1.127017 +*/
1.127018 +static void fts3PutDeltaVarint3(
1.127019 +  char **pp,                      /* IN/OUT: Output pointer */
1.127020 +  int bDescIdx,                   /* True for descending docids */
1.127021 +  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
1.127022 +  int *pbFirst,                   /* IN/OUT: True after first int written */
1.127023 +  sqlite3_int64 iVal              /* Write this value to the list */
1.127024 +){
1.127025 +  sqlite3_int64 iWrite;
1.127026 +  if( bDescIdx==0 || *pbFirst==0 ){
1.127027 +    iWrite = iVal - *piPrev;
1.127028 +  }else{
1.127029 +    iWrite = *piPrev - iVal;
1.127030 +  }
1.127031 +  assert( *pbFirst || *piPrev==0 );
1.127032 +  assert( *pbFirst==0 || iWrite>0 );
1.127033 +  *pp += sqlite3Fts3PutVarint(*pp, iWrite);
1.127034 +  *piPrev = iVal;
1.127035 +  *pbFirst = 1;
1.127036 +}
1.127037 +
1.127038 +
1.127039 +/*
1.127040 +** This macro is used by various functions that merge doclists. The two
1.127041 +** arguments are 64-bit docid values. If the value of the stack variable
1.127042 +** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). 
1.127043 +** Otherwise, (i2-i1).
1.127044 +**
1.127045 +** Using this makes it easier to write code that can merge doclists that are
1.127046 +** sorted in either ascending or descending order.
1.127047 +*/
1.127048 +#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
1.127049 +
1.127050 +/*
1.127051 +** This function does an "OR" merge of two doclists (output contains all
1.127052 +** positions contained in either argument doclist). If the docids in the 
1.127053 +** input doclists are sorted in ascending order, parameter bDescDoclist
1.127054 +** should be false. If they are sorted in ascending order, it should be
1.127055 +** passed a non-zero value.
1.127056 +**
1.127057 +** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
1.127058 +** containing the output doclist and SQLITE_OK is returned. In this case
1.127059 +** *pnOut is set to the number of bytes in the output doclist.
1.127060 +**
1.127061 +** If an error occurs, an SQLite error code is returned. The output values
1.127062 +** are undefined in this case.
1.127063 +*/
1.127064 +static int fts3DoclistOrMerge(
1.127065 +  int bDescDoclist,               /* True if arguments are desc */
1.127066 +  char *a1, int n1,               /* First doclist */
1.127067 +  char *a2, int n2,               /* Second doclist */
1.127068 +  char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
1.127069 +){
1.127070 +  sqlite3_int64 i1 = 0;
1.127071 +  sqlite3_int64 i2 = 0;
1.127072 +  sqlite3_int64 iPrev = 0;
1.127073 +  char *pEnd1 = &a1[n1];
1.127074 +  char *pEnd2 = &a2[n2];
1.127075 +  char *p1 = a1;
1.127076 +  char *p2 = a2;
1.127077 +  char *p;
1.127078 +  char *aOut;
1.127079 +  int bFirstOut = 0;
1.127080 +
1.127081 +  *paOut = 0;
1.127082 +  *pnOut = 0;
1.127083 +
1.127084 +  /* Allocate space for the output. Both the input and output doclists
1.127085 +  ** are delta encoded. If they are in ascending order (bDescDoclist==0),
1.127086 +  ** then the first docid in each list is simply encoded as a varint. For
1.127087 +  ** each subsequent docid, the varint stored is the difference between the
1.127088 +  ** current and previous docid (a positive number - since the list is in
1.127089 +  ** ascending order).
1.127090 +  **
1.127091 +  ** The first docid written to the output is therefore encoded using the 
1.127092 +  ** same number of bytes as it is in whichever of the input lists it is
1.127093 +  ** read from. And each subsequent docid read from the same input list 
1.127094 +  ** consumes either the same or less bytes as it did in the input (since
1.127095 +  ** the difference between it and the previous value in the output must
1.127096 +  ** be a positive value less than or equal to the delta value read from 
1.127097 +  ** the input list). The same argument applies to all but the first docid
1.127098 +  ** read from the 'other' list. And to the contents of all position lists
1.127099 +  ** that will be copied and merged from the input to the output.
1.127100 +  **
1.127101 +  ** However, if the first docid copied to the output is a negative number,
1.127102 +  ** then the encoding of the first docid from the 'other' input list may
1.127103 +  ** be larger in the output than it was in the input (since the delta value
1.127104 +  ** may be a larger positive integer than the actual docid).
1.127105 +  **
1.127106 +  ** The space required to store the output is therefore the sum of the
1.127107 +  ** sizes of the two inputs, plus enough space for exactly one of the input
1.127108 +  ** docids to grow. 
1.127109 +  **
1.127110 +  ** A symetric argument may be made if the doclists are in descending 
1.127111 +  ** order.
1.127112 +  */
1.127113 +  aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
1.127114 +  if( !aOut ) return SQLITE_NOMEM;
1.127115 +
1.127116 +  p = aOut;
1.127117 +  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
1.127118 +  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
1.127119 +  while( p1 || p2 ){
1.127120 +    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
1.127121 +
1.127122 +    if( p2 && p1 && iDiff==0 ){
1.127123 +      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
1.127124 +      fts3PoslistMerge(&p, &p1, &p2);
1.127125 +      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
1.127126 +      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
1.127127 +    }else if( !p2 || (p1 && iDiff<0) ){
1.127128 +      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
1.127129 +      fts3PoslistCopy(&p, &p1);
1.127130 +      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
1.127131 +    }else{
1.127132 +      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
1.127133 +      fts3PoslistCopy(&p, &p2);
1.127134 +      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
1.127135 +    }
1.127136 +  }
1.127137 +
1.127138 +  *paOut = aOut;
1.127139 +  *pnOut = (int)(p-aOut);
1.127140 +  assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
1.127141 +  return SQLITE_OK;
1.127142 +}
1.127143 +
1.127144 +/*
1.127145 +** This function does a "phrase" merge of two doclists. In a phrase merge,
1.127146 +** the output contains a copy of each position from the right-hand input
1.127147 +** doclist for which there is a position in the left-hand input doclist
1.127148 +** exactly nDist tokens before it.
1.127149 +**
1.127150 +** If the docids in the input doclists are sorted in ascending order,
1.127151 +** parameter bDescDoclist should be false. If they are sorted in ascending 
1.127152 +** order, it should be passed a non-zero value.
1.127153 +**
1.127154 +** The right-hand input doclist is overwritten by this function.
1.127155 +*/
1.127156 +static void fts3DoclistPhraseMerge(
1.127157 +  int bDescDoclist,               /* True if arguments are desc */
1.127158 +  int nDist,                      /* Distance from left to right (1=adjacent) */
1.127159 +  char *aLeft, int nLeft,         /* Left doclist */
1.127160 +  char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
1.127161 +){
1.127162 +  sqlite3_int64 i1 = 0;
1.127163 +  sqlite3_int64 i2 = 0;
1.127164 +  sqlite3_int64 iPrev = 0;
1.127165 +  char *pEnd1 = &aLeft[nLeft];
1.127166 +  char *pEnd2 = &aRight[*pnRight];
1.127167 +  char *p1 = aLeft;
1.127168 +  char *p2 = aRight;
1.127169 +  char *p;
1.127170 +  int bFirstOut = 0;
1.127171 +  char *aOut = aRight;
1.127172 +
1.127173 +  assert( nDist>0 );
1.127174 +
1.127175 +  p = aOut;
1.127176 +  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
1.127177 +  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
1.127178 +
1.127179 +  while( p1 && p2 ){
1.127180 +    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
1.127181 +    if( iDiff==0 ){
1.127182 +      char *pSave = p;
1.127183 +      sqlite3_int64 iPrevSave = iPrev;
1.127184 +      int bFirstOutSave = bFirstOut;
1.127185 +
1.127186 +      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
1.127187 +      if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
1.127188 +        p = pSave;
1.127189 +        iPrev = iPrevSave;
1.127190 +        bFirstOut = bFirstOutSave;
1.127191 +      }
1.127192 +      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
1.127193 +      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
1.127194 +    }else if( iDiff<0 ){
1.127195 +      fts3PoslistCopy(0, &p1);
1.127196 +      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
1.127197 +    }else{
1.127198 +      fts3PoslistCopy(0, &p2);
1.127199 +      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
1.127200 +    }
1.127201 +  }
1.127202 +
1.127203 +  *pnRight = (int)(p - aOut);
1.127204 +}
1.127205 +
1.127206 +/*
1.127207 +** Argument pList points to a position list nList bytes in size. This
1.127208 +** function checks to see if the position list contains any entries for
1.127209 +** a token in position 0 (of any column). If so, it writes argument iDelta
1.127210 +** to the output buffer pOut, followed by a position list consisting only
1.127211 +** of the entries from pList at position 0, and terminated by an 0x00 byte.
1.127212 +** The value returned is the number of bytes written to pOut (if any).
1.127213 +*/
1.127214 +SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
1.127215 +  sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
1.127216 +  char *pList,                    /* Position list (no 0x00 term) */
1.127217 +  int nList,                      /* Size of pList in bytes */
1.127218 +  char *pOut                      /* Write output here */
1.127219 +){
1.127220 +  int nOut = 0;
1.127221 +  int bWritten = 0;               /* True once iDelta has been written */
1.127222 +  char *p = pList;
1.127223 +  char *pEnd = &pList[nList];
1.127224 +
1.127225 +  if( *p!=0x01 ){
1.127226 +    if( *p==0x02 ){
1.127227 +      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
1.127228 +      pOut[nOut++] = 0x02;
1.127229 +      bWritten = 1;
1.127230 +    }
1.127231 +    fts3ColumnlistCopy(0, &p);
1.127232 +  }
1.127233 +
1.127234 +  while( p<pEnd && *p==0x01 ){
1.127235 +    sqlite3_int64 iCol;
1.127236 +    p++;
1.127237 +    p += sqlite3Fts3GetVarint(p, &iCol);
1.127238 +    if( *p==0x02 ){
1.127239 +      if( bWritten==0 ){
1.127240 +        nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
1.127241 +        bWritten = 1;
1.127242 +      }
1.127243 +      pOut[nOut++] = 0x01;
1.127244 +      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
1.127245 +      pOut[nOut++] = 0x02;
1.127246 +    }
1.127247 +    fts3ColumnlistCopy(0, &p);
1.127248 +  }
1.127249 +  if( bWritten ){
1.127250 +    pOut[nOut++] = 0x00;
1.127251 +  }
1.127252 +
1.127253 +  return nOut;
1.127254 +}
1.127255 +
1.127256 +
1.127257 +/*
1.127258 +** Merge all doclists in the TermSelect.aaOutput[] array into a single
1.127259 +** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
1.127260 +** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
1.127261 +**
1.127262 +** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
1.127263 +** the responsibility of the caller to free any doclists left in the
1.127264 +** TermSelect.aaOutput[] array.
1.127265 +*/
1.127266 +static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
1.127267 +  char *aOut = 0;
1.127268 +  int nOut = 0;
1.127269 +  int i;
1.127270 +
1.127271 +  /* Loop through the doclists in the aaOutput[] array. Merge them all
1.127272 +  ** into a single doclist.
1.127273 +  */
1.127274 +  for(i=0; i<SizeofArray(pTS->aaOutput); i++){
1.127275 +    if( pTS->aaOutput[i] ){
1.127276 +      if( !aOut ){
1.127277 +        aOut = pTS->aaOutput[i];
1.127278 +        nOut = pTS->anOutput[i];
1.127279 +        pTS->aaOutput[i] = 0;
1.127280 +      }else{
1.127281 +        int nNew;
1.127282 +        char *aNew;
1.127283 +
1.127284 +        int rc = fts3DoclistOrMerge(p->bDescIdx, 
1.127285 +            pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
1.127286 +        );
1.127287 +        if( rc!=SQLITE_OK ){
1.127288 +          sqlite3_free(aOut);
1.127289 +          return rc;
1.127290 +        }
1.127291 +
1.127292 +        sqlite3_free(pTS->aaOutput[i]);
1.127293 +        sqlite3_free(aOut);
1.127294 +        pTS->aaOutput[i] = 0;
1.127295 +        aOut = aNew;
1.127296 +        nOut = nNew;
1.127297 +      }
1.127298 +    }
1.127299 +  }
1.127300 +
1.127301 +  pTS->aaOutput[0] = aOut;
1.127302 +  pTS->anOutput[0] = nOut;
1.127303 +  return SQLITE_OK;
1.127304 +}
1.127305 +
1.127306 +/*
1.127307 +** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
1.127308 +** as the first argument. The merge is an "OR" merge (see function
1.127309 +** fts3DoclistOrMerge() for details).
1.127310 +**
1.127311 +** This function is called with the doclist for each term that matches
1.127312 +** a queried prefix. It merges all these doclists into one, the doclist
1.127313 +** for the specified prefix. Since there can be a very large number of
1.127314 +** doclists to merge, the merging is done pair-wise using the TermSelect
1.127315 +** object.
1.127316 +**
1.127317 +** This function returns SQLITE_OK if the merge is successful, or an
1.127318 +** SQLite error code (SQLITE_NOMEM) if an error occurs.
1.127319 +*/
1.127320 +static int fts3TermSelectMerge(
1.127321 +  Fts3Table *p,                   /* FTS table handle */
1.127322 +  TermSelect *pTS,                /* TermSelect object to merge into */
1.127323 +  char *aDoclist,                 /* Pointer to doclist */
1.127324 +  int nDoclist                    /* Size of aDoclist in bytes */
1.127325 +){
1.127326 +  if( pTS->aaOutput[0]==0 ){
1.127327 +    /* If this is the first term selected, copy the doclist to the output
1.127328 +    ** buffer using memcpy(). */
1.127329 +    pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
1.127330 +    pTS->anOutput[0] = nDoclist;
1.127331 +    if( pTS->aaOutput[0] ){
1.127332 +      memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
1.127333 +    }else{
1.127334 +      return SQLITE_NOMEM;
1.127335 +    }
1.127336 +  }else{
1.127337 +    char *aMerge = aDoclist;
1.127338 +    int nMerge = nDoclist;
1.127339 +    int iOut;
1.127340 +
1.127341 +    for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
1.127342 +      if( pTS->aaOutput[iOut]==0 ){
1.127343 +        assert( iOut>0 );
1.127344 +        pTS->aaOutput[iOut] = aMerge;
1.127345 +        pTS->anOutput[iOut] = nMerge;
1.127346 +        break;
1.127347 +      }else{
1.127348 +        char *aNew;
1.127349 +        int nNew;
1.127350 +
1.127351 +        int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, 
1.127352 +            pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
1.127353 +        );
1.127354 +        if( rc!=SQLITE_OK ){
1.127355 +          if( aMerge!=aDoclist ) sqlite3_free(aMerge);
1.127356 +          return rc;
1.127357 +        }
1.127358 +
1.127359 +        if( aMerge!=aDoclist ) sqlite3_free(aMerge);
1.127360 +        sqlite3_free(pTS->aaOutput[iOut]);
1.127361 +        pTS->aaOutput[iOut] = 0;
1.127362 +  
1.127363 +        aMerge = aNew;
1.127364 +        nMerge = nNew;
1.127365 +        if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
1.127366 +          pTS->aaOutput[iOut] = aMerge;
1.127367 +          pTS->anOutput[iOut] = nMerge;
1.127368 +        }
1.127369 +      }
1.127370 +    }
1.127371 +  }
1.127372 +  return SQLITE_OK;
1.127373 +}
1.127374 +
1.127375 +/*
1.127376 +** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
1.127377 +*/
1.127378 +static int fts3SegReaderCursorAppend(
1.127379 +  Fts3MultiSegReader *pCsr, 
1.127380 +  Fts3SegReader *pNew
1.127381 +){
1.127382 +  if( (pCsr->nSegment%16)==0 ){
1.127383 +    Fts3SegReader **apNew;
1.127384 +    int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
1.127385 +    apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
1.127386 +    if( !apNew ){
1.127387 +      sqlite3Fts3SegReaderFree(pNew);
1.127388 +      return SQLITE_NOMEM;
1.127389 +    }
1.127390 +    pCsr->apSegment = apNew;
1.127391 +  }
1.127392 +  pCsr->apSegment[pCsr->nSegment++] = pNew;
1.127393 +  return SQLITE_OK;
1.127394 +}
1.127395 +
1.127396 +/*
1.127397 +** Add seg-reader objects to the Fts3MultiSegReader object passed as the
1.127398 +** 8th argument.
1.127399 +**
1.127400 +** This function returns SQLITE_OK if successful, or an SQLite error code
1.127401 +** otherwise.
1.127402 +*/
1.127403 +static int fts3SegReaderCursor(
1.127404 +  Fts3Table *p,                   /* FTS3 table handle */
1.127405 +  int iLangid,                    /* Language id */
1.127406 +  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
1.127407 +  int iLevel,                     /* Level of segments to scan */
1.127408 +  const char *zTerm,              /* Term to query for */
1.127409 +  int nTerm,                      /* Size of zTerm in bytes */
1.127410 +  int isPrefix,                   /* True for a prefix search */
1.127411 +  int isScan,                     /* True to scan from zTerm to EOF */
1.127412 +  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
1.127413 +){
1.127414 +  int rc = SQLITE_OK;             /* Error code */
1.127415 +  sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
1.127416 +  int rc2;                        /* Result of sqlite3_reset() */
1.127417 +
1.127418 +  /* If iLevel is less than 0 and this is not a scan, include a seg-reader 
1.127419 +  ** for the pending-terms. If this is a scan, then this call must be being
1.127420 +  ** made by an fts4aux module, not an FTS table. In this case calling
1.127421 +  ** Fts3SegReaderPending might segfault, as the data structures used by 
1.127422 +  ** fts4aux are not completely populated. So it's easiest to filter these
1.127423 +  ** calls out here.  */
1.127424 +  if( iLevel<0 && p->aIndex ){
1.127425 +    Fts3SegReader *pSeg = 0;
1.127426 +    rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
1.127427 +    if( rc==SQLITE_OK && pSeg ){
1.127428 +      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
1.127429 +    }
1.127430 +  }
1.127431 +
1.127432 +  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
1.127433 +    if( rc==SQLITE_OK ){
1.127434 +      rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
1.127435 +    }
1.127436 +
1.127437 +    while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
1.127438 +      Fts3SegReader *pSeg = 0;
1.127439 +
1.127440 +      /* Read the values returned by the SELECT into local variables. */
1.127441 +      sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
1.127442 +      sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
1.127443 +      sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
1.127444 +      int nRoot = sqlite3_column_bytes(pStmt, 4);
1.127445 +      char const *zRoot = sqlite3_column_blob(pStmt, 4);
1.127446 +
1.127447 +      /* If zTerm is not NULL, and this segment is not stored entirely on its
1.127448 +      ** root node, the range of leaves scanned can be reduced. Do this. */
1.127449 +      if( iStartBlock && zTerm ){
1.127450 +        sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
1.127451 +        rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
1.127452 +        if( rc!=SQLITE_OK ) goto finished;
1.127453 +        if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
1.127454 +      }
1.127455 + 
1.127456 +      rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, 
1.127457 +          (isPrefix==0 && isScan==0),
1.127458 +          iStartBlock, iLeavesEndBlock, 
1.127459 +          iEndBlock, zRoot, nRoot, &pSeg
1.127460 +      );
1.127461 +      if( rc!=SQLITE_OK ) goto finished;
1.127462 +      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
1.127463 +    }
1.127464 +  }
1.127465 +
1.127466 + finished:
1.127467 +  rc2 = sqlite3_reset(pStmt);
1.127468 +  if( rc==SQLITE_DONE ) rc = rc2;
1.127469 +
1.127470 +  return rc;
1.127471 +}
1.127472 +
1.127473 +/*
1.127474 +** Set up a cursor object for iterating through a full-text index or a 
1.127475 +** single level therein.
1.127476 +*/
1.127477 +SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
1.127478 +  Fts3Table *p,                   /* FTS3 table handle */
1.127479 +  int iLangid,                    /* Language-id to search */
1.127480 +  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
1.127481 +  int iLevel,                     /* Level of segments to scan */
1.127482 +  const char *zTerm,              /* Term to query for */
1.127483 +  int nTerm,                      /* Size of zTerm in bytes */
1.127484 +  int isPrefix,                   /* True for a prefix search */
1.127485 +  int isScan,                     /* True to scan from zTerm to EOF */
1.127486 +  Fts3MultiSegReader *pCsr       /* Cursor object to populate */
1.127487 +){
1.127488 +  assert( iIndex>=0 && iIndex<p->nIndex );
1.127489 +  assert( iLevel==FTS3_SEGCURSOR_ALL
1.127490 +      ||  iLevel==FTS3_SEGCURSOR_PENDING 
1.127491 +      ||  iLevel>=0
1.127492 +  );
1.127493 +  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
1.127494 +  assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
1.127495 +  assert( isPrefix==0 || isScan==0 );
1.127496 +
1.127497 +  memset(pCsr, 0, sizeof(Fts3MultiSegReader));
1.127498 +  return fts3SegReaderCursor(
1.127499 +      p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
1.127500 +  );
1.127501 +}
1.127502 +
1.127503 +/*
1.127504 +** In addition to its current configuration, have the Fts3MultiSegReader
1.127505 +** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
1.127506 +**
1.127507 +** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
1.127508 +*/
1.127509 +static int fts3SegReaderCursorAddZero(
1.127510 +  Fts3Table *p,                   /* FTS virtual table handle */
1.127511 +  int iLangid,
1.127512 +  const char *zTerm,              /* Term to scan doclist of */
1.127513 +  int nTerm,                      /* Number of bytes in zTerm */
1.127514 +  Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
1.127515 +){
1.127516 +  return fts3SegReaderCursor(p, 
1.127517 +      iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
1.127518 +  );
1.127519 +}
1.127520 +
1.127521 +/*
1.127522 +** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
1.127523 +** if isPrefix is true, to scan the doclist for all terms for which 
1.127524 +** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
1.127525 +** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
1.127526 +** an SQLite error code.
1.127527 +**
1.127528 +** It is the responsibility of the caller to free this object by eventually
1.127529 +** passing it to fts3SegReaderCursorFree() 
1.127530 +**
1.127531 +** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
1.127532 +** Output parameter *ppSegcsr is set to 0 if an error occurs.
1.127533 +*/
1.127534 +static int fts3TermSegReaderCursor(
1.127535 +  Fts3Cursor *pCsr,               /* Virtual table cursor handle */
1.127536 +  const char *zTerm,              /* Term to query for */
1.127537 +  int nTerm,                      /* Size of zTerm in bytes */
1.127538 +  int isPrefix,                   /* True for a prefix search */
1.127539 +  Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
1.127540 +){
1.127541 +  Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
1.127542 +  int rc = SQLITE_NOMEM;          /* Return code */
1.127543 +
1.127544 +  pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
1.127545 +  if( pSegcsr ){
1.127546 +    int i;
1.127547 +    int bFound = 0;               /* True once an index has been found */
1.127548 +    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
1.127549 +
1.127550 +    if( isPrefix ){
1.127551 +      for(i=1; bFound==0 && i<p->nIndex; i++){
1.127552 +        if( p->aIndex[i].nPrefix==nTerm ){
1.127553 +          bFound = 1;
1.127554 +          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
1.127555 +              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
1.127556 +          );
1.127557 +          pSegcsr->bLookup = 1;
1.127558 +        }
1.127559 +      }
1.127560 +
1.127561 +      for(i=1; bFound==0 && i<p->nIndex; i++){
1.127562 +        if( p->aIndex[i].nPrefix==nTerm+1 ){
1.127563 +          bFound = 1;
1.127564 +          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
1.127565 +              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
1.127566 +          );
1.127567 +          if( rc==SQLITE_OK ){
1.127568 +            rc = fts3SegReaderCursorAddZero(
1.127569 +                p, pCsr->iLangid, zTerm, nTerm, pSegcsr
1.127570 +            );
1.127571 +          }
1.127572 +        }
1.127573 +      }
1.127574 +    }
1.127575 +
1.127576 +    if( bFound==0 ){
1.127577 +      rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
1.127578 +          0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
1.127579 +      );
1.127580 +      pSegcsr->bLookup = !isPrefix;
1.127581 +    }
1.127582 +  }
1.127583 +
1.127584 +  *ppSegcsr = pSegcsr;
1.127585 +  return rc;
1.127586 +}
1.127587 +
1.127588 +/*
1.127589 +** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
1.127590 +*/
1.127591 +static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
1.127592 +  sqlite3Fts3SegReaderFinish(pSegcsr);
1.127593 +  sqlite3_free(pSegcsr);
1.127594 +}
1.127595 +
1.127596 +/*
1.127597 +** This function retrieves the doclist for the specified term (or term
1.127598 +** prefix) from the database.
1.127599 +*/
1.127600 +static int fts3TermSelect(
1.127601 +  Fts3Table *p,                   /* Virtual table handle */
1.127602 +  Fts3PhraseToken *pTok,          /* Token to query for */
1.127603 +  int iColumn,                    /* Column to query (or -ve for all columns) */
1.127604 +  int *pnOut,                     /* OUT: Size of buffer at *ppOut */
1.127605 +  char **ppOut                    /* OUT: Malloced result buffer */
1.127606 +){
1.127607 +  int rc;                         /* Return code */
1.127608 +  Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
1.127609 +  TermSelect tsc;                 /* Object for pair-wise doclist merging */
1.127610 +  Fts3SegFilter filter;           /* Segment term filter configuration */
1.127611 +
1.127612 +  pSegcsr = pTok->pSegcsr;
1.127613 +  memset(&tsc, 0, sizeof(TermSelect));
1.127614 +
1.127615 +  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
1.127616 +        | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
1.127617 +        | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
1.127618 +        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
1.127619 +  filter.iCol = iColumn;
1.127620 +  filter.zTerm = pTok->z;
1.127621 +  filter.nTerm = pTok->n;
1.127622 +
1.127623 +  rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
1.127624 +  while( SQLITE_OK==rc
1.127625 +      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) 
1.127626 +  ){
1.127627 +    rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
1.127628 +  }
1.127629 +
1.127630 +  if( rc==SQLITE_OK ){
1.127631 +    rc = fts3TermSelectFinishMerge(p, &tsc);
1.127632 +  }
1.127633 +  if( rc==SQLITE_OK ){
1.127634 +    *ppOut = tsc.aaOutput[0];
1.127635 +    *pnOut = tsc.anOutput[0];
1.127636 +  }else{
1.127637 +    int i;
1.127638 +    for(i=0; i<SizeofArray(tsc.aaOutput); i++){
1.127639 +      sqlite3_free(tsc.aaOutput[i]);
1.127640 +    }
1.127641 +  }
1.127642 +
1.127643 +  fts3SegReaderCursorFree(pSegcsr);
1.127644 +  pTok->pSegcsr = 0;
1.127645 +  return rc;
1.127646 +}
1.127647 +
1.127648 +/*
1.127649 +** This function counts the total number of docids in the doclist stored
1.127650 +** in buffer aList[], size nList bytes.
1.127651 +**
1.127652 +** If the isPoslist argument is true, then it is assumed that the doclist
1.127653 +** contains a position-list following each docid. Otherwise, it is assumed
1.127654 +** that the doclist is simply a list of docids stored as delta encoded 
1.127655 +** varints.
1.127656 +*/
1.127657 +static int fts3DoclistCountDocids(char *aList, int nList){
1.127658 +  int nDoc = 0;                   /* Return value */
1.127659 +  if( aList ){
1.127660 +    char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
1.127661 +    char *p = aList;              /* Cursor */
1.127662 +    while( p<aEnd ){
1.127663 +      nDoc++;
1.127664 +      while( (*p++)&0x80 );     /* Skip docid varint */
1.127665 +      fts3PoslistCopy(0, &p);   /* Skip over position list */
1.127666 +    }
1.127667 +  }
1.127668 +
1.127669 +  return nDoc;
1.127670 +}
1.127671 +
1.127672 +/*
1.127673 +** Advance the cursor to the next row in the %_content table that
1.127674 +** matches the search criteria.  For a MATCH search, this will be
1.127675 +** the next row that matches. For a full-table scan, this will be
1.127676 +** simply the next row in the %_content table.  For a docid lookup,
1.127677 +** this routine simply sets the EOF flag.
1.127678 +**
1.127679 +** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
1.127680 +** even if we reach end-of-file.  The fts3EofMethod() will be called
1.127681 +** subsequently to determine whether or not an EOF was hit.
1.127682 +*/
1.127683 +static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
1.127684 +  int rc;
1.127685 +  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
1.127686 +  if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
1.127687 +    if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
1.127688 +      pCsr->isEof = 1;
1.127689 +      rc = sqlite3_reset(pCsr->pStmt);
1.127690 +    }else{
1.127691 +      pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
1.127692 +      rc = SQLITE_OK;
1.127693 +    }
1.127694 +  }else{
1.127695 +    rc = fts3EvalNext((Fts3Cursor *)pCursor);
1.127696 +  }
1.127697 +  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
1.127698 +  return rc;
1.127699 +}
1.127700 +
1.127701 +/*
1.127702 +** The following are copied from sqliteInt.h.
1.127703 +**
1.127704 +** Constants for the largest and smallest possible 64-bit signed integers.
1.127705 +** These macros are designed to work correctly on both 32-bit and 64-bit
1.127706 +** compilers.
1.127707 +*/
1.127708 +#ifndef SQLITE_AMALGAMATION
1.127709 +# define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
1.127710 +# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
1.127711 +#endif
1.127712 +
1.127713 +/*
1.127714 +** If the numeric type of argument pVal is "integer", then return it
1.127715 +** converted to a 64-bit signed integer. Otherwise, return a copy of
1.127716 +** the second parameter, iDefault.
1.127717 +*/
1.127718 +static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
1.127719 +  if( pVal ){
1.127720 +    int eType = sqlite3_value_numeric_type(pVal);
1.127721 +    if( eType==SQLITE_INTEGER ){
1.127722 +      return sqlite3_value_int64(pVal);
1.127723 +    }
1.127724 +  }
1.127725 +  return iDefault;
1.127726 +}
1.127727 +
1.127728 +/*
1.127729 +** This is the xFilter interface for the virtual table.  See
1.127730 +** the virtual table xFilter method documentation for additional
1.127731 +** information.
1.127732 +**
1.127733 +** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
1.127734 +** the %_content table.
1.127735 +**
1.127736 +** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
1.127737 +** in the %_content table.
1.127738 +**
1.127739 +** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
1.127740 +** column on the left-hand side of the MATCH operator is column
1.127741 +** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
1.127742 +** side of the MATCH operator.
1.127743 +*/
1.127744 +static int fts3FilterMethod(
1.127745 +  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
1.127746 +  int idxNum,                     /* Strategy index */
1.127747 +  const char *idxStr,             /* Unused */
1.127748 +  int nVal,                       /* Number of elements in apVal */
1.127749 +  sqlite3_value **apVal           /* Arguments for the indexing scheme */
1.127750 +){
1.127751 +  int rc;
1.127752 +  char *zSql;                     /* SQL statement used to access %_content */
1.127753 +  int eSearch;
1.127754 +  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
1.127755 +  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
1.127756 +
1.127757 +  sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */
1.127758 +  sqlite3_value *pLangid = 0;     /* The "langid = ?" constraint, if any */
1.127759 +  sqlite3_value *pDocidGe = 0;    /* The "docid >= ?" constraint, if any */
1.127760 +  sqlite3_value *pDocidLe = 0;    /* The "docid <= ?" constraint, if any */
1.127761 +  int iIdx;
1.127762 +
1.127763 +  UNUSED_PARAMETER(idxStr);
1.127764 +  UNUSED_PARAMETER(nVal);
1.127765 +
1.127766 +  eSearch = (idxNum & 0x0000FFFF);
1.127767 +  assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
1.127768 +  assert( p->pSegments==0 );
1.127769 +
1.127770 +  /* Collect arguments into local variables */
1.127771 +  iIdx = 0;
1.127772 +  if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
1.127773 +  if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
1.127774 +  if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
1.127775 +  if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
1.127776 +  assert( iIdx==nVal );
1.127777 +
1.127778 +  /* In case the cursor has been used before, clear it now. */
1.127779 +  sqlite3_finalize(pCsr->pStmt);
1.127780 +  sqlite3_free(pCsr->aDoclist);
1.127781 +  sqlite3Fts3ExprFree(pCsr->pExpr);
1.127782 +  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
1.127783 +
1.127784 +  /* Set the lower and upper bounds on docids to return */
1.127785 +  pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
1.127786 +  pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
1.127787 +
1.127788 +  if( idxStr ){
1.127789 +    pCsr->bDesc = (idxStr[0]=='D');
1.127790 +  }else{
1.127791 +    pCsr->bDesc = p->bDescIdx;
1.127792 +  }
1.127793 +  pCsr->eSearch = (i16)eSearch;
1.127794 +
1.127795 +  if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
1.127796 +    int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
1.127797 +    const char *zQuery = (const char *)sqlite3_value_text(pCons);
1.127798 +
1.127799 +    if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
1.127800 +      return SQLITE_NOMEM;
1.127801 +    }
1.127802 +
1.127803 +    pCsr->iLangid = 0;
1.127804 +    if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
1.127805 +
1.127806 +    assert( p->base.zErrMsg==0 );
1.127807 +    rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
1.127808 +        p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr, 
1.127809 +        &p->base.zErrMsg
1.127810 +    );
1.127811 +    if( rc!=SQLITE_OK ){
1.127812 +      return rc;
1.127813 +    }
1.127814 +
1.127815 +    rc = fts3EvalStart(pCsr);
1.127816 +    sqlite3Fts3SegmentsClose(p);
1.127817 +    if( rc!=SQLITE_OK ) return rc;
1.127818 +    pCsr->pNextId = pCsr->aDoclist;
1.127819 +    pCsr->iPrevId = 0;
1.127820 +  }
1.127821 +
1.127822 +  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
1.127823 +  ** statement loops through all rows of the %_content table. For a
1.127824 +  ** full-text query or docid lookup, the statement retrieves a single
1.127825 +  ** row by docid.
1.127826 +  */
1.127827 +  if( eSearch==FTS3_FULLSCAN_SEARCH ){
1.127828 +    zSql = sqlite3_mprintf(
1.127829 +        "SELECT %s ORDER BY rowid %s",
1.127830 +        p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
1.127831 +    );
1.127832 +    if( zSql ){
1.127833 +      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
1.127834 +      sqlite3_free(zSql);
1.127835 +    }else{
1.127836 +      rc = SQLITE_NOMEM;
1.127837 +    }
1.127838 +  }else if( eSearch==FTS3_DOCID_SEARCH ){
1.127839 +    rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
1.127840 +    if( rc==SQLITE_OK ){
1.127841 +      rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
1.127842 +    }
1.127843 +  }
1.127844 +  if( rc!=SQLITE_OK ) return rc;
1.127845 +
1.127846 +  return fts3NextMethod(pCursor);
1.127847 +}
1.127848 +
1.127849 +/* 
1.127850 +** This is the xEof method of the virtual table. SQLite calls this 
1.127851 +** routine to find out if it has reached the end of a result set.
1.127852 +*/
1.127853 +static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
1.127854 +  return ((Fts3Cursor *)pCursor)->isEof;
1.127855 +}
1.127856 +
1.127857 +/* 
1.127858 +** This is the xRowid method. The SQLite core calls this routine to
1.127859 +** retrieve the rowid for the current row of the result set. fts3
1.127860 +** exposes %_content.docid as the rowid for the virtual table. The
1.127861 +** rowid should be written to *pRowid.
1.127862 +*/
1.127863 +static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
1.127864 +  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
1.127865 +  *pRowid = pCsr->iPrevId;
1.127866 +  return SQLITE_OK;
1.127867 +}
1.127868 +
1.127869 +/* 
1.127870 +** This is the xColumn method, called by SQLite to request a value from
1.127871 +** the row that the supplied cursor currently points to.
1.127872 +**
1.127873 +** If:
1.127874 +**
1.127875 +**   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
1.127876 +**   (iCol == p->nColumn)   -> Magic column with the same name as the table.
1.127877 +**   (iCol == p->nColumn+1) -> Docid column
1.127878 +**   (iCol == p->nColumn+2) -> Langid column
1.127879 +*/
1.127880 +static int fts3ColumnMethod(
1.127881 +  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
1.127882 +  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
1.127883 +  int iCol                        /* Index of column to read value from */
1.127884 +){
1.127885 +  int rc = SQLITE_OK;             /* Return Code */
1.127886 +  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
1.127887 +  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
1.127888 +
1.127889 +  /* The column value supplied by SQLite must be in range. */
1.127890 +  assert( iCol>=0 && iCol<=p->nColumn+2 );
1.127891 +
1.127892 +  if( iCol==p->nColumn+1 ){
1.127893 +    /* This call is a request for the "docid" column. Since "docid" is an 
1.127894 +    ** alias for "rowid", use the xRowid() method to obtain the value.
1.127895 +    */
1.127896 +    sqlite3_result_int64(pCtx, pCsr->iPrevId);
1.127897 +  }else if( iCol==p->nColumn ){
1.127898 +    /* The extra column whose name is the same as the table.
1.127899 +    ** Return a blob which is a pointer to the cursor.  */
1.127900 +    sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
1.127901 +  }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
1.127902 +    sqlite3_result_int64(pCtx, pCsr->iLangid);
1.127903 +  }else{
1.127904 +    /* The requested column is either a user column (one that contains 
1.127905 +    ** indexed data), or the language-id column.  */
1.127906 +    rc = fts3CursorSeek(0, pCsr);
1.127907 +
1.127908 +    if( rc==SQLITE_OK ){
1.127909 +      if( iCol==p->nColumn+2 ){
1.127910 +        int iLangid = 0;
1.127911 +        if( p->zLanguageid ){
1.127912 +          iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
1.127913 +        }
1.127914 +        sqlite3_result_int(pCtx, iLangid);
1.127915 +      }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
1.127916 +        sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
1.127917 +      }
1.127918 +    }
1.127919 +  }
1.127920 +
1.127921 +  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
1.127922 +  return rc;
1.127923 +}
1.127924 +
1.127925 +/* 
1.127926 +** This function is the implementation of the xUpdate callback used by 
1.127927 +** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
1.127928 +** inserted, updated or deleted.
1.127929 +*/
1.127930 +static int fts3UpdateMethod(
1.127931 +  sqlite3_vtab *pVtab,            /* Virtual table handle */
1.127932 +  int nArg,                       /* Size of argument array */
1.127933 +  sqlite3_value **apVal,          /* Array of arguments */
1.127934 +  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
1.127935 +){
1.127936 +  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
1.127937 +}
1.127938 +
1.127939 +/*
1.127940 +** Implementation of xSync() method. Flush the contents of the pending-terms
1.127941 +** hash-table to the database.
1.127942 +*/
1.127943 +static int fts3SyncMethod(sqlite3_vtab *pVtab){
1.127944 +
1.127945 +  /* Following an incremental-merge operation, assuming that the input
1.127946 +  ** segments are not completely consumed (the usual case), they are updated
1.127947 +  ** in place to remove the entries that have already been merged. This
1.127948 +  ** involves updating the leaf block that contains the smallest unmerged
1.127949 +  ** entry and each block (if any) between the leaf and the root node. So
1.127950 +  ** if the height of the input segment b-trees is N, and input segments
1.127951 +  ** are merged eight at a time, updating the input segments at the end
1.127952 +  ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
1.127953 +  ** small - often between 0 and 2. So the overhead of the incremental
1.127954 +  ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
1.127955 +  ** dwarfing the actual productive work accomplished, the incremental merge
1.127956 +  ** is only attempted if it will write at least 64 leaf blocks. Hence
1.127957 +  ** nMinMerge.
1.127958 +  **
1.127959 +  ** Of course, updating the input segments also involves deleting a bunch
1.127960 +  ** of blocks from the segments table. But this is not considered overhead
1.127961 +  ** as it would also be required by a crisis-merge that used the same input 
1.127962 +  ** segments.
1.127963 +  */
1.127964 +  const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
1.127965 +
1.127966 +  Fts3Table *p = (Fts3Table*)pVtab;
1.127967 +  int rc = sqlite3Fts3PendingTermsFlush(p);
1.127968 +
1.127969 +  if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){
1.127970 +    int mxLevel = 0;              /* Maximum relative level value in db */
1.127971 +    int A;                        /* Incr-merge parameter A */
1.127972 +
1.127973 +    rc = sqlite3Fts3MaxLevel(p, &mxLevel);
1.127974 +    assert( rc==SQLITE_OK || mxLevel==0 );
1.127975 +    A = p->nLeafAdd * mxLevel;
1.127976 +    A += (A/2);
1.127977 +    if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8);
1.127978 +  }
1.127979 +  sqlite3Fts3SegmentsClose(p);
1.127980 +  return rc;
1.127981 +}
1.127982 +
1.127983 +/*
1.127984 +** Implementation of xBegin() method. This is a no-op.
1.127985 +*/
1.127986 +static int fts3BeginMethod(sqlite3_vtab *pVtab){
1.127987 +  Fts3Table *p = (Fts3Table*)pVtab;
1.127988 +  UNUSED_PARAMETER(pVtab);
1.127989 +  assert( p->pSegments==0 );
1.127990 +  assert( p->nPendingData==0 );
1.127991 +  assert( p->inTransaction!=1 );
1.127992 +  TESTONLY( p->inTransaction = 1 );
1.127993 +  TESTONLY( p->mxSavepoint = -1; );
1.127994 +  p->nLeafAdd = 0;
1.127995 +  return SQLITE_OK;
1.127996 +}
1.127997 +
1.127998 +/*
1.127999 +** Implementation of xCommit() method. This is a no-op. The contents of
1.128000 +** the pending-terms hash-table have already been flushed into the database
1.128001 +** by fts3SyncMethod().
1.128002 +*/
1.128003 +static int fts3CommitMethod(sqlite3_vtab *pVtab){
1.128004 +  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
1.128005 +  UNUSED_PARAMETER(pVtab);
1.128006 +  assert( p->nPendingData==0 );
1.128007 +  assert( p->inTransaction!=0 );
1.128008 +  assert( p->pSegments==0 );
1.128009 +  TESTONLY( p->inTransaction = 0 );
1.128010 +  TESTONLY( p->mxSavepoint = -1; );
1.128011 +  return SQLITE_OK;
1.128012 +}
1.128013 +
1.128014 +/*
1.128015 +** Implementation of xRollback(). Discard the contents of the pending-terms
1.128016 +** hash-table. Any changes made to the database are reverted by SQLite.
1.128017 +*/
1.128018 +static int fts3RollbackMethod(sqlite3_vtab *pVtab){
1.128019 +  Fts3Table *p = (Fts3Table*)pVtab;
1.128020 +  sqlite3Fts3PendingTermsClear(p);
1.128021 +  assert( p->inTransaction!=0 );
1.128022 +  TESTONLY( p->inTransaction = 0 );
1.128023 +  TESTONLY( p->mxSavepoint = -1; );
1.128024 +  return SQLITE_OK;
1.128025 +}
1.128026 +
1.128027 +/*
1.128028 +** When called, *ppPoslist must point to the byte immediately following the
1.128029 +** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
1.128030 +** moves *ppPoslist so that it instead points to the first byte of the
1.128031 +** same position list.
1.128032 +*/
1.128033 +static void fts3ReversePoslist(char *pStart, char **ppPoslist){
1.128034 +  char *p = &(*ppPoslist)[-2];
1.128035 +  char c = 0;
1.128036 +
1.128037 +  while( p>pStart && (c=*p--)==0 );
1.128038 +  while( p>pStart && (*p & 0x80) | c ){ 
1.128039 +    c = *p--; 
1.128040 +  }
1.128041 +  if( p>pStart ){ p = &p[2]; }
1.128042 +  while( *p++&0x80 );
1.128043 +  *ppPoslist = p;
1.128044 +}
1.128045 +
1.128046 +/*
1.128047 +** Helper function used by the implementation of the overloaded snippet(),
1.128048 +** offsets() and optimize() SQL functions.
1.128049 +**
1.128050 +** If the value passed as the third argument is a blob of size
1.128051 +** sizeof(Fts3Cursor*), then the blob contents are copied to the 
1.128052 +** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
1.128053 +** message is written to context pContext and SQLITE_ERROR returned. The
1.128054 +** string passed via zFunc is used as part of the error message.
1.128055 +*/
1.128056 +static int fts3FunctionArg(
1.128057 +  sqlite3_context *pContext,      /* SQL function call context */
1.128058 +  const char *zFunc,              /* Function name */
1.128059 +  sqlite3_value *pVal,            /* argv[0] passed to function */
1.128060 +  Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
1.128061 +){
1.128062 +  Fts3Cursor *pRet;
1.128063 +  if( sqlite3_value_type(pVal)!=SQLITE_BLOB 
1.128064 +   || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
1.128065 +  ){
1.128066 +    char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
1.128067 +    sqlite3_result_error(pContext, zErr, -1);
1.128068 +    sqlite3_free(zErr);
1.128069 +    return SQLITE_ERROR;
1.128070 +  }
1.128071 +  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
1.128072 +  *ppCsr = pRet;
1.128073 +  return SQLITE_OK;
1.128074 +}
1.128075 +
1.128076 +/*
1.128077 +** Implementation of the snippet() function for FTS3
1.128078 +*/
1.128079 +static void fts3SnippetFunc(
1.128080 +  sqlite3_context *pContext,      /* SQLite function call context */
1.128081 +  int nVal,                       /* Size of apVal[] array */
1.128082 +  sqlite3_value **apVal           /* Array of arguments */
1.128083 +){
1.128084 +  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
1.128085 +  const char *zStart = "<b>";
1.128086 +  const char *zEnd = "</b>";
1.128087 +  const char *zEllipsis = "<b>...</b>";
1.128088 +  int iCol = -1;
1.128089 +  int nToken = 15;                /* Default number of tokens in snippet */
1.128090 +
1.128091 +  /* There must be at least one argument passed to this function (otherwise
1.128092 +  ** the non-overloaded version would have been called instead of this one).
1.128093 +  */
1.128094 +  assert( nVal>=1 );
1.128095 +
1.128096 +  if( nVal>6 ){
1.128097 +    sqlite3_result_error(pContext, 
1.128098 +        "wrong number of arguments to function snippet()", -1);
1.128099 +    return;
1.128100 +  }
1.128101 +  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
1.128102 +
1.128103 +  switch( nVal ){
1.128104 +    case 6: nToken = sqlite3_value_int(apVal[5]);
1.128105 +    case 5: iCol = sqlite3_value_int(apVal[4]);
1.128106 +    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
1.128107 +    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
1.128108 +    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
1.128109 +  }
1.128110 +  if( !zEllipsis || !zEnd || !zStart ){
1.128111 +    sqlite3_result_error_nomem(pContext);
1.128112 +  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
1.128113 +    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
1.128114 +  }
1.128115 +}
1.128116 +
1.128117 +/*
1.128118 +** Implementation of the offsets() function for FTS3
1.128119 +*/
1.128120 +static void fts3OffsetsFunc(
1.128121 +  sqlite3_context *pContext,      /* SQLite function call context */
1.128122 +  int nVal,                       /* Size of argument array */
1.128123 +  sqlite3_value **apVal           /* Array of arguments */
1.128124 +){
1.128125 +  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
1.128126 +
1.128127 +  UNUSED_PARAMETER(nVal);
1.128128 +
1.128129 +  assert( nVal==1 );
1.128130 +  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
1.128131 +  assert( pCsr );
1.128132 +  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
1.128133 +    sqlite3Fts3Offsets(pContext, pCsr);
1.128134 +  }
1.128135 +}
1.128136 +
1.128137 +/* 
1.128138 +** Implementation of the special optimize() function for FTS3. This 
1.128139 +** function merges all segments in the database to a single segment.
1.128140 +** Example usage is:
1.128141 +**
1.128142 +**   SELECT optimize(t) FROM t LIMIT 1;
1.128143 +**
1.128144 +** where 't' is the name of an FTS3 table.
1.128145 +*/
1.128146 +static void fts3OptimizeFunc(
1.128147 +  sqlite3_context *pContext,      /* SQLite function call context */
1.128148 +  int nVal,                       /* Size of argument array */
1.128149 +  sqlite3_value **apVal           /* Array of arguments */
1.128150 +){
1.128151 +  int rc;                         /* Return code */
1.128152 +  Fts3Table *p;                   /* Virtual table handle */
1.128153 +  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
1.128154 +
1.128155 +  UNUSED_PARAMETER(nVal);
1.128156 +
1.128157 +  assert( nVal==1 );
1.128158 +  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
1.128159 +  p = (Fts3Table *)pCursor->base.pVtab;
1.128160 +  assert( p );
1.128161 +
1.128162 +  rc = sqlite3Fts3Optimize(p);
1.128163 +
1.128164 +  switch( rc ){
1.128165 +    case SQLITE_OK:
1.128166 +      sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
1.128167 +      break;
1.128168 +    case SQLITE_DONE:
1.128169 +      sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
1.128170 +      break;
1.128171 +    default:
1.128172 +      sqlite3_result_error_code(pContext, rc);
1.128173 +      break;
1.128174 +  }
1.128175 +}
1.128176 +
1.128177 +/*
1.128178 +** Implementation of the matchinfo() function for FTS3
1.128179 +*/
1.128180 +static void fts3MatchinfoFunc(
1.128181 +  sqlite3_context *pContext,      /* SQLite function call context */
1.128182 +  int nVal,                       /* Size of argument array */
1.128183 +  sqlite3_value **apVal           /* Array of arguments */
1.128184 +){
1.128185 +  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
1.128186 +  assert( nVal==1 || nVal==2 );
1.128187 +  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
1.128188 +    const char *zArg = 0;
1.128189 +    if( nVal>1 ){
1.128190 +      zArg = (const char *)sqlite3_value_text(apVal[1]);
1.128191 +    }
1.128192 +    sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
1.128193 +  }
1.128194 +}
1.128195 +
1.128196 +/*
1.128197 +** This routine implements the xFindFunction method for the FTS3
1.128198 +** virtual table.
1.128199 +*/
1.128200 +static int fts3FindFunctionMethod(
1.128201 +  sqlite3_vtab *pVtab,            /* Virtual table handle */
1.128202 +  int nArg,                       /* Number of SQL function arguments */
1.128203 +  const char *zName,              /* Name of SQL function */
1.128204 +  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
1.128205 +  void **ppArg                    /* Unused */
1.128206 +){
1.128207 +  struct Overloaded {
1.128208 +    const char *zName;
1.128209 +    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
1.128210 +  } aOverload[] = {
1.128211 +    { "snippet", fts3SnippetFunc },
1.128212 +    { "offsets", fts3OffsetsFunc },
1.128213 +    { "optimize", fts3OptimizeFunc },
1.128214 +    { "matchinfo", fts3MatchinfoFunc },
1.128215 +  };
1.128216 +  int i;                          /* Iterator variable */
1.128217 +
1.128218 +  UNUSED_PARAMETER(pVtab);
1.128219 +  UNUSED_PARAMETER(nArg);
1.128220 +  UNUSED_PARAMETER(ppArg);
1.128221 +
1.128222 +  for(i=0; i<SizeofArray(aOverload); i++){
1.128223 +    if( strcmp(zName, aOverload[i].zName)==0 ){
1.128224 +      *pxFunc = aOverload[i].xFunc;
1.128225 +      return 1;
1.128226 +    }
1.128227 +  }
1.128228 +
1.128229 +  /* No function of the specified name was found. Return 0. */
1.128230 +  return 0;
1.128231 +}
1.128232 +
1.128233 +/*
1.128234 +** Implementation of FTS3 xRename method. Rename an fts3 table.
1.128235 +*/
1.128236 +static int fts3RenameMethod(
1.128237 +  sqlite3_vtab *pVtab,            /* Virtual table handle */
1.128238 +  const char *zName               /* New name of table */
1.128239 +){
1.128240 +  Fts3Table *p = (Fts3Table *)pVtab;
1.128241 +  sqlite3 *db = p->db;            /* Database connection */
1.128242 +  int rc;                         /* Return Code */
1.128243 +
1.128244 +  /* As it happens, the pending terms table is always empty here. This is
1.128245 +  ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction 
1.128246 +  ** always opens a savepoint transaction. And the xSavepoint() method 
1.128247 +  ** flushes the pending terms table. But leave the (no-op) call to
1.128248 +  ** PendingTermsFlush() in in case that changes.
1.128249 +  */
1.128250 +  assert( p->nPendingData==0 );
1.128251 +  rc = sqlite3Fts3PendingTermsFlush(p);
1.128252 +
1.128253 +  if( p->zContentTbl==0 ){
1.128254 +    fts3DbExec(&rc, db,
1.128255 +      "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
1.128256 +      p->zDb, p->zName, zName
1.128257 +    );
1.128258 +  }
1.128259 +
1.128260 +  if( p->bHasDocsize ){
1.128261 +    fts3DbExec(&rc, db,
1.128262 +      "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
1.128263 +      p->zDb, p->zName, zName
1.128264 +    );
1.128265 +  }
1.128266 +  if( p->bHasStat ){
1.128267 +    fts3DbExec(&rc, db,
1.128268 +      "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
1.128269 +      p->zDb, p->zName, zName
1.128270 +    );
1.128271 +  }
1.128272 +  fts3DbExec(&rc, db,
1.128273 +    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
1.128274 +    p->zDb, p->zName, zName
1.128275 +  );
1.128276 +  fts3DbExec(&rc, db,
1.128277 +    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
1.128278 +    p->zDb, p->zName, zName
1.128279 +  );
1.128280 +  return rc;
1.128281 +}
1.128282 +
1.128283 +/*
1.128284 +** The xSavepoint() method.
1.128285 +**
1.128286 +** Flush the contents of the pending-terms table to disk.
1.128287 +*/
1.128288 +static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
1.128289 +  int rc = SQLITE_OK;
1.128290 +  UNUSED_PARAMETER(iSavepoint);
1.128291 +  assert( ((Fts3Table *)pVtab)->inTransaction );
1.128292 +  assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
1.128293 +  TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
1.128294 +  if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
1.128295 +    rc = fts3SyncMethod(pVtab);
1.128296 +  }
1.128297 +  return rc;
1.128298 +}
1.128299 +
1.128300 +/*
1.128301 +** The xRelease() method.
1.128302 +**
1.128303 +** This is a no-op.
1.128304 +*/
1.128305 +static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
1.128306 +  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
1.128307 +  UNUSED_PARAMETER(iSavepoint);
1.128308 +  UNUSED_PARAMETER(pVtab);
1.128309 +  assert( p->inTransaction );
1.128310 +  assert( p->mxSavepoint >= iSavepoint );
1.128311 +  TESTONLY( p->mxSavepoint = iSavepoint-1 );
1.128312 +  return SQLITE_OK;
1.128313 +}
1.128314 +
1.128315 +/*
1.128316 +** The xRollbackTo() method.
1.128317 +**
1.128318 +** Discard the contents of the pending terms table.
1.128319 +*/
1.128320 +static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
1.128321 +  Fts3Table *p = (Fts3Table*)pVtab;
1.128322 +  UNUSED_PARAMETER(iSavepoint);
1.128323 +  assert( p->inTransaction );
1.128324 +  assert( p->mxSavepoint >= iSavepoint );
1.128325 +  TESTONLY( p->mxSavepoint = iSavepoint );
1.128326 +  sqlite3Fts3PendingTermsClear(p);
1.128327 +  return SQLITE_OK;
1.128328 +}
1.128329 +
1.128330 +static const sqlite3_module fts3Module = {
1.128331 +  /* iVersion      */ 2,
1.128332 +  /* xCreate       */ fts3CreateMethod,
1.128333 +  /* xConnect      */ fts3ConnectMethod,
1.128334 +  /* xBestIndex    */ fts3BestIndexMethod,
1.128335 +  /* xDisconnect   */ fts3DisconnectMethod,
1.128336 +  /* xDestroy      */ fts3DestroyMethod,
1.128337 +  /* xOpen         */ fts3OpenMethod,
1.128338 +  /* xClose        */ fts3CloseMethod,
1.128339 +  /* xFilter       */ fts3FilterMethod,
1.128340 +  /* xNext         */ fts3NextMethod,
1.128341 +  /* xEof          */ fts3EofMethod,
1.128342 +  /* xColumn       */ fts3ColumnMethod,
1.128343 +  /* xRowid        */ fts3RowidMethod,
1.128344 +  /* xUpdate       */ fts3UpdateMethod,
1.128345 +  /* xBegin        */ fts3BeginMethod,
1.128346 +  /* xSync         */ fts3SyncMethod,
1.128347 +  /* xCommit       */ fts3CommitMethod,
1.128348 +  /* xRollback     */ fts3RollbackMethod,
1.128349 +  /* xFindFunction */ fts3FindFunctionMethod,
1.128350 +  /* xRename */       fts3RenameMethod,
1.128351 +  /* xSavepoint    */ fts3SavepointMethod,
1.128352 +  /* xRelease      */ fts3ReleaseMethod,
1.128353 +  /* xRollbackTo   */ fts3RollbackToMethod,
1.128354 +};
1.128355 +
1.128356 +/*
1.128357 +** This function is registered as the module destructor (called when an
1.128358 +** FTS3 enabled database connection is closed). It frees the memory
1.128359 +** allocated for the tokenizer hash table.
1.128360 +*/
1.128361 +static void hashDestroy(void *p){
1.128362 +  Fts3Hash *pHash = (Fts3Hash *)p;
1.128363 +  sqlite3Fts3HashClear(pHash);
1.128364 +  sqlite3_free(pHash);
1.128365 +}
1.128366 +
1.128367 +/*
1.128368 +** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are 
1.128369 +** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
1.128370 +** respectively. The following three forward declarations are for functions
1.128371 +** declared in these files used to retrieve the respective implementations.
1.128372 +**
1.128373 +** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
1.128374 +** to by the argument to point to the "simple" tokenizer implementation.
1.128375 +** And so on.
1.128376 +*/
1.128377 +SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
1.128378 +SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
1.128379 +#ifdef SQLITE_ENABLE_FTS4_UNICODE61
1.128380 +SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
1.128381 +#endif
1.128382 +#ifdef SQLITE_ENABLE_ICU
1.128383 +SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
1.128384 +#endif
1.128385 +
1.128386 +/*
1.128387 +** Initialize the fts3 extension. If this extension is built as part
1.128388 +** of the sqlite library, then this function is called directly by
1.128389 +** SQLite. If fts3 is built as a dynamically loadable extension, this
1.128390 +** function is called by the sqlite3_extension_init() entry point.
1.128391 +*/
1.128392 +SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
1.128393 +  int rc = SQLITE_OK;
1.128394 +  Fts3Hash *pHash = 0;
1.128395 +  const sqlite3_tokenizer_module *pSimple = 0;
1.128396 +  const sqlite3_tokenizer_module *pPorter = 0;
1.128397 +#ifdef SQLITE_ENABLE_FTS4_UNICODE61
1.128398 +  const sqlite3_tokenizer_module *pUnicode = 0;
1.128399 +#endif
1.128400 +
1.128401 +#ifdef SQLITE_ENABLE_ICU
1.128402 +  const sqlite3_tokenizer_module *pIcu = 0;
1.128403 +  sqlite3Fts3IcuTokenizerModule(&pIcu);
1.128404 +#endif
1.128405 +
1.128406 +#ifdef SQLITE_ENABLE_FTS4_UNICODE61
1.128407 +  sqlite3Fts3UnicodeTokenizer(&pUnicode);
1.128408 +#endif
1.128409 +
1.128410 +#ifdef SQLITE_TEST
1.128411 +  rc = sqlite3Fts3InitTerm(db);
1.128412 +  if( rc!=SQLITE_OK ) return rc;
1.128413 +#endif
1.128414 +
1.128415 +  rc = sqlite3Fts3InitAux(db);
1.128416 +  if( rc!=SQLITE_OK ) return rc;
1.128417 +
1.128418 +  sqlite3Fts3SimpleTokenizerModule(&pSimple);
1.128419 +  sqlite3Fts3PorterTokenizerModule(&pPorter);
1.128420 +
1.128421 +  /* Allocate and initialize the hash-table used to store tokenizers. */
1.128422 +  pHash = sqlite3_malloc(sizeof(Fts3Hash));
1.128423 +  if( !pHash ){
1.128424 +    rc = SQLITE_NOMEM;
1.128425 +  }else{
1.128426 +    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
1.128427 +  }
1.128428 +
1.128429 +  /* Load the built-in tokenizers into the hash table */
1.128430 +  if( rc==SQLITE_OK ){
1.128431 +    if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
1.128432 +     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
1.128433 +
1.128434 +#ifdef SQLITE_ENABLE_FTS4_UNICODE61
1.128435 +     || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode) 
1.128436 +#endif
1.128437 +#ifdef SQLITE_ENABLE_ICU
1.128438 +     || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
1.128439 +#endif
1.128440 +    ){
1.128441 +      rc = SQLITE_NOMEM;
1.128442 +    }
1.128443 +  }
1.128444 +
1.128445 +#ifdef SQLITE_TEST
1.128446 +  if( rc==SQLITE_OK ){
1.128447 +    rc = sqlite3Fts3ExprInitTestInterface(db);
1.128448 +  }
1.128449 +#endif
1.128450 +
1.128451 +  /* Create the virtual table wrapper around the hash-table and overload 
1.128452 +  ** the two scalar functions. If this is successful, register the
1.128453 +  ** module with sqlite.
1.128454 +  */
1.128455 +  if( SQLITE_OK==rc 
1.128456 +   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
1.128457 +   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
1.128458 +   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
1.128459 +   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
1.128460 +   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
1.128461 +   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
1.128462 +  ){
1.128463 +    rc = sqlite3_create_module_v2(
1.128464 +        db, "fts3", &fts3Module, (void *)pHash, hashDestroy
1.128465 +    );
1.128466 +    if( rc==SQLITE_OK ){
1.128467 +      rc = sqlite3_create_module_v2(
1.128468 +          db, "fts4", &fts3Module, (void *)pHash, 0
1.128469 +      );
1.128470 +    }
1.128471 +    if( rc==SQLITE_OK ){
1.128472 +      rc = sqlite3Fts3InitTok(db, (void *)pHash);
1.128473 +    }
1.128474 +    return rc;
1.128475 +  }
1.128476 +
1.128477 +
1.128478 +  /* An error has occurred. Delete the hash table and return the error code. */
1.128479 +  assert( rc!=SQLITE_OK );
1.128480 +  if( pHash ){
1.128481 +    sqlite3Fts3HashClear(pHash);
1.128482 +    sqlite3_free(pHash);
1.128483 +  }
1.128484 +  return rc;
1.128485 +}
1.128486 +
1.128487 +/*
1.128488 +** Allocate an Fts3MultiSegReader for each token in the expression headed
1.128489 +** by pExpr. 
1.128490 +**
1.128491 +** An Fts3SegReader object is a cursor that can seek or scan a range of
1.128492 +** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
1.128493 +** Fts3SegReader objects internally to provide an interface to seek or scan
1.128494 +** within the union of all segments of a b-tree. Hence the name.
1.128495 +**
1.128496 +** If the allocated Fts3MultiSegReader just seeks to a single entry in a
1.128497 +** segment b-tree (if the term is not a prefix or it is a prefix for which
1.128498 +** there exists prefix b-tree of the right length) then it may be traversed
1.128499 +** and merged incrementally. Otherwise, it has to be merged into an in-memory 
1.128500 +** doclist and then traversed.
1.128501 +*/
1.128502 +static void fts3EvalAllocateReaders(
1.128503 +  Fts3Cursor *pCsr,               /* FTS cursor handle */
1.128504 +  Fts3Expr *pExpr,                /* Allocate readers for this expression */
1.128505 +  int *pnToken,                   /* OUT: Total number of tokens in phrase. */
1.128506 +  int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
1.128507 +  int *pRc                        /* IN/OUT: Error code */
1.128508 +){
1.128509 +  if( pExpr && SQLITE_OK==*pRc ){
1.128510 +    if( pExpr->eType==FTSQUERY_PHRASE ){
1.128511 +      int i;
1.128512 +      int nToken = pExpr->pPhrase->nToken;
1.128513 +      *pnToken += nToken;
1.128514 +      for(i=0; i<nToken; i++){
1.128515 +        Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
1.128516 +        int rc = fts3TermSegReaderCursor(pCsr, 
1.128517 +            pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
1.128518 +        );
1.128519 +        if( rc!=SQLITE_OK ){
1.128520 +          *pRc = rc;
1.128521 +          return;
1.128522 +        }
1.128523 +      }
1.128524 +      assert( pExpr->pPhrase->iDoclistToken==0 );
1.128525 +      pExpr->pPhrase->iDoclistToken = -1;
1.128526 +    }else{
1.128527 +      *pnOr += (pExpr->eType==FTSQUERY_OR);
1.128528 +      fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
1.128529 +      fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
1.128530 +    }
1.128531 +  }
1.128532 +}
1.128533 +
1.128534 +/*
1.128535 +** Arguments pList/nList contain the doclist for token iToken of phrase p.
1.128536 +** It is merged into the main doclist stored in p->doclist.aAll/nAll.
1.128537 +**
1.128538 +** This function assumes that pList points to a buffer allocated using
1.128539 +** sqlite3_malloc(). This function takes responsibility for eventually
1.128540 +** freeing the buffer.
1.128541 +*/
1.128542 +static void fts3EvalPhraseMergeToken(
1.128543 +  Fts3Table *pTab,                /* FTS Table pointer */
1.128544 +  Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
1.128545 +  int iToken,                     /* Token pList/nList corresponds to */
1.128546 +  char *pList,                    /* Pointer to doclist */
1.128547 +  int nList                       /* Number of bytes in pList */
1.128548 +){
1.128549 +  assert( iToken!=p->iDoclistToken );
1.128550 +
1.128551 +  if( pList==0 ){
1.128552 +    sqlite3_free(p->doclist.aAll);
1.128553 +    p->doclist.aAll = 0;
1.128554 +    p->doclist.nAll = 0;
1.128555 +  }
1.128556 +
1.128557 +  else if( p->iDoclistToken<0 ){
1.128558 +    p->doclist.aAll = pList;
1.128559 +    p->doclist.nAll = nList;
1.128560 +  }
1.128561 +
1.128562 +  else if( p->doclist.aAll==0 ){
1.128563 +    sqlite3_free(pList);
1.128564 +  }
1.128565 +
1.128566 +  else {
1.128567 +    char *pLeft;
1.128568 +    char *pRight;
1.128569 +    int nLeft;
1.128570 +    int nRight;
1.128571 +    int nDiff;
1.128572 +
1.128573 +    if( p->iDoclistToken<iToken ){
1.128574 +      pLeft = p->doclist.aAll;
1.128575 +      nLeft = p->doclist.nAll;
1.128576 +      pRight = pList;
1.128577 +      nRight = nList;
1.128578 +      nDiff = iToken - p->iDoclistToken;
1.128579 +    }else{
1.128580 +      pRight = p->doclist.aAll;
1.128581 +      nRight = p->doclist.nAll;
1.128582 +      pLeft = pList;
1.128583 +      nLeft = nList;
1.128584 +      nDiff = p->iDoclistToken - iToken;
1.128585 +    }
1.128586 +
1.128587 +    fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
1.128588 +    sqlite3_free(pLeft);
1.128589 +    p->doclist.aAll = pRight;
1.128590 +    p->doclist.nAll = nRight;
1.128591 +  }
1.128592 +
1.128593 +  if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
1.128594 +}
1.128595 +
1.128596 +/*
1.128597 +** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
1.128598 +** does not take deferred tokens into account.
1.128599 +**
1.128600 +** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
1.128601 +*/
1.128602 +static int fts3EvalPhraseLoad(
1.128603 +  Fts3Cursor *pCsr,               /* FTS Cursor handle */
1.128604 +  Fts3Phrase *p                   /* Phrase object */
1.128605 +){
1.128606 +  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
1.128607 +  int iToken;
1.128608 +  int rc = SQLITE_OK;
1.128609 +
1.128610 +  for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
1.128611 +    Fts3PhraseToken *pToken = &p->aToken[iToken];
1.128612 +    assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
1.128613 +
1.128614 +    if( pToken->pSegcsr ){
1.128615 +      int nThis = 0;
1.128616 +      char *pThis = 0;
1.128617 +      rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
1.128618 +      if( rc==SQLITE_OK ){
1.128619 +        fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
1.128620 +      }
1.128621 +    }
1.128622 +    assert( pToken->pSegcsr==0 );
1.128623 +  }
1.128624 +
1.128625 +  return rc;
1.128626 +}
1.128627 +
1.128628 +/*
1.128629 +** This function is called on each phrase after the position lists for
1.128630 +** any deferred tokens have been loaded into memory. It updates the phrases
1.128631 +** current position list to include only those positions that are really
1.128632 +** instances of the phrase (after considering deferred tokens). If this
1.128633 +** means that the phrase does not appear in the current row, doclist.pList
1.128634 +** and doclist.nList are both zeroed.
1.128635 +**
1.128636 +** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
1.128637 +*/
1.128638 +static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
1.128639 +  int iToken;                     /* Used to iterate through phrase tokens */
1.128640 +  char *aPoslist = 0;             /* Position list for deferred tokens */
1.128641 +  int nPoslist = 0;               /* Number of bytes in aPoslist */
1.128642 +  int iPrev = -1;                 /* Token number of previous deferred token */
1.128643 +
1.128644 +  assert( pPhrase->doclist.bFreeList==0 );
1.128645 +
1.128646 +  for(iToken=0; iToken<pPhrase->nToken; iToken++){
1.128647 +    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
1.128648 +    Fts3DeferredToken *pDeferred = pToken->pDeferred;
1.128649 +
1.128650 +    if( pDeferred ){
1.128651 +      char *pList;
1.128652 +      int nList;
1.128653 +      int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
1.128654 +      if( rc!=SQLITE_OK ) return rc;
1.128655 +
1.128656 +      if( pList==0 ){
1.128657 +        sqlite3_free(aPoslist);
1.128658 +        pPhrase->doclist.pList = 0;
1.128659 +        pPhrase->doclist.nList = 0;
1.128660 +        return SQLITE_OK;
1.128661 +
1.128662 +      }else if( aPoslist==0 ){
1.128663 +        aPoslist = pList;
1.128664 +        nPoslist = nList;
1.128665 +
1.128666 +      }else{
1.128667 +        char *aOut = pList;
1.128668 +        char *p1 = aPoslist;
1.128669 +        char *p2 = aOut;
1.128670 +
1.128671 +        assert( iPrev>=0 );
1.128672 +        fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
1.128673 +        sqlite3_free(aPoslist);
1.128674 +        aPoslist = pList;
1.128675 +        nPoslist = (int)(aOut - aPoslist);
1.128676 +        if( nPoslist==0 ){
1.128677 +          sqlite3_free(aPoslist);
1.128678 +          pPhrase->doclist.pList = 0;
1.128679 +          pPhrase->doclist.nList = 0;
1.128680 +          return SQLITE_OK;
1.128681 +        }
1.128682 +      }
1.128683 +      iPrev = iToken;
1.128684 +    }
1.128685 +  }
1.128686 +
1.128687 +  if( iPrev>=0 ){
1.128688 +    int nMaxUndeferred = pPhrase->iDoclistToken;
1.128689 +    if( nMaxUndeferred<0 ){
1.128690 +      pPhrase->doclist.pList = aPoslist;
1.128691 +      pPhrase->doclist.nList = nPoslist;
1.128692 +      pPhrase->doclist.iDocid = pCsr->iPrevId;
1.128693 +      pPhrase->doclist.bFreeList = 1;
1.128694 +    }else{
1.128695 +      int nDistance;
1.128696 +      char *p1;
1.128697 +      char *p2;
1.128698 +      char *aOut;
1.128699 +
1.128700 +      if( nMaxUndeferred>iPrev ){
1.128701 +        p1 = aPoslist;
1.128702 +        p2 = pPhrase->doclist.pList;
1.128703 +        nDistance = nMaxUndeferred - iPrev;
1.128704 +      }else{
1.128705 +        p1 = pPhrase->doclist.pList;
1.128706 +        p2 = aPoslist;
1.128707 +        nDistance = iPrev - nMaxUndeferred;
1.128708 +      }
1.128709 +
1.128710 +      aOut = (char *)sqlite3_malloc(nPoslist+8);
1.128711 +      if( !aOut ){
1.128712 +        sqlite3_free(aPoslist);
1.128713 +        return SQLITE_NOMEM;
1.128714 +      }
1.128715 +      
1.128716 +      pPhrase->doclist.pList = aOut;
1.128717 +      if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
1.128718 +        pPhrase->doclist.bFreeList = 1;
1.128719 +        pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
1.128720 +      }else{
1.128721 +        sqlite3_free(aOut);
1.128722 +        pPhrase->doclist.pList = 0;
1.128723 +        pPhrase->doclist.nList = 0;
1.128724 +      }
1.128725 +      sqlite3_free(aPoslist);
1.128726 +    }
1.128727 +  }
1.128728 +
1.128729 +  return SQLITE_OK;
1.128730 +}
1.128731 +
1.128732 +/*
1.128733 +** Maximum number of tokens a phrase may have to be considered for the
1.128734 +** incremental doclists strategy.
1.128735 +*/
1.128736 +#define MAX_INCR_PHRASE_TOKENS 4
1.128737 +
1.128738 +/*
1.128739 +** This function is called for each Fts3Phrase in a full-text query 
1.128740 +** expression to initialize the mechanism for returning rows. Once this
1.128741 +** function has been called successfully on an Fts3Phrase, it may be
1.128742 +** used with fts3EvalPhraseNext() to iterate through the matching docids.
1.128743 +**
1.128744 +** If parameter bOptOk is true, then the phrase may (or may not) use the
1.128745 +** incremental loading strategy. Otherwise, the entire doclist is loaded into
1.128746 +** memory within this call.
1.128747 +**
1.128748 +** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
1.128749 +*/
1.128750 +static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
1.128751 +  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
1.128752 +  int rc = SQLITE_OK;             /* Error code */
1.128753 +  int i;
1.128754 +
1.128755 +  /* Determine if doclists may be loaded from disk incrementally. This is
1.128756 +  ** possible if the bOptOk argument is true, the FTS doclists will be
1.128757 +  ** scanned in forward order, and the phrase consists of 
1.128758 +  ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
1.128759 +  ** tokens or prefix tokens that cannot use a prefix-index.  */
1.128760 +  int bHaveIncr = 0;
1.128761 +  int bIncrOk = (bOptOk 
1.128762 +   && pCsr->bDesc==pTab->bDescIdx 
1.128763 +   && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
1.128764 +   && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
1.128765 +#ifdef SQLITE_TEST
1.128766 +   && pTab->bNoIncrDoclist==0
1.128767 +#endif
1.128768 +  );
1.128769 +  for(i=0; bIncrOk==1 && i<p->nToken; i++){
1.128770 +    Fts3PhraseToken *pToken = &p->aToken[i];
1.128771 +    if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
1.128772 +      bIncrOk = 0;
1.128773 +    }
1.128774 +    if( pToken->pSegcsr ) bHaveIncr = 1;
1.128775 +  }
1.128776 +
1.128777 +  if( bIncrOk && bHaveIncr ){
1.128778 +    /* Use the incremental approach. */
1.128779 +    int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
1.128780 +    for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
1.128781 +      Fts3PhraseToken *pToken = &p->aToken[i];
1.128782 +      Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
1.128783 +      if( pSegcsr ){
1.128784 +        rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
1.128785 +      }
1.128786 +    }
1.128787 +    p->bIncr = 1;
1.128788 +  }else{
1.128789 +    /* Load the full doclist for the phrase into memory. */
1.128790 +    rc = fts3EvalPhraseLoad(pCsr, p);
1.128791 +    p->bIncr = 0;
1.128792 +  }
1.128793 +
1.128794 +  assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
1.128795 +  return rc;
1.128796 +}
1.128797 +
1.128798 +/*
1.128799 +** This function is used to iterate backwards (from the end to start) 
1.128800 +** through doclists. It is used by this module to iterate through phrase
1.128801 +** doclists in reverse and by the fts3_write.c module to iterate through
1.128802 +** pending-terms lists when writing to databases with "order=desc".
1.128803 +**
1.128804 +** The doclist may be sorted in ascending (parameter bDescIdx==0) or 
1.128805 +** descending (parameter bDescIdx==1) order of docid. Regardless, this
1.128806 +** function iterates from the end of the doclist to the beginning.
1.128807 +*/
1.128808 +SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
1.128809 +  int bDescIdx,                   /* True if the doclist is desc */
1.128810 +  char *aDoclist,                 /* Pointer to entire doclist */
1.128811 +  int nDoclist,                   /* Length of aDoclist in bytes */
1.128812 +  char **ppIter,                  /* IN/OUT: Iterator pointer */
1.128813 +  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
1.128814 +  int *pnList,                    /* OUT: List length pointer */
1.128815 +  u8 *pbEof                       /* OUT: End-of-file flag */
1.128816 +){
1.128817 +  char *p = *ppIter;
1.128818 +
1.128819 +  assert( nDoclist>0 );
1.128820 +  assert( *pbEof==0 );
1.128821 +  assert( p || *piDocid==0 );
1.128822 +  assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
1.128823 +
1.128824 +  if( p==0 ){
1.128825 +    sqlite3_int64 iDocid = 0;
1.128826 +    char *pNext = 0;
1.128827 +    char *pDocid = aDoclist;
1.128828 +    char *pEnd = &aDoclist[nDoclist];
1.128829 +    int iMul = 1;
1.128830 +
1.128831 +    while( pDocid<pEnd ){
1.128832 +      sqlite3_int64 iDelta;
1.128833 +      pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
1.128834 +      iDocid += (iMul * iDelta);
1.128835 +      pNext = pDocid;
1.128836 +      fts3PoslistCopy(0, &pDocid);
1.128837 +      while( pDocid<pEnd && *pDocid==0 ) pDocid++;
1.128838 +      iMul = (bDescIdx ? -1 : 1);
1.128839 +    }
1.128840 +
1.128841 +    *pnList = (int)(pEnd - pNext);
1.128842 +    *ppIter = pNext;
1.128843 +    *piDocid = iDocid;
1.128844 +  }else{
1.128845 +    int iMul = (bDescIdx ? -1 : 1);
1.128846 +    sqlite3_int64 iDelta;
1.128847 +    fts3GetReverseVarint(&p, aDoclist, &iDelta);
1.128848 +    *piDocid -= (iMul * iDelta);
1.128849 +
1.128850 +    if( p==aDoclist ){
1.128851 +      *pbEof = 1;
1.128852 +    }else{
1.128853 +      char *pSave = p;
1.128854 +      fts3ReversePoslist(aDoclist, &p);
1.128855 +      *pnList = (int)(pSave - p);
1.128856 +    }
1.128857 +    *ppIter = p;
1.128858 +  }
1.128859 +}
1.128860 +
1.128861 +/*
1.128862 +** Iterate forwards through a doclist.
1.128863 +*/
1.128864 +SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
1.128865 +  int bDescIdx,                   /* True if the doclist is desc */
1.128866 +  char *aDoclist,                 /* Pointer to entire doclist */
1.128867 +  int nDoclist,                   /* Length of aDoclist in bytes */
1.128868 +  char **ppIter,                  /* IN/OUT: Iterator pointer */
1.128869 +  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
1.128870 +  u8 *pbEof                       /* OUT: End-of-file flag */
1.128871 +){
1.128872 +  char *p = *ppIter;
1.128873 +
1.128874 +  assert( nDoclist>0 );
1.128875 +  assert( *pbEof==0 );
1.128876 +  assert( p || *piDocid==0 );
1.128877 +  assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
1.128878 +
1.128879 +  if( p==0 ){
1.128880 +    p = aDoclist;
1.128881 +    p += sqlite3Fts3GetVarint(p, piDocid);
1.128882 +  }else{
1.128883 +    fts3PoslistCopy(0, &p);
1.128884 +    if( p>=&aDoclist[nDoclist] ){
1.128885 +      *pbEof = 1;
1.128886 +    }else{
1.128887 +      sqlite3_int64 iVar;
1.128888 +      p += sqlite3Fts3GetVarint(p, &iVar);
1.128889 +      *piDocid += ((bDescIdx ? -1 : 1) * iVar);
1.128890 +    }
1.128891 +  }
1.128892 +
1.128893 +  *ppIter = p;
1.128894 +}
1.128895 +
1.128896 +/*
1.128897 +** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
1.128898 +** to true if EOF is reached.
1.128899 +*/
1.128900 +static void fts3EvalDlPhraseNext(
1.128901 +  Fts3Table *pTab,
1.128902 +  Fts3Doclist *pDL,
1.128903 +  u8 *pbEof
1.128904 +){
1.128905 +  char *pIter;                            /* Used to iterate through aAll */
1.128906 +  char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
1.128907 + 
1.128908 +  if( pDL->pNextDocid ){
1.128909 +    pIter = pDL->pNextDocid;
1.128910 +  }else{
1.128911 +    pIter = pDL->aAll;
1.128912 +  }
1.128913 +
1.128914 +  if( pIter>=pEnd ){
1.128915 +    /* We have already reached the end of this doclist. EOF. */
1.128916 +    *pbEof = 1;
1.128917 +  }else{
1.128918 +    sqlite3_int64 iDelta;
1.128919 +    pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
1.128920 +    if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
1.128921 +      pDL->iDocid += iDelta;
1.128922 +    }else{
1.128923 +      pDL->iDocid -= iDelta;
1.128924 +    }
1.128925 +    pDL->pList = pIter;
1.128926 +    fts3PoslistCopy(0, &pIter);
1.128927 +    pDL->nList = (int)(pIter - pDL->pList);
1.128928 +
1.128929 +    /* pIter now points just past the 0x00 that terminates the position-
1.128930 +    ** list for document pDL->iDocid. However, if this position-list was
1.128931 +    ** edited in place by fts3EvalNearTrim(), then pIter may not actually
1.128932 +    ** point to the start of the next docid value. The following line deals
1.128933 +    ** with this case by advancing pIter past the zero-padding added by
1.128934 +    ** fts3EvalNearTrim().  */
1.128935 +    while( pIter<pEnd && *pIter==0 ) pIter++;
1.128936 +
1.128937 +    pDL->pNextDocid = pIter;
1.128938 +    assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
1.128939 +    *pbEof = 0;
1.128940 +  }
1.128941 +}
1.128942 +
1.128943 +/*
1.128944 +** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
1.128945 +*/
1.128946 +typedef struct TokenDoclist TokenDoclist;
1.128947 +struct TokenDoclist {
1.128948 +  int bIgnore;
1.128949 +  sqlite3_int64 iDocid;
1.128950 +  char *pList;
1.128951 +  int nList;
1.128952 +};
1.128953 +
1.128954 +/*
1.128955 +** Token pToken is an incrementally loaded token that is part of a 
1.128956 +** multi-token phrase. Advance it to the next matching document in the
1.128957 +** database and populate output variable *p with the details of the new
1.128958 +** entry. Or, if the iterator has reached EOF, set *pbEof to true.
1.128959 +**
1.128960 +** If an error occurs, return an SQLite error code. Otherwise, return 
1.128961 +** SQLITE_OK.
1.128962 +*/
1.128963 +static int incrPhraseTokenNext(
1.128964 +  Fts3Table *pTab,                /* Virtual table handle */
1.128965 +  Fts3Phrase *pPhrase,            /* Phrase to advance token of */
1.128966 +  int iToken,                     /* Specific token to advance */
1.128967 +  TokenDoclist *p,                /* OUT: Docid and doclist for new entry */
1.128968 +  u8 *pbEof                       /* OUT: True if iterator is at EOF */
1.128969 +){
1.128970 +  int rc = SQLITE_OK;
1.128971 +
1.128972 +  if( pPhrase->iDoclistToken==iToken ){
1.128973 +    assert( p->bIgnore==0 );
1.128974 +    assert( pPhrase->aToken[iToken].pSegcsr==0 );
1.128975 +    fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
1.128976 +    p->pList = pPhrase->doclist.pList;
1.128977 +    p->nList = pPhrase->doclist.nList;
1.128978 +    p->iDocid = pPhrase->doclist.iDocid;
1.128979 +  }else{
1.128980 +    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
1.128981 +    assert( pToken->pDeferred==0 );
1.128982 +    assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
1.128983 +    if( pToken->pSegcsr ){
1.128984 +      assert( p->bIgnore==0 );
1.128985 +      rc = sqlite3Fts3MsrIncrNext(
1.128986 +          pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
1.128987 +      );
1.128988 +      if( p->pList==0 ) *pbEof = 1;
1.128989 +    }else{
1.128990 +      p->bIgnore = 1;
1.128991 +    }
1.128992 +  }
1.128993 +
1.128994 +  return rc;
1.128995 +}
1.128996 +
1.128997 +
1.128998 +/*
1.128999 +** The phrase iterator passed as the second argument:
1.129000 +**
1.129001 +**   * features at least one token that uses an incremental doclist, and 
1.129002 +**
1.129003 +**   * does not contain any deferred tokens.
1.129004 +**
1.129005 +** Advance it to the next matching documnent in the database and populate
1.129006 +** the Fts3Doclist.pList and nList fields. 
1.129007 +**
1.129008 +** If there is no "next" entry and no error occurs, then *pbEof is set to
1.129009 +** 1 before returning. Otherwise, if no error occurs and the iterator is
1.129010 +** successfully advanced, *pbEof is set to 0.
1.129011 +**
1.129012 +** If an error occurs, return an SQLite error code. Otherwise, return 
1.129013 +** SQLITE_OK.
1.129014 +*/
1.129015 +static int fts3EvalIncrPhraseNext(
1.129016 +  Fts3Cursor *pCsr,               /* FTS Cursor handle */
1.129017 +  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
1.129018 +  u8 *pbEof                       /* OUT: Set to 1 if EOF */
1.129019 +){
1.129020 +  int rc = SQLITE_OK;
1.129021 +  Fts3Doclist *pDL = &p->doclist;
1.129022 +  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
1.129023 +  u8 bEof = 0;
1.129024 +
1.129025 +  /* This is only called if it is guaranteed that the phrase has at least
1.129026 +  ** one incremental token. In which case the bIncr flag is set. */
1.129027 +  assert( p->bIncr==1 );
1.129028 +
1.129029 +  if( p->nToken==1 && p->bIncr ){
1.129030 +    rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, 
1.129031 +        &pDL->iDocid, &pDL->pList, &pDL->nList
1.129032 +    );
1.129033 +    if( pDL->pList==0 ) bEof = 1;
1.129034 +  }else{
1.129035 +    int bDescDoclist = pCsr->bDesc;
1.129036 +    struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
1.129037 +
1.129038 +    memset(a, 0, sizeof(a));
1.129039 +    assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
1.129040 +    assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
1.129041 +
1.129042 +    while( bEof==0 ){
1.129043 +      int bMaxSet = 0;
1.129044 +      sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */
1.129045 +      int i;                      /* Used to iterate through tokens */
1.129046 +
1.129047 +      /* Advance the iterator for each token in the phrase once. */
1.129048 +      for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
1.129049 +        rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
1.129050 +        if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
1.129051 +          iMax = a[i].iDocid;
1.129052 +          bMaxSet = 1;
1.129053 +        }
1.129054 +      }
1.129055 +      assert( rc!=SQLITE_OK || a[p->nToken-1].bIgnore==0 );
1.129056 +      assert( rc!=SQLITE_OK || bMaxSet );
1.129057 +
1.129058 +      /* Keep advancing iterators until they all point to the same document */
1.129059 +      for(i=0; i<p->nToken; i++){
1.129060 +        while( rc==SQLITE_OK && bEof==0 
1.129061 +            && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0 
1.129062 +        ){
1.129063 +          rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
1.129064 +          if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
1.129065 +            iMax = a[i].iDocid;
1.129066 +            i = 0;
1.129067 +          }
1.129068 +        }
1.129069 +      }
1.129070 +
1.129071 +      /* Check if the current entries really are a phrase match */
1.129072 +      if( bEof==0 ){
1.129073 +        int nList = 0;
1.129074 +        int nByte = a[p->nToken-1].nList;
1.129075 +        char *aDoclist = sqlite3_malloc(nByte+1);
1.129076 +        if( !aDoclist ) return SQLITE_NOMEM;
1.129077 +        memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
1.129078 +
1.129079 +        for(i=0; i<(p->nToken-1); i++){
1.129080 +          if( a[i].bIgnore==0 ){
1.129081 +            char *pL = a[i].pList;
1.129082 +            char *pR = aDoclist;
1.129083 +            char *pOut = aDoclist;
1.129084 +            int nDist = p->nToken-1-i;
1.129085 +            int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
1.129086 +            if( res==0 ) break;
1.129087 +            nList = (int)(pOut - aDoclist);
1.129088 +          }
1.129089 +        }
1.129090 +        if( i==(p->nToken-1) ){
1.129091 +          pDL->iDocid = iMax;
1.129092 +          pDL->pList = aDoclist;
1.129093 +          pDL->nList = nList;
1.129094 +          pDL->bFreeList = 1;
1.129095 +          break;
1.129096 +        }
1.129097 +        sqlite3_free(aDoclist);
1.129098 +      }
1.129099 +    }
1.129100 +  }
1.129101 +
1.129102 +  *pbEof = bEof;
1.129103 +  return rc;
1.129104 +}
1.129105 +
1.129106 +/*
1.129107 +** Attempt to move the phrase iterator to point to the next matching docid. 
1.129108 +** If an error occurs, return an SQLite error code. Otherwise, return 
1.129109 +** SQLITE_OK.
1.129110 +**
1.129111 +** If there is no "next" entry and no error occurs, then *pbEof is set to
1.129112 +** 1 before returning. Otherwise, if no error occurs and the iterator is
1.129113 +** successfully advanced, *pbEof is set to 0.
1.129114 +*/
1.129115 +static int fts3EvalPhraseNext(
1.129116 +  Fts3Cursor *pCsr,               /* FTS Cursor handle */
1.129117 +  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
1.129118 +  u8 *pbEof                       /* OUT: Set to 1 if EOF */
1.129119 +){
1.129120 +  int rc = SQLITE_OK;
1.129121 +  Fts3Doclist *pDL = &p->doclist;
1.129122 +  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
1.129123 +
1.129124 +  if( p->bIncr ){
1.129125 +    rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
1.129126 +  }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
1.129127 +    sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, 
1.129128 +        &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
1.129129 +    );
1.129130 +    pDL->pList = pDL->pNextDocid;
1.129131 +  }else{
1.129132 +    fts3EvalDlPhraseNext(pTab, pDL, pbEof);
1.129133 +  }
1.129134 +
1.129135 +  return rc;
1.129136 +}
1.129137 +
1.129138 +/*
1.129139 +**
1.129140 +** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
1.129141 +** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
1.129142 +** expression. Also the Fts3Expr.bDeferred variable is set to true for any
1.129143 +** expressions for which all descendent tokens are deferred.
1.129144 +**
1.129145 +** If parameter bOptOk is zero, then it is guaranteed that the
1.129146 +** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
1.129147 +** each phrase in the expression (subject to deferred token processing).
1.129148 +** Or, if bOptOk is non-zero, then one or more tokens within the expression
1.129149 +** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
1.129150 +**
1.129151 +** If an error occurs within this function, *pRc is set to an SQLite error
1.129152 +** code before returning.
1.129153 +*/
1.129154 +static void fts3EvalStartReaders(
1.129155 +  Fts3Cursor *pCsr,               /* FTS Cursor handle */
1.129156 +  Fts3Expr *pExpr,                /* Expression to initialize phrases in */
1.129157 +  int *pRc                        /* IN/OUT: Error code */
1.129158 +){
1.129159 +  if( pExpr && SQLITE_OK==*pRc ){
1.129160 +    if( pExpr->eType==FTSQUERY_PHRASE ){
1.129161 +      int i;
1.129162 +      int nToken = pExpr->pPhrase->nToken;
1.129163 +      for(i=0; i<nToken; i++){
1.129164 +        if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
1.129165 +      }
1.129166 +      pExpr->bDeferred = (i==nToken);
1.129167 +      *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
1.129168 +    }else{
1.129169 +      fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
1.129170 +      fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
1.129171 +      pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
1.129172 +    }
1.129173 +  }
1.129174 +}
1.129175 +
1.129176 +/*
1.129177 +** An array of the following structures is assembled as part of the process
1.129178 +** of selecting tokens to defer before the query starts executing (as part
1.129179 +** of the xFilter() method). There is one element in the array for each
1.129180 +** token in the FTS expression.
1.129181 +**
1.129182 +** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
1.129183 +** to phrases that are connected only by AND and NEAR operators (not OR or
1.129184 +** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
1.129185 +** separately. The root of a tokens AND/NEAR cluster is stored in 
1.129186 +** Fts3TokenAndCost.pRoot.
1.129187 +*/
1.129188 +typedef struct Fts3TokenAndCost Fts3TokenAndCost;
1.129189 +struct Fts3TokenAndCost {
1.129190 +  Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
1.129191 +  int iToken;                     /* Position of token in phrase */
1.129192 +  Fts3PhraseToken *pToken;        /* The token itself */
1.129193 +  Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
1.129194 +  int nOvfl;                      /* Number of overflow pages to load doclist */
1.129195 +  int iCol;                       /* The column the token must match */
1.129196 +};
1.129197 +
1.129198 +/*
1.129199 +** This function is used to populate an allocated Fts3TokenAndCost array.
1.129200 +**
1.129201 +** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
1.129202 +** Otherwise, if an error occurs during execution, *pRc is set to an
1.129203 +** SQLite error code.
1.129204 +*/
1.129205 +static void fts3EvalTokenCosts(
1.129206 +  Fts3Cursor *pCsr,               /* FTS Cursor handle */
1.129207 +  Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
1.129208 +  Fts3Expr *pExpr,                /* Expression to consider */
1.129209 +  Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
1.129210 +  Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
1.129211 +  int *pRc                        /* IN/OUT: Error code */
1.129212 +){
1.129213 +  if( *pRc==SQLITE_OK ){
1.129214 +    if( pExpr->eType==FTSQUERY_PHRASE ){
1.129215 +      Fts3Phrase *pPhrase = pExpr->pPhrase;
1.129216 +      int i;
1.129217 +      for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
1.129218 +        Fts3TokenAndCost *pTC = (*ppTC)++;
1.129219 +        pTC->pPhrase = pPhrase;
1.129220 +        pTC->iToken = i;
1.129221 +        pTC->pRoot = pRoot;
1.129222 +        pTC->pToken = &pPhrase->aToken[i];
1.129223 +        pTC->iCol = pPhrase->iColumn;
1.129224 +        *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
1.129225 +      }
1.129226 +    }else if( pExpr->eType!=FTSQUERY_NOT ){
1.129227 +      assert( pExpr->eType==FTSQUERY_OR
1.129228 +           || pExpr->eType==FTSQUERY_AND
1.129229 +           || pExpr->eType==FTSQUERY_NEAR
1.129230 +      );
1.129231 +      assert( pExpr->pLeft && pExpr->pRight );
1.129232 +      if( pExpr->eType==FTSQUERY_OR ){
1.129233 +        pRoot = pExpr->pLeft;
1.129234 +        **ppOr = pRoot;
1.129235 +        (*ppOr)++;
1.129236 +      }
1.129237 +      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
1.129238 +      if( pExpr->eType==FTSQUERY_OR ){
1.129239 +        pRoot = pExpr->pRight;
1.129240 +        **ppOr = pRoot;
1.129241 +        (*ppOr)++;
1.129242 +      }
1.129243 +      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
1.129244 +    }
1.129245 +  }
1.129246 +}
1.129247 +
1.129248 +/*
1.129249 +** Determine the average document (row) size in pages. If successful,
1.129250 +** write this value to *pnPage and return SQLITE_OK. Otherwise, return
1.129251 +** an SQLite error code.
1.129252 +**
1.129253 +** The average document size in pages is calculated by first calculating 
1.129254 +** determining the average size in bytes, B. If B is less than the amount
1.129255 +** of data that will fit on a single leaf page of an intkey table in
1.129256 +** this database, then the average docsize is 1. Otherwise, it is 1 plus
1.129257 +** the number of overflow pages consumed by a record B bytes in size.
1.129258 +*/
1.129259 +static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
1.129260 +  if( pCsr->nRowAvg==0 ){
1.129261 +    /* The average document size, which is required to calculate the cost
1.129262 +    ** of each doclist, has not yet been determined. Read the required 
1.129263 +    ** data from the %_stat table to calculate it.
1.129264 +    **
1.129265 +    ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 
1.129266 +    ** varints, where nCol is the number of columns in the FTS3 table.
1.129267 +    ** The first varint is the number of documents currently stored in
1.129268 +    ** the table. The following nCol varints contain the total amount of
1.129269 +    ** data stored in all rows of each column of the table, from left
1.129270 +    ** to right.
1.129271 +    */
1.129272 +    int rc;
1.129273 +    Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
1.129274 +    sqlite3_stmt *pStmt;
1.129275 +    sqlite3_int64 nDoc = 0;
1.129276 +    sqlite3_int64 nByte = 0;
1.129277 +    const char *pEnd;
1.129278 +    const char *a;
1.129279 +
1.129280 +    rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
1.129281 +    if( rc!=SQLITE_OK ) return rc;
1.129282 +    a = sqlite3_column_blob(pStmt, 0);
1.129283 +    assert( a );
1.129284 +
1.129285 +    pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
1.129286 +    a += sqlite3Fts3GetVarint(a, &nDoc);
1.129287 +    while( a<pEnd ){
1.129288 +      a += sqlite3Fts3GetVarint(a, &nByte);
1.129289 +    }
1.129290 +    if( nDoc==0 || nByte==0 ){
1.129291 +      sqlite3_reset(pStmt);
1.129292 +      return FTS_CORRUPT_VTAB;
1.129293 +    }
1.129294 +
1.129295 +    pCsr->nDoc = nDoc;
1.129296 +    pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
1.129297 +    assert( pCsr->nRowAvg>0 ); 
1.129298 +    rc = sqlite3_reset(pStmt);
1.129299 +    if( rc!=SQLITE_OK ) return rc;
1.129300 +  }
1.129301 +
1.129302 +  *pnPage = pCsr->nRowAvg;
1.129303 +  return SQLITE_OK;
1.129304 +}
1.129305 +
1.129306 +/*
1.129307 +** This function is called to select the tokens (if any) that will be 
1.129308 +** deferred. The array aTC[] has already been populated when this is
1.129309 +** called.
1.129310 +**
1.129311 +** This function is called once for each AND/NEAR cluster in the 
1.129312 +** expression. Each invocation determines which tokens to defer within
1.129313 +** the cluster with root node pRoot. See comments above the definition
1.129314 +** of struct Fts3TokenAndCost for more details.
1.129315 +**
1.129316 +** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
1.129317 +** called on each token to defer. Otherwise, an SQLite error code is
1.129318 +** returned.
1.129319 +*/
1.129320 +static int fts3EvalSelectDeferred(
1.129321 +  Fts3Cursor *pCsr,               /* FTS Cursor handle */
1.129322 +  Fts3Expr *pRoot,                /* Consider tokens with this root node */
1.129323 +  Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
1.129324 +  int nTC                         /* Number of entries in aTC[] */
1.129325 +){
1.129326 +  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
1.129327 +  int nDocSize = 0;               /* Number of pages per doc loaded */
1.129328 +  int rc = SQLITE_OK;             /* Return code */
1.129329 +  int ii;                         /* Iterator variable for various purposes */
1.129330 +  int nOvfl = 0;                  /* Total overflow pages used by doclists */
1.129331 +  int nToken = 0;                 /* Total number of tokens in cluster */
1.129332 +
1.129333 +  int nMinEst = 0;                /* The minimum count for any phrase so far. */
1.129334 +  int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
1.129335 +
1.129336 +  /* Tokens are never deferred for FTS tables created using the content=xxx
1.129337 +  ** option. The reason being that it is not guaranteed that the content
1.129338 +  ** table actually contains the same data as the index. To prevent this from
1.129339 +  ** causing any problems, the deferred token optimization is completely
1.129340 +  ** disabled for content=xxx tables. */
1.129341 +  if( pTab->zContentTbl ){
1.129342 +    return SQLITE_OK;
1.129343 +  }
1.129344 +
1.129345 +  /* Count the tokens in this AND/NEAR cluster. If none of the doclists
1.129346 +  ** associated with the tokens spill onto overflow pages, or if there is
1.129347 +  ** only 1 token, exit early. No tokens to defer in this case. */
1.129348 +  for(ii=0; ii<nTC; ii++){
1.129349 +    if( aTC[ii].pRoot==pRoot ){
1.129350 +      nOvfl += aTC[ii].nOvfl;
1.129351 +      nToken++;
1.129352 +    }
1.129353 +  }
1.129354 +  if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
1.129355 +
1.129356 +  /* Obtain the average docsize (in pages). */
1.129357 +  rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
1.129358 +  assert( rc!=SQLITE_OK || nDocSize>0 );
1.129359 +
1.129360 +
1.129361 +  /* Iterate through all tokens in this AND/NEAR cluster, in ascending order 
1.129362 +  ** of the number of overflow pages that will be loaded by the pager layer 
1.129363 +  ** to retrieve the entire doclist for the token from the full-text index.
1.129364 +  ** Load the doclists for tokens that are either:
1.129365 +  **
1.129366 +  **   a. The cheapest token in the entire query (i.e. the one visited by the
1.129367 +  **      first iteration of this loop), or
1.129368 +  **
1.129369 +  **   b. Part of a multi-token phrase.
1.129370 +  **
1.129371 +  ** After each token doclist is loaded, merge it with the others from the
1.129372 +  ** same phrase and count the number of documents that the merged doclist
1.129373 +  ** contains. Set variable "nMinEst" to the smallest number of documents in 
1.129374 +  ** any phrase doclist for which 1 or more token doclists have been loaded.
1.129375 +  ** Let nOther be the number of other phrases for which it is certain that
1.129376 +  ** one or more tokens will not be deferred.
1.129377 +  **
1.129378 +  ** Then, for each token, defer it if loading the doclist would result in
1.129379 +  ** loading N or more overflow pages into memory, where N is computed as:
1.129380 +  **
1.129381 +  **    (nMinEst + 4^nOther - 1) / (4^nOther)
1.129382 +  */
1.129383 +  for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
1.129384 +    int iTC;                      /* Used to iterate through aTC[] array. */
1.129385 +    Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
1.129386 +
1.129387 +    /* Set pTC to point to the cheapest remaining token. */
1.129388 +    for(iTC=0; iTC<nTC; iTC++){
1.129389 +      if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot 
1.129390 +       && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl) 
1.129391 +      ){
1.129392 +        pTC = &aTC[iTC];
1.129393 +      }
1.129394 +    }
1.129395 +    assert( pTC );
1.129396 +
1.129397 +    if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
1.129398 +      /* The number of overflow pages to load for this (and therefore all
1.129399 +      ** subsequent) tokens is greater than the estimated number of pages 
1.129400 +      ** that will be loaded if all subsequent tokens are deferred.
1.129401 +      */
1.129402 +      Fts3PhraseToken *pToken = pTC->pToken;
1.129403 +      rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
1.129404 +      fts3SegReaderCursorFree(pToken->pSegcsr);
1.129405 +      pToken->pSegcsr = 0;
1.129406 +    }else{
1.129407 +      /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
1.129408 +      ** for-loop. Except, limit the value to 2^24 to prevent it from 
1.129409 +      ** overflowing the 32-bit integer it is stored in. */
1.129410 +      if( ii<12 ) nLoad4 = nLoad4*4;
1.129411 +
1.129412 +      if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
1.129413 +        /* Either this is the cheapest token in the entire query, or it is
1.129414 +        ** part of a multi-token phrase. Either way, the entire doclist will
1.129415 +        ** (eventually) be loaded into memory. It may as well be now. */
1.129416 +        Fts3PhraseToken *pToken = pTC->pToken;
1.129417 +        int nList = 0;
1.129418 +        char *pList = 0;
1.129419 +        rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
1.129420 +        assert( rc==SQLITE_OK || pList==0 );
1.129421 +        if( rc==SQLITE_OK ){
1.129422 +          int nCount;
1.129423 +          fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
1.129424 +          nCount = fts3DoclistCountDocids(
1.129425 +              pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
1.129426 +          );
1.129427 +          if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
1.129428 +        }
1.129429 +      }
1.129430 +    }
1.129431 +    pTC->pToken = 0;
1.129432 +  }
1.129433 +
1.129434 +  return rc;
1.129435 +}
1.129436 +
1.129437 +/*
1.129438 +** This function is called from within the xFilter method. It initializes
1.129439 +** the full-text query currently stored in pCsr->pExpr. To iterate through
1.129440 +** the results of a query, the caller does:
1.129441 +**
1.129442 +**    fts3EvalStart(pCsr);
1.129443 +**    while( 1 ){
1.129444 +**      fts3EvalNext(pCsr);
1.129445 +**      if( pCsr->bEof ) break;
1.129446 +**      ... return row pCsr->iPrevId to the caller ...
1.129447 +**    }
1.129448 +*/
1.129449 +static int fts3EvalStart(Fts3Cursor *pCsr){
1.129450 +  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
1.129451 +  int rc = SQLITE_OK;
1.129452 +  int nToken = 0;
1.129453 +  int nOr = 0;
1.129454 +
1.129455 +  /* Allocate a MultiSegReader for each token in the expression. */
1.129456 +  fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
1.129457 +
1.129458 +  /* Determine which, if any, tokens in the expression should be deferred. */
1.129459 +#ifndef SQLITE_DISABLE_FTS4_DEFERRED
1.129460 +  if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
1.129461 +    Fts3TokenAndCost *aTC;
1.129462 +    Fts3Expr **apOr;
1.129463 +    aTC = (Fts3TokenAndCost *)sqlite3_malloc(
1.129464 +        sizeof(Fts3TokenAndCost) * nToken
1.129465 +      + sizeof(Fts3Expr *) * nOr * 2
1.129466 +    );
1.129467 +    apOr = (Fts3Expr **)&aTC[nToken];
1.129468 +
1.129469 +    if( !aTC ){
1.129470 +      rc = SQLITE_NOMEM;
1.129471 +    }else{
1.129472 +      int ii;
1.129473 +      Fts3TokenAndCost *pTC = aTC;
1.129474 +      Fts3Expr **ppOr = apOr;
1.129475 +
1.129476 +      fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
1.129477 +      nToken = (int)(pTC-aTC);
1.129478 +      nOr = (int)(ppOr-apOr);
1.129479 +
1.129480 +      if( rc==SQLITE_OK ){
1.129481 +        rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
1.129482 +        for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
1.129483 +          rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
1.129484 +        }
1.129485 +      }
1.129486 +
1.129487 +      sqlite3_free(aTC);
1.129488 +    }
1.129489 +  }
1.129490 +#endif
1.129491 +
1.129492 +  fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
1.129493 +  return rc;
1.129494 +}
1.129495 +
1.129496 +/*
1.129497 +** Invalidate the current position list for phrase pPhrase.
1.129498 +*/
1.129499 +static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
1.129500 +  if( pPhrase->doclist.bFreeList ){
1.129501 +    sqlite3_free(pPhrase->doclist.pList);
1.129502 +  }
1.129503 +  pPhrase->doclist.pList = 0;
1.129504 +  pPhrase->doclist.nList = 0;
1.129505 +  pPhrase->doclist.bFreeList = 0;
1.129506 +}
1.129507 +
1.129508 +/*
1.129509 +** This function is called to edit the position list associated with
1.129510 +** the phrase object passed as the fifth argument according to a NEAR
1.129511 +** condition. For example:
1.129512 +**
1.129513 +**     abc NEAR/5 "def ghi"
1.129514 +**
1.129515 +** Parameter nNear is passed the NEAR distance of the expression (5 in
1.129516 +** the example above). When this function is called, *paPoslist points to
1.129517 +** the position list, and *pnToken is the number of phrase tokens in, the
1.129518 +** phrase on the other side of the NEAR operator to pPhrase. For example,
1.129519 +** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
1.129520 +** the position list associated with phrase "abc".
1.129521 +**
1.129522 +** All positions in the pPhrase position list that are not sufficiently
1.129523 +** close to a position in the *paPoslist position list are removed. If this
1.129524 +** leaves 0 positions, zero is returned. Otherwise, non-zero.
1.129525 +**
1.129526 +** Before returning, *paPoslist is set to point to the position lsit 
1.129527 +** associated with pPhrase. And *pnToken is set to the number of tokens in
1.129528 +** pPhrase.
1.129529 +*/
1.129530 +static int fts3EvalNearTrim(
1.129531 +  int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
1.129532 +  char *aTmp,                     /* Temporary space to use */
1.129533 +  char **paPoslist,               /* IN/OUT: Position list */
1.129534 +  int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
1.129535 +  Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
1.129536 +){
1.129537 +  int nParam1 = nNear + pPhrase->nToken;
1.129538 +  int nParam2 = nNear + *pnToken;
1.129539 +  int nNew;
1.129540 +  char *p2; 
1.129541 +  char *pOut; 
1.129542 +  int res;
1.129543 +
1.129544 +  assert( pPhrase->doclist.pList );
1.129545 +
1.129546 +  p2 = pOut = pPhrase->doclist.pList;
1.129547 +  res = fts3PoslistNearMerge(
1.129548 +    &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
1.129549 +  );
1.129550 +  if( res ){
1.129551 +    nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
1.129552 +    assert( pPhrase->doclist.pList[nNew]=='\0' );
1.129553 +    assert( nNew<=pPhrase->doclist.nList && nNew>0 );
1.129554 +    memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
1.129555 +    pPhrase->doclist.nList = nNew;
1.129556 +    *paPoslist = pPhrase->doclist.pList;
1.129557 +    *pnToken = pPhrase->nToken;
1.129558 +  }
1.129559 +
1.129560 +  return res;
1.129561 +}
1.129562 +
1.129563 +/*
1.129564 +** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
1.129565 +** Otherwise, it advances the expression passed as the second argument to
1.129566 +** point to the next matching row in the database. Expressions iterate through
1.129567 +** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
1.129568 +** or descending if it is non-zero.
1.129569 +**
1.129570 +** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
1.129571 +** successful, the following variables in pExpr are set:
1.129572 +**
1.129573 +**   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
1.129574 +**   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
1.129575 +**
1.129576 +** If the expression is of type FTSQUERY_PHRASE, and the expression is not
1.129577 +** at EOF, then the following variables are populated with the position list
1.129578 +** for the phrase for the visited row:
1.129579 +**
1.129580 +**   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
1.129581 +**   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
1.129582 +**
1.129583 +** It says above that this function advances the expression to the next
1.129584 +** matching row. This is usually true, but there are the following exceptions:
1.129585 +**
1.129586 +**   1. Deferred tokens are not taken into account. If a phrase consists
1.129587 +**      entirely of deferred tokens, it is assumed to match every row in
1.129588 +**      the db. In this case the position-list is not populated at all. 
1.129589 +**
1.129590 +**      Or, if a phrase contains one or more deferred tokens and one or
1.129591 +**      more non-deferred tokens, then the expression is advanced to the 
1.129592 +**      next possible match, considering only non-deferred tokens. In other
1.129593 +**      words, if the phrase is "A B C", and "B" is deferred, the expression
1.129594 +**      is advanced to the next row that contains an instance of "A * C", 
1.129595 +**      where "*" may match any single token. The position list in this case
1.129596 +**      is populated as for "A * C" before returning.
1.129597 +**
1.129598 +**   2. NEAR is treated as AND. If the expression is "x NEAR y", it is 
1.129599 +**      advanced to point to the next row that matches "x AND y".
1.129600 +** 
1.129601 +** See fts3EvalTestDeferredAndNear() for details on testing if a row is
1.129602 +** really a match, taking into account deferred tokens and NEAR operators.
1.129603 +*/
1.129604 +static void fts3EvalNextRow(
1.129605 +  Fts3Cursor *pCsr,               /* FTS Cursor handle */
1.129606 +  Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
1.129607 +  int *pRc                        /* IN/OUT: Error code */
1.129608 +){
1.129609 +  if( *pRc==SQLITE_OK ){
1.129610 +    int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
1.129611 +    assert( pExpr->bEof==0 );
1.129612 +    pExpr->bStart = 1;
1.129613 +
1.129614 +    switch( pExpr->eType ){
1.129615 +      case FTSQUERY_NEAR:
1.129616 +      case FTSQUERY_AND: {
1.129617 +        Fts3Expr *pLeft = pExpr->pLeft;
1.129618 +        Fts3Expr *pRight = pExpr->pRight;
1.129619 +        assert( !pLeft->bDeferred || !pRight->bDeferred );
1.129620 +
1.129621 +        if( pLeft->bDeferred ){
1.129622 +          /* LHS is entirely deferred. So we assume it matches every row.
1.129623 +          ** Advance the RHS iterator to find the next row visited. */
1.129624 +          fts3EvalNextRow(pCsr, pRight, pRc);
1.129625 +          pExpr->iDocid = pRight->iDocid;
1.129626 +          pExpr->bEof = pRight->bEof;
1.129627 +        }else if( pRight->bDeferred ){
1.129628 +          /* RHS is entirely deferred. So we assume it matches every row.
1.129629 +          ** Advance the LHS iterator to find the next row visited. */
1.129630 +          fts3EvalNextRow(pCsr, pLeft, pRc);
1.129631 +          pExpr->iDocid = pLeft->iDocid;
1.129632 +          pExpr->bEof = pLeft->bEof;
1.129633 +        }else{
1.129634 +          /* Neither the RHS or LHS are deferred. */
1.129635 +          fts3EvalNextRow(pCsr, pLeft, pRc);
1.129636 +          fts3EvalNextRow(pCsr, pRight, pRc);
1.129637 +          while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
1.129638 +            sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
1.129639 +            if( iDiff==0 ) break;
1.129640 +            if( iDiff<0 ){
1.129641 +              fts3EvalNextRow(pCsr, pLeft, pRc);
1.129642 +            }else{
1.129643 +              fts3EvalNextRow(pCsr, pRight, pRc);
1.129644 +            }
1.129645 +          }
1.129646 +          pExpr->iDocid = pLeft->iDocid;
1.129647 +          pExpr->bEof = (pLeft->bEof || pRight->bEof);
1.129648 +        }
1.129649 +        break;
1.129650 +      }
1.129651 +  
1.129652 +      case FTSQUERY_OR: {
1.129653 +        Fts3Expr *pLeft = pExpr->pLeft;
1.129654 +        Fts3Expr *pRight = pExpr->pRight;
1.129655 +        sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
1.129656 +
1.129657 +        assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
1.129658 +        assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
1.129659 +
1.129660 +        if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
1.129661 +          fts3EvalNextRow(pCsr, pLeft, pRc);
1.129662 +        }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
1.129663 +          fts3EvalNextRow(pCsr, pRight, pRc);
1.129664 +        }else{
1.129665 +          fts3EvalNextRow(pCsr, pLeft, pRc);
1.129666 +          fts3EvalNextRow(pCsr, pRight, pRc);
1.129667 +        }
1.129668 +
1.129669 +        pExpr->bEof = (pLeft->bEof && pRight->bEof);
1.129670 +        iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
1.129671 +        if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
1.129672 +          pExpr->iDocid = pLeft->iDocid;
1.129673 +        }else{
1.129674 +          pExpr->iDocid = pRight->iDocid;
1.129675 +        }
1.129676 +
1.129677 +        break;
1.129678 +      }
1.129679 +
1.129680 +      case FTSQUERY_NOT: {
1.129681 +        Fts3Expr *pLeft = pExpr->pLeft;
1.129682 +        Fts3Expr *pRight = pExpr->pRight;
1.129683 +
1.129684 +        if( pRight->bStart==0 ){
1.129685 +          fts3EvalNextRow(pCsr, pRight, pRc);
1.129686 +          assert( *pRc!=SQLITE_OK || pRight->bStart );
1.129687 +        }
1.129688 +
1.129689 +        fts3EvalNextRow(pCsr, pLeft, pRc);
1.129690 +        if( pLeft->bEof==0 ){
1.129691 +          while( !*pRc 
1.129692 +              && !pRight->bEof 
1.129693 +              && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 
1.129694 +          ){
1.129695 +            fts3EvalNextRow(pCsr, pRight, pRc);
1.129696 +          }
1.129697 +        }
1.129698 +        pExpr->iDocid = pLeft->iDocid;
1.129699 +        pExpr->bEof = pLeft->bEof;
1.129700 +        break;
1.129701 +      }
1.129702 +
1.129703 +      default: {
1.129704 +        Fts3Phrase *pPhrase = pExpr->pPhrase;
1.129705 +        fts3EvalInvalidatePoslist(pPhrase);
1.129706 +        *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
1.129707 +        pExpr->iDocid = pPhrase->doclist.iDocid;
1.129708 +        break;
1.129709 +      }
1.129710 +    }
1.129711 +  }
1.129712 +}
1.129713 +
1.129714 +/*
1.129715 +** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
1.129716 +** cluster, then this function returns 1 immediately.
1.129717 +**
1.129718 +** Otherwise, it checks if the current row really does match the NEAR 
1.129719 +** expression, using the data currently stored in the position lists 
1.129720 +** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. 
1.129721 +**
1.129722 +** If the current row is a match, the position list associated with each
1.129723 +** phrase in the NEAR expression is edited in place to contain only those
1.129724 +** phrase instances sufficiently close to their peers to satisfy all NEAR
1.129725 +** constraints. In this case it returns 1. If the NEAR expression does not 
1.129726 +** match the current row, 0 is returned. The position lists may or may not
1.129727 +** be edited if 0 is returned.
1.129728 +*/
1.129729 +static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
1.129730 +  int res = 1;
1.129731 +
1.129732 +  /* The following block runs if pExpr is the root of a NEAR query.
1.129733 +  ** For example, the query:
1.129734 +  **
1.129735 +  **         "w" NEAR "x" NEAR "y" NEAR "z"
1.129736 +  **
1.129737 +  ** which is represented in tree form as:
1.129738 +  **
1.129739 +  **                               |
1.129740 +  **                          +--NEAR--+      <-- root of NEAR query
1.129741 +  **                          |        |
1.129742 +  **                     +--NEAR--+   "z"
1.129743 +  **                     |        |
1.129744 +  **                +--NEAR--+   "y"
1.129745 +  **                |        |
1.129746 +  **               "w"      "x"
1.129747 +  **
1.129748 +  ** The right-hand child of a NEAR node is always a phrase. The 
1.129749 +  ** left-hand child may be either a phrase or a NEAR node. There are
1.129750 +  ** no exceptions to this - it's the way the parser in fts3_expr.c works.
1.129751 +  */
1.129752 +  if( *pRc==SQLITE_OK 
1.129753 +   && pExpr->eType==FTSQUERY_NEAR 
1.129754 +   && pExpr->bEof==0
1.129755 +   && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
1.129756 +  ){
1.129757 +    Fts3Expr *p; 
1.129758 +    int nTmp = 0;                 /* Bytes of temp space */
1.129759 +    char *aTmp;                   /* Temp space for PoslistNearMerge() */
1.129760 +
1.129761 +    /* Allocate temporary working space. */
1.129762 +    for(p=pExpr; p->pLeft; p=p->pLeft){
1.129763 +      nTmp += p->pRight->pPhrase->doclist.nList;
1.129764 +    }
1.129765 +    nTmp += p->pPhrase->doclist.nList;
1.129766 +    if( nTmp==0 ){
1.129767 +      res = 0;
1.129768 +    }else{
1.129769 +      aTmp = sqlite3_malloc(nTmp*2);
1.129770 +      if( !aTmp ){
1.129771 +        *pRc = SQLITE_NOMEM;
1.129772 +        res = 0;
1.129773 +      }else{
1.129774 +        char *aPoslist = p->pPhrase->doclist.pList;
1.129775 +        int nToken = p->pPhrase->nToken;
1.129776 +
1.129777 +        for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
1.129778 +          Fts3Phrase *pPhrase = p->pRight->pPhrase;
1.129779 +          int nNear = p->nNear;
1.129780 +          res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
1.129781 +        }
1.129782 +
1.129783 +        aPoslist = pExpr->pRight->pPhrase->doclist.pList;
1.129784 +        nToken = pExpr->pRight->pPhrase->nToken;
1.129785 +        for(p=pExpr->pLeft; p && res; p=p->pLeft){
1.129786 +          int nNear;
1.129787 +          Fts3Phrase *pPhrase;
1.129788 +          assert( p->pParent && p->pParent->pLeft==p );
1.129789 +          nNear = p->pParent->nNear;
1.129790 +          pPhrase = (
1.129791 +              p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
1.129792 +              );
1.129793 +          res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
1.129794 +        }
1.129795 +      }
1.129796 +
1.129797 +      sqlite3_free(aTmp);
1.129798 +    }
1.129799 +  }
1.129800 +
1.129801 +  return res;
1.129802 +}
1.129803 +
1.129804 +/*
1.129805 +** This function is a helper function for fts3EvalTestDeferredAndNear().
1.129806 +** Assuming no error occurs or has occurred, It returns non-zero if the
1.129807 +** expression passed as the second argument matches the row that pCsr 
1.129808 +** currently points to, or zero if it does not.
1.129809 +**
1.129810 +** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
1.129811 +** If an error occurs during execution of this function, *pRc is set to 
1.129812 +** the appropriate SQLite error code. In this case the returned value is 
1.129813 +** undefined.
1.129814 +*/
1.129815 +static int fts3EvalTestExpr(
1.129816 +  Fts3Cursor *pCsr,               /* FTS cursor handle */
1.129817 +  Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
1.129818 +  int *pRc                        /* IN/OUT: Error code */
1.129819 +){
1.129820 +  int bHit = 1;                   /* Return value */
1.129821 +  if( *pRc==SQLITE_OK ){
1.129822 +    switch( pExpr->eType ){
1.129823 +      case FTSQUERY_NEAR:
1.129824 +      case FTSQUERY_AND:
1.129825 +        bHit = (
1.129826 +            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
1.129827 +         && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
1.129828 +         && fts3EvalNearTest(pExpr, pRc)
1.129829 +        );
1.129830 +
1.129831 +        /* If the NEAR expression does not match any rows, zero the doclist for 
1.129832 +        ** all phrases involved in the NEAR. This is because the snippet(),
1.129833 +        ** offsets() and matchinfo() functions are not supposed to recognize 
1.129834 +        ** any instances of phrases that are part of unmatched NEAR queries. 
1.129835 +        ** For example if this expression:
1.129836 +        **
1.129837 +        **    ... MATCH 'a OR (b NEAR c)'
1.129838 +        **
1.129839 +        ** is matched against a row containing:
1.129840 +        **
1.129841 +        **        'a b d e'
1.129842 +        **
1.129843 +        ** then any snippet() should ony highlight the "a" term, not the "b"
1.129844 +        ** (as "b" is part of a non-matching NEAR clause).
1.129845 +        */
1.129846 +        if( bHit==0 
1.129847 +         && pExpr->eType==FTSQUERY_NEAR 
1.129848 +         && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
1.129849 +        ){
1.129850 +          Fts3Expr *p;
1.129851 +          for(p=pExpr; p->pPhrase==0; p=p->pLeft){
1.129852 +            if( p->pRight->iDocid==pCsr->iPrevId ){
1.129853 +              fts3EvalInvalidatePoslist(p->pRight->pPhrase);
1.129854 +            }
1.129855 +          }
1.129856 +          if( p->iDocid==pCsr->iPrevId ){
1.129857 +            fts3EvalInvalidatePoslist(p->pPhrase);
1.129858 +          }
1.129859 +        }
1.129860 +
1.129861 +        break;
1.129862 +
1.129863 +      case FTSQUERY_OR: {
1.129864 +        int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
1.129865 +        int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
1.129866 +        bHit = bHit1 || bHit2;
1.129867 +        break;
1.129868 +      }
1.129869 +
1.129870 +      case FTSQUERY_NOT:
1.129871 +        bHit = (
1.129872 +            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
1.129873 +         && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
1.129874 +        );
1.129875 +        break;
1.129876 +
1.129877 +      default: {
1.129878 +#ifndef SQLITE_DISABLE_FTS4_DEFERRED
1.129879 +        if( pCsr->pDeferred 
1.129880 +         && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
1.129881 +        ){
1.129882 +          Fts3Phrase *pPhrase = pExpr->pPhrase;
1.129883 +          assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
1.129884 +          if( pExpr->bDeferred ){
1.129885 +            fts3EvalInvalidatePoslist(pPhrase);
1.129886 +          }
1.129887 +          *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
1.129888 +          bHit = (pPhrase->doclist.pList!=0);
1.129889 +          pExpr->iDocid = pCsr->iPrevId;
1.129890 +        }else
1.129891 +#endif
1.129892 +        {
1.129893 +          bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
1.129894 +        }
1.129895 +        break;
1.129896 +      }
1.129897 +    }
1.129898 +  }
1.129899 +  return bHit;
1.129900 +}
1.129901 +
1.129902 +/*
1.129903 +** This function is called as the second part of each xNext operation when
1.129904 +** iterating through the results of a full-text query. At this point the
1.129905 +** cursor points to a row that matches the query expression, with the
1.129906 +** following caveats:
1.129907 +**
1.129908 +**   * Up until this point, "NEAR" operators in the expression have been
1.129909 +**     treated as "AND".
1.129910 +**
1.129911 +**   * Deferred tokens have not yet been considered.
1.129912 +**
1.129913 +** If *pRc is not SQLITE_OK when this function is called, it immediately
1.129914 +** returns 0. Otherwise, it tests whether or not after considering NEAR
1.129915 +** operators and deferred tokens the current row is still a match for the
1.129916 +** expression. It returns 1 if both of the following are true:
1.129917 +**
1.129918 +**   1. *pRc is SQLITE_OK when this function returns, and
1.129919 +**
1.129920 +**   2. After scanning the current FTS table row for the deferred tokens,
1.129921 +**      it is determined that the row does *not* match the query.
1.129922 +**
1.129923 +** Or, if no error occurs and it seems the current row does match the FTS
1.129924 +** query, return 0.
1.129925 +*/
1.129926 +static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
1.129927 +  int rc = *pRc;
1.129928 +  int bMiss = 0;
1.129929 +  if( rc==SQLITE_OK ){
1.129930 +
1.129931 +    /* If there are one or more deferred tokens, load the current row into
1.129932 +    ** memory and scan it to determine the position list for each deferred
1.129933 +    ** token. Then, see if this row is really a match, considering deferred
1.129934 +    ** tokens and NEAR operators (neither of which were taken into account
1.129935 +    ** earlier, by fts3EvalNextRow()). 
1.129936 +    */
1.129937 +    if( pCsr->pDeferred ){
1.129938 +      rc = fts3CursorSeek(0, pCsr);
1.129939 +      if( rc==SQLITE_OK ){
1.129940 +        rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
1.129941 +      }
1.129942 +    }
1.129943 +    bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
1.129944 +
1.129945 +    /* Free the position-lists accumulated for each deferred token above. */
1.129946 +    sqlite3Fts3FreeDeferredDoclists(pCsr);
1.129947 +    *pRc = rc;
1.129948 +  }
1.129949 +  return (rc==SQLITE_OK && bMiss);
1.129950 +}
1.129951 +
1.129952 +/*
1.129953 +** Advance to the next document that matches the FTS expression in
1.129954 +** Fts3Cursor.pExpr.
1.129955 +*/
1.129956 +static int fts3EvalNext(Fts3Cursor *pCsr){
1.129957 +  int rc = SQLITE_OK;             /* Return Code */
1.129958 +  Fts3Expr *pExpr = pCsr->pExpr;
1.129959 +  assert( pCsr->isEof==0 );
1.129960 +  if( pExpr==0 ){
1.129961 +    pCsr->isEof = 1;
1.129962 +  }else{
1.129963 +    do {
1.129964 +      if( pCsr->isRequireSeek==0 ){
1.129965 +        sqlite3_reset(pCsr->pStmt);
1.129966 +      }
1.129967 +      assert( sqlite3_data_count(pCsr->pStmt)==0 );
1.129968 +      fts3EvalNextRow(pCsr, pExpr, &rc);
1.129969 +      pCsr->isEof = pExpr->bEof;
1.129970 +      pCsr->isRequireSeek = 1;
1.129971 +      pCsr->isMatchinfoNeeded = 1;
1.129972 +      pCsr->iPrevId = pExpr->iDocid;
1.129973 +    }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
1.129974 +  }
1.129975 +
1.129976 +  /* Check if the cursor is past the end of the docid range specified
1.129977 +  ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */
1.129978 +  if( rc==SQLITE_OK && (
1.129979 +        (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
1.129980 +     || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
1.129981 +  )){
1.129982 +    pCsr->isEof = 1;
1.129983 +  }
1.129984 +
1.129985 +  return rc;
1.129986 +}
1.129987 +
1.129988 +/*
1.129989 +** Restart interation for expression pExpr so that the next call to
1.129990 +** fts3EvalNext() visits the first row. Do not allow incremental 
1.129991 +** loading or merging of phrase doclists for this iteration.
1.129992 +**
1.129993 +** If *pRc is other than SQLITE_OK when this function is called, it is
1.129994 +** a no-op. If an error occurs within this function, *pRc is set to an
1.129995 +** SQLite error code before returning.
1.129996 +*/
1.129997 +static void fts3EvalRestart(
1.129998 +  Fts3Cursor *pCsr,
1.129999 +  Fts3Expr *pExpr,
1.130000 +  int *pRc
1.130001 +){
1.130002 +  if( pExpr && *pRc==SQLITE_OK ){
1.130003 +    Fts3Phrase *pPhrase = pExpr->pPhrase;
1.130004 +
1.130005 +    if( pPhrase ){
1.130006 +      fts3EvalInvalidatePoslist(pPhrase);
1.130007 +      if( pPhrase->bIncr ){
1.130008 +        int i;
1.130009 +        for(i=0; i<pPhrase->nToken; i++){
1.130010 +          Fts3PhraseToken *pToken = &pPhrase->aToken[i];
1.130011 +          assert( pToken->pDeferred==0 );
1.130012 +          if( pToken->pSegcsr ){
1.130013 +            sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
1.130014 +          }
1.130015 +        }
1.130016 +        *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
1.130017 +      }
1.130018 +      pPhrase->doclist.pNextDocid = 0;
1.130019 +      pPhrase->doclist.iDocid = 0;
1.130020 +    }
1.130021 +
1.130022 +    pExpr->iDocid = 0;
1.130023 +    pExpr->bEof = 0;
1.130024 +    pExpr->bStart = 0;
1.130025 +
1.130026 +    fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
1.130027 +    fts3EvalRestart(pCsr, pExpr->pRight, pRc);
1.130028 +  }
1.130029 +}
1.130030 +
1.130031 +/*
1.130032 +** After allocating the Fts3Expr.aMI[] array for each phrase in the 
1.130033 +** expression rooted at pExpr, the cursor iterates through all rows matched
1.130034 +** by pExpr, calling this function for each row. This function increments
1.130035 +** the values in Fts3Expr.aMI[] according to the position-list currently
1.130036 +** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase 
1.130037 +** expression nodes.
1.130038 +*/
1.130039 +static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
1.130040 +  if( pExpr ){
1.130041 +    Fts3Phrase *pPhrase = pExpr->pPhrase;
1.130042 +    if( pPhrase && pPhrase->doclist.pList ){
1.130043 +      int iCol = 0;
1.130044 +      char *p = pPhrase->doclist.pList;
1.130045 +
1.130046 +      assert( *p );
1.130047 +      while( 1 ){
1.130048 +        u8 c = 0;
1.130049 +        int iCnt = 0;
1.130050 +        while( 0xFE & (*p | c) ){
1.130051 +          if( (c&0x80)==0 ) iCnt++;
1.130052 +          c = *p++ & 0x80;
1.130053 +        }
1.130054 +
1.130055 +        /* aMI[iCol*3 + 1] = Number of occurrences
1.130056 +        ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
1.130057 +        */
1.130058 +        pExpr->aMI[iCol*3 + 1] += iCnt;
1.130059 +        pExpr->aMI[iCol*3 + 2] += (iCnt>0);
1.130060 +        if( *p==0x00 ) break;
1.130061 +        p++;
1.130062 +        p += fts3GetVarint32(p, &iCol);
1.130063 +      }
1.130064 +    }
1.130065 +
1.130066 +    fts3EvalUpdateCounts(pExpr->pLeft);
1.130067 +    fts3EvalUpdateCounts(pExpr->pRight);
1.130068 +  }
1.130069 +}
1.130070 +
1.130071 +/*
1.130072 +** Expression pExpr must be of type FTSQUERY_PHRASE.
1.130073 +**
1.130074 +** If it is not already allocated and populated, this function allocates and
1.130075 +** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
1.130076 +** of a NEAR expression, then it also allocates and populates the same array
1.130077 +** for all other phrases that are part of the NEAR expression.
1.130078 +**
1.130079 +** SQLITE_OK is returned if the aMI[] array is successfully allocated and
1.130080 +** populated. Otherwise, if an error occurs, an SQLite error code is returned.
1.130081 +*/
1.130082 +static int fts3EvalGatherStats(
1.130083 +  Fts3Cursor *pCsr,               /* Cursor object */
1.130084 +  Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
1.130085 +){
1.130086 +  int rc = SQLITE_OK;             /* Return code */
1.130087 +
1.130088 +  assert( pExpr->eType==FTSQUERY_PHRASE );
1.130089 +  if( pExpr->aMI==0 ){
1.130090 +    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
1.130091 +    Fts3Expr *pRoot;                /* Root of NEAR expression */
1.130092 +    Fts3Expr *p;                    /* Iterator used for several purposes */
1.130093 +
1.130094 +    sqlite3_int64 iPrevId = pCsr->iPrevId;
1.130095 +    sqlite3_int64 iDocid;
1.130096 +    u8 bEof;
1.130097 +
1.130098 +    /* Find the root of the NEAR expression */
1.130099 +    pRoot = pExpr;
1.130100 +    while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
1.130101 +      pRoot = pRoot->pParent;
1.130102 +    }
1.130103 +    iDocid = pRoot->iDocid;
1.130104 +    bEof = pRoot->bEof;
1.130105 +    assert( pRoot->bStart );
1.130106 +
1.130107 +    /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
1.130108 +    for(p=pRoot; p; p=p->pLeft){
1.130109 +      Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
1.130110 +      assert( pE->aMI==0 );
1.130111 +      pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
1.130112 +      if( !pE->aMI ) return SQLITE_NOMEM;
1.130113 +      memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
1.130114 +    }
1.130115 +
1.130116 +    fts3EvalRestart(pCsr, pRoot, &rc);
1.130117 +
1.130118 +    while( pCsr->isEof==0 && rc==SQLITE_OK ){
1.130119 +
1.130120 +      do {
1.130121 +        /* Ensure the %_content statement is reset. */
1.130122 +        if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
1.130123 +        assert( sqlite3_data_count(pCsr->pStmt)==0 );
1.130124 +
1.130125 +        /* Advance to the next document */
1.130126 +        fts3EvalNextRow(pCsr, pRoot, &rc);
1.130127 +        pCsr->isEof = pRoot->bEof;
1.130128 +        pCsr->isRequireSeek = 1;
1.130129 +        pCsr->isMatchinfoNeeded = 1;
1.130130 +        pCsr->iPrevId = pRoot->iDocid;
1.130131 +      }while( pCsr->isEof==0 
1.130132 +           && pRoot->eType==FTSQUERY_NEAR 
1.130133 +           && fts3EvalTestDeferredAndNear(pCsr, &rc) 
1.130134 +      );
1.130135 +
1.130136 +      if( rc==SQLITE_OK && pCsr->isEof==0 ){
1.130137 +        fts3EvalUpdateCounts(pRoot);
1.130138 +      }
1.130139 +    }
1.130140 +
1.130141 +    pCsr->isEof = 0;
1.130142 +    pCsr->iPrevId = iPrevId;
1.130143 +
1.130144 +    if( bEof ){
1.130145 +      pRoot->bEof = bEof;
1.130146 +    }else{
1.130147 +      /* Caution: pRoot may iterate through docids in ascending or descending
1.130148 +      ** order. For this reason, even though it seems more defensive, the 
1.130149 +      ** do loop can not be written:
1.130150 +      **
1.130151 +      **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
1.130152 +      */
1.130153 +      fts3EvalRestart(pCsr, pRoot, &rc);
1.130154 +      do {
1.130155 +        fts3EvalNextRow(pCsr, pRoot, &rc);
1.130156 +        assert( pRoot->bEof==0 );
1.130157 +      }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
1.130158 +      fts3EvalTestDeferredAndNear(pCsr, &rc);
1.130159 +    }
1.130160 +  }
1.130161 +  return rc;
1.130162 +}
1.130163 +
1.130164 +/*
1.130165 +** This function is used by the matchinfo() module to query a phrase 
1.130166 +** expression node for the following information:
1.130167 +**
1.130168 +**   1. The total number of occurrences of the phrase in each column of 
1.130169 +**      the FTS table (considering all rows), and
1.130170 +**
1.130171 +**   2. For each column, the number of rows in the table for which the
1.130172 +**      column contains at least one instance of the phrase.
1.130173 +**
1.130174 +** If no error occurs, SQLITE_OK is returned and the values for each column
1.130175 +** written into the array aiOut as follows:
1.130176 +**
1.130177 +**   aiOut[iCol*3 + 1] = Number of occurrences
1.130178 +**   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
1.130179 +**
1.130180 +** Caveats:
1.130181 +**
1.130182 +**   * If a phrase consists entirely of deferred tokens, then all output 
1.130183 +**     values are set to the number of documents in the table. In other
1.130184 +**     words we assume that very common tokens occur exactly once in each 
1.130185 +**     column of each row of the table.
1.130186 +**
1.130187 +**   * If a phrase contains some deferred tokens (and some non-deferred 
1.130188 +**     tokens), count the potential occurrence identified by considering
1.130189 +**     the non-deferred tokens instead of actual phrase occurrences.
1.130190 +**
1.130191 +**   * If the phrase is part of a NEAR expression, then only phrase instances
1.130192 +**     that meet the NEAR constraint are included in the counts.
1.130193 +*/
1.130194 +SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
1.130195 +  Fts3Cursor *pCsr,               /* FTS cursor handle */
1.130196 +  Fts3Expr *pExpr,                /* Phrase expression */
1.130197 +  u32 *aiOut                      /* Array to write results into (see above) */
1.130198 +){
1.130199 +  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
1.130200 +  int rc = SQLITE_OK;
1.130201 +  int iCol;
1.130202 +
1.130203 +  if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
1.130204 +    assert( pCsr->nDoc>0 );
1.130205 +    for(iCol=0; iCol<pTab->nColumn; iCol++){
1.130206 +      aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
1.130207 +      aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
1.130208 +    }
1.130209 +  }else{
1.130210 +    rc = fts3EvalGatherStats(pCsr, pExpr);
1.130211 +    if( rc==SQLITE_OK ){
1.130212 +      assert( pExpr->aMI );
1.130213 +      for(iCol=0; iCol<pTab->nColumn; iCol++){
1.130214 +        aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
1.130215 +        aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
1.130216 +      }
1.130217 +    }
1.130218 +  }
1.130219 +
1.130220 +  return rc;
1.130221 +}
1.130222 +
1.130223 +/*
1.130224 +** The expression pExpr passed as the second argument to this function
1.130225 +** must be of type FTSQUERY_PHRASE. 
1.130226 +**
1.130227 +** The returned value is either NULL or a pointer to a buffer containing
1.130228 +** a position-list indicating the occurrences of the phrase in column iCol
1.130229 +** of the current row. 
1.130230 +**
1.130231 +** More specifically, the returned buffer contains 1 varint for each 
1.130232 +** occurrence of the phrase in the column, stored using the normal (delta+2) 
1.130233 +** compression and is terminated by either an 0x01 or 0x00 byte. For example,
1.130234 +** if the requested column contains "a b X c d X X" and the position-list
1.130235 +** for 'X' is requested, the buffer returned may contain:
1.130236 +**
1.130237 +**     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
1.130238 +**
1.130239 +** This function works regardless of whether or not the phrase is deferred,
1.130240 +** incremental, or neither.
1.130241 +*/
1.130242 +SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
1.130243 +  Fts3Cursor *pCsr,               /* FTS3 cursor object */
1.130244 +  Fts3Expr *pExpr,                /* Phrase to return doclist for */
1.130245 +  int iCol,                       /* Column to return position list for */
1.130246 +  char **ppOut                    /* OUT: Pointer to position list */
1.130247 +){
1.130248 +  Fts3Phrase *pPhrase = pExpr->pPhrase;
1.130249 +  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
1.130250 +  char *pIter;
1.130251 +  int iThis;
1.130252 +  sqlite3_int64 iDocid;
1.130253 +
1.130254 +  /* If this phrase is applies specifically to some column other than 
1.130255 +  ** column iCol, return a NULL pointer.  */
1.130256 +  *ppOut = 0;
1.130257 +  assert( iCol>=0 && iCol<pTab->nColumn );
1.130258 +  if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
1.130259 +    return SQLITE_OK;
1.130260 +  }
1.130261 +
1.130262 +  iDocid = pExpr->iDocid;
1.130263 +  pIter = pPhrase->doclist.pList;
1.130264 +  if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
1.130265 +    int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
1.130266 +    int iMul;                     /* +1 if csr dir matches index dir, else -1 */
1.130267 +    int bOr = 0;
1.130268 +    u8 bEof = 0;
1.130269 +    u8 bTreeEof = 0;
1.130270 +    Fts3Expr *p;                  /* Used to iterate from pExpr to root */
1.130271 +    Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
1.130272 +
1.130273 +    /* Check if this phrase descends from an OR expression node. If not, 
1.130274 +    ** return NULL. Otherwise, the entry that corresponds to docid 
1.130275 +    ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
1.130276 +    ** tree that the node is part of has been marked as EOF, but the node
1.130277 +    ** itself is not EOF, then it may point to an earlier entry. */
1.130278 +    pNear = pExpr;
1.130279 +    for(p=pExpr->pParent; p; p=p->pParent){
1.130280 +      if( p->eType==FTSQUERY_OR ) bOr = 1;
1.130281 +      if( p->eType==FTSQUERY_NEAR ) pNear = p;
1.130282 +      if( p->bEof ) bTreeEof = 1;
1.130283 +    }
1.130284 +    if( bOr==0 ) return SQLITE_OK;
1.130285 +
1.130286 +    /* This is the descendent of an OR node. In this case we cannot use
1.130287 +    ** an incremental phrase. Load the entire doclist for the phrase
1.130288 +    ** into memory in this case.  */
1.130289 +    if( pPhrase->bIncr ){
1.130290 +      int rc = SQLITE_OK;
1.130291 +      int bEofSave = pExpr->bEof;
1.130292 +      fts3EvalRestart(pCsr, pExpr, &rc);
1.130293 +      while( rc==SQLITE_OK && !pExpr->bEof ){
1.130294 +        fts3EvalNextRow(pCsr, pExpr, &rc);
1.130295 +        if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
1.130296 +      }
1.130297 +      pIter = pPhrase->doclist.pList;
1.130298 +      assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
1.130299 +      if( rc!=SQLITE_OK ) return rc;
1.130300 +    }
1.130301 +    
1.130302 +    iMul = ((pCsr->bDesc==bDescDoclist) ? 1 : -1);
1.130303 +    while( bTreeEof==1 
1.130304 +        && pNear->bEof==0
1.130305 +        && (DOCID_CMP(pNear->iDocid, pCsr->iPrevId) * iMul)<0
1.130306 +    ){
1.130307 +      int rc = SQLITE_OK;
1.130308 +      fts3EvalNextRow(pCsr, pExpr, &rc);
1.130309 +      if( rc!=SQLITE_OK ) return rc;
1.130310 +      iDocid = pExpr->iDocid;
1.130311 +      pIter = pPhrase->doclist.pList;
1.130312 +    }
1.130313 +
1.130314 +    bEof = (pPhrase->doclist.nAll==0);
1.130315 +    assert( bDescDoclist==0 || bDescDoclist==1 );
1.130316 +    assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
1.130317 +
1.130318 +    if( bEof==0 ){
1.130319 +      if( pCsr->bDesc==bDescDoclist ){
1.130320 +        int dummy;
1.130321 +        if( pNear->bEof ){
1.130322 +          /* This expression is already at EOF. So position it to point to the
1.130323 +          ** last entry in the doclist at pPhrase->doclist.aAll[]. Variable
1.130324 +          ** iDocid is already set for this entry, so all that is required is
1.130325 +          ** to set pIter to point to the first byte of the last position-list
1.130326 +          ** in the doclist. 
1.130327 +          **
1.130328 +          ** It would also be correct to set pIter and iDocid to zero. In
1.130329 +          ** this case, the first call to sqltie3Fts4DoclistPrev() below
1.130330 +          ** would also move the iterator to point to the last entry in the 
1.130331 +          ** doclist. However, this is expensive, as to do so it has to 
1.130332 +          ** iterate through the entire doclist from start to finish (since
1.130333 +          ** it does not know the docid for the last entry).  */
1.130334 +          pIter = &pPhrase->doclist.aAll[pPhrase->doclist.nAll-1];
1.130335 +          fts3ReversePoslist(pPhrase->doclist.aAll, &pIter);
1.130336 +        }
1.130337 +        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
1.130338 +          sqlite3Fts3DoclistPrev(
1.130339 +              bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, 
1.130340 +              &pIter, &iDocid, &dummy, &bEof
1.130341 +          );
1.130342 +        }
1.130343 +      }else{
1.130344 +        if( pNear->bEof ){
1.130345 +          pIter = 0;
1.130346 +          iDocid = 0;
1.130347 +        }
1.130348 +        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
1.130349 +          sqlite3Fts3DoclistNext(
1.130350 +              bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, 
1.130351 +              &pIter, &iDocid, &bEof
1.130352 +          );
1.130353 +        }
1.130354 +      }
1.130355 +    }
1.130356 +
1.130357 +    if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
1.130358 +  }
1.130359 +  if( pIter==0 ) return SQLITE_OK;
1.130360 +
1.130361 +  if( *pIter==0x01 ){
1.130362 +    pIter++;
1.130363 +    pIter += fts3GetVarint32(pIter, &iThis);
1.130364 +  }else{
1.130365 +    iThis = 0;
1.130366 +  }
1.130367 +  while( iThis<iCol ){
1.130368 +    fts3ColumnlistCopy(0, &pIter);
1.130369 +    if( *pIter==0x00 ) return 0;
1.130370 +    pIter++;
1.130371 +    pIter += fts3GetVarint32(pIter, &iThis);
1.130372 +  }
1.130373 +
1.130374 +  *ppOut = ((iCol==iThis)?pIter:0);
1.130375 +  return SQLITE_OK;
1.130376 +}
1.130377 +
1.130378 +/*
1.130379 +** Free all components of the Fts3Phrase structure that were allocated by
1.130380 +** the eval module. Specifically, this means to free:
1.130381 +**
1.130382 +**   * the contents of pPhrase->doclist, and
1.130383 +**   * any Fts3MultiSegReader objects held by phrase tokens.
1.130384 +*/
1.130385 +SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
1.130386 +  if( pPhrase ){
1.130387 +    int i;
1.130388 +    sqlite3_free(pPhrase->doclist.aAll);
1.130389 +    fts3EvalInvalidatePoslist(pPhrase);
1.130390 +    memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
1.130391 +    for(i=0; i<pPhrase->nToken; i++){
1.130392 +      fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
1.130393 +      pPhrase->aToken[i].pSegcsr = 0;
1.130394 +    }
1.130395 +  }
1.130396 +}
1.130397 +
1.130398 +
1.130399 +/*
1.130400 +** Return SQLITE_CORRUPT_VTAB.
1.130401 +*/
1.130402 +#ifdef SQLITE_DEBUG
1.130403 +SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
1.130404 +  return SQLITE_CORRUPT_VTAB;
1.130405 +}
1.130406 +#endif
1.130407 +
1.130408 +#if !SQLITE_CORE
1.130409 +/*
1.130410 +** Initialize API pointer table, if required.
1.130411 +*/
1.130412 +#ifdef _WIN32
1.130413 +__declspec(dllexport)
1.130414 +#endif
1.130415 +SQLITE_API int sqlite3_fts3_init(
1.130416 +  sqlite3 *db, 
1.130417 +  char **pzErrMsg,
1.130418 +  const sqlite3_api_routines *pApi
1.130419 +){
1.130420 +  SQLITE_EXTENSION_INIT2(pApi)
1.130421 +  return sqlite3Fts3Init(db);
1.130422 +}
1.130423 +#endif
1.130424 +
1.130425 +#endif
1.130426 +
1.130427 +/************** End of fts3.c ************************************************/
1.130428 +/************** Begin file fts3_aux.c ****************************************/
1.130429 +/*
1.130430 +** 2011 Jan 27
1.130431 +**
1.130432 +** The author disclaims copyright to this source code.  In place of
1.130433 +** a legal notice, here is a blessing:
1.130434 +**
1.130435 +**    May you do good and not evil.
1.130436 +**    May you find forgiveness for yourself and forgive others.
1.130437 +**    May you share freely, never taking more than you give.
1.130438 +**
1.130439 +******************************************************************************
1.130440 +**
1.130441 +*/
1.130442 +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
1.130443 +
1.130444 +/* #include <string.h> */
1.130445 +/* #include <assert.h> */
1.130446 +
1.130447 +typedef struct Fts3auxTable Fts3auxTable;
1.130448 +typedef struct Fts3auxCursor Fts3auxCursor;
1.130449 +
1.130450 +struct Fts3auxTable {
1.130451 +  sqlite3_vtab base;              /* Base class used by SQLite core */
1.130452 +  Fts3Table *pFts3Tab;
1.130453 +};
1.130454 +
1.130455 +struct Fts3auxCursor {
1.130456 +  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
1.130457 +  Fts3MultiSegReader csr;        /* Must be right after "base" */
1.130458 +  Fts3SegFilter filter;
1.130459 +  char *zStop;
1.130460 +  int nStop;                      /* Byte-length of string zStop */
1.130461 +  int iLangid;                    /* Language id to query */
1.130462 +  int isEof;                      /* True if cursor is at EOF */
1.130463 +  sqlite3_int64 iRowid;           /* Current rowid */
1.130464 +
1.130465 +  int iCol;                       /* Current value of 'col' column */
1.130466 +  int nStat;                      /* Size of aStat[] array */
1.130467 +  struct Fts3auxColstats {
1.130468 +    sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
1.130469 +    sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
1.130470 +  } *aStat;
1.130471 +};
1.130472 +
1.130473 +/*
1.130474 +** Schema of the terms table.
1.130475 +*/
1.130476 +#define FTS3_AUX_SCHEMA \
1.130477 +  "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
1.130478 +
1.130479 +/*
1.130480 +** This function does all the work for both the xConnect and xCreate methods.
1.130481 +** These tables have no persistent representation of their own, so xConnect
1.130482 +** and xCreate are identical operations.
1.130483 +*/
1.130484 +static int fts3auxConnectMethod(
1.130485 +  sqlite3 *db,                    /* Database connection */
1.130486 +  void *pUnused,                  /* Unused */
1.130487 +  int argc,                       /* Number of elements in argv array */
1.130488 +  const char * const *argv,       /* xCreate/xConnect argument array */
1.130489 +  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
1.130490 +  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
1.130491 +){
1.130492 +  char const *zDb;                /* Name of database (e.g. "main") */
1.130493 +  char const *zFts3;              /* Name of fts3 table */
1.130494 +  int nDb;                        /* Result of strlen(zDb) */
1.130495 +  int nFts3;                      /* Result of strlen(zFts3) */
1.130496 +  int nByte;                      /* Bytes of space to allocate here */
1.130497 +  int rc;                         /* value returned by declare_vtab() */
1.130498 +  Fts3auxTable *p;                /* Virtual table object to return */
1.130499 +
1.130500 +  UNUSED_PARAMETER(pUnused);
1.130501 +
1.130502 +  /* The user should invoke this in one of two forms:
1.130503 +  **
1.130504 +  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
1.130505 +  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
1.130506 +  */
1.130507 +  if( argc!=4 && argc!=5 ) goto bad_args;
1.130508 +
1.130509 +  zDb = argv[1]; 
1.130510 +  nDb = (int)strlen(zDb);
1.130511 +  if( argc==5 ){
1.130512 +    if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
1.130513 +      zDb = argv[3]; 
1.130514 +      nDb = (int)strlen(zDb);
1.130515 +      zFts3 = argv[4];
1.130516 +    }else{
1.130517 +      goto bad_args;
1.130518 +    }
1.130519 +  }else{
1.130520 +    zFts3 = argv[3];
1.130521 +  }
1.130522 +  nFts3 = (int)strlen(zFts3);
1.130523 +
1.130524 +  rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
1.130525 +  if( rc!=SQLITE_OK ) return rc;
1.130526 +
1.130527 +  nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
1.130528 +  p = (Fts3auxTable *)sqlite3_malloc(nByte);
1.130529 +  if( !p ) return SQLITE_NOMEM;
1.130530 +  memset(p, 0, nByte);
1.130531 +
1.130532 +  p->pFts3Tab = (Fts3Table *)&p[1];
1.130533 +  p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
1.130534 +  p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
1.130535 +  p->pFts3Tab->db = db;
1.130536 +  p->pFts3Tab->nIndex = 1;
1.130537 +
1.130538 +  memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
1.130539 +  memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
1.130540 +  sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
1.130541 +
1.130542 +  *ppVtab = (sqlite3_vtab *)p;
1.130543 +  return SQLITE_OK;
1.130544 +
1.130545 + bad_args:
1.130546 +  *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor");
1.130547 +  return SQLITE_ERROR;
1.130548 +}
1.130549 +
1.130550 +/*
1.130551 +** This function does the work for both the xDisconnect and xDestroy methods.
1.130552 +** These tables have no persistent representation of their own, so xDisconnect
1.130553 +** and xDestroy are identical operations.
1.130554 +*/
1.130555 +static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
1.130556 +  Fts3auxTable *p = (Fts3auxTable *)pVtab;
1.130557 +  Fts3Table *pFts3 = p->pFts3Tab;
1.130558 +  int i;
1.130559 +
1.130560 +  /* Free any prepared statements held */
1.130561 +  for(i=0; i<SizeofArray(pFts3->aStmt); i++){
1.130562 +    sqlite3_finalize(pFts3->aStmt[i]);
1.130563 +  }
1.130564 +  sqlite3_free(pFts3->zSegmentsTbl);
1.130565 +  sqlite3_free(p);
1.130566 +  return SQLITE_OK;
1.130567 +}
1.130568 +
1.130569 +#define FTS4AUX_EQ_CONSTRAINT 1
1.130570 +#define FTS4AUX_GE_CONSTRAINT 2
1.130571 +#define FTS4AUX_LE_CONSTRAINT 4
1.130572 +
1.130573 +/*
1.130574 +** xBestIndex - Analyze a WHERE and ORDER BY clause.
1.130575 +*/
1.130576 +static int fts3auxBestIndexMethod(
1.130577 +  sqlite3_vtab *pVTab, 
1.130578 +  sqlite3_index_info *pInfo
1.130579 +){
1.130580 +  int i;
1.130581 +  int iEq = -1;
1.130582 +  int iGe = -1;
1.130583 +  int iLe = -1;
1.130584 +  int iLangid = -1;
1.130585 +  int iNext = 1;                  /* Next free argvIndex value */
1.130586 +
1.130587 +  UNUSED_PARAMETER(pVTab);
1.130588 +
1.130589 +  /* This vtab delivers always results in "ORDER BY term ASC" order. */
1.130590 +  if( pInfo->nOrderBy==1 
1.130591 +   && pInfo->aOrderBy[0].iColumn==0 
1.130592 +   && pInfo->aOrderBy[0].desc==0
1.130593 +  ){
1.130594 +    pInfo->orderByConsumed = 1;
1.130595 +  }
1.130596 +
1.130597 +  /* Search for equality and range constraints on the "term" column. 
1.130598 +  ** And equality constraints on the hidden "languageid" column. */
1.130599 +  for(i=0; i<pInfo->nConstraint; i++){
1.130600 +    if( pInfo->aConstraint[i].usable ){
1.130601 +      int op = pInfo->aConstraint[i].op;
1.130602 +      int iCol = pInfo->aConstraint[i].iColumn;
1.130603 +
1.130604 +      if( iCol==0 ){
1.130605 +        if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
1.130606 +        if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
1.130607 +        if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
1.130608 +        if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
1.130609 +        if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
1.130610 +      }
1.130611 +      if( iCol==4 ){
1.130612 +        if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
1.130613 +      }
1.130614 +    }
1.130615 +  }
1.130616 +
1.130617 +  if( iEq>=0 ){
1.130618 +    pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
1.130619 +    pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
1.130620 +    pInfo->estimatedCost = 5;
1.130621 +  }else{
1.130622 +    pInfo->idxNum = 0;
1.130623 +    pInfo->estimatedCost = 20000;
1.130624 +    if( iGe>=0 ){
1.130625 +      pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
1.130626 +      pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
1.130627 +      pInfo->estimatedCost /= 2;
1.130628 +    }
1.130629 +    if( iLe>=0 ){
1.130630 +      pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
1.130631 +      pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
1.130632 +      pInfo->estimatedCost /= 2;
1.130633 +    }
1.130634 +  }
1.130635 +  if( iLangid>=0 ){
1.130636 +    pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
1.130637 +    pInfo->estimatedCost--;
1.130638 +  }
1.130639 +
1.130640 +  return SQLITE_OK;
1.130641 +}
1.130642 +
1.130643 +/*
1.130644 +** xOpen - Open a cursor.
1.130645 +*/
1.130646 +static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
1.130647 +  Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
1.130648 +
1.130649 +  UNUSED_PARAMETER(pVTab);
1.130650 +
1.130651 +  pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
1.130652 +  if( !pCsr ) return SQLITE_NOMEM;
1.130653 +  memset(pCsr, 0, sizeof(Fts3auxCursor));
1.130654 +
1.130655 +  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
1.130656 +  return SQLITE_OK;
1.130657 +}
1.130658 +
1.130659 +/*
1.130660 +** xClose - Close a cursor.
1.130661 +*/
1.130662 +static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
1.130663 +  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
1.130664 +  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
1.130665 +
1.130666 +  sqlite3Fts3SegmentsClose(pFts3);
1.130667 +  sqlite3Fts3SegReaderFinish(&pCsr->csr);
1.130668 +  sqlite3_free((void *)pCsr->filter.zTerm);
1.130669 +  sqlite3_free(pCsr->zStop);
1.130670 +  sqlite3_free(pCsr->aStat);
1.130671 +  sqlite3_free(pCsr);
1.130672 +  return SQLITE_OK;
1.130673 +}
1.130674 +
1.130675 +static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
1.130676 +  if( nSize>pCsr->nStat ){
1.130677 +    struct Fts3auxColstats *aNew;
1.130678 +    aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat, 
1.130679 +        sizeof(struct Fts3auxColstats) * nSize
1.130680 +    );
1.130681 +    if( aNew==0 ) return SQLITE_NOMEM;
1.130682 +    memset(&aNew[pCsr->nStat], 0, 
1.130683 +        sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
1.130684 +    );
1.130685 +    pCsr->aStat = aNew;
1.130686 +    pCsr->nStat = nSize;
1.130687 +  }
1.130688 +  return SQLITE_OK;
1.130689 +}
1.130690 +
1.130691 +/*
1.130692 +** xNext - Advance the cursor to the next row, if any.
1.130693 +*/
1.130694 +static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
1.130695 +  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
1.130696 +  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
1.130697 +  int rc;
1.130698 +
1.130699 +  /* Increment our pretend rowid value. */
1.130700 +  pCsr->iRowid++;
1.130701 +
1.130702 +  for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
1.130703 +    if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
1.130704 +  }
1.130705 +
1.130706 +  rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
1.130707 +  if( rc==SQLITE_ROW ){
1.130708 +    int i = 0;
1.130709 +    int nDoclist = pCsr->csr.nDoclist;
1.130710 +    char *aDoclist = pCsr->csr.aDoclist;
1.130711 +    int iCol;
1.130712 +
1.130713 +    int eState = 0;
1.130714 +
1.130715 +    if( pCsr->zStop ){
1.130716 +      int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
1.130717 +      int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
1.130718 +      if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
1.130719 +        pCsr->isEof = 1;
1.130720 +        return SQLITE_OK;
1.130721 +      }
1.130722 +    }
1.130723 +
1.130724 +    if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
1.130725 +    memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
1.130726 +    iCol = 0;
1.130727 +
1.130728 +    while( i<nDoclist ){
1.130729 +      sqlite3_int64 v = 0;
1.130730 +
1.130731 +      i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
1.130732 +      switch( eState ){
1.130733 +        /* State 0. In this state the integer just read was a docid. */
1.130734 +        case 0:
1.130735 +          pCsr->aStat[0].nDoc++;
1.130736 +          eState = 1;
1.130737 +          iCol = 0;
1.130738 +          break;
1.130739 +
1.130740 +        /* State 1. In this state we are expecting either a 1, indicating
1.130741 +        ** that the following integer will be a column number, or the
1.130742 +        ** start of a position list for column 0.  
1.130743 +        ** 
1.130744 +        ** The only difference between state 1 and state 2 is that if the
1.130745 +        ** integer encountered in state 1 is not 0 or 1, then we need to
1.130746 +        ** increment the column 0 "nDoc" count for this term.
1.130747 +        */
1.130748 +        case 1:
1.130749 +          assert( iCol==0 );
1.130750 +          if( v>1 ){
1.130751 +            pCsr->aStat[1].nDoc++;
1.130752 +          }
1.130753 +          eState = 2;
1.130754 +          /* fall through */
1.130755 +
1.130756 +        case 2:
1.130757 +          if( v==0 ){       /* 0x00. Next integer will be a docid. */
1.130758 +            eState = 0;
1.130759 +          }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
1.130760 +            eState = 3;
1.130761 +          }else{            /* 2 or greater. A position. */
1.130762 +            pCsr->aStat[iCol+1].nOcc++;
1.130763 +            pCsr->aStat[0].nOcc++;
1.130764 +          }
1.130765 +          break;
1.130766 +
1.130767 +        /* State 3. The integer just read is a column number. */
1.130768 +        default: assert( eState==3 );
1.130769 +          iCol = (int)v;
1.130770 +          if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
1.130771 +          pCsr->aStat[iCol+1].nDoc++;
1.130772 +          eState = 2;
1.130773 +          break;
1.130774 +      }
1.130775 +    }
1.130776 +
1.130777 +    pCsr->iCol = 0;
1.130778 +    rc = SQLITE_OK;
1.130779 +  }else{
1.130780 +    pCsr->isEof = 1;
1.130781 +  }
1.130782 +  return rc;
1.130783 +}
1.130784 +
1.130785 +/*
1.130786 +** xFilter - Initialize a cursor to point at the start of its data.
1.130787 +*/
1.130788 +static int fts3auxFilterMethod(
1.130789 +  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
1.130790 +  int idxNum,                     /* Strategy index */
1.130791 +  const char *idxStr,             /* Unused */
1.130792 +  int nVal,                       /* Number of elements in apVal */
1.130793 +  sqlite3_value **apVal           /* Arguments for the indexing scheme */
1.130794 +){
1.130795 +  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
1.130796 +  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
1.130797 +  int rc;
1.130798 +  int isScan = 0;
1.130799 +  int iLangVal = 0;               /* Language id to query */
1.130800 +
1.130801 +  int iEq = -1;                   /* Index of term=? value in apVal */
1.130802 +  int iGe = -1;                   /* Index of term>=? value in apVal */
1.130803 +  int iLe = -1;                   /* Index of term<=? value in apVal */
1.130804 +  int iLangid = -1;               /* Index of languageid=? value in apVal */
1.130805 +  int iNext = 0;
1.130806 +
1.130807 +  UNUSED_PARAMETER(nVal);
1.130808 +  UNUSED_PARAMETER(idxStr);
1.130809 +
1.130810 +  assert( idxStr==0 );
1.130811 +  assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
1.130812 +       || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
1.130813 +       || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
1.130814 +  );
1.130815 +
1.130816 +  if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
1.130817 +    iEq = iNext++;
1.130818 +  }else{
1.130819 +    isScan = 1;
1.130820 +    if( idxNum & FTS4AUX_GE_CONSTRAINT ){
1.130821 +      iGe = iNext++;
1.130822 +    }
1.130823 +    if( idxNum & FTS4AUX_LE_CONSTRAINT ){
1.130824 +      iLe = iNext++;
1.130825 +    }
1.130826 +  }
1.130827 +  if( iNext<nVal ){
1.130828 +    iLangid = iNext++;
1.130829 +  }
1.130830 +
1.130831 +  /* In case this cursor is being reused, close and zero it. */
1.130832 +  testcase(pCsr->filter.zTerm);
1.130833 +  sqlite3Fts3SegReaderFinish(&pCsr->csr);
1.130834 +  sqlite3_free((void *)pCsr->filter.zTerm);
1.130835 +  sqlite3_free(pCsr->aStat);
1.130836 +  memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
1.130837 +
1.130838 +  pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
1.130839 +  if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
1.130840 +
1.130841 +  if( iEq>=0 || iGe>=0 ){
1.130842 +    const unsigned char *zStr = sqlite3_value_text(apVal[0]);
1.130843 +    assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
1.130844 +    if( zStr ){
1.130845 +      pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
1.130846 +      pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
1.130847 +      if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
1.130848 +    }
1.130849 +  }
1.130850 +
1.130851 +  if( iLe>=0 ){
1.130852 +    pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
1.130853 +    pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
1.130854 +    if( pCsr->zStop==0 ) return SQLITE_NOMEM;
1.130855 +  }
1.130856 +  
1.130857 +  if( iLangid>=0 ){
1.130858 +    iLangVal = sqlite3_value_int(apVal[iLangid]);
1.130859 +
1.130860 +    /* If the user specified a negative value for the languageid, use zero
1.130861 +    ** instead. This works, as the "languageid=?" constraint will also
1.130862 +    ** be tested by the VDBE layer. The test will always be false (since
1.130863 +    ** this module will not return a row with a negative languageid), and
1.130864 +    ** so the overall query will return zero rows.  */
1.130865 +    if( iLangVal<0 ) iLangVal = 0;
1.130866 +  }
1.130867 +  pCsr->iLangid = iLangVal;
1.130868 +
1.130869 +  rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
1.130870 +      pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
1.130871 +  );
1.130872 +  if( rc==SQLITE_OK ){
1.130873 +    rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
1.130874 +  }
1.130875 +
1.130876 +  if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
1.130877 +  return rc;
1.130878 +}
1.130879 +
1.130880 +/*
1.130881 +** xEof - Return true if the cursor is at EOF, or false otherwise.
1.130882 +*/
1.130883 +static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
1.130884 +  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
1.130885 +  return pCsr->isEof;
1.130886 +}
1.130887 +
1.130888 +/*
1.130889 +** xColumn - Return a column value.
1.130890 +*/
1.130891 +static int fts3auxColumnMethod(
1.130892 +  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
1.130893 +  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
1.130894 +  int iCol                        /* Index of column to read value from */
1.130895 +){
1.130896 +  Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
1.130897 +
1.130898 +  assert( p->isEof==0 );
1.130899 +  switch( iCol ){
1.130900 +    case 0: /* term */
1.130901 +      sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
1.130902 +      break;
1.130903 +
1.130904 +    case 1: /* col */
1.130905 +      if( p->iCol ){
1.130906 +        sqlite3_result_int(pCtx, p->iCol-1);
1.130907 +      }else{
1.130908 +        sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
1.130909 +      }
1.130910 +      break;
1.130911 +
1.130912 +    case 2: /* documents */
1.130913 +      sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
1.130914 +      break;
1.130915 +
1.130916 +    case 3: /* occurrences */
1.130917 +      sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
1.130918 +      break;
1.130919 +
1.130920 +    default: /* languageid */
1.130921 +      assert( iCol==4 );
1.130922 +      sqlite3_result_int(pCtx, p->iLangid);
1.130923 +      break;
1.130924 +  }
1.130925 +
1.130926 +  return SQLITE_OK;
1.130927 +}
1.130928 +
1.130929 +/*
1.130930 +** xRowid - Return the current rowid for the cursor.
1.130931 +*/
1.130932 +static int fts3auxRowidMethod(
1.130933 +  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
1.130934 +  sqlite_int64 *pRowid            /* OUT: Rowid value */
1.130935 +){
1.130936 +  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
1.130937 +  *pRowid = pCsr->iRowid;
1.130938 +  return SQLITE_OK;
1.130939 +}
1.130940 +
1.130941 +/*
1.130942 +** Register the fts3aux module with database connection db. Return SQLITE_OK
1.130943 +** if successful or an error code if sqlite3_create_module() fails.
1.130944 +*/
1.130945 +SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
1.130946 +  static const sqlite3_module fts3aux_module = {
1.130947 +     0,                           /* iVersion      */
1.130948 +     fts3auxConnectMethod,        /* xCreate       */
1.130949 +     fts3auxConnectMethod,        /* xConnect      */
1.130950 +     fts3auxBestIndexMethod,      /* xBestIndex    */
1.130951 +     fts3auxDisconnectMethod,     /* xDisconnect   */
1.130952 +     fts3auxDisconnectMethod,     /* xDestroy      */
1.130953 +     fts3auxOpenMethod,           /* xOpen         */
1.130954 +     fts3auxCloseMethod,          /* xClose        */
1.130955 +     fts3auxFilterMethod,         /* xFilter       */
1.130956 +     fts3auxNextMethod,           /* xNext         */
1.130957 +     fts3auxEofMethod,            /* xEof          */
1.130958 +     fts3auxColumnMethod,         /* xColumn       */
1.130959 +     fts3auxRowidMethod,          /* xRowid        */
1.130960 +     0,                           /* xUpdate       */
1.130961 +     0,                           /* xBegin        */
1.130962 +     0,                           /* xSync         */
1.130963 +     0,                           /* xCommit       */
1.130964 +     0,                           /* xRollback     */
1.130965 +     0,                           /* xFindFunction */
1.130966 +     0,                           /* xRename       */
1.130967 +     0,                           /* xSavepoint    */
1.130968 +     0,                           /* xRelease      */
1.130969 +     0                            /* xRollbackTo   */
1.130970 +  };
1.130971 +  int rc;                         /* Return code */
1.130972 +
1.130973 +  rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
1.130974 +  return rc;
1.130975 +}
1.130976 +
1.130977 +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
1.130978 +
1.130979 +/************** End of fts3_aux.c ********************************************/
1.130980 +/************** Begin file fts3_expr.c ***************************************/
1.130981 +/*
1.130982 +** 2008 Nov 28
1.130983 +**
1.130984 +** The author disclaims copyright to this source code.  In place of
1.130985 +** a legal notice, here is a blessing:
1.130986 +**
1.130987 +**    May you do good and not evil.
1.130988 +**    May you find forgiveness for yourself and forgive others.
1.130989 +**    May you share freely, never taking more than you give.
1.130990 +**
1.130991 +******************************************************************************
1.130992 +**
1.130993 +** This module contains code that implements a parser for fts3 query strings
1.130994 +** (the right-hand argument to the MATCH operator). Because the supported 
1.130995 +** syntax is relatively simple, the whole tokenizer/parser system is
1.130996 +** hand-coded. 
1.130997 +*/
1.130998 +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
1.130999 +
1.131000 +/*
1.131001 +** By default, this module parses the legacy syntax that has been 
1.131002 +** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
1.131003 +** is defined, then it uses the new syntax. The differences between
1.131004 +** the new and the old syntaxes are:
1.131005 +**
1.131006 +**  a) The new syntax supports parenthesis. The old does not.
1.131007 +**
1.131008 +**  b) The new syntax supports the AND and NOT operators. The old does not.
1.131009 +**
1.131010 +**  c) The old syntax supports the "-" token qualifier. This is not 
1.131011 +**     supported by the new syntax (it is replaced by the NOT operator).
1.131012 +**
1.131013 +**  d) When using the old syntax, the OR operator has a greater precedence
1.131014 +**     than an implicit AND. When using the new, both implicity and explicit
1.131015 +**     AND operators have a higher precedence than OR.
1.131016 +**
1.131017 +** If compiled with SQLITE_TEST defined, then this module exports the
1.131018 +** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
1.131019 +** to zero causes the module to use the old syntax. If it is set to 
1.131020 +** non-zero the new syntax is activated. This is so both syntaxes can
1.131021 +** be tested using a single build of testfixture.
1.131022 +**
1.131023 +** The following describes the syntax supported by the fts3 MATCH
1.131024 +** operator in a similar format to that used by the lemon parser
1.131025 +** generator. This module does not use actually lemon, it uses a
1.131026 +** custom parser.
1.131027 +**
1.131028 +**   query ::= andexpr (OR andexpr)*.
1.131029 +**
1.131030 +**   andexpr ::= notexpr (AND? notexpr)*.
1.131031 +**
1.131032 +**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
1.131033 +**   notexpr ::= LP query RP.
1.131034 +**
1.131035 +**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
1.131036 +**
1.131037 +**   distance_opt ::= .
1.131038 +**   distance_opt ::= / INTEGER.
1.131039 +**
1.131040 +**   phrase ::= TOKEN.
1.131041 +**   phrase ::= COLUMN:TOKEN.
1.131042 +**   phrase ::= "TOKEN TOKEN TOKEN...".
1.131043 +*/
1.131044 +
1.131045 +#ifdef SQLITE_TEST
1.131046 +SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
1.131047 +#else
1.131048 +# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
1.131049 +#  define sqlite3_fts3_enable_parentheses 1
1.131050 +# else
1.131051 +#  define sqlite3_fts3_enable_parentheses 0
1.131052 +# endif
1.131053 +#endif
1.131054 +
1.131055 +/*
1.131056 +** Default span for NEAR operators.
1.131057 +*/
1.131058 +#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
1.131059 +
1.131060 +/* #include <string.h> */
1.131061 +/* #include <assert.h> */
1.131062 +
1.131063 +/*
1.131064 +** isNot:
1.131065 +**   This variable is used by function getNextNode(). When getNextNode() is
1.131066 +**   called, it sets ParseContext.isNot to true if the 'next node' is a 
1.131067 +**   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
1.131068 +**   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
1.131069 +**   zero.
1.131070 +*/
1.131071 +typedef struct ParseContext ParseContext;
1.131072 +struct ParseContext {
1.131073 +  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
1.131074 +  int iLangid;                        /* Language id used with tokenizer */
1.131075 +  const char **azCol;                 /* Array of column names for fts3 table */
1.131076 +  int bFts4;                          /* True to allow FTS4-only syntax */
1.131077 +  int nCol;                           /* Number of entries in azCol[] */
1.131078 +  int iDefaultCol;                    /* Default column to query */
1.131079 +  int isNot;                          /* True if getNextNode() sees a unary - */
1.131080 +  sqlite3_context *pCtx;              /* Write error message here */
1.131081 +  int nNest;                          /* Number of nested brackets */
1.131082 +};
1.131083 +
1.131084 +/*
1.131085 +** This function is equivalent to the standard isspace() function. 
1.131086 +**
1.131087 +** The standard isspace() can be awkward to use safely, because although it
1.131088 +** is defined to accept an argument of type int, its behavior when passed
1.131089 +** an integer that falls outside of the range of the unsigned char type
1.131090 +** is undefined (and sometimes, "undefined" means segfault). This wrapper
1.131091 +** is defined to accept an argument of type char, and always returns 0 for
1.131092 +** any values that fall outside of the range of the unsigned char type (i.e.
1.131093 +** negative values).
1.131094 +*/
1.131095 +static int fts3isspace(char c){
1.131096 +  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
1.131097 +}
1.131098 +
1.131099 +/*
1.131100 +** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
1.131101 +** zero the memory before returning a pointer to it. If unsuccessful, 
1.131102 +** return NULL.
1.131103 +*/
1.131104 +static void *fts3MallocZero(int nByte){
1.131105 +  void *pRet = sqlite3_malloc(nByte);
1.131106 +  if( pRet ) memset(pRet, 0, nByte);
1.131107 +  return pRet;
1.131108 +}
1.131109 +
1.131110 +SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
1.131111 +  sqlite3_tokenizer *pTokenizer,
1.131112 +  int iLangid,
1.131113 +  const char *z,
1.131114 +  int n,
1.131115 +  sqlite3_tokenizer_cursor **ppCsr
1.131116 +){
1.131117 +  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
1.131118 +  sqlite3_tokenizer_cursor *pCsr = 0;
1.131119 +  int rc;
1.131120 +
1.131121 +  rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
1.131122 +  assert( rc==SQLITE_OK || pCsr==0 );
1.131123 +  if( rc==SQLITE_OK ){
1.131124 +    pCsr->pTokenizer = pTokenizer;
1.131125 +    if( pModule->iVersion>=1 ){
1.131126 +      rc = pModule->xLanguageid(pCsr, iLangid);
1.131127 +      if( rc!=SQLITE_OK ){
1.131128 +        pModule->xClose(pCsr);
1.131129 +        pCsr = 0;
1.131130 +      }
1.131131 +    }
1.131132 +  }
1.131133 +  *ppCsr = pCsr;
1.131134 +  return rc;
1.131135 +}
1.131136 +
1.131137 +/*
1.131138 +** Function getNextNode(), which is called by fts3ExprParse(), may itself
1.131139 +** call fts3ExprParse(). So this forward declaration is required.
1.131140 +*/
1.131141 +static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
1.131142 +
1.131143 +/*
1.131144 +** Extract the next token from buffer z (length n) using the tokenizer
1.131145 +** and other information (column names etc.) in pParse. Create an Fts3Expr
1.131146 +** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
1.131147 +** single token and set *ppExpr to point to it. If the end of the buffer is
1.131148 +** reached before a token is found, set *ppExpr to zero. It is the
1.131149 +** responsibility of the caller to eventually deallocate the allocated 
1.131150 +** Fts3Expr structure (if any) by passing it to sqlite3_free().
1.131151 +**
1.131152 +** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
1.131153 +** fails.
1.131154 +*/
1.131155 +static int getNextToken(
1.131156 +  ParseContext *pParse,                   /* fts3 query parse context */
1.131157 +  int iCol,                               /* Value for Fts3Phrase.iColumn */
1.131158 +  const char *z, int n,                   /* Input string */
1.131159 +  Fts3Expr **ppExpr,                      /* OUT: expression */
1.131160 +  int *pnConsumed                         /* OUT: Number of bytes consumed */
1.131161 +){
1.131162 +  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
1.131163 +  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
1.131164 +  int rc;
1.131165 +  sqlite3_tokenizer_cursor *pCursor;
1.131166 +  Fts3Expr *pRet = 0;
1.131167 +  int nConsumed = 0;
1.131168 +
1.131169 +  rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
1.131170 +  if( rc==SQLITE_OK ){
1.131171 +    const char *zToken;
1.131172 +    int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
1.131173 +    int nByte;                               /* total space to allocate */
1.131174 +
1.131175 +    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
1.131176 +
1.131177 +    if( (rc==SQLITE_OK || rc==SQLITE_DONE) && sqlite3_fts3_enable_parentheses ){
1.131178 +      int i;
1.131179 +      if( rc==SQLITE_DONE ) iStart = n;
1.131180 +      for(i=0; i<iStart; i++){
1.131181 +        if( z[i]=='(' ){
1.131182 +          pParse->nNest++;
1.131183 +          rc = fts3ExprParse(pParse, &z[i+1], n-i-1, &pRet, &nConsumed);
1.131184 +          if( rc==SQLITE_OK && !pRet ){
1.131185 +            rc = SQLITE_DONE;
1.131186 +          }
1.131187 +          nConsumed = (int)(i + 1 + nConsumed);
1.131188 +          break;
1.131189 +        }
1.131190 +
1.131191 +        if( z[i]==')' ){
1.131192 +          rc = SQLITE_DONE;
1.131193 +          pParse->nNest--;
1.131194 +          nConsumed = i+1;
1.131195 +          break;
1.131196 +        }
1.131197 +      }
1.131198 +    }
1.131199 +
1.131200 +    if( nConsumed==0 && rc==SQLITE_OK ){
1.131201 +      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
1.131202 +      pRet = (Fts3Expr *)fts3MallocZero(nByte);
1.131203 +      if( !pRet ){
1.131204 +        rc = SQLITE_NOMEM;
1.131205 +      }else{
1.131206 +        pRet->eType = FTSQUERY_PHRASE;
1.131207 +        pRet->pPhrase = (Fts3Phrase *)&pRet[1];
1.131208 +        pRet->pPhrase->nToken = 1;
1.131209 +        pRet->pPhrase->iColumn = iCol;
1.131210 +        pRet->pPhrase->aToken[0].n = nToken;
1.131211 +        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
1.131212 +        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
1.131213 +
1.131214 +        if( iEnd<n && z[iEnd]=='*' ){
1.131215 +          pRet->pPhrase->aToken[0].isPrefix = 1;
1.131216 +          iEnd++;
1.131217 +        }
1.131218 +
1.131219 +        while( 1 ){
1.131220 +          if( !sqlite3_fts3_enable_parentheses 
1.131221 +           && iStart>0 && z[iStart-1]=='-' 
1.131222 +          ){
1.131223 +            pParse->isNot = 1;
1.131224 +            iStart--;
1.131225 +          }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
1.131226 +            pRet->pPhrase->aToken[0].bFirst = 1;
1.131227 +            iStart--;
1.131228 +          }else{
1.131229 +            break;
1.131230 +          }
1.131231 +        }
1.131232 +
1.131233 +      }
1.131234 +      nConsumed = iEnd;
1.131235 +    }
1.131236 +
1.131237 +    pModule->xClose(pCursor);
1.131238 +  }
1.131239 +  
1.131240 +  *pnConsumed = nConsumed;
1.131241 +  *ppExpr = pRet;
1.131242 +  return rc;
1.131243 +}
1.131244 +
1.131245 +
1.131246 +/*
1.131247 +** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
1.131248 +** then free the old allocation.
1.131249 +*/
1.131250 +static void *fts3ReallocOrFree(void *pOrig, int nNew){
1.131251 +  void *pRet = sqlite3_realloc(pOrig, nNew);
1.131252 +  if( !pRet ){
1.131253 +    sqlite3_free(pOrig);
1.131254 +  }
1.131255 +  return pRet;
1.131256 +}
1.131257 +
1.131258 +/*
1.131259 +** Buffer zInput, length nInput, contains the contents of a quoted string
1.131260 +** that appeared as part of an fts3 query expression. Neither quote character
1.131261 +** is included in the buffer. This function attempts to tokenize the entire
1.131262 +** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
1.131263 +** containing the results.
1.131264 +**
1.131265 +** If successful, SQLITE_OK is returned and *ppExpr set to point at the
1.131266 +** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
1.131267 +** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
1.131268 +** to 0.
1.131269 +*/
1.131270 +static int getNextString(
1.131271 +  ParseContext *pParse,                   /* fts3 query parse context */
1.131272 +  const char *zInput, int nInput,         /* Input string */
1.131273 +  Fts3Expr **ppExpr                       /* OUT: expression */
1.131274 +){
1.131275 +  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
1.131276 +  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
1.131277 +  int rc;
1.131278 +  Fts3Expr *p = 0;
1.131279 +  sqlite3_tokenizer_cursor *pCursor = 0;
1.131280 +  char *zTemp = 0;
1.131281 +  int nTemp = 0;
1.131282 +
1.131283 +  const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
1.131284 +  int nToken = 0;
1.131285 +
1.131286 +  /* The final Fts3Expr data structure, including the Fts3Phrase,
1.131287 +  ** Fts3PhraseToken structures token buffers are all stored as a single 
1.131288 +  ** allocation so that the expression can be freed with a single call to
1.131289 +  ** sqlite3_free(). Setting this up requires a two pass approach.
1.131290 +  **
1.131291 +  ** The first pass, in the block below, uses a tokenizer cursor to iterate
1.131292 +  ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
1.131293 +  ** to assemble data in two dynamic buffers:
1.131294 +  **
1.131295 +  **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
1.131296 +  **             structure, followed by the array of Fts3PhraseToken 
1.131297 +  **             structures. This pass only populates the Fts3PhraseToken array.
1.131298 +  **
1.131299 +  **   Buffer zTemp: Contains copies of all tokens.
1.131300 +  **
1.131301 +  ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
1.131302 +  ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
1.131303 +  ** structures.
1.131304 +  */
1.131305 +  rc = sqlite3Fts3OpenTokenizer(
1.131306 +      pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
1.131307 +  if( rc==SQLITE_OK ){
1.131308 +    int ii;
1.131309 +    for(ii=0; rc==SQLITE_OK; ii++){
1.131310 +      const char *zByte;
1.131311 +      int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
1.131312 +      rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
1.131313 +      if( rc==SQLITE_OK ){
1.131314 +        Fts3PhraseToken *pToken;
1.131315 +
1.131316 +        p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
1.131317 +        if( !p ) goto no_mem;
1.131318 +
1.131319 +        zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
1.131320 +        if( !zTemp ) goto no_mem;
1.131321 +
1.131322 +        assert( nToken==ii );
1.131323 +        pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
1.131324 +        memset(pToken, 0, sizeof(Fts3PhraseToken));
1.131325 +
1.131326 +        memcpy(&zTemp[nTemp], zByte, nByte);
1.131327 +        nTemp += nByte;
1.131328 +
1.131329 +        pToken->n = nByte;
1.131330 +        pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
1.131331 +        pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
1.131332 +        nToken = ii+1;
1.131333 +      }
1.131334 +    }
1.131335 +
1.131336 +    pModule->xClose(pCursor);
1.131337 +    pCursor = 0;
1.131338 +  }
1.131339 +
1.131340 +  if( rc==SQLITE_DONE ){
1.131341 +    int jj;
1.131342 +    char *zBuf = 0;
1.131343 +
1.131344 +    p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
1.131345 +    if( !p ) goto no_mem;
1.131346 +    memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
1.131347 +    p->eType = FTSQUERY_PHRASE;
1.131348 +    p->pPhrase = (Fts3Phrase *)&p[1];
1.131349 +    p->pPhrase->iColumn = pParse->iDefaultCol;
1.131350 +    p->pPhrase->nToken = nToken;
1.131351 +
1.131352 +    zBuf = (char *)&p->pPhrase->aToken[nToken];
1.131353 +    if( zTemp ){
1.131354 +      memcpy(zBuf, zTemp, nTemp);
1.131355 +      sqlite3_free(zTemp);
1.131356 +    }else{
1.131357 +      assert( nTemp==0 );
1.131358 +    }
1.131359 +
1.131360 +    for(jj=0; jj<p->pPhrase->nToken; jj++){
1.131361 +      p->pPhrase->aToken[jj].z = zBuf;
1.131362 +      zBuf += p->pPhrase->aToken[jj].n;
1.131363 +    }
1.131364 +    rc = SQLITE_OK;
1.131365 +  }
1.131366 +
1.131367 +  *ppExpr = p;
1.131368 +  return rc;
1.131369 +no_mem:
1.131370 +
1.131371 +  if( pCursor ){
1.131372 +    pModule->xClose(pCursor);
1.131373 +  }
1.131374 +  sqlite3_free(zTemp);
1.131375 +  sqlite3_free(p);
1.131376 +  *ppExpr = 0;
1.131377 +  return SQLITE_NOMEM;
1.131378 +}
1.131379 +
1.131380 +/*
1.131381 +** The output variable *ppExpr is populated with an allocated Fts3Expr 
1.131382 +** structure, or set to 0 if the end of the input buffer is reached.
1.131383 +**
1.131384 +** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
1.131385 +** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
1.131386 +** If SQLITE_ERROR is returned, pContext is populated with an error message.
1.131387 +*/
1.131388 +static int getNextNode(
1.131389 +  ParseContext *pParse,                   /* fts3 query parse context */
1.131390 +  const char *z, int n,                   /* Input string */
1.131391 +  Fts3Expr **ppExpr,                      /* OUT: expression */
1.131392 +  int *pnConsumed                         /* OUT: Number of bytes consumed */
1.131393 +){
1.131394 +  static const struct Fts3Keyword {
1.131395 +    char *z;                              /* Keyword text */
1.131396 +    unsigned char n;                      /* Length of the keyword */
1.131397 +    unsigned char parenOnly;              /* Only valid in paren mode */
1.131398 +    unsigned char eType;                  /* Keyword code */
1.131399 +  } aKeyword[] = {
1.131400 +    { "OR" ,  2, 0, FTSQUERY_OR   },
1.131401 +    { "AND",  3, 1, FTSQUERY_AND  },
1.131402 +    { "NOT",  3, 1, FTSQUERY_NOT  },
1.131403 +    { "NEAR", 4, 0, FTSQUERY_NEAR }
1.131404 +  };
1.131405 +  int ii;
1.131406 +  int iCol;
1.131407 +  int iColLen;
1.131408 +  int rc;
1.131409 +  Fts3Expr *pRet = 0;
1.131410 +
1.131411 +  const char *zInput = z;
1.131412 +  int nInput = n;
1.131413 +
1.131414 +  pParse->isNot = 0;
1.131415 +
1.131416 +  /* Skip over any whitespace before checking for a keyword, an open or
1.131417 +  ** close bracket, or a quoted string. 
1.131418 +  */
1.131419 +  while( nInput>0 && fts3isspace(*zInput) ){
1.131420 +    nInput--;
1.131421 +    zInput++;
1.131422 +  }
1.131423 +  if( nInput==0 ){
1.131424 +    return SQLITE_DONE;
1.131425 +  }
1.131426 +
1.131427 +  /* See if we are dealing with a keyword. */
1.131428 +  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
1.131429 +    const struct Fts3Keyword *pKey = &aKeyword[ii];
1.131430 +
1.131431 +    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
1.131432 +      continue;
1.131433 +    }
1.131434 +
1.131435 +    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
1.131436 +      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
1.131437 +      int nKey = pKey->n;
1.131438 +      char cNext;
1.131439 +
1.131440 +      /* If this is a "NEAR" keyword, check for an explicit nearness. */
1.131441 +      if( pKey->eType==FTSQUERY_NEAR ){
1.131442 +        assert( nKey==4 );
1.131443 +        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
1.131444 +          nNear = 0;
1.131445 +          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
1.131446 +            nNear = nNear * 10 + (zInput[nKey] - '0');
1.131447 +          }
1.131448 +        }
1.131449 +      }
1.131450 +
1.131451 +      /* At this point this is probably a keyword. But for that to be true,
1.131452 +      ** the next byte must contain either whitespace, an open or close
1.131453 +      ** parenthesis, a quote character, or EOF. 
1.131454 +      */
1.131455 +      cNext = zInput[nKey];
1.131456 +      if( fts3isspace(cNext) 
1.131457 +       || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
1.131458 +      ){
1.131459 +        pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
1.131460 +        if( !pRet ){
1.131461 +          return SQLITE_NOMEM;
1.131462 +        }
1.131463 +        pRet->eType = pKey->eType;
1.131464 +        pRet->nNear = nNear;
1.131465 +        *ppExpr = pRet;
1.131466 +        *pnConsumed = (int)((zInput - z) + nKey);
1.131467 +        return SQLITE_OK;
1.131468 +      }
1.131469 +
1.131470 +      /* Turns out that wasn't a keyword after all. This happens if the
1.131471 +      ** user has supplied a token such as "ORacle". Continue.
1.131472 +      */
1.131473 +    }
1.131474 +  }
1.131475 +
1.131476 +  /* See if we are dealing with a quoted phrase. If this is the case, then
1.131477 +  ** search for the closing quote and pass the whole string to getNextString()
1.131478 +  ** for processing. This is easy to do, as fts3 has no syntax for escaping
1.131479 +  ** a quote character embedded in a string.
1.131480 +  */
1.131481 +  if( *zInput=='"' ){
1.131482 +    for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
1.131483 +    *pnConsumed = (int)((zInput - z) + ii + 1);
1.131484 +    if( ii==nInput ){
1.131485 +      return SQLITE_ERROR;
1.131486 +    }
1.131487 +    return getNextString(pParse, &zInput[1], ii-1, ppExpr);
1.131488 +  }
1.131489 +
1.131490 +
1.131491 +  /* If control flows to this point, this must be a regular token, or 
1.131492 +  ** the end of the input. Read a regular token using the sqlite3_tokenizer
1.131493 +  ** interface. Before doing so, figure out if there is an explicit
1.131494 +  ** column specifier for the token. 
1.131495 +  **
1.131496 +  ** TODO: Strangely, it is not possible to associate a column specifier
1.131497 +  ** with a quoted phrase, only with a single token. Not sure if this was
1.131498 +  ** an implementation artifact or an intentional decision when fts3 was
1.131499 +  ** first implemented. Whichever it was, this module duplicates the 
1.131500 +  ** limitation.
1.131501 +  */
1.131502 +  iCol = pParse->iDefaultCol;
1.131503 +  iColLen = 0;
1.131504 +  for(ii=0; ii<pParse->nCol; ii++){
1.131505 +    const char *zStr = pParse->azCol[ii];
1.131506 +    int nStr = (int)strlen(zStr);
1.131507 +    if( nInput>nStr && zInput[nStr]==':' 
1.131508 +     && sqlite3_strnicmp(zStr, zInput, nStr)==0 
1.131509 +    ){
1.131510 +      iCol = ii;
1.131511 +      iColLen = (int)((zInput - z) + nStr + 1);
1.131512 +      break;
1.131513 +    }
1.131514 +  }
1.131515 +  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
1.131516 +  *pnConsumed += iColLen;
1.131517 +  return rc;
1.131518 +}
1.131519 +
1.131520 +/*
1.131521 +** The argument is an Fts3Expr structure for a binary operator (any type
1.131522 +** except an FTSQUERY_PHRASE). Return an integer value representing the
1.131523 +** precedence of the operator. Lower values have a higher precedence (i.e.
1.131524 +** group more tightly). For example, in the C language, the == operator
1.131525 +** groups more tightly than ||, and would therefore have a higher precedence.
1.131526 +**
1.131527 +** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
1.131528 +** is defined), the order of the operators in precedence from highest to
1.131529 +** lowest is:
1.131530 +**
1.131531 +**   NEAR
1.131532 +**   NOT
1.131533 +**   AND (including implicit ANDs)
1.131534 +**   OR
1.131535 +**
1.131536 +** Note that when using the old query syntax, the OR operator has a higher
1.131537 +** precedence than the AND operator.
1.131538 +*/
1.131539 +static int opPrecedence(Fts3Expr *p){
1.131540 +  assert( p->eType!=FTSQUERY_PHRASE );
1.131541 +  if( sqlite3_fts3_enable_parentheses ){
1.131542 +    return p->eType;
1.131543 +  }else if( p->eType==FTSQUERY_NEAR ){
1.131544 +    return 1;
1.131545 +  }else if( p->eType==FTSQUERY_OR ){
1.131546 +    return 2;
1.131547 +  }
1.131548 +  assert( p->eType==FTSQUERY_AND );
1.131549 +  return 3;
1.131550 +}
1.131551 +
1.131552 +/*
1.131553 +** Argument ppHead contains a pointer to the current head of a query 
1.131554 +** expression tree being parsed. pPrev is the expression node most recently
1.131555 +** inserted into the tree. This function adds pNew, which is always a binary
1.131556 +** operator node, into the expression tree based on the relative precedence
1.131557 +** of pNew and the existing nodes of the tree. This may result in the head
1.131558 +** of the tree changing, in which case *ppHead is set to the new root node.
1.131559 +*/
1.131560 +static void insertBinaryOperator(
1.131561 +  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
1.131562 +  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
1.131563 +  Fts3Expr *pNew           /* New binary node to insert into expression tree */
1.131564 +){
1.131565 +  Fts3Expr *pSplit = pPrev;
1.131566 +  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
1.131567 +    pSplit = pSplit->pParent;
1.131568 +  }
1.131569 +
1.131570 +  if( pSplit->pParent ){
1.131571 +    assert( pSplit->pParent->pRight==pSplit );
1.131572 +    pSplit->pParent->pRight = pNew;
1.131573 +    pNew->pParent = pSplit->pParent;
1.131574 +  }else{
1.131575 +    *ppHead = pNew;
1.131576 +  }
1.131577 +  pNew->pLeft = pSplit;
1.131578 +  pSplit->pParent = pNew;
1.131579 +}
1.131580 +
1.131581 +/*
1.131582 +** Parse the fts3 query expression found in buffer z, length n. This function
1.131583 +** returns either when the end of the buffer is reached or an unmatched 
1.131584 +** closing bracket - ')' - is encountered.
1.131585 +**
1.131586 +** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
1.131587 +** parsed form of the expression and *pnConsumed is set to the number of
1.131588 +** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
1.131589 +** (out of memory error) or SQLITE_ERROR (parse error) is returned.
1.131590 +*/
1.131591 +static int fts3ExprParse(
1.131592 +  ParseContext *pParse,                   /* fts3 query parse context */
1.131593 +  const char *z, int n,                   /* Text of MATCH query */
1.131594 +  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
1.131595 +  int *pnConsumed                         /* OUT: Number of bytes consumed */
1.131596 +){
1.131597 +  Fts3Expr *pRet = 0;
1.131598 +  Fts3Expr *pPrev = 0;
1.131599 +  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
1.131600 +  int nIn = n;
1.131601 +  const char *zIn = z;
1.131602 +  int rc = SQLITE_OK;
1.131603 +  int isRequirePhrase = 1;
1.131604 +
1.131605 +  while( rc==SQLITE_OK ){
1.131606 +    Fts3Expr *p = 0;
1.131607 +    int nByte = 0;
1.131608 +    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
1.131609 +    if( rc==SQLITE_OK ){
1.131610 +      int isPhrase;
1.131611 +
1.131612 +      if( !sqlite3_fts3_enable_parentheses 
1.131613 +       && p->eType==FTSQUERY_PHRASE && pParse->isNot 
1.131614 +      ){
1.131615 +        /* Create an implicit NOT operator. */
1.131616 +        Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
1.131617 +        if( !pNot ){
1.131618 +          sqlite3Fts3ExprFree(p);
1.131619 +          rc = SQLITE_NOMEM;
1.131620 +          goto exprparse_out;
1.131621 +        }
1.131622 +        pNot->eType = FTSQUERY_NOT;
1.131623 +        pNot->pRight = p;
1.131624 +        p->pParent = pNot;
1.131625 +        if( pNotBranch ){
1.131626 +          pNot->pLeft = pNotBranch;
1.131627 +          pNotBranch->pParent = pNot;
1.131628 +        }
1.131629 +        pNotBranch = pNot;
1.131630 +        p = pPrev;
1.131631 +      }else{
1.131632 +        int eType = p->eType;
1.131633 +        isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
1.131634 +
1.131635 +        /* The isRequirePhrase variable is set to true if a phrase or
1.131636 +        ** an expression contained in parenthesis is required. If a
1.131637 +        ** binary operator (AND, OR, NOT or NEAR) is encounted when
1.131638 +        ** isRequirePhrase is set, this is a syntax error.
1.131639 +        */
1.131640 +        if( !isPhrase && isRequirePhrase ){
1.131641 +          sqlite3Fts3ExprFree(p);
1.131642 +          rc = SQLITE_ERROR;
1.131643 +          goto exprparse_out;
1.131644 +        }
1.131645 +  
1.131646 +        if( isPhrase && !isRequirePhrase ){
1.131647 +          /* Insert an implicit AND operator. */
1.131648 +          Fts3Expr *pAnd;
1.131649 +          assert( pRet && pPrev );
1.131650 +          pAnd = fts3MallocZero(sizeof(Fts3Expr));
1.131651 +          if( !pAnd ){
1.131652 +            sqlite3Fts3ExprFree(p);
1.131653 +            rc = SQLITE_NOMEM;
1.131654 +            goto exprparse_out;
1.131655 +          }
1.131656 +          pAnd->eType = FTSQUERY_AND;
1.131657 +          insertBinaryOperator(&pRet, pPrev, pAnd);
1.131658 +          pPrev = pAnd;
1.131659 +        }
1.131660 +
1.131661 +        /* This test catches attempts to make either operand of a NEAR
1.131662 +        ** operator something other than a phrase. For example, either of
1.131663 +        ** the following:
1.131664 +        **
1.131665 +        **    (bracketed expression) NEAR phrase
1.131666 +        **    phrase NEAR (bracketed expression)
1.131667 +        **
1.131668 +        ** Return an error in either case.
1.131669 +        */
1.131670 +        if( pPrev && (
1.131671 +            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
1.131672 +         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
1.131673 +        )){
1.131674 +          sqlite3Fts3ExprFree(p);
1.131675 +          rc = SQLITE_ERROR;
1.131676 +          goto exprparse_out;
1.131677 +        }
1.131678 +  
1.131679 +        if( isPhrase ){
1.131680 +          if( pRet ){
1.131681 +            assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
1.131682 +            pPrev->pRight = p;
1.131683 +            p->pParent = pPrev;
1.131684 +          }else{
1.131685 +            pRet = p;
1.131686 +          }
1.131687 +        }else{
1.131688 +          insertBinaryOperator(&pRet, pPrev, p);
1.131689 +        }
1.131690 +        isRequirePhrase = !isPhrase;
1.131691 +      }
1.131692 +      assert( nByte>0 );
1.131693 +    }
1.131694 +    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
1.131695 +    nIn -= nByte;
1.131696 +    zIn += nByte;
1.131697 +    pPrev = p;
1.131698 +  }
1.131699 +
1.131700 +  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
1.131701 +    rc = SQLITE_ERROR;
1.131702 +  }
1.131703 +
1.131704 +  if( rc==SQLITE_DONE ){
1.131705 +    rc = SQLITE_OK;
1.131706 +    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
1.131707 +      if( !pRet ){
1.131708 +        rc = SQLITE_ERROR;
1.131709 +      }else{
1.131710 +        Fts3Expr *pIter = pNotBranch;
1.131711 +        while( pIter->pLeft ){
1.131712 +          pIter = pIter->pLeft;
1.131713 +        }
1.131714 +        pIter->pLeft = pRet;
1.131715 +        pRet->pParent = pIter;
1.131716 +        pRet = pNotBranch;
1.131717 +      }
1.131718 +    }
1.131719 +  }
1.131720 +  *pnConsumed = n - nIn;
1.131721 +
1.131722 +exprparse_out:
1.131723 +  if( rc!=SQLITE_OK ){
1.131724 +    sqlite3Fts3ExprFree(pRet);
1.131725 +    sqlite3Fts3ExprFree(pNotBranch);
1.131726 +    pRet = 0;
1.131727 +  }
1.131728 +  *ppExpr = pRet;
1.131729 +  return rc;
1.131730 +}
1.131731 +
1.131732 +/*
1.131733 +** Return SQLITE_ERROR if the maximum depth of the expression tree passed 
1.131734 +** as the only argument is more than nMaxDepth.
1.131735 +*/
1.131736 +static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
1.131737 +  int rc = SQLITE_OK;
1.131738 +  if( p ){
1.131739 +    if( nMaxDepth<0 ){ 
1.131740 +      rc = SQLITE_TOOBIG;
1.131741 +    }else{
1.131742 +      rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
1.131743 +      if( rc==SQLITE_OK ){
1.131744 +        rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
1.131745 +      }
1.131746 +    }
1.131747 +  }
1.131748 +  return rc;
1.131749 +}
1.131750 +
1.131751 +/*
1.131752 +** This function attempts to transform the expression tree at (*pp) to
1.131753 +** an equivalent but more balanced form. The tree is modified in place.
1.131754 +** If successful, SQLITE_OK is returned and (*pp) set to point to the 
1.131755 +** new root expression node. 
1.131756 +**
1.131757 +** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
1.131758 +**
1.131759 +** Otherwise, if an error occurs, an SQLite error code is returned and 
1.131760 +** expression (*pp) freed.
1.131761 +*/
1.131762 +static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
1.131763 +  int rc = SQLITE_OK;             /* Return code */
1.131764 +  Fts3Expr *pRoot = *pp;          /* Initial root node */
1.131765 +  Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */
1.131766 +  int eType = pRoot->eType;       /* Type of node in this tree */
1.131767 +
1.131768 +  if( nMaxDepth==0 ){
1.131769 +    rc = SQLITE_ERROR;
1.131770 +  }
1.131771 +
1.131772 +  if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
1.131773 +    Fts3Expr **apLeaf;
1.131774 +    apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
1.131775 +    if( 0==apLeaf ){
1.131776 +      rc = SQLITE_NOMEM;
1.131777 +    }else{
1.131778 +      memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
1.131779 +    }
1.131780 +
1.131781 +    if( rc==SQLITE_OK ){
1.131782 +      int i;
1.131783 +      Fts3Expr *p;
1.131784 +
1.131785 +      /* Set $p to point to the left-most leaf in the tree of eType nodes. */
1.131786 +      for(p=pRoot; p->eType==eType; p=p->pLeft){
1.131787 +        assert( p->pParent==0 || p->pParent->pLeft==p );
1.131788 +        assert( p->pLeft && p->pRight );
1.131789 +      }
1.131790 +
1.131791 +      /* This loop runs once for each leaf in the tree of eType nodes. */
1.131792 +      while( 1 ){
1.131793 +        int iLvl;
1.131794 +        Fts3Expr *pParent = p->pParent;     /* Current parent of p */
1.131795 +
1.131796 +        assert( pParent==0 || pParent->pLeft==p );
1.131797 +        p->pParent = 0;
1.131798 +        if( pParent ){
1.131799 +          pParent->pLeft = 0;
1.131800 +        }else{
1.131801 +          pRoot = 0;
1.131802 +        }
1.131803 +        rc = fts3ExprBalance(&p, nMaxDepth-1);
1.131804 +        if( rc!=SQLITE_OK ) break;
1.131805 +
1.131806 +        for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
1.131807 +          if( apLeaf[iLvl]==0 ){
1.131808 +            apLeaf[iLvl] = p;
1.131809 +            p = 0;
1.131810 +          }else{
1.131811 +            assert( pFree );
1.131812 +            pFree->pLeft = apLeaf[iLvl];
1.131813 +            pFree->pRight = p;
1.131814 +            pFree->pLeft->pParent = pFree;
1.131815 +            pFree->pRight->pParent = pFree;
1.131816 +
1.131817 +            p = pFree;
1.131818 +            pFree = pFree->pParent;
1.131819 +            p->pParent = 0;
1.131820 +            apLeaf[iLvl] = 0;
1.131821 +          }
1.131822 +        }
1.131823 +        if( p ){
1.131824 +          sqlite3Fts3ExprFree(p);
1.131825 +          rc = SQLITE_TOOBIG;
1.131826 +          break;
1.131827 +        }
1.131828 +
1.131829 +        /* If that was the last leaf node, break out of the loop */
1.131830 +        if( pParent==0 ) break;
1.131831 +
1.131832 +        /* Set $p to point to the next leaf in the tree of eType nodes */
1.131833 +        for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
1.131834 +
1.131835 +        /* Remove pParent from the original tree. */
1.131836 +        assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
1.131837 +        pParent->pRight->pParent = pParent->pParent;
1.131838 +        if( pParent->pParent ){
1.131839 +          pParent->pParent->pLeft = pParent->pRight;
1.131840 +        }else{
1.131841 +          assert( pParent==pRoot );
1.131842 +          pRoot = pParent->pRight;
1.131843 +        }
1.131844 +
1.131845 +        /* Link pParent into the free node list. It will be used as an
1.131846 +        ** internal node of the new tree.  */
1.131847 +        pParent->pParent = pFree;
1.131848 +        pFree = pParent;
1.131849 +      }
1.131850 +
1.131851 +      if( rc==SQLITE_OK ){
1.131852 +        p = 0;
1.131853 +        for(i=0; i<nMaxDepth; i++){
1.131854 +          if( apLeaf[i] ){
1.131855 +            if( p==0 ){
1.131856 +              p = apLeaf[i];
1.131857 +              p->pParent = 0;
1.131858 +            }else{
1.131859 +              assert( pFree!=0 );
1.131860 +              pFree->pRight = p;
1.131861 +              pFree->pLeft = apLeaf[i];
1.131862 +              pFree->pLeft->pParent = pFree;
1.131863 +              pFree->pRight->pParent = pFree;
1.131864 +
1.131865 +              p = pFree;
1.131866 +              pFree = pFree->pParent;
1.131867 +              p->pParent = 0;
1.131868 +            }
1.131869 +          }
1.131870 +        }
1.131871 +        pRoot = p;
1.131872 +      }else{
1.131873 +        /* An error occurred. Delete the contents of the apLeaf[] array 
1.131874 +        ** and pFree list. Everything else is cleaned up by the call to
1.131875 +        ** sqlite3Fts3ExprFree(pRoot) below.  */
1.131876 +        Fts3Expr *pDel;
1.131877 +        for(i=0; i<nMaxDepth; i++){
1.131878 +          sqlite3Fts3ExprFree(apLeaf[i]);
1.131879 +        }
1.131880 +        while( (pDel=pFree)!=0 ){
1.131881 +          pFree = pDel->pParent;
1.131882 +          sqlite3_free(pDel);
1.131883 +        }
1.131884 +      }
1.131885 +
1.131886 +      assert( pFree==0 );
1.131887 +      sqlite3_free( apLeaf );
1.131888 +    }
1.131889 +  }
1.131890 +
1.131891 +  if( rc!=SQLITE_OK ){
1.131892 +    sqlite3Fts3ExprFree(pRoot);
1.131893 +    pRoot = 0;
1.131894 +  }
1.131895 +  *pp = pRoot;
1.131896 +  return rc;
1.131897 +}
1.131898 +
1.131899 +/*
1.131900 +** This function is similar to sqlite3Fts3ExprParse(), with the following
1.131901 +** differences:
1.131902 +**
1.131903 +**   1. It does not do expression rebalancing.
1.131904 +**   2. It does not check that the expression does not exceed the 
1.131905 +**      maximum allowable depth.
1.131906 +**   3. Even if it fails, *ppExpr may still be set to point to an 
1.131907 +**      expression tree. It should be deleted using sqlite3Fts3ExprFree()
1.131908 +**      in this case.
1.131909 +*/
1.131910 +static int fts3ExprParseUnbalanced(
1.131911 +  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
1.131912 +  int iLangid,                        /* Language id for tokenizer */
1.131913 +  char **azCol,                       /* Array of column names for fts3 table */
1.131914 +  int bFts4,                          /* True to allow FTS4-only syntax */
1.131915 +  int nCol,                           /* Number of entries in azCol[] */
1.131916 +  int iDefaultCol,                    /* Default column to query */
1.131917 +  const char *z, int n,               /* Text of MATCH query */
1.131918 +  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
1.131919 +){
1.131920 +  int nParsed;
1.131921 +  int rc;
1.131922 +  ParseContext sParse;
1.131923 +
1.131924 +  memset(&sParse, 0, sizeof(ParseContext));
1.131925 +  sParse.pTokenizer = pTokenizer;
1.131926 +  sParse.iLangid = iLangid;
1.131927 +  sParse.azCol = (const char **)azCol;
1.131928 +  sParse.nCol = nCol;
1.131929 +  sParse.iDefaultCol = iDefaultCol;
1.131930 +  sParse.bFts4 = bFts4;
1.131931 +  if( z==0 ){
1.131932 +    *ppExpr = 0;
1.131933 +    return SQLITE_OK;
1.131934 +  }
1.131935 +  if( n<0 ){
1.131936 +    n = (int)strlen(z);
1.131937 +  }
1.131938 +  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
1.131939 +  assert( rc==SQLITE_OK || *ppExpr==0 );
1.131940 +
1.131941 +  /* Check for mismatched parenthesis */
1.131942 +  if( rc==SQLITE_OK && sParse.nNest ){
1.131943 +    rc = SQLITE_ERROR;
1.131944 +  }
1.131945 +  
1.131946 +  return rc;
1.131947 +}
1.131948 +
1.131949 +/*
1.131950 +** Parameters z and n contain a pointer to and length of a buffer containing
1.131951 +** an fts3 query expression, respectively. This function attempts to parse the
1.131952 +** query expression and create a tree of Fts3Expr structures representing the
1.131953 +** parsed expression. If successful, *ppExpr is set to point to the head
1.131954 +** of the parsed expression tree and SQLITE_OK is returned. If an error
1.131955 +** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
1.131956 +** error) is returned and *ppExpr is set to 0.
1.131957 +**
1.131958 +** If parameter n is a negative number, then z is assumed to point to a
1.131959 +** nul-terminated string and the length is determined using strlen().
1.131960 +**
1.131961 +** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
1.131962 +** use to normalize query tokens while parsing the expression. The azCol[]
1.131963 +** array, which is assumed to contain nCol entries, should contain the names
1.131964 +** of each column in the target fts3 table, in order from left to right. 
1.131965 +** Column names must be nul-terminated strings.
1.131966 +**
1.131967 +** The iDefaultCol parameter should be passed the index of the table column
1.131968 +** that appears on the left-hand-side of the MATCH operator (the default
1.131969 +** column to match against for tokens for which a column name is not explicitly
1.131970 +** specified as part of the query string), or -1 if tokens may by default
1.131971 +** match any table column.
1.131972 +*/
1.131973 +SQLITE_PRIVATE int sqlite3Fts3ExprParse(
1.131974 +  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
1.131975 +  int iLangid,                        /* Language id for tokenizer */
1.131976 +  char **azCol,                       /* Array of column names for fts3 table */
1.131977 +  int bFts4,                          /* True to allow FTS4-only syntax */
1.131978 +  int nCol,                           /* Number of entries in azCol[] */
1.131979 +  int iDefaultCol,                    /* Default column to query */
1.131980 +  const char *z, int n,               /* Text of MATCH query */
1.131981 +  Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */
1.131982 +  char **pzErr                        /* OUT: Error message (sqlite3_malloc) */
1.131983 +){
1.131984 +  int rc = fts3ExprParseUnbalanced(
1.131985 +      pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
1.131986 +  );
1.131987 +  
1.131988 +  /* Rebalance the expression. And check that its depth does not exceed
1.131989 +  ** SQLITE_FTS3_MAX_EXPR_DEPTH.  */
1.131990 +  if( rc==SQLITE_OK && *ppExpr ){
1.131991 +    rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
1.131992 +    if( rc==SQLITE_OK ){
1.131993 +      rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
1.131994 +    }
1.131995 +  }
1.131996 +
1.131997 +  if( rc!=SQLITE_OK ){
1.131998 +    sqlite3Fts3ExprFree(*ppExpr);
1.131999 +    *ppExpr = 0;
1.132000 +    if( rc==SQLITE_TOOBIG ){
1.132001 +      *pzErr = sqlite3_mprintf(
1.132002 +          "FTS expression tree is too large (maximum depth %d)", 
1.132003 +          SQLITE_FTS3_MAX_EXPR_DEPTH
1.132004 +      );
1.132005 +      rc = SQLITE_ERROR;
1.132006 +    }else if( rc==SQLITE_ERROR ){
1.132007 +      *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
1.132008 +    }
1.132009 +  }
1.132010 +
1.132011 +  return rc;
1.132012 +}
1.132013 +
1.132014 +/*
1.132015 +** Free a single node of an expression tree.
1.132016 +*/
1.132017 +static void fts3FreeExprNode(Fts3Expr *p){
1.132018 +  assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
1.132019 +  sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
1.132020 +  sqlite3_free(p->aMI);
1.132021 +  sqlite3_free(p);
1.132022 +}
1.132023 +
1.132024 +/*
1.132025 +** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
1.132026 +**
1.132027 +** This function would be simpler if it recursively called itself. But
1.132028 +** that would mean passing a sufficiently large expression to ExprParse()
1.132029 +** could cause a stack overflow.
1.132030 +*/
1.132031 +SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
1.132032 +  Fts3Expr *p;
1.132033 +  assert( pDel==0 || pDel->pParent==0 );
1.132034 +  for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
1.132035 +    assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
1.132036 +  }
1.132037 +  while( p ){
1.132038 +    Fts3Expr *pParent = p->pParent;
1.132039 +    fts3FreeExprNode(p);
1.132040 +    if( pParent && p==pParent->pLeft && pParent->pRight ){
1.132041 +      p = pParent->pRight;
1.132042 +      while( p && (p->pLeft || p->pRight) ){
1.132043 +        assert( p==p->pParent->pRight || p==p->pParent->pLeft );
1.132044 +        p = (p->pLeft ? p->pLeft : p->pRight);
1.132045 +      }
1.132046 +    }else{
1.132047 +      p = pParent;
1.132048 +    }
1.132049 +  }
1.132050 +}
1.132051 +
1.132052 +/****************************************************************************
1.132053 +*****************************************************************************
1.132054 +** Everything after this point is just test code.
1.132055 +*/
1.132056 +
1.132057 +#ifdef SQLITE_TEST
1.132058 +
1.132059 +/* #include <stdio.h> */
1.132060 +
1.132061 +/*
1.132062 +** Function to query the hash-table of tokenizers (see README.tokenizers).
1.132063 +*/
1.132064 +static int queryTestTokenizer(
1.132065 +  sqlite3 *db, 
1.132066 +  const char *zName,  
1.132067 +  const sqlite3_tokenizer_module **pp
1.132068 +){
1.132069 +  int rc;
1.132070 +  sqlite3_stmt *pStmt;
1.132071 +  const char zSql[] = "SELECT fts3_tokenizer(?)";
1.132072 +
1.132073 +  *pp = 0;
1.132074 +  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
1.132075 +  if( rc!=SQLITE_OK ){
1.132076 +    return rc;
1.132077 +  }
1.132078 +
1.132079 +  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
1.132080 +  if( SQLITE_ROW==sqlite3_step(pStmt) ){
1.132081 +    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
1.132082 +      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
1.132083 +    }
1.132084 +  }
1.132085 +
1.132086 +  return sqlite3_finalize(pStmt);
1.132087 +}
1.132088 +
1.132089 +/*
1.132090 +** Return a pointer to a buffer containing a text representation of the
1.132091 +** expression passed as the first argument. The buffer is obtained from
1.132092 +** sqlite3_malloc(). It is the responsibility of the caller to use 
1.132093 +** sqlite3_free() to release the memory. If an OOM condition is encountered,
1.132094 +** NULL is returned.
1.132095 +**
1.132096 +** If the second argument is not NULL, then its contents are prepended to 
1.132097 +** the returned expression text and then freed using sqlite3_free().
1.132098 +*/
1.132099 +static char *exprToString(Fts3Expr *pExpr, char *zBuf){
1.132100 +  if( pExpr==0 ){
1.132101 +    return sqlite3_mprintf("");
1.132102 +  }
1.132103 +  switch( pExpr->eType ){
1.132104 +    case FTSQUERY_PHRASE: {
1.132105 +      Fts3Phrase *pPhrase = pExpr->pPhrase;
1.132106 +      int i;
1.132107 +      zBuf = sqlite3_mprintf(
1.132108 +          "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
1.132109 +      for(i=0; zBuf && i<pPhrase->nToken; i++){
1.132110 +        zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, 
1.132111 +            pPhrase->aToken[i].n, pPhrase->aToken[i].z,
1.132112 +            (pPhrase->aToken[i].isPrefix?"+":"")
1.132113 +        );
1.132114 +      }
1.132115 +      return zBuf;
1.132116 +    }
1.132117 +
1.132118 +    case FTSQUERY_NEAR:
1.132119 +      zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
1.132120 +      break;
1.132121 +    case FTSQUERY_NOT:
1.132122 +      zBuf = sqlite3_mprintf("%zNOT ", zBuf);
1.132123 +      break;
1.132124 +    case FTSQUERY_AND:
1.132125 +      zBuf = sqlite3_mprintf("%zAND ", zBuf);
1.132126 +      break;
1.132127 +    case FTSQUERY_OR:
1.132128 +      zBuf = sqlite3_mprintf("%zOR ", zBuf);
1.132129 +      break;
1.132130 +  }
1.132131 +
1.132132 +  if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
1.132133 +  if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
1.132134 +  if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
1.132135 +
1.132136 +  if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
1.132137 +  if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
1.132138 +
1.132139 +  return zBuf;
1.132140 +}
1.132141 +
1.132142 +/*
1.132143 +** This is the implementation of a scalar SQL function used to test the 
1.132144 +** expression parser. It should be called as follows:
1.132145 +**
1.132146 +**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
1.132147 +**
1.132148 +** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
1.132149 +** to parse the query expression (see README.tokenizers). The second argument
1.132150 +** is the query expression to parse. Each subsequent argument is the name
1.132151 +** of a column of the fts3 table that the query expression may refer to.
1.132152 +** For example:
1.132153 +**
1.132154 +**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
1.132155 +*/
1.132156 +static void fts3ExprTest(
1.132157 +  sqlite3_context *context,
1.132158 +  int argc,
1.132159 +  sqlite3_value **argv
1.132160 +){
1.132161 +  sqlite3_tokenizer_module const *pModule = 0;
1.132162 +  sqlite3_tokenizer *pTokenizer = 0;
1.132163 +  int rc;
1.132164 +  char **azCol = 0;
1.132165 +  const char *zExpr;
1.132166 +  int nExpr;
1.132167 +  int nCol;
1.132168 +  int ii;
1.132169 +  Fts3Expr *pExpr;
1.132170 +  char *zBuf = 0;
1.132171 +  sqlite3 *db = sqlite3_context_db_handle(context);
1.132172 +
1.132173 +  if( argc<3 ){
1.132174 +    sqlite3_result_error(context, 
1.132175 +        "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
1.132176 +    );
1.132177 +    return;
1.132178 +  }
1.132179 +
1.132180 +  rc = queryTestTokenizer(db,
1.132181 +                          (const char *)sqlite3_value_text(argv[0]), &pModule);
1.132182 +  if( rc==SQLITE_NOMEM ){
1.132183 +    sqlite3_result_error_nomem(context);
1.132184 +    goto exprtest_out;
1.132185 +  }else if( !pModule ){
1.132186 +    sqlite3_result_error(context, "No such tokenizer module", -1);
1.132187 +    goto exprtest_out;
1.132188 +  }
1.132189 +
1.132190 +  rc = pModule->xCreate(0, 0, &pTokenizer);
1.132191 +  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
1.132192 +  if( rc==SQLITE_NOMEM ){
1.132193 +    sqlite3_result_error_nomem(context);
1.132194 +    goto exprtest_out;
1.132195 +  }
1.132196 +  pTokenizer->pModule = pModule;
1.132197 +
1.132198 +  zExpr = (const char *)sqlite3_value_text(argv[1]);
1.132199 +  nExpr = sqlite3_value_bytes(argv[1]);
1.132200 +  nCol = argc-2;
1.132201 +  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
1.132202 +  if( !azCol ){
1.132203 +    sqlite3_result_error_nomem(context);
1.132204 +    goto exprtest_out;
1.132205 +  }
1.132206 +  for(ii=0; ii<nCol; ii++){
1.132207 +    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
1.132208 +  }
1.132209 +
1.132210 +  if( sqlite3_user_data(context) ){
1.132211 +    char *zDummy = 0;
1.132212 +    rc = sqlite3Fts3ExprParse(
1.132213 +        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
1.132214 +    );
1.132215 +    assert( rc==SQLITE_OK || pExpr==0 );
1.132216 +    sqlite3_free(zDummy);
1.132217 +  }else{
1.132218 +    rc = fts3ExprParseUnbalanced(
1.132219 +        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
1.132220 +    );
1.132221 +  }
1.132222 +
1.132223 +  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
1.132224 +    sqlite3Fts3ExprFree(pExpr);
1.132225 +    sqlite3_result_error(context, "Error parsing expression", -1);
1.132226 +  }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
1.132227 +    sqlite3_result_error_nomem(context);
1.132228 +  }else{
1.132229 +    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
1.132230 +    sqlite3_free(zBuf);
1.132231 +  }
1.132232 +
1.132233 +  sqlite3Fts3ExprFree(pExpr);
1.132234 +
1.132235 +exprtest_out:
1.132236 +  if( pModule && pTokenizer ){
1.132237 +    rc = pModule->xDestroy(pTokenizer);
1.132238 +  }
1.132239 +  sqlite3_free(azCol);
1.132240 +}
1.132241 +
1.132242 +/*
1.132243 +** Register the query expression parser test function fts3_exprtest() 
1.132244 +** with database connection db. 
1.132245 +*/
1.132246 +SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
1.132247 +  int rc = sqlite3_create_function(
1.132248 +      db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
1.132249 +  );
1.132250 +  if( rc==SQLITE_OK ){
1.132251 +    rc = sqlite3_create_function(db, "fts3_exprtest_rebalance", 
1.132252 +        -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
1.132253 +    );
1.132254 +  }
1.132255 +  return rc;
1.132256 +}
1.132257 +
1.132258 +#endif
1.132259 +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
1.132260 +
1.132261 +/************** End of fts3_expr.c *******************************************/
1.132262 +/************** Begin file fts3_hash.c ***************************************/
1.132263 +/*
1.132264 +** 2001 September 22
1.132265 +**
1.132266 +** The author disclaims copyright to this source code.  In place of
1.132267 +** a legal notice, here is a blessing:
1.132268 +**
1.132269 +**    May you do good and not evil.
1.132270 +**    May you find forgiveness for yourself and forgive others.
1.132271 +**    May you share freely, never taking more than you give.
1.132272 +**
1.132273 +*************************************************************************
1.132274 +** This is the implementation of generic hash-tables used in SQLite.
1.132275 +** We've modified it slightly to serve as a standalone hash table
1.132276 +** implementation for the full-text indexing module.
1.132277 +*/
1.132278 +
1.132279 +/*
1.132280 +** The code in this file is only compiled if:
1.132281 +**
1.132282 +**     * The FTS3 module is being built as an extension
1.132283 +**       (in which case SQLITE_CORE is not defined), or
1.132284 +**
1.132285 +**     * The FTS3 module is being built into the core of
1.132286 +**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
1.132287 +*/
1.132288 +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
1.132289 +
1.132290 +/* #include <assert.h> */
1.132291 +/* #include <stdlib.h> */
1.132292 +/* #include <string.h> */
1.132293 +
1.132294 +
1.132295 +/*
1.132296 +** Malloc and Free functions
1.132297 +*/
1.132298 +static void *fts3HashMalloc(int n){
1.132299 +  void *p = sqlite3_malloc(n);
1.132300 +  if( p ){
1.132301 +    memset(p, 0, n);
1.132302 +  }
1.132303 +  return p;
1.132304 +}
1.132305 +static void fts3HashFree(void *p){
1.132306 +  sqlite3_free(p);
1.132307 +}
1.132308 +
1.132309 +/* Turn bulk memory into a hash table object by initializing the
1.132310 +** fields of the Hash structure.
1.132311 +**
1.132312 +** "pNew" is a pointer to the hash table that is to be initialized.
1.132313 +** keyClass is one of the constants 
1.132314 +** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
1.132315 +** determines what kind of key the hash table will use.  "copyKey" is
1.132316 +** true if the hash table should make its own private copy of keys and
1.132317 +** false if it should just use the supplied pointer.
1.132318 +*/
1.132319 +SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
1.132320 +  assert( pNew!=0 );
1.132321 +  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
1.132322 +  pNew->keyClass = keyClass;
1.132323 +  pNew->copyKey = copyKey;
1.132324 +  pNew->first = 0;
1.132325 +  pNew->count = 0;
1.132326 +  pNew->htsize = 0;
1.132327 +  pNew->ht = 0;
1.132328 +}
1.132329 +
1.132330 +/* Remove all entries from a hash table.  Reclaim all memory.
1.132331 +** Call this routine to delete a hash table or to reset a hash table
1.132332 +** to the empty state.
1.132333 +*/
1.132334 +SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
1.132335 +  Fts3HashElem *elem;         /* For looping over all elements of the table */
1.132336 +
1.132337 +  assert( pH!=0 );
1.132338 +  elem = pH->first;
1.132339 +  pH->first = 0;
1.132340 +  fts3HashFree(pH->ht);
1.132341 +  pH->ht = 0;
1.132342 +  pH->htsize = 0;
1.132343 +  while( elem ){
1.132344 +    Fts3HashElem *next_elem = elem->next;
1.132345 +    if( pH->copyKey && elem->pKey ){
1.132346 +      fts3HashFree(elem->pKey);
1.132347 +    }
1.132348 +    fts3HashFree(elem);
1.132349 +    elem = next_elem;
1.132350 +  }
1.132351 +  pH->count = 0;
1.132352 +}
1.132353 +
1.132354 +/*
1.132355 +** Hash and comparison functions when the mode is FTS3_HASH_STRING
1.132356 +*/
1.132357 +static int fts3StrHash(const void *pKey, int nKey){
1.132358 +  const char *z = (const char *)pKey;
1.132359 +  unsigned h = 0;
1.132360 +  if( nKey<=0 ) nKey = (int) strlen(z);
1.132361 +  while( nKey > 0  ){
1.132362 +    h = (h<<3) ^ h ^ *z++;
1.132363 +    nKey--;
1.132364 +  }
1.132365 +  return (int)(h & 0x7fffffff);
1.132366 +}
1.132367 +static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
1.132368 +  if( n1!=n2 ) return 1;
1.132369 +  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
1.132370 +}
1.132371 +
1.132372 +/*
1.132373 +** Hash and comparison functions when the mode is FTS3_HASH_BINARY
1.132374 +*/
1.132375 +static int fts3BinHash(const void *pKey, int nKey){
1.132376 +  int h = 0;
1.132377 +  const char *z = (const char *)pKey;
1.132378 +  while( nKey-- > 0 ){
1.132379 +    h = (h<<3) ^ h ^ *(z++);
1.132380 +  }
1.132381 +  return h & 0x7fffffff;
1.132382 +}
1.132383 +static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
1.132384 +  if( n1!=n2 ) return 1;
1.132385 +  return memcmp(pKey1,pKey2,n1);
1.132386 +}
1.132387 +
1.132388 +/*
1.132389 +** Return a pointer to the appropriate hash function given the key class.
1.132390 +**
1.132391 +** The C syntax in this function definition may be unfamilar to some 
1.132392 +** programmers, so we provide the following additional explanation:
1.132393 +**
1.132394 +** The name of the function is "ftsHashFunction".  The function takes a
1.132395 +** single parameter "keyClass".  The return value of ftsHashFunction()
1.132396 +** is a pointer to another function.  Specifically, the return value
1.132397 +** of ftsHashFunction() is a pointer to a function that takes two parameters
1.132398 +** with types "const void*" and "int" and returns an "int".
1.132399 +*/
1.132400 +static int (*ftsHashFunction(int keyClass))(const void*,int){
1.132401 +  if( keyClass==FTS3_HASH_STRING ){
1.132402 +    return &fts3StrHash;
1.132403 +  }else{
1.132404 +    assert( keyClass==FTS3_HASH_BINARY );
1.132405 +    return &fts3BinHash;
1.132406 +  }
1.132407 +}
1.132408 +
1.132409 +/*
1.132410 +** Return a pointer to the appropriate hash function given the key class.
1.132411 +**
1.132412 +** For help in interpreted the obscure C code in the function definition,
1.132413 +** see the header comment on the previous function.
1.132414 +*/
1.132415 +static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
1.132416 +  if( keyClass==FTS3_HASH_STRING ){
1.132417 +    return &fts3StrCompare;
1.132418 +  }else{
1.132419 +    assert( keyClass==FTS3_HASH_BINARY );
1.132420 +    return &fts3BinCompare;
1.132421 +  }
1.132422 +}
1.132423 +
1.132424 +/* Link an element into the hash table
1.132425 +*/
1.132426 +static void fts3HashInsertElement(
1.132427 +  Fts3Hash *pH,            /* The complete hash table */
1.132428 +  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
1.132429 +  Fts3HashElem *pNew       /* The element to be inserted */
1.132430 +){
1.132431 +  Fts3HashElem *pHead;     /* First element already in pEntry */
1.132432 +  pHead = pEntry->chain;
1.132433 +  if( pHead ){
1.132434 +    pNew->next = pHead;
1.132435 +    pNew->prev = pHead->prev;
1.132436 +    if( pHead->prev ){ pHead->prev->next = pNew; }
1.132437 +    else             { pH->first = pNew; }
1.132438 +    pHead->prev = pNew;
1.132439 +  }else{
1.132440 +    pNew->next = pH->first;
1.132441 +    if( pH->first ){ pH->first->prev = pNew; }
1.132442 +    pNew->prev = 0;
1.132443 +    pH->first = pNew;
1.132444 +  }
1.132445 +  pEntry->count++;
1.132446 +  pEntry->chain = pNew;
1.132447 +}
1.132448 +
1.132449 +
1.132450 +/* Resize the hash table so that it cantains "new_size" buckets.
1.132451 +** "new_size" must be a power of 2.  The hash table might fail 
1.132452 +** to resize if sqliteMalloc() fails.
1.132453 +**
1.132454 +** Return non-zero if a memory allocation error occurs.
1.132455 +*/
1.132456 +static int fts3Rehash(Fts3Hash *pH, int new_size){
1.132457 +  struct _fts3ht *new_ht;          /* The new hash table */
1.132458 +  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
1.132459 +  int (*xHash)(const void*,int);   /* The hash function */
1.132460 +
1.132461 +  assert( (new_size & (new_size-1))==0 );
1.132462 +  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
1.132463 +  if( new_ht==0 ) return 1;
1.132464 +  fts3HashFree(pH->ht);
1.132465 +  pH->ht = new_ht;
1.132466 +  pH->htsize = new_size;
1.132467 +  xHash = ftsHashFunction(pH->keyClass);
1.132468 +  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
1.132469 +    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
1.132470 +    next_elem = elem->next;
1.132471 +    fts3HashInsertElement(pH, &new_ht[h], elem);
1.132472 +  }
1.132473 +  return 0;
1.132474 +}
1.132475 +
1.132476 +/* This function (for internal use only) locates an element in an
1.132477 +** hash table that matches the given key.  The hash for this key has
1.132478 +** already been computed and is passed as the 4th parameter.
1.132479 +*/
1.132480 +static Fts3HashElem *fts3FindElementByHash(
1.132481 +  const Fts3Hash *pH, /* The pH to be searched */
1.132482 +  const void *pKey,   /* The key we are searching for */
1.132483 +  int nKey,
1.132484 +  int h               /* The hash for this key. */
1.132485 +){
1.132486 +  Fts3HashElem *elem;            /* Used to loop thru the element list */
1.132487 +  int count;                     /* Number of elements left to test */
1.132488 +  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
1.132489 +
1.132490 +  if( pH->ht ){
1.132491 +    struct _fts3ht *pEntry = &pH->ht[h];
1.132492 +    elem = pEntry->chain;
1.132493 +    count = pEntry->count;
1.132494 +    xCompare = ftsCompareFunction(pH->keyClass);
1.132495 +    while( count-- && elem ){
1.132496 +      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
1.132497 +        return elem;
1.132498 +      }
1.132499 +      elem = elem->next;
1.132500 +    }
1.132501 +  }
1.132502 +  return 0;
1.132503 +}
1.132504 +
1.132505 +/* Remove a single entry from the hash table given a pointer to that
1.132506 +** element and a hash on the element's key.
1.132507 +*/
1.132508 +static void fts3RemoveElementByHash(
1.132509 +  Fts3Hash *pH,         /* The pH containing "elem" */
1.132510 +  Fts3HashElem* elem,   /* The element to be removed from the pH */
1.132511 +  int h                 /* Hash value for the element */
1.132512 +){
1.132513 +  struct _fts3ht *pEntry;
1.132514 +  if( elem->prev ){
1.132515 +    elem->prev->next = elem->next; 
1.132516 +  }else{
1.132517 +    pH->first = elem->next;
1.132518 +  }
1.132519 +  if( elem->next ){
1.132520 +    elem->next->prev = elem->prev;
1.132521 +  }
1.132522 +  pEntry = &pH->ht[h];
1.132523 +  if( pEntry->chain==elem ){
1.132524 +    pEntry->chain = elem->next;
1.132525 +  }
1.132526 +  pEntry->count--;
1.132527 +  if( pEntry->count<=0 ){
1.132528 +    pEntry->chain = 0;
1.132529 +  }
1.132530 +  if( pH->copyKey && elem->pKey ){
1.132531 +    fts3HashFree(elem->pKey);
1.132532 +  }
1.132533 +  fts3HashFree( elem );
1.132534 +  pH->count--;
1.132535 +  if( pH->count<=0 ){
1.132536 +    assert( pH->first==0 );
1.132537 +    assert( pH->count==0 );
1.132538 +    fts3HashClear(pH);
1.132539 +  }
1.132540 +}
1.132541 +
1.132542 +SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
1.132543 +  const Fts3Hash *pH, 
1.132544 +  const void *pKey, 
1.132545 +  int nKey
1.132546 +){
1.132547 +  int h;                          /* A hash on key */
1.132548 +  int (*xHash)(const void*,int);  /* The hash function */
1.132549 +
1.132550 +  if( pH==0 || pH->ht==0 ) return 0;
1.132551 +  xHash = ftsHashFunction(pH->keyClass);
1.132552 +  assert( xHash!=0 );
1.132553 +  h = (*xHash)(pKey,nKey);
1.132554 +  assert( (pH->htsize & (pH->htsize-1))==0 );
1.132555 +  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
1.132556 +}
1.132557 +
1.132558 +/* 
1.132559 +** Attempt to locate an element of the hash table pH with a key
1.132560 +** that matches pKey,nKey.  Return the data for this element if it is
1.132561 +** found, or NULL if there is no match.
1.132562 +*/
1.132563 +SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
1.132564 +  Fts3HashElem *pElem;            /* The element that matches key (if any) */
1.132565 +
1.132566 +  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
1.132567 +  return pElem ? pElem->data : 0;
1.132568 +}
1.132569 +
1.132570 +/* Insert an element into the hash table pH.  The key is pKey,nKey
1.132571 +** and the data is "data".
1.132572 +**
1.132573 +** If no element exists with a matching key, then a new
1.132574 +** element is created.  A copy of the key is made if the copyKey
1.132575 +** flag is set.  NULL is returned.
1.132576 +**
1.132577 +** If another element already exists with the same key, then the
1.132578 +** new data replaces the old data and the old data is returned.
1.132579 +** The key is not copied in this instance.  If a malloc fails, then
1.132580 +** the new data is returned and the hash table is unchanged.
1.132581 +**
1.132582 +** If the "data" parameter to this function is NULL, then the
1.132583 +** element corresponding to "key" is removed from the hash table.
1.132584 +*/
1.132585 +SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
1.132586 +  Fts3Hash *pH,        /* The hash table to insert into */
1.132587 +  const void *pKey,    /* The key */
1.132588 +  int nKey,            /* Number of bytes in the key */
1.132589 +  void *data           /* The data */
1.132590 +){
1.132591 +  int hraw;                 /* Raw hash value of the key */
1.132592 +  int h;                    /* the hash of the key modulo hash table size */
1.132593 +  Fts3HashElem *elem;       /* Used to loop thru the element list */
1.132594 +  Fts3HashElem *new_elem;   /* New element added to the pH */
1.132595 +  int (*xHash)(const void*,int);  /* The hash function */
1.132596 +
1.132597 +  assert( pH!=0 );
1.132598 +  xHash = ftsHashFunction(pH->keyClass);
1.132599 +  assert( xHash!=0 );
1.132600 +  hraw = (*xHash)(pKey, nKey);
1.132601 +  assert( (pH->htsize & (pH->htsize-1))==0 );
1.132602 +  h = hraw & (pH->htsize-1);
1.132603 +  elem = fts3FindElementByHash(pH,pKey,nKey,h);
1.132604 +  if( elem ){
1.132605 +    void *old_data = elem->data;
1.132606 +    if( data==0 ){
1.132607 +      fts3RemoveElementByHash(pH,elem,h);
1.132608 +    }else{
1.132609 +      elem->data = data;
1.132610 +    }
1.132611 +    return old_data;
1.132612 +  }
1.132613 +  if( data==0 ) return 0;
1.132614 +  if( (pH->htsize==0 && fts3Rehash(pH,8))
1.132615 +   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
1.132616 +  ){
1.132617 +    pH->count = 0;
1.132618 +    return data;
1.132619 +  }
1.132620 +  assert( pH->htsize>0 );
1.132621 +  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
1.132622 +  if( new_elem==0 ) return data;
1.132623 +  if( pH->copyKey && pKey!=0 ){
1.132624 +    new_elem->pKey = fts3HashMalloc( nKey );
1.132625 +    if( new_elem->pKey==0 ){
1.132626 +      fts3HashFree(new_elem);
1.132627 +      return data;
1.132628 +    }
1.132629 +    memcpy((void*)new_elem->pKey, pKey, nKey);
1.132630 +  }else{
1.132631 +    new_elem->pKey = (void*)pKey;
1.132632 +  }
1.132633 +  new_elem->nKey = nKey;
1.132634 +  pH->count++;
1.132635 +  assert( pH->htsize>0 );
1.132636 +  assert( (pH->htsize & (pH->htsize-1))==0 );
1.132637 +  h = hraw & (pH->htsize-1);
1.132638 +  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
1.132639 +  new_elem->data = data;
1.132640 +  return 0;
1.132641 +}
1.132642 +
1.132643 +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
1.132644 +
1.132645 +/************** End of fts3_hash.c *******************************************/
1.132646 +/************** Begin file fts3_porter.c *************************************/
1.132647 +/*
1.132648 +** 2006 September 30
1.132649 +**
1.132650 +** The author disclaims copyright to this source code.  In place of
1.132651 +** a legal notice, here is a blessing:
1.132652 +**
1.132653 +**    May you do good and not evil.
1.132654 +**    May you find forgiveness for yourself and forgive others.
1.132655 +**    May you share freely, never taking more than you give.
1.132656 +**
1.132657 +*************************************************************************
1.132658 +** Implementation of the full-text-search tokenizer that implements
1.132659 +** a Porter stemmer.
1.132660 +*/
1.132661 +
1.132662 +/*
1.132663 +** The code in this file is only compiled if:
1.132664 +**
1.132665 +**     * The FTS3 module is being built as an extension
1.132666 +**       (in which case SQLITE_CORE is not defined), or
1.132667 +**
1.132668 +**     * The FTS3 module is being built into the core of
1.132669 +**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
1.132670 +*/
1.132671 +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
1.132672 +
1.132673 +/* #include <assert.h> */
1.132674 +/* #include <stdlib.h> */
1.132675 +/* #include <stdio.h> */
1.132676 +/* #include <string.h> */
1.132677 +
1.132678 +
1.132679 +/*
1.132680 +** Class derived from sqlite3_tokenizer
1.132681 +*/
1.132682 +typedef struct porter_tokenizer {
1.132683 +  sqlite3_tokenizer base;      /* Base class */
1.132684 +} porter_tokenizer;
1.132685 +
1.132686 +/*
1.132687 +** Class derived from sqlite3_tokenizer_cursor
1.132688 +*/
1.132689 +typedef struct porter_tokenizer_cursor {
1.132690 +  sqlite3_tokenizer_cursor base;
1.132691 +  const char *zInput;          /* input we are tokenizing */
1.132692 +  int nInput;                  /* size of the input */
1.132693 +  int iOffset;                 /* current position in zInput */
1.132694 +  int iToken;                  /* index of next token to be returned */
1.132695 +  char *zToken;                /* storage for current token */
1.132696 +  int nAllocated;              /* space allocated to zToken buffer */
1.132697 +} porter_tokenizer_cursor;
1.132698 +
1.132699 +
1.132700 +/*
1.132701 +** Create a new tokenizer instance.
1.132702 +*/
1.132703 +static int porterCreate(
1.132704 +  int argc, const char * const *argv,
1.132705 +  sqlite3_tokenizer **ppTokenizer
1.132706 +){
1.132707 +  porter_tokenizer *t;
1.132708 +
1.132709 +  UNUSED_PARAMETER(argc);
1.132710 +  UNUSED_PARAMETER(argv);
1.132711 +
1.132712 +  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
1.132713 +  if( t==NULL ) return SQLITE_NOMEM;
1.132714 +  memset(t, 0, sizeof(*t));
1.132715 +  *ppTokenizer = &t->base;
1.132716 +  return SQLITE_OK;
1.132717 +}
1.132718 +
1.132719 +/*
1.132720 +** Destroy a tokenizer
1.132721 +*/
1.132722 +static int porterDestroy(sqlite3_tokenizer *pTokenizer){
1.132723 +  sqlite3_free(pTokenizer);
1.132724 +  return SQLITE_OK;
1.132725 +}
1.132726 +
1.132727 +/*
1.132728 +** Prepare to begin tokenizing a particular string.  The input
1.132729 +** string to be tokenized is zInput[0..nInput-1].  A cursor
1.132730 +** used to incrementally tokenize this string is returned in 
1.132731 +** *ppCursor.
1.132732 +*/
1.132733 +static int porterOpen(
1.132734 +  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
1.132735 +  const char *zInput, int nInput,        /* String to be tokenized */
1.132736 +  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
1.132737 +){
1.132738 +  porter_tokenizer_cursor *c;
1.132739 +
1.132740 +  UNUSED_PARAMETER(pTokenizer);
1.132741 +
1.132742 +  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
1.132743 +  if( c==NULL ) return SQLITE_NOMEM;
1.132744 +
1.132745 +  c->zInput = zInput;
1.132746 +  if( zInput==0 ){
1.132747 +    c->nInput = 0;
1.132748 +  }else if( nInput<0 ){
1.132749 +    c->nInput = (int)strlen(zInput);
1.132750 +  }else{
1.132751 +    c->nInput = nInput;
1.132752 +  }
1.132753 +  c->iOffset = 0;                 /* start tokenizing at the beginning */
1.132754 +  c->iToken = 0;
1.132755 +  c->zToken = NULL;               /* no space allocated, yet. */
1.132756 +  c->nAllocated = 0;
1.132757 +
1.132758 +  *ppCursor = &c->base;
1.132759 +  return SQLITE_OK;
1.132760 +}
1.132761 +
1.132762 +/*
1.132763 +** Close a tokenization cursor previously opened by a call to
1.132764 +** porterOpen() above.
1.132765 +*/
1.132766 +static int porterClose(sqlite3_tokenizer_cursor *pCursor){
1.132767 +  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
1.132768 +  sqlite3_free(c->zToken);
1.132769 +  sqlite3_free(c);
1.132770 +  return SQLITE_OK;
1.132771 +}
1.132772 +/*
1.132773 +** Vowel or consonant
1.132774 +*/
1.132775 +static const char cType[] = {
1.132776 +   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
1.132777 +   1, 1, 1, 2, 1
1.132778 +};
1.132779 +
1.132780 +/*
1.132781 +** isConsonant() and isVowel() determine if their first character in
1.132782 +** the string they point to is a consonant or a vowel, according
1.132783 +** to Porter ruls.  
1.132784 +**
1.132785 +** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
1.132786 +** 'Y' is a consonant unless it follows another consonant,
1.132787 +** in which case it is a vowel.
1.132788 +**
1.132789 +** In these routine, the letters are in reverse order.  So the 'y' rule
1.132790 +** is that 'y' is a consonant unless it is followed by another
1.132791 +** consonent.
1.132792 +*/
1.132793 +static int isVowel(const char*);
1.132794 +static int isConsonant(const char *z){
1.132795 +  int j;
1.132796 +  char x = *z;
1.132797 +  if( x==0 ) return 0;
1.132798 +  assert( x>='a' && x<='z' );
1.132799 +  j = cType[x-'a'];
1.132800 +  if( j<2 ) return j;
1.132801 +  return z[1]==0 || isVowel(z + 1);
1.132802 +}
1.132803 +static int isVowel(const char *z){
1.132804 +  int j;
1.132805 +  char x = *z;
1.132806 +  if( x==0 ) return 0;
1.132807 +  assert( x>='a' && x<='z' );
1.132808 +  j = cType[x-'a'];
1.132809 +  if( j<2 ) return 1-j;
1.132810 +  return isConsonant(z + 1);
1.132811 +}
1.132812 +
1.132813 +/*
1.132814 +** Let any sequence of one or more vowels be represented by V and let
1.132815 +** C be sequence of one or more consonants.  Then every word can be
1.132816 +** represented as:
1.132817 +**
1.132818 +**           [C] (VC){m} [V]
1.132819 +**
1.132820 +** In prose:  A word is an optional consonant followed by zero or
1.132821 +** vowel-consonant pairs followed by an optional vowel.  "m" is the
1.132822 +** number of vowel consonant pairs.  This routine computes the value
1.132823 +** of m for the first i bytes of a word.
1.132824 +**
1.132825 +** Return true if the m-value for z is 1 or more.  In other words,
1.132826 +** return true if z contains at least one vowel that is followed
1.132827 +** by a consonant.
1.132828 +**
1.132829 +** In this routine z[] is in reverse order.  So we are really looking
1.132830 +** for an instance of of a consonant followed by a vowel.
1.132831 +*/
1.132832 +static int m_gt_0(const char *z){
1.132833 +  while( isVowel(z) ){ z++; }
1.132834 +  if( *z==0 ) return 0;
1.132835 +  while( isConsonant(z) ){ z++; }
1.132836 +  return *z!=0;
1.132837 +}
1.132838 +
1.132839 +/* Like mgt0 above except we are looking for a value of m which is
1.132840 +** exactly 1
1.132841 +*/
1.132842 +static int m_eq_1(const char *z){
1.132843 +  while( isVowel(z) ){ z++; }
1.132844 +  if( *z==0 ) return 0;
1.132845 +  while( isConsonant(z) ){ z++; }
1.132846 +  if( *z==0 ) return 0;
1.132847 +  while( isVowel(z) ){ z++; }
1.132848 +  if( *z==0 ) return 1;
1.132849 +  while( isConsonant(z) ){ z++; }
1.132850 +  return *z==0;
1.132851 +}
1.132852 +
1.132853 +/* Like mgt0 above except we are looking for a value of m>1 instead
1.132854 +** or m>0
1.132855 +*/
1.132856 +static int m_gt_1(const char *z){
1.132857 +  while( isVowel(z) ){ z++; }
1.132858 +  if( *z==0 ) return 0;
1.132859 +  while( isConsonant(z) ){ z++; }
1.132860 +  if( *z==0 ) return 0;
1.132861 +  while( isVowel(z) ){ z++; }
1.132862 +  if( *z==0 ) return 0;
1.132863 +  while( isConsonant(z) ){ z++; }
1.132864 +  return *z!=0;
1.132865 +}
1.132866 +
1.132867 +/*
1.132868 +** Return TRUE if there is a vowel anywhere within z[0..n-1]
1.132869 +*/
1.132870 +static int hasVowel(const char *z){
1.132871 +  while( isConsonant(z) ){ z++; }
1.132872 +  return *z!=0;
1.132873 +}
1.132874 +
1.132875 +/*
1.132876 +** Return TRUE if the word ends in a double consonant.
1.132877 +**
1.132878 +** The text is reversed here. So we are really looking at
1.132879 +** the first two characters of z[].
1.132880 +*/
1.132881 +static int doubleConsonant(const char *z){
1.132882 +  return isConsonant(z) && z[0]==z[1];
1.132883 +}
1.132884 +
1.132885 +/*
1.132886 +** Return TRUE if the word ends with three letters which
1.132887 +** are consonant-vowel-consonent and where the final consonant
1.132888 +** is not 'w', 'x', or 'y'.
1.132889 +**
1.132890 +** The word is reversed here.  So we are really checking the
1.132891 +** first three letters and the first one cannot be in [wxy].
1.132892 +*/
1.132893 +static int star_oh(const char *z){
1.132894 +  return
1.132895 +    isConsonant(z) &&
1.132896 +    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
1.132897 +    isVowel(z+1) &&
1.132898 +    isConsonant(z+2);
1.132899 +}
1.132900 +
1.132901 +/*
1.132902 +** If the word ends with zFrom and xCond() is true for the stem
1.132903 +** of the word that preceeds the zFrom ending, then change the 
1.132904 +** ending to zTo.
1.132905 +**
1.132906 +** The input word *pz and zFrom are both in reverse order.  zTo
1.132907 +** is in normal order. 
1.132908 +**
1.132909 +** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
1.132910 +** match.  Not that TRUE is returned even if xCond() fails and
1.132911 +** no substitution occurs.
1.132912 +*/
1.132913 +static int stem(
1.132914 +  char **pz,             /* The word being stemmed (Reversed) */
1.132915 +  const char *zFrom,     /* If the ending matches this... (Reversed) */
1.132916 +  const char *zTo,       /* ... change the ending to this (not reversed) */
1.132917 +  int (*xCond)(const char*)   /* Condition that must be true */
1.132918 +){
1.132919 +  char *z = *pz;
1.132920 +  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
1.132921 +  if( *zFrom!=0 ) return 0;
1.132922 +  if( xCond && !xCond(z) ) return 1;
1.132923 +  while( *zTo ){
1.132924 +    *(--z) = *(zTo++);
1.132925 +  }
1.132926 +  *pz = z;
1.132927 +  return 1;
1.132928 +}
1.132929 +
1.132930 +/*
1.132931 +** This is the fallback stemmer used when the porter stemmer is
1.132932 +** inappropriate.  The input word is copied into the output with
1.132933 +** US-ASCII case folding.  If the input word is too long (more
1.132934 +** than 20 bytes if it contains no digits or more than 6 bytes if
1.132935 +** it contains digits) then word is truncated to 20 or 6 bytes
1.132936 +** by taking 10 or 3 bytes from the beginning and end.
1.132937 +*/
1.132938 +static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
1.132939 +  int i, mx, j;
1.132940 +  int hasDigit = 0;
1.132941 +  for(i=0; i<nIn; i++){
1.132942 +    char c = zIn[i];
1.132943 +    if( c>='A' && c<='Z' ){
1.132944 +      zOut[i] = c - 'A' + 'a';
1.132945 +    }else{
1.132946 +      if( c>='0' && c<='9' ) hasDigit = 1;
1.132947 +      zOut[i] = c;
1.132948 +    }
1.132949 +  }
1.132950 +  mx = hasDigit ? 3 : 10;
1.132951 +  if( nIn>mx*2 ){
1.132952 +    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
1.132953 +      zOut[j] = zOut[i];
1.132954 +    }
1.132955 +    i = j;
1.132956 +  }
1.132957 +  zOut[i] = 0;
1.132958 +  *pnOut = i;
1.132959 +}
1.132960 +
1.132961 +
1.132962 +/*
1.132963 +** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
1.132964 +** zOut is at least big enough to hold nIn bytes.  Write the actual
1.132965 +** size of the output word (exclusive of the '\0' terminator) into *pnOut.
1.132966 +**
1.132967 +** Any upper-case characters in the US-ASCII character set ([A-Z])
1.132968 +** are converted to lower case.  Upper-case UTF characters are
1.132969 +** unchanged.
1.132970 +**
1.132971 +** Words that are longer than about 20 bytes are stemmed by retaining
1.132972 +** a few bytes from the beginning and the end of the word.  If the
1.132973 +** word contains digits, 3 bytes are taken from the beginning and
1.132974 +** 3 bytes from the end.  For long words without digits, 10 bytes
1.132975 +** are taken from each end.  US-ASCII case folding still applies.
1.132976 +** 
1.132977 +** If the input word contains not digits but does characters not 
1.132978 +** in [a-zA-Z] then no stemming is attempted and this routine just 
1.132979 +** copies the input into the input into the output with US-ASCII
1.132980 +** case folding.
1.132981 +**
1.132982 +** Stemming never increases the length of the word.  So there is
1.132983 +** no chance of overflowing the zOut buffer.
1.132984 +*/
1.132985 +static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
1.132986 +  int i, j;
1.132987 +  char zReverse[28];
1.132988 +  char *z, *z2;
1.132989 +  if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
1.132990 +    /* The word is too big or too small for the porter stemmer.
1.132991 +    ** Fallback to the copy stemmer */
1.132992 +    copy_stemmer(zIn, nIn, zOut, pnOut);
1.132993 +    return;
1.132994 +  }
1.132995 +  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
1.132996 +    char c = zIn[i];
1.132997 +    if( c>='A' && c<='Z' ){
1.132998 +      zReverse[j] = c + 'a' - 'A';
1.132999 +    }else if( c>='a' && c<='z' ){
1.133000 +      zReverse[j] = c;
1.133001 +    }else{
1.133002 +      /* The use of a character not in [a-zA-Z] means that we fallback
1.133003 +      ** to the copy stemmer */
1.133004 +      copy_stemmer(zIn, nIn, zOut, pnOut);
1.133005 +      return;
1.133006 +    }
1.133007 +  }
1.133008 +  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
1.133009 +  z = &zReverse[j+1];
1.133010 +
1.133011 +
1.133012 +  /* Step 1a */
1.133013 +  if( z[0]=='s' ){
1.133014 +    if(
1.133015 +     !stem(&z, "sess", "ss", 0) &&
1.133016 +     !stem(&z, "sei", "i", 0)  &&
1.133017 +     !stem(&z, "ss", "ss", 0)
1.133018 +    ){
1.133019 +      z++;
1.133020 +    }
1.133021 +  }
1.133022 +
1.133023 +  /* Step 1b */  
1.133024 +  z2 = z;
1.133025 +  if( stem(&z, "dee", "ee", m_gt_0) ){
1.133026 +    /* Do nothing.  The work was all in the test */
1.133027 +  }else if( 
1.133028 +     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
1.133029 +      && z!=z2
1.133030 +  ){
1.133031 +     if( stem(&z, "ta", "ate", 0) ||
1.133032 +         stem(&z, "lb", "ble", 0) ||
1.133033 +         stem(&z, "zi", "ize", 0) ){
1.133034 +       /* Do nothing.  The work was all in the test */
1.133035 +     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
1.133036 +       z++;
1.133037 +     }else if( m_eq_1(z) && star_oh(z) ){
1.133038 +       *(--z) = 'e';
1.133039 +     }
1.133040 +  }
1.133041 +
1.133042 +  /* Step 1c */
1.133043 +  if( z[0]=='y' && hasVowel(z+1) ){
1.133044 +    z[0] = 'i';
1.133045 +  }
1.133046 +
1.133047 +  /* Step 2 */
1.133048 +  switch( z[1] ){
1.133049 +   case 'a':
1.133050 +     if( !stem(&z, "lanoita", "ate", m_gt_0) ){
1.133051 +       stem(&z, "lanoit", "tion", m_gt_0);
1.133052 +     }
1.133053 +     break;
1.133054 +   case 'c':
1.133055 +     if( !stem(&z, "icne", "ence", m_gt_0) ){
1.133056 +       stem(&z, "icna", "ance", m_gt_0);
1.133057 +     }
1.133058 +     break;
1.133059 +   case 'e':
1.133060 +     stem(&z, "rezi", "ize", m_gt_0);
1.133061 +     break;
1.133062 +   case 'g':
1.133063 +     stem(&z, "igol", "log", m_gt_0);
1.133064 +     break;
1.133065 +   case 'l':
1.133066 +     if( !stem(&z, "ilb", "ble", m_gt_0) 
1.133067 +      && !stem(&z, "illa", "al", m_gt_0)
1.133068 +      && !stem(&z, "iltne", "ent", m_gt_0)
1.133069 +      && !stem(&z, "ile", "e", m_gt_0)
1.133070 +     ){
1.133071 +       stem(&z, "ilsuo", "ous", m_gt_0);
1.133072 +     }
1.133073 +     break;
1.133074 +   case 'o':
1.133075 +     if( !stem(&z, "noitazi", "ize", m_gt_0)
1.133076 +      && !stem(&z, "noita", "ate", m_gt_0)
1.133077 +     ){
1.133078 +       stem(&z, "rota", "ate", m_gt_0);
1.133079 +     }
1.133080 +     break;
1.133081 +   case 's':
1.133082 +     if( !stem(&z, "msila", "al", m_gt_0)
1.133083 +      && !stem(&z, "ssenevi", "ive", m_gt_0)
1.133084 +      && !stem(&z, "ssenluf", "ful", m_gt_0)
1.133085 +     ){
1.133086 +       stem(&z, "ssensuo", "ous", m_gt_0);
1.133087 +     }
1.133088 +     break;
1.133089 +   case 't':
1.133090 +     if( !stem(&z, "itila", "al", m_gt_0)
1.133091 +      && !stem(&z, "itivi", "ive", m_gt_0)
1.133092 +     ){
1.133093 +       stem(&z, "itilib", "ble", m_gt_0);
1.133094 +     }
1.133095 +     break;
1.133096 +  }
1.133097 +
1.133098 +  /* Step 3 */
1.133099 +  switch( z[0] ){
1.133100 +   case 'e':
1.133101 +     if( !stem(&z, "etaci", "ic", m_gt_0)
1.133102 +      && !stem(&z, "evita", "", m_gt_0)
1.133103 +     ){
1.133104 +       stem(&z, "ezila", "al", m_gt_0);
1.133105 +     }
1.133106 +     break;
1.133107 +   case 'i':
1.133108 +     stem(&z, "itici", "ic", m_gt_0);
1.133109 +     break;
1.133110 +   case 'l':
1.133111 +     if( !stem(&z, "laci", "ic", m_gt_0) ){
1.133112 +       stem(&z, "luf", "", m_gt_0);
1.133113 +     }
1.133114 +     break;
1.133115 +   case 's':
1.133116 +     stem(&z, "ssen", "", m_gt_0);
1.133117 +     break;
1.133118 +  }
1.133119 +
1.133120 +  /* Step 4 */
1.133121 +  switch( z[1] ){
1.133122 +   case 'a':
1.133123 +     if( z[0]=='l' && m_gt_1(z+2) ){
1.133124 +       z += 2;
1.133125 +     }
1.133126 +     break;
1.133127 +   case 'c':
1.133128 +     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
1.133129 +       z += 4;
1.133130 +     }
1.133131 +     break;
1.133132 +   case 'e':
1.133133 +     if( z[0]=='r' && m_gt_1(z+2) ){
1.133134 +       z += 2;
1.133135 +     }
1.133136 +     break;
1.133137 +   case 'i':
1.133138 +     if( z[0]=='c' && m_gt_1(z+2) ){
1.133139 +       z += 2;
1.133140 +     }
1.133141 +     break;
1.133142 +   case 'l':
1.133143 +     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
1.133144 +       z += 4;
1.133145 +     }
1.133146 +     break;
1.133147 +   case 'n':
1.133148 +     if( z[0]=='t' ){
1.133149 +       if( z[2]=='a' ){
1.133150 +         if( m_gt_1(z+3) ){
1.133151 +           z += 3;
1.133152 +         }
1.133153 +       }else if( z[2]=='e' ){
1.133154 +         if( !stem(&z, "tneme", "", m_gt_1)
1.133155 +          && !stem(&z, "tnem", "", m_gt_1)
1.133156 +         ){
1.133157 +           stem(&z, "tne", "", m_gt_1);
1.133158 +         }
1.133159 +       }
1.133160 +     }
1.133161 +     break;
1.133162 +   case 'o':
1.133163 +     if( z[0]=='u' ){
1.133164 +       if( m_gt_1(z+2) ){
1.133165 +         z += 2;
1.133166 +       }
1.133167 +     }else if( z[3]=='s' || z[3]=='t' ){
1.133168 +       stem(&z, "noi", "", m_gt_1);
1.133169 +     }
1.133170 +     break;
1.133171 +   case 's':
1.133172 +     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
1.133173 +       z += 3;
1.133174 +     }
1.133175 +     break;
1.133176 +   case 't':
1.133177 +     if( !stem(&z, "eta", "", m_gt_1) ){
1.133178 +       stem(&z, "iti", "", m_gt_1);
1.133179 +     }
1.133180 +     break;
1.133181 +   case 'u':
1.133182 +     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
1.133183 +       z += 3;
1.133184 +     }
1.133185 +     break;
1.133186 +   case 'v':
1.133187 +   case 'z':
1.133188 +     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
1.133189 +       z += 3;
1.133190 +     }
1.133191 +     break;
1.133192 +  }
1.133193 +
1.133194 +  /* Step 5a */
1.133195 +  if( z[0]=='e' ){
1.133196 +    if( m_gt_1(z+1) ){
1.133197 +      z++;
1.133198 +    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
1.133199 +      z++;
1.133200 +    }
1.133201 +  }
1.133202 +
1.133203 +  /* Step 5b */
1.133204 +  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
1.133205 +    z++;
1.133206 +  }
1.133207 +
1.133208 +  /* z[] is now the stemmed word in reverse order.  Flip it back
1.133209 +  ** around into forward order and return.
1.133210 +  */
1.133211 +  *pnOut = i = (int)strlen(z);
1.133212 +  zOut[i] = 0;
1.133213 +  while( *z ){
1.133214 +    zOut[--i] = *(z++);
1.133215 +  }
1.133216 +}
1.133217 +
1.133218 +/*
1.133219 +** Characters that can be part of a token.  We assume any character
1.133220 +** whose value is greater than 0x80 (any UTF character) can be
1.133221 +** part of a token.  In other words, delimiters all must have
1.133222 +** values of 0x7f or lower.
1.133223 +*/
1.133224 +static const char porterIdChar[] = {
1.133225 +/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
1.133226 +    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
1.133227 +    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
1.133228 +    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
1.133229 +    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
1.133230 +    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
1.133231 +};
1.133232 +#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
1.133233 +
1.133234 +/*
1.133235 +** Extract the next token from a tokenization cursor.  The cursor must
1.133236 +** have been opened by a prior call to porterOpen().
1.133237 +*/
1.133238 +static int porterNext(
1.133239 +  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
1.133240 +  const char **pzToken,               /* OUT: *pzToken is the token text */
1.133241 +  int *pnBytes,                       /* OUT: Number of bytes in token */
1.133242 +  int *piStartOffset,                 /* OUT: Starting offset of token */
1.133243 +  int *piEndOffset,                   /* OUT: Ending offset of token */
1.133244 +  int *piPosition                     /* OUT: Position integer of token */
1.133245 +){
1.133246 +  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
1.133247 +  const char *z = c->zInput;
1.133248 +
1.133249 +  while( c->iOffset<c->nInput ){
1.133250 +    int iStartOffset, ch;
1.133251 +
1.133252 +    /* Scan past delimiter characters */
1.133253 +    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
1.133254 +      c->iOffset++;
1.133255 +    }
1.133256 +
1.133257 +    /* Count non-delimiter characters. */
1.133258 +    iStartOffset = c->iOffset;
1.133259 +    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
1.133260 +      c->iOffset++;
1.133261 +    }
1.133262 +
1.133263 +    if( c->iOffset>iStartOffset ){
1.133264 +      int n = c->iOffset-iStartOffset;
1.133265 +      if( n>c->nAllocated ){
1.133266 +        char *pNew;
1.133267 +        c->nAllocated = n+20;
1.133268 +        pNew = sqlite3_realloc(c->zToken, c->nAllocated);
1.133269 +        if( !pNew ) return SQLITE_NOMEM;
1.133270 +        c->zToken = pNew;
1.133271 +      }
1.133272 +      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
1.133273 +      *pzToken = c->zToken;
1.133274 +      *piStartOffset = iStartOffset;
1.133275 +      *piEndOffset = c->iOffset;
1.133276 +      *piPosition = c->iToken++;
1.133277 +      return SQLITE_OK;
1.133278 +    }
1.133279 +  }
1.133280 +  return SQLITE_DONE;
1.133281 +}
1.133282 +
1.133283 +/*
1.133284 +** The set of routines that implement the porter-stemmer tokenizer
1.133285 +*/
1.133286 +static const sqlite3_tokenizer_module porterTokenizerModule = {
1.133287 +  0,
1.133288 +  porterCreate,
1.133289 +  porterDestroy,
1.133290 +  porterOpen,
1.133291 +  porterClose,
1.133292 +  porterNext,
1.133293 +  0
1.133294 +};
1.133295 +
1.133296 +/*
1.133297 +** Allocate a new porter tokenizer.  Return a pointer to the new
1.133298 +** tokenizer in *ppModule
1.133299 +*/
1.133300 +SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
1.133301 +  sqlite3_tokenizer_module const**ppModule
1.133302 +){
1.133303 +  *ppModule = &porterTokenizerModule;
1.133304 +}
1.133305 +
1.133306 +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
1.133307 +
1.133308 +/************** End of fts3_porter.c *****************************************/
1.133309 +/************** Begin file fts3_tokenizer.c **********************************/
1.133310 +/*
1.133311 +** 2007 June 22
1.133312 +**
1.133313 +** The author disclaims copyright to this source code.  In place of
1.133314 +** a legal notice, here is a blessing:
1.133315 +**
1.133316 +**    May you do good and not evil.
1.133317 +**    May you find forgiveness for yourself and forgive others.
1.133318 +**    May you share freely, never taking more than you give.
1.133319 +**
1.133320 +******************************************************************************
1.133321 +**
1.133322 +** This is part of an SQLite module implementing full-text search.
1.133323 +** This particular file implements the generic tokenizer interface.
1.133324 +*/
1.133325 +
1.133326 +/*
1.133327 +** The code in this file is only compiled if:
1.133328 +**
1.133329 +**     * The FTS3 module is being built as an extension
1.133330 +**       (in which case SQLITE_CORE is not defined), or
1.133331 +**
1.133332 +**     * The FTS3 module is being built into the core of
1.133333 +**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
1.133334 +*/
1.133335 +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
1.133336 +
1.133337 +/* #include <assert.h> */
1.133338 +/* #include <string.h> */
1.133339 +
1.133340 +/*
1.133341 +** Implementation of the SQL scalar function for accessing the underlying 
1.133342 +** hash table. This function may be called as follows:
1.133343 +**
1.133344 +**   SELECT <function-name>(<key-name>);
1.133345 +**   SELECT <function-name>(<key-name>, <pointer>);
1.133346 +**
1.133347 +** where <function-name> is the name passed as the second argument
1.133348 +** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
1.133349 +**
1.133350 +** If the <pointer> argument is specified, it must be a blob value
1.133351 +** containing a pointer to be stored as the hash data corresponding
1.133352 +** to the string <key-name>. If <pointer> is not specified, then
1.133353 +** the string <key-name> must already exist in the has table. Otherwise,
1.133354 +** an error is returned.
1.133355 +**
1.133356 +** Whether or not the <pointer> argument is specified, the value returned
1.133357 +** is a blob containing the pointer stored as the hash data corresponding
1.133358 +** to string <key-name> (after the hash-table is updated, if applicable).
1.133359 +*/
1.133360 +static void scalarFunc(
1.133361 +  sqlite3_context *context,
1.133362 +  int argc,
1.133363 +  sqlite3_value **argv
1.133364 +){
1.133365 +  Fts3Hash *pHash;
1.133366 +  void *pPtr = 0;
1.133367 +  const unsigned char *zName;
1.133368 +  int nName;
1.133369 +
1.133370 +  assert( argc==1 || argc==2 );
1.133371 +
1.133372 +  pHash = (Fts3Hash *)sqlite3_user_data(context);
1.133373 +
1.133374 +  zName = sqlite3_value_text(argv[0]);
1.133375 +  nName = sqlite3_value_bytes(argv[0])+1;
1.133376 +
1.133377 +  if( argc==2 ){
1.133378 +    void *pOld;
1.133379 +    int n = sqlite3_value_bytes(argv[1]);
1.133380 +    if( n!=sizeof(pPtr) ){
1.133381 +      sqlite3_result_error(context, "argument type mismatch", -1);
1.133382 +      return;
1.133383 +    }
1.133384 +    pPtr = *(void **)sqlite3_value_blob(argv[1]);
1.133385 +    pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
1.133386 +    if( pOld==pPtr ){
1.133387 +      sqlite3_result_error(context, "out of memory", -1);
1.133388 +      return;
1.133389 +    }
1.133390 +  }else{
1.133391 +    pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
1.133392 +    if( !pPtr ){
1.133393 +      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
1.133394 +      sqlite3_result_error(context, zErr, -1);
1.133395 +      sqlite3_free(zErr);
1.133396 +      return;
1.133397 +    }
1.133398 +  }
1.133399 +
1.133400 +  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
1.133401 +}
1.133402 +
1.133403 +SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
1.133404 +  static const char isFtsIdChar[] = {
1.133405 +      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
1.133406 +      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
1.133407 +      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
1.133408 +      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
1.133409 +      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
1.133410 +      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
1.133411 +      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
1.133412 +      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
1.133413 +  };
1.133414 +  return (c&0x80 || isFtsIdChar[(int)(c)]);
1.133415 +}
1.133416 +
1.133417 +SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
1.133418 +  const char *z1;
1.133419 +  const char *z2 = 0;
1.133420 +
1.133421 +  /* Find the start of the next token. */
1.133422 +  z1 = zStr;
1.133423 +  while( z2==0 ){
1.133424 +    char c = *z1;
1.133425 +    switch( c ){
1.133426 +      case '\0': return 0;        /* No more tokens here */
1.133427 +      case '\'':
1.133428 +      case '"':
1.133429 +      case '`': {
1.133430 +        z2 = z1;
1.133431 +        while( *++z2 && (*z2!=c || *++z2==c) );
1.133432 +        break;
1.133433 +      }
1.133434 +      case '[':
1.133435 +        z2 = &z1[1];
1.133436 +        while( *z2 && z2[0]!=']' ) z2++;
1.133437 +        if( *z2 ) z2++;
1.133438 +        break;
1.133439 +
1.133440 +      default:
1.133441 +        if( sqlite3Fts3IsIdChar(*z1) ){
1.133442 +          z2 = &z1[1];
1.133443 +          while( sqlite3Fts3IsIdChar(*z2) ) z2++;
1.133444 +        }else{
1.133445 +          z1++;
1.133446 +        }
1.133447 +    }
1.133448 +  }
1.133449 +
1.133450 +  *pn = (int)(z2-z1);
1.133451 +  return z1;
1.133452 +}
1.133453 +
1.133454 +SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
1.133455 +  Fts3Hash *pHash,                /* Tokenizer hash table */
1.133456 +  const char *zArg,               /* Tokenizer name */
1.133457 +  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
1.133458 +  char **pzErr                    /* OUT: Set to malloced error message */
1.133459 +){
1.133460 +  int rc;
1.133461 +  char *z = (char *)zArg;
1.133462 +  int n = 0;
1.133463 +  char *zCopy;
1.133464 +  char *zEnd;                     /* Pointer to nul-term of zCopy */
1.133465 +  sqlite3_tokenizer_module *m;
1.133466 +
1.133467 +  zCopy = sqlite3_mprintf("%s", zArg);
1.133468 +  if( !zCopy ) return SQLITE_NOMEM;
1.133469 +  zEnd = &zCopy[strlen(zCopy)];
1.133470 +
1.133471 +  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
1.133472 +  z[n] = '\0';
1.133473 +  sqlite3Fts3Dequote(z);
1.133474 +
1.133475 +  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
1.133476 +  if( !m ){
1.133477 +    *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
1.133478 +    rc = SQLITE_ERROR;
1.133479 +  }else{
1.133480 +    char const **aArg = 0;
1.133481 +    int iArg = 0;
1.133482 +    z = &z[n+1];
1.133483 +    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
1.133484 +      int nNew = sizeof(char *)*(iArg+1);
1.133485 +      char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
1.133486 +      if( !aNew ){
1.133487 +        sqlite3_free(zCopy);
1.133488 +        sqlite3_free((void *)aArg);
1.133489 +        return SQLITE_NOMEM;
1.133490 +      }
1.133491 +      aArg = aNew;
1.133492 +      aArg[iArg++] = z;
1.133493 +      z[n] = '\0';
1.133494 +      sqlite3Fts3Dequote(z);
1.133495 +      z = &z[n+1];
1.133496 +    }
1.133497 +    rc = m->xCreate(iArg, aArg, ppTok);
1.133498 +    assert( rc!=SQLITE_OK || *ppTok );
1.133499 +    if( rc!=SQLITE_OK ){
1.133500 +      *pzErr = sqlite3_mprintf("unknown tokenizer");
1.133501 +    }else{
1.133502 +      (*ppTok)->pModule = m; 
1.133503 +    }
1.133504 +    sqlite3_free((void *)aArg);
1.133505 +  }
1.133506 +
1.133507 +  sqlite3_free(zCopy);
1.133508 +  return rc;
1.133509 +}
1.133510 +
1.133511 +
1.133512 +#ifdef SQLITE_TEST
1.133513 +
1.133514 +#include <tcl.h>
1.133515 +/* #include <string.h> */
1.133516 +
1.133517 +/*
1.133518 +** Implementation of a special SQL scalar function for testing tokenizers 
1.133519 +** designed to be used in concert with the Tcl testing framework. This
1.133520 +** function must be called with two or more arguments:
1.133521 +**
1.133522 +**   SELECT <function-name>(<key-name>, ..., <input-string>);
1.133523 +**
1.133524 +** where <function-name> is the name passed as the second argument
1.133525 +** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
1.133526 +** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
1.133527 +**
1.133528 +** The return value is a string that may be interpreted as a Tcl
1.133529 +** list. For each token in the <input-string>, three elements are
1.133530 +** added to the returned list. The first is the token position, the 
1.133531 +** second is the token text (folded, stemmed, etc.) and the third is the
1.133532 +** substring of <input-string> associated with the token. For example, 
1.133533 +** using the built-in "simple" tokenizer:
1.133534 +**
1.133535 +**   SELECT fts_tokenizer_test('simple', 'I don't see how');
1.133536 +**
1.133537 +** will return the string:
1.133538 +**
1.133539 +**   "{0 i I 1 dont don't 2 see see 3 how how}"
1.133540 +**   
1.133541 +*/
1.133542 +static void testFunc(
1.133543 +  sqlite3_context *context,
1.133544 +  int argc,
1.133545 +  sqlite3_value **argv
1.133546 +){
1.133547 +  Fts3Hash *pHash;
1.133548 +  sqlite3_tokenizer_module *p;
1.133549 +  sqlite3_tokenizer *pTokenizer = 0;
1.133550 +  sqlite3_tokenizer_cursor *pCsr = 0;
1.133551 +
1.133552 +  const char *zErr = 0;
1.133553 +
1.133554 +  const char *zName;
1.133555 +  int nName;
1.133556 +  const char *zInput;
1.133557 +  int nInput;
1.133558 +
1.133559 +  const char *azArg[64];
1.133560 +
1.133561 +  const char *zToken;
1.133562 +  int nToken = 0;
1.133563 +  int iStart = 0;
1.133564 +  int iEnd = 0;
1.133565 +  int iPos = 0;
1.133566 +  int i;
1.133567 +
1.133568 +  Tcl_Obj *pRet;
1.133569 +
1.133570 +  if( argc<2 ){
1.133571 +    sqlite3_result_error(context, "insufficient arguments", -1);
1.133572 +    return;
1.133573 +  }
1.133574 +
1.133575 +  nName = sqlite3_value_bytes(argv[0]);
1.133576 +  zName = (const char *)sqlite3_value_text(argv[0]);
1.133577 +  nInput = sqlite3_value_bytes(argv[argc-1]);
1.133578 +  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
1.133579 +
1.133580 +  pHash = (Fts3Hash *)sqlite3_user_data(context);
1.133581 +  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
1.133582 +
1.133583 +  if( !p ){
1.133584 +    char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
1.133585 +    sqlite3_result_error(context, zErr, -1);
1.133586 +    sqlite3_free(zErr);
1.133587 +    return;
1.133588 +  }
1.133589 +
1.133590 +  pRet = Tcl_NewObj();
1.133591 +  Tcl_IncrRefCount(pRet);
1.133592 +
1.133593 +  for(i=1; i<argc-1; i++){
1.133594 +    azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
1.133595 +  }
1.133596 +
1.133597 +  if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
1.133598 +    zErr = "error in xCreate()";
1.133599 +    goto finish;
1.133600 +  }
1.133601 +  pTokenizer->pModule = p;
1.133602 +  if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
1.133603 +    zErr = "error in xOpen()";
1.133604 +    goto finish;
1.133605 +  }
1.133606 +
1.133607 +  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
1.133608 +    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
1.133609 +    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
1.133610 +    zToken = &zInput[iStart];
1.133611 +    nToken = iEnd-iStart;
1.133612 +    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
1.133613 +  }
1.133614 +
1.133615 +  if( SQLITE_OK!=p->xClose(pCsr) ){
1.133616 +    zErr = "error in xClose()";
1.133617 +    goto finish;
1.133618 +  }
1.133619 +  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
1.133620 +    zErr = "error in xDestroy()";
1.133621 +    goto finish;
1.133622 +  }
1.133623 +
1.133624 +finish:
1.133625 +  if( zErr ){
1.133626 +    sqlite3_result_error(context, zErr, -1);
1.133627 +  }else{
1.133628 +    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
1.133629 +  }
1.133630 +  Tcl_DecrRefCount(pRet);
1.133631 +}
1.133632 +
1.133633 +static
1.133634 +int registerTokenizer(
1.133635 +  sqlite3 *db, 
1.133636 +  char *zName, 
1.133637 +  const sqlite3_tokenizer_module *p
1.133638 +){
1.133639 +  int rc;
1.133640 +  sqlite3_stmt *pStmt;
1.133641 +  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
1.133642 +
1.133643 +  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
1.133644 +  if( rc!=SQLITE_OK ){
1.133645 +    return rc;
1.133646 +  }
1.133647 +
1.133648 +  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
1.133649 +  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
1.133650 +  sqlite3_step(pStmt);
1.133651 +
1.133652 +  return sqlite3_finalize(pStmt);
1.133653 +}
1.133654 +
1.133655 +static
1.133656 +int queryTokenizer(
1.133657 +  sqlite3 *db, 
1.133658 +  char *zName,  
1.133659 +  const sqlite3_tokenizer_module **pp
1.133660 +){
1.133661 +  int rc;
1.133662 +  sqlite3_stmt *pStmt;
1.133663 +  const char zSql[] = "SELECT fts3_tokenizer(?)";
1.133664 +
1.133665 +  *pp = 0;
1.133666 +  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
1.133667 +  if( rc!=SQLITE_OK ){
1.133668 +    return rc;
1.133669 +  }
1.133670 +
1.133671 +  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
1.133672 +  if( SQLITE_ROW==sqlite3_step(pStmt) ){
1.133673 +    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
1.133674 +      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
1.133675 +    }
1.133676 +  }
1.133677 +
1.133678 +  return sqlite3_finalize(pStmt);
1.133679 +}
1.133680 +
1.133681 +SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
1.133682 +
1.133683 +/*
1.133684 +** Implementation of the scalar function fts3_tokenizer_internal_test().
1.133685 +** This function is used for testing only, it is not included in the
1.133686 +** build unless SQLITE_TEST is defined.
1.133687 +**
1.133688 +** The purpose of this is to test that the fts3_tokenizer() function
1.133689 +** can be used as designed by the C-code in the queryTokenizer and
1.133690 +** registerTokenizer() functions above. These two functions are repeated
1.133691 +** in the README.tokenizer file as an example, so it is important to
1.133692 +** test them.
1.133693 +**
1.133694 +** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
1.133695 +** function with no arguments. An assert() will fail if a problem is
1.133696 +** detected. i.e.:
1.133697 +**
1.133698 +**     SELECT fts3_tokenizer_internal_test();
1.133699 +**
1.133700 +*/
1.133701 +static void intTestFunc(
1.133702 +  sqlite3_context *context,
1.133703 +  int argc,
1.133704 +  sqlite3_value **argv
1.133705 +){
1.133706 +  int rc;
1.133707 +  const sqlite3_tokenizer_module *p1;
1.133708 +  const sqlite3_tokenizer_module *p2;
1.133709 +  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
1.133710 +
1.133711 +  UNUSED_PARAMETER(argc);
1.133712 +  UNUSED_PARAMETER(argv);
1.133713 +
1.133714 +  /* Test the query function */
1.133715 +  sqlite3Fts3SimpleTokenizerModule(&p1);
1.133716 +  rc = queryTokenizer(db, "simple", &p2);
1.133717 +  assert( rc==SQLITE_OK );
1.133718 +  assert( p1==p2 );
1.133719 +  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
1.133720 +  assert( rc==SQLITE_ERROR );
1.133721 +  assert( p2==0 );
1.133722 +  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
1.133723 +
1.133724 +  /* Test the storage function */
1.133725 +  rc = registerTokenizer(db, "nosuchtokenizer", p1);
1.133726 +  assert( rc==SQLITE_OK );
1.133727 +  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
1.133728 +  assert( rc==SQLITE_OK );
1.133729 +  assert( p2==p1 );
1.133730 +
1.133731 +  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
1.133732 +}
1.133733 +
1.133734 +#endif
1.133735 +
1.133736 +/*
1.133737 +** Set up SQL objects in database db used to access the contents of
1.133738 +** the hash table pointed to by argument pHash. The hash table must
1.133739 +** been initialized to use string keys, and to take a private copy 
1.133740 +** of the key when a value is inserted. i.e. by a call similar to:
1.133741 +**
1.133742 +**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
1.133743 +**
1.133744 +** This function adds a scalar function (see header comment above
1.133745 +** scalarFunc() in this file for details) and, if ENABLE_TABLE is
1.133746 +** defined at compilation time, a temporary virtual table (see header 
1.133747 +** comment above struct HashTableVtab) to the database schema. Both 
1.133748 +** provide read/write access to the contents of *pHash.
1.133749 +**
1.133750 +** The third argument to this function, zName, is used as the name
1.133751 +** of both the scalar and, if created, the virtual table.
1.133752 +*/
1.133753 +SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
1.133754 +  sqlite3 *db, 
1.133755 +  Fts3Hash *pHash, 
1.133756 +  const char *zName
1.133757 +){
1.133758 +  int rc = SQLITE_OK;
1.133759 +  void *p = (void *)pHash;
1.133760 +  const int any = SQLITE_ANY;
1.133761 +
1.133762 +#ifdef SQLITE_TEST
1.133763 +  char *zTest = 0;
1.133764 +  char *zTest2 = 0;
1.133765 +  void *pdb = (void *)db;
1.133766 +  zTest = sqlite3_mprintf("%s_test", zName);
1.133767 +  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
1.133768 +  if( !zTest || !zTest2 ){
1.133769 +    rc = SQLITE_NOMEM;
1.133770 +  }
1.133771 +#endif
1.133772 +
1.133773 +  if( SQLITE_OK==rc ){
1.133774 +    rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
1.133775 +  }
1.133776 +  if( SQLITE_OK==rc ){
1.133777 +    rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
1.133778 +  }
1.133779 +#ifdef SQLITE_TEST
1.133780 +  if( SQLITE_OK==rc ){
1.133781 +    rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
1.133782 +  }
1.133783 +  if( SQLITE_OK==rc ){
1.133784 +    rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
1.133785 +  }
1.133786 +#endif
1.133787 +
1.133788 +#ifdef SQLITE_TEST
1.133789 +  sqlite3_free(zTest);
1.133790 +  sqlite3_free(zTest2);
1.133791 +#endif
1.133792 +
1.133793 +  return rc;
1.133794 +}
1.133795 +
1.133796 +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
1.133797 +
1.133798 +/************** End of fts3_tokenizer.c **************************************/
1.133799 +/************** Begin file fts3_tokenizer1.c *********************************/
1.133800 +/*
1.133801 +** 2006 Oct 10
1.133802 +**
1.133803 +** The author disclaims copyright to this source code.  In place of
1.133804 +** a legal notice, here is a blessing:
1.133805 +**
1.133806 +**    May you do good and not evil.
1.133807 +**    May you find forgiveness for yourself and forgive others.
1.133808 +**    May you share freely, never taking more than you give.
1.133809 +**
1.133810 +******************************************************************************
1.133811 +**
1.133812 +** Implementation of the "simple" full-text-search tokenizer.
1.133813 +*/
1.133814 +
1.133815 +/*
1.133816 +** The code in this file is only compiled if:
1.133817 +**
1.133818 +**     * The FTS3 module is being built as an extension
1.133819 +**       (in which case SQLITE_CORE is not defined), or
1.133820 +**
1.133821 +**     * The FTS3 module is being built into the core of
1.133822 +**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
1.133823 +*/
1.133824 +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
1.133825 +
1.133826 +/* #include <assert.h> */
1.133827 +/* #include <stdlib.h> */
1.133828 +/* #include <stdio.h> */
1.133829 +/* #include <string.h> */
1.133830 +
1.133831 +
1.133832 +typedef struct simple_tokenizer {
1.133833 +  sqlite3_tokenizer base;
1.133834 +  char delim[128];             /* flag ASCII delimiters */
1.133835 +} simple_tokenizer;
1.133836 +
1.133837 +typedef struct simple_tokenizer_cursor {
1.133838 +  sqlite3_tokenizer_cursor base;
1.133839 +  const char *pInput;          /* input we are tokenizing */
1.133840 +  int nBytes;                  /* size of the input */
1.133841 +  int iOffset;                 /* current position in pInput */
1.133842 +  int iToken;                  /* index of next token to be returned */
1.133843 +  char *pToken;                /* storage for current token */
1.133844 +  int nTokenAllocated;         /* space allocated to zToken buffer */
1.133845 +} simple_tokenizer_cursor;
1.133846 +
1.133847 +
1.133848 +static int simpleDelim(simple_tokenizer *t, unsigned char c){
1.133849 +  return c<0x80 && t->delim[c];
1.133850 +}
1.133851 +static int fts3_isalnum(int x){
1.133852 +  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
1.133853 +}
1.133854 +
1.133855 +/*
1.133856 +** Create a new tokenizer instance.
1.133857 +*/
1.133858 +static int simpleCreate(
1.133859 +  int argc, const char * const *argv,
1.133860 +  sqlite3_tokenizer **ppTokenizer
1.133861 +){
1.133862 +  simple_tokenizer *t;
1.133863 +
1.133864 +  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
1.133865 +  if( t==NULL ) return SQLITE_NOMEM;
1.133866 +  memset(t, 0, sizeof(*t));
1.133867 +
1.133868 +  /* TODO(shess) Delimiters need to remain the same from run to run,
1.133869 +  ** else we need to reindex.  One solution would be a meta-table to
1.133870 +  ** track such information in the database, then we'd only want this
1.133871 +  ** information on the initial create.
1.133872 +  */
1.133873 +  if( argc>1 ){
1.133874 +    int i, n = (int)strlen(argv[1]);
1.133875 +    for(i=0; i<n; i++){
1.133876 +      unsigned char ch = argv[1][i];
1.133877 +      /* We explicitly don't support UTF-8 delimiters for now. */
1.133878 +      if( ch>=0x80 ){
1.133879 +        sqlite3_free(t);
1.133880 +        return SQLITE_ERROR;
1.133881 +      }
1.133882 +      t->delim[ch] = 1;
1.133883 +    }
1.133884 +  } else {
1.133885 +    /* Mark non-alphanumeric ASCII characters as delimiters */
1.133886 +    int i;
1.133887 +    for(i=1; i<0x80; i++){
1.133888 +      t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
1.133889 +    }
1.133890 +  }
1.133891 +
1.133892 +  *ppTokenizer = &t->base;
1.133893 +  return SQLITE_OK;
1.133894 +}
1.133895 +
1.133896 +/*
1.133897 +** Destroy a tokenizer
1.133898 +*/
1.133899 +static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
1.133900 +  sqlite3_free(pTokenizer);
1.133901 +  return SQLITE_OK;
1.133902 +}
1.133903 +
1.133904 +/*
1.133905 +** Prepare to begin tokenizing a particular string.  The input
1.133906 +** string to be tokenized is pInput[0..nBytes-1].  A cursor
1.133907 +** used to incrementally tokenize this string is returned in 
1.133908 +** *ppCursor.
1.133909 +*/
1.133910 +static int simpleOpen(
1.133911 +  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
1.133912 +  const char *pInput, int nBytes,        /* String to be tokenized */
1.133913 +  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
1.133914 +){
1.133915 +  simple_tokenizer_cursor *c;
1.133916 +
1.133917 +  UNUSED_PARAMETER(pTokenizer);
1.133918 +
1.133919 +  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
1.133920 +  if( c==NULL ) return SQLITE_NOMEM;
1.133921 +
1.133922 +  c->pInput = pInput;
1.133923 +  if( pInput==0 ){
1.133924 +    c->nBytes = 0;
1.133925 +  }else if( nBytes<0 ){
1.133926 +    c->nBytes = (int)strlen(pInput);
1.133927 +  }else{
1.133928 +    c->nBytes = nBytes;
1.133929 +  }
1.133930 +  c->iOffset = 0;                 /* start tokenizing at the beginning */
1.133931 +  c->iToken = 0;
1.133932 +  c->pToken = NULL;               /* no space allocated, yet. */
1.133933 +  c->nTokenAllocated = 0;
1.133934 +
1.133935 +  *ppCursor = &c->base;
1.133936 +  return SQLITE_OK;
1.133937 +}
1.133938 +
1.133939 +/*
1.133940 +** Close a tokenization cursor previously opened by a call to
1.133941 +** simpleOpen() above.
1.133942 +*/
1.133943 +static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
1.133944 +  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
1.133945 +  sqlite3_free(c->pToken);
1.133946 +  sqlite3_free(c);
1.133947 +  return SQLITE_OK;
1.133948 +}
1.133949 +
1.133950 +/*
1.133951 +** Extract the next token from a tokenization cursor.  The cursor must
1.133952 +** have been opened by a prior call to simpleOpen().
1.133953 +*/
1.133954 +static int simpleNext(
1.133955 +  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
1.133956 +  const char **ppToken,               /* OUT: *ppToken is the token text */
1.133957 +  int *pnBytes,                       /* OUT: Number of bytes in token */
1.133958 +  int *piStartOffset,                 /* OUT: Starting offset of token */
1.133959 +  int *piEndOffset,                   /* OUT: Ending offset of token */
1.133960 +  int *piPosition                     /* OUT: Position integer of token */
1.133961 +){
1.133962 +  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
1.133963 +  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
1.133964 +  unsigned char *p = (unsigned char *)c->pInput;
1.133965 +
1.133966 +  while( c->iOffset<c->nBytes ){
1.133967 +    int iStartOffset;
1.133968 +
1.133969 +    /* Scan past delimiter characters */
1.133970 +    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
1.133971 +      c->iOffset++;
1.133972 +    }
1.133973 +
1.133974 +    /* Count non-delimiter characters. */
1.133975 +    iStartOffset = c->iOffset;
1.133976 +    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
1.133977 +      c->iOffset++;
1.133978 +    }
1.133979 +
1.133980 +    if( c->iOffset>iStartOffset ){
1.133981 +      int i, n = c->iOffset-iStartOffset;
1.133982 +      if( n>c->nTokenAllocated ){
1.133983 +        char *pNew;
1.133984 +        c->nTokenAllocated = n+20;
1.133985 +        pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
1.133986 +        if( !pNew ) return SQLITE_NOMEM;
1.133987 +        c->pToken = pNew;
1.133988 +      }
1.133989 +      for(i=0; i<n; i++){
1.133990 +        /* TODO(shess) This needs expansion to handle UTF-8
1.133991 +        ** case-insensitivity.
1.133992 +        */
1.133993 +        unsigned char ch = p[iStartOffset+i];
1.133994 +        c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
1.133995 +      }
1.133996 +      *ppToken = c->pToken;
1.133997 +      *pnBytes = n;
1.133998 +      *piStartOffset = iStartOffset;
1.133999 +      *piEndOffset = c->iOffset;
1.134000 +      *piPosition = c->iToken++;
1.134001 +
1.134002 +      return SQLITE_OK;
1.134003 +    }
1.134004 +  }
1.134005 +  return SQLITE_DONE;
1.134006 +}
1.134007 +
1.134008 +/*
1.134009 +** The set of routines that implement the simple tokenizer
1.134010 +*/
1.134011 +static const sqlite3_tokenizer_module simpleTokenizerModule = {
1.134012 +  0,
1.134013 +  simpleCreate,
1.134014 +  simpleDestroy,
1.134015 +  simpleOpen,
1.134016 +  simpleClose,
1.134017 +  simpleNext,
1.134018 +  0,
1.134019 +};
1.134020 +
1.134021 +/*
1.134022 +** Allocate a new simple tokenizer.  Return a pointer to the new
1.134023 +** tokenizer in *ppModule
1.134024 +*/
1.134025 +SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
1.134026 +  sqlite3_tokenizer_module const**ppModule
1.134027 +){
1.134028 +  *ppModule = &simpleTokenizerModule;
1.134029 +}
1.134030 +
1.134031 +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
1.134032 +
1.134033 +/************** End of fts3_tokenizer1.c *************************************/
1.134034 +/************** Begin file fts3_tokenize_vtab.c ******************************/
1.134035 +/*
1.134036 +** 2013 Apr 22
1.134037 +**
1.134038 +** The author disclaims copyright to this source code.  In place of
1.134039 +** a legal notice, here is a blessing:
1.134040 +**
1.134041 +**    May you do good and not evil.
1.134042 +**    May you find forgiveness for yourself and forgive others.
1.134043 +**    May you share freely, never taking more than you give.
1.134044 +**
1.134045 +******************************************************************************
1.134046 +**
1.134047 +** This file contains code for the "fts3tokenize" virtual table module.
1.134048 +** An fts3tokenize virtual table is created as follows:
1.134049 +**
1.134050 +**   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
1.134051 +**       <tokenizer-name>, <arg-1>, ...
1.134052 +**   );
1.134053 +**
1.134054 +** The table created has the following schema:
1.134055 +**
1.134056 +**   CREATE TABLE <tbl>(input, token, start, end, position)
1.134057 +**
1.134058 +** When queried, the query must include a WHERE clause of type:
1.134059 +**
1.134060 +**   input = <string>
1.134061 +**
1.134062 +** The virtual table module tokenizes this <string>, using the FTS3 
1.134063 +** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE 
1.134064 +** statement and returns one row for each token in the result. With
1.134065 +** fields set as follows:
1.134066 +**
1.134067 +**   input:   Always set to a copy of <string>
1.134068 +**   token:   A token from the input.
1.134069 +**   start:   Byte offset of the token within the input <string>.
1.134070 +**   end:     Byte offset of the byte immediately following the end of the
1.134071 +**            token within the input string.
1.134072 +**   pos:     Token offset of token within input.
1.134073 +**
1.134074 +*/
1.134075 +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
1.134076 +
1.134077 +/* #include <string.h> */
1.134078 +/* #include <assert.h> */
1.134079 +
1.134080 +typedef struct Fts3tokTable Fts3tokTable;
1.134081 +typedef struct Fts3tokCursor Fts3tokCursor;
1.134082 +
1.134083 +/*
1.134084 +** Virtual table structure.
1.134085 +*/
1.134086 +struct Fts3tokTable {
1.134087 +  sqlite3_vtab base;              /* Base class used by SQLite core */
1.134088 +  const sqlite3_tokenizer_module *pMod;
1.134089 +  sqlite3_tokenizer *pTok;
1.134090 +};
1.134091 +
1.134092 +/*
1.134093 +** Virtual table cursor structure.
1.134094 +*/
1.134095 +struct Fts3tokCursor {
1.134096 +  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
1.134097 +  char *zInput;                   /* Input string */
1.134098 +  sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
1.134099 +  int iRowid;                     /* Current 'rowid' value */
1.134100 +  const char *zToken;             /* Current 'token' value */
1.134101 +  int nToken;                     /* Size of zToken in bytes */
1.134102 +  int iStart;                     /* Current 'start' value */
1.134103 +  int iEnd;                       /* Current 'end' value */
1.134104 +  int iPos;                       /* Current 'pos' value */
1.134105 +};
1.134106 +
1.134107 +/*
1.134108 +** Query FTS for the tokenizer implementation named zName.
1.134109 +*/
1.134110 +static int fts3tokQueryTokenizer(
1.134111 +  Fts3Hash *pHash,
1.134112 +  const char *zName,
1.134113 +  const sqlite3_tokenizer_module **pp,
1.134114 +  char **pzErr
1.134115 +){
1.134116 +  sqlite3_tokenizer_module *p;
1.134117 +  int nName = (int)strlen(zName);
1.134118 +
1.134119 +  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
1.134120 +  if( !p ){
1.134121 +    *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
1.134122 +    return SQLITE_ERROR;
1.134123 +  }
1.134124 +
1.134125 +  *pp = p;
1.134126 +  return SQLITE_OK;
1.134127 +}
1.134128 +
1.134129 +/*
1.134130 +** The second argument, argv[], is an array of pointers to nul-terminated
1.134131 +** strings. This function makes a copy of the array and strings into a 
1.134132 +** single block of memory. It then dequotes any of the strings that appear
1.134133 +** to be quoted.
1.134134 +**
1.134135 +** If successful, output parameter *pazDequote is set to point at the
1.134136 +** array of dequoted strings and SQLITE_OK is returned. The caller is
1.134137 +** responsible for eventually calling sqlite3_free() to free the array
1.134138 +** in this case. Or, if an error occurs, an SQLite error code is returned.
1.134139 +** The final value of *pazDequote is undefined in this case.
1.134140 +*/
1.134141 +static int fts3tokDequoteArray(
1.134142 +  int argc,                       /* Number of elements in argv[] */
1.134143 +  const char * const *argv,       /* Input array */
1.134144 +  char ***pazDequote              /* Output array */
1.134145 +){
1.134146 +  int rc = SQLITE_OK;             /* Return code */
1.134147 +  if( argc==0 ){
1.134148 +    *pazDequote = 0;
1.134149 +  }else{
1.134150 +    int i;
1.134151 +    int nByte = 0;
1.134152 +    char **azDequote;
1.134153 +
1.134154 +    for(i=0; i<argc; i++){
1.134155 +      nByte += (int)(strlen(argv[i]) + 1);
1.134156 +    }
1.134157 +
1.134158 +    *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
1.134159 +    if( azDequote==0 ){
1.134160 +      rc = SQLITE_NOMEM;
1.134161 +    }else{
1.134162 +      char *pSpace = (char *)&azDequote[argc];
1.134163 +      for(i=0; i<argc; i++){
1.134164 +        int n = (int)strlen(argv[i]);
1.134165 +        azDequote[i] = pSpace;
1.134166 +        memcpy(pSpace, argv[i], n+1);
1.134167 +        sqlite3Fts3Dequote(pSpace);
1.134168 +        pSpace += (n+1);
1.134169 +      }
1.134170 +    }
1.134171 +  }
1.134172 +
1.134173 +  return rc;
1.134174 +}
1.134175 +
1.134176 +/*
1.134177 +** Schema of the tokenizer table.
1.134178 +*/
1.134179 +#define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
1.134180 +
1.134181 +/*
1.134182 +** This function does all the work for both the xConnect and xCreate methods.
1.134183 +** These tables have no persistent representation of their own, so xConnect
1.134184 +** and xCreate are identical operations.
1.134185 +**
1.134186 +**   argv[0]: module name
1.134187 +**   argv[1]: database name 
1.134188 +**   argv[2]: table name
1.134189 +**   argv[3]: first argument (tokenizer name)
1.134190 +*/
1.134191 +static int fts3tokConnectMethod(
1.134192 +  sqlite3 *db,                    /* Database connection */
1.134193 +  void *pHash,                    /* Hash table of tokenizers */
1.134194 +  int argc,                       /* Number of elements in argv array */
1.134195 +  const char * const *argv,       /* xCreate/xConnect argument array */
1.134196 +  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
1.134197 +  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
1.134198 +){
1.134199 +  Fts3tokTable *pTab;
1.134200 +  const sqlite3_tokenizer_module *pMod = 0;
1.134201 +  sqlite3_tokenizer *pTok = 0;
1.134202 +  int rc;
1.134203 +  char **azDequote = 0;
1.134204 +  int nDequote;
1.134205 +
1.134206 +  rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
1.134207 +  if( rc!=SQLITE_OK ) return rc;
1.134208 +
1.134209 +  nDequote = argc-3;
1.134210 +  rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
1.134211 +
1.134212 +  if( rc==SQLITE_OK ){
1.134213 +    const char *zModule;
1.134214 +    if( nDequote<1 ){
1.134215 +      zModule = "simple";
1.134216 +    }else{
1.134217 +      zModule = azDequote[0];
1.134218 +    }
1.134219 +    rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
1.134220 +  }
1.134221 +
1.134222 +  assert( (rc==SQLITE_OK)==(pMod!=0) );
1.134223 +  if( rc==SQLITE_OK ){
1.134224 +    const char * const *azArg = (const char * const *)&azDequote[1];
1.134225 +    rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
1.134226 +  }
1.134227 +
1.134228 +  if( rc==SQLITE_OK ){
1.134229 +    pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
1.134230 +    if( pTab==0 ){
1.134231 +      rc = SQLITE_NOMEM;
1.134232 +    }
1.134233 +  }
1.134234 +
1.134235 +  if( rc==SQLITE_OK ){
1.134236 +    memset(pTab, 0, sizeof(Fts3tokTable));
1.134237 +    pTab->pMod = pMod;
1.134238 +    pTab->pTok = pTok;
1.134239 +    *ppVtab = &pTab->base;
1.134240 +  }else{
1.134241 +    if( pTok ){
1.134242 +      pMod->xDestroy(pTok);
1.134243 +    }
1.134244 +  }
1.134245 +
1.134246 +  sqlite3_free(azDequote);
1.134247 +  return rc;
1.134248 +}
1.134249 +
1.134250 +/*
1.134251 +** This function does the work for both the xDisconnect and xDestroy methods.
1.134252 +** These tables have no persistent representation of their own, so xDisconnect
1.134253 +** and xDestroy are identical operations.
1.134254 +*/
1.134255 +static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
1.134256 +  Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
1.134257 +
1.134258 +  pTab->pMod->xDestroy(pTab->pTok);
1.134259 +  sqlite3_free(pTab);
1.134260 +  return SQLITE_OK;
1.134261 +}
1.134262 +
1.134263 +/*
1.134264 +** xBestIndex - Analyze a WHERE and ORDER BY clause.
1.134265 +*/
1.134266 +static int fts3tokBestIndexMethod(
1.134267 +  sqlite3_vtab *pVTab, 
1.134268 +  sqlite3_index_info *pInfo
1.134269 +){
1.134270 +  int i;
1.134271 +  UNUSED_PARAMETER(pVTab);
1.134272 +
1.134273 +  for(i=0; i<pInfo->nConstraint; i++){
1.134274 +    if( pInfo->aConstraint[i].usable 
1.134275 +     && pInfo->aConstraint[i].iColumn==0 
1.134276 +     && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ 
1.134277 +    ){
1.134278 +      pInfo->idxNum = 1;
1.134279 +      pInfo->aConstraintUsage[i].argvIndex = 1;
1.134280 +      pInfo->aConstraintUsage[i].omit = 1;
1.134281 +      pInfo->estimatedCost = 1;
1.134282 +      return SQLITE_OK;
1.134283 +    }
1.134284 +  }
1.134285 +
1.134286 +  pInfo->idxNum = 0;
1.134287 +  assert( pInfo->estimatedCost>1000000.0 );
1.134288 +
1.134289 +  return SQLITE_OK;
1.134290 +}
1.134291 +
1.134292 +/*
1.134293 +** xOpen - Open a cursor.
1.134294 +*/
1.134295 +static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
1.134296 +  Fts3tokCursor *pCsr;
1.134297 +  UNUSED_PARAMETER(pVTab);
1.134298 +
1.134299 +  pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
1.134300 +  if( pCsr==0 ){
1.134301 +    return SQLITE_NOMEM;
1.134302 +  }
1.134303 +  memset(pCsr, 0, sizeof(Fts3tokCursor));
1.134304 +
1.134305 +  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
1.134306 +  return SQLITE_OK;
1.134307 +}
1.134308 +
1.134309 +/*
1.134310 +** Reset the tokenizer cursor passed as the only argument. As if it had
1.134311 +** just been returned by fts3tokOpenMethod().
1.134312 +*/
1.134313 +static void fts3tokResetCursor(Fts3tokCursor *pCsr){
1.134314 +  if( pCsr->pCsr ){
1.134315 +    Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
1.134316 +    pTab->pMod->xClose(pCsr->pCsr);
1.134317 +    pCsr->pCsr = 0;
1.134318 +  }
1.134319 +  sqlite3_free(pCsr->zInput);
1.134320 +  pCsr->zInput = 0;
1.134321 +  pCsr->zToken = 0;
1.134322 +  pCsr->nToken = 0;
1.134323 +  pCsr->iStart = 0;
1.134324 +  pCsr->iEnd = 0;
1.134325 +  pCsr->iPos = 0;
1.134326 +  pCsr->iRowid = 0;
1.134327 +}
1.134328 +
1.134329 +/*
1.134330 +** xClose - Close a cursor.
1.134331 +*/
1.134332 +static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
1.134333 +  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
1.134334 +
1.134335 +  fts3tokResetCursor(pCsr);
1.134336 +  sqlite3_free(pCsr);
1.134337 +  return SQLITE_OK;
1.134338 +}
1.134339 +
1.134340 +/*
1.134341 +** xNext - Advance the cursor to the next row, if any.
1.134342 +*/
1.134343 +static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
1.134344 +  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
1.134345 +  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
1.134346 +  int rc;                         /* Return code */
1.134347 +
1.134348 +  pCsr->iRowid++;
1.134349 +  rc = pTab->pMod->xNext(pCsr->pCsr,
1.134350 +      &pCsr->zToken, &pCsr->nToken,
1.134351 +      &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
1.134352 +  );
1.134353 +
1.134354 +  if( rc!=SQLITE_OK ){
1.134355 +    fts3tokResetCursor(pCsr);
1.134356 +    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
1.134357 +  }
1.134358 +
1.134359 +  return rc;
1.134360 +}
1.134361 +
1.134362 +/*
1.134363 +** xFilter - Initialize a cursor to point at the start of its data.
1.134364 +*/
1.134365 +static int fts3tokFilterMethod(
1.134366 +  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
1.134367 +  int idxNum,                     /* Strategy index */
1.134368 +  const char *idxStr,             /* Unused */
1.134369 +  int nVal,                       /* Number of elements in apVal */
1.134370 +  sqlite3_value **apVal           /* Arguments for the indexing scheme */
1.134371 +){
1.134372 +  int rc = SQLITE_ERROR;
1.134373 +  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
1.134374 +  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
1.134375 +  UNUSED_PARAMETER(idxStr);
1.134376 +  UNUSED_PARAMETER(nVal);
1.134377 +
1.134378 +  fts3tokResetCursor(pCsr);
1.134379 +  if( idxNum==1 ){
1.134380 +    const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
1.134381 +    int nByte = sqlite3_value_bytes(apVal[0]);
1.134382 +    pCsr->zInput = sqlite3_malloc(nByte+1);
1.134383 +    if( pCsr->zInput==0 ){
1.134384 +      rc = SQLITE_NOMEM;
1.134385 +    }else{
1.134386 +      memcpy(pCsr->zInput, zByte, nByte);
1.134387 +      pCsr->zInput[nByte] = 0;
1.134388 +      rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
1.134389 +      if( rc==SQLITE_OK ){
1.134390 +        pCsr->pCsr->pTokenizer = pTab->pTok;
1.134391 +      }
1.134392 +    }
1.134393 +  }
1.134394 +
1.134395 +  if( rc!=SQLITE_OK ) return rc;
1.134396 +  return fts3tokNextMethod(pCursor);
1.134397 +}
1.134398 +
1.134399 +/*
1.134400 +** xEof - Return true if the cursor is at EOF, or false otherwise.
1.134401 +*/
1.134402 +static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
1.134403 +  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
1.134404 +  return (pCsr->zToken==0);
1.134405 +}
1.134406 +
1.134407 +/*
1.134408 +** xColumn - Return a column value.
1.134409 +*/
1.134410 +static int fts3tokColumnMethod(
1.134411 +  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
1.134412 +  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
1.134413 +  int iCol                        /* Index of column to read value from */
1.134414 +){
1.134415 +  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
1.134416 +
1.134417 +  /* CREATE TABLE x(input, token, start, end, position) */
1.134418 +  switch( iCol ){
1.134419 +    case 0:
1.134420 +      sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
1.134421 +      break;
1.134422 +    case 1:
1.134423 +      sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
1.134424 +      break;
1.134425 +    case 2:
1.134426 +      sqlite3_result_int(pCtx, pCsr->iStart);
1.134427 +      break;
1.134428 +    case 3:
1.134429 +      sqlite3_result_int(pCtx, pCsr->iEnd);
1.134430 +      break;
1.134431 +    default:
1.134432 +      assert( iCol==4 );
1.134433 +      sqlite3_result_int(pCtx, pCsr->iPos);
1.134434 +      break;
1.134435 +  }
1.134436 +  return SQLITE_OK;
1.134437 +}
1.134438 +
1.134439 +/*
1.134440 +** xRowid - Return the current rowid for the cursor.
1.134441 +*/
1.134442 +static int fts3tokRowidMethod(
1.134443 +  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
1.134444 +  sqlite_int64 *pRowid            /* OUT: Rowid value */
1.134445 +){
1.134446 +  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
1.134447 +  *pRowid = (sqlite3_int64)pCsr->iRowid;
1.134448 +  return SQLITE_OK;
1.134449 +}
1.134450 +
1.134451 +/*
1.134452 +** Register the fts3tok module with database connection db. Return SQLITE_OK
1.134453 +** if successful or an error code if sqlite3_create_module() fails.
1.134454 +*/
1.134455 +SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
1.134456 +  static const sqlite3_module fts3tok_module = {
1.134457 +     0,                           /* iVersion      */
1.134458 +     fts3tokConnectMethod,        /* xCreate       */
1.134459 +     fts3tokConnectMethod,        /* xConnect      */
1.134460 +     fts3tokBestIndexMethod,      /* xBestIndex    */
1.134461 +     fts3tokDisconnectMethod,     /* xDisconnect   */
1.134462 +     fts3tokDisconnectMethod,     /* xDestroy      */
1.134463 +     fts3tokOpenMethod,           /* xOpen         */
1.134464 +     fts3tokCloseMethod,          /* xClose        */
1.134465 +     fts3tokFilterMethod,         /* xFilter       */
1.134466 +     fts3tokNextMethod,           /* xNext         */
1.134467 +     fts3tokEofMethod,            /* xEof          */
1.134468 +     fts3tokColumnMethod,         /* xColumn       */
1.134469 +     fts3tokRowidMethod,          /* xRowid        */
1.134470 +     0,                           /* xUpdate       */
1.134471 +     0,                           /* xBegin        */
1.134472 +     0,                           /* xSync         */
1.134473 +     0,                           /* xCommit       */
1.134474 +     0,                           /* xRollback     */
1.134475 +     0,                           /* xFindFunction */
1.134476 +     0,                           /* xRename       */
1.134477 +     0,                           /* xSavepoint    */
1.134478 +     0,                           /* xRelease      */
1.134479 +     0                            /* xRollbackTo   */
1.134480 +  };
1.134481 +  int rc;                         /* Return code */
1.134482 +
1.134483 +  rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
1.134484 +  return rc;
1.134485 +}
1.134486 +
1.134487 +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
1.134488 +
1.134489 +/************** End of fts3_tokenize_vtab.c **********************************/
1.134490 +/************** Begin file fts3_write.c **************************************/
1.134491 +/*
1.134492 +** 2009 Oct 23
1.134493 +**
1.134494 +** The author disclaims copyright to this source code.  In place of
1.134495 +** a legal notice, here is a blessing:
1.134496 +**
1.134497 +**    May you do good and not evil.
1.134498 +**    May you find forgiveness for yourself and forgive others.
1.134499 +**    May you share freely, never taking more than you give.
1.134500 +**
1.134501 +******************************************************************************
1.134502 +**
1.134503 +** This file is part of the SQLite FTS3 extension module. Specifically,
1.134504 +** this file contains code to insert, update and delete rows from FTS3
1.134505 +** tables. It also contains code to merge FTS3 b-tree segments. Some
1.134506 +** of the sub-routines used to merge segments are also used by the query 
1.134507 +** code in fts3.c.
1.134508 +*/
1.134509 +
1.134510 +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
1.134511 +
1.134512 +/* #include <string.h> */
1.134513 +/* #include <assert.h> */
1.134514 +/* #include <stdlib.h> */
1.134515 +
1.134516 +
1.134517 +#define FTS_MAX_APPENDABLE_HEIGHT 16
1.134518 +
1.134519 +/*
1.134520 +** When full-text index nodes are loaded from disk, the buffer that they
1.134521 +** are loaded into has the following number of bytes of padding at the end 
1.134522 +** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
1.134523 +** of 920 bytes is allocated for it.
1.134524 +**
1.134525 +** This means that if we have a pointer into a buffer containing node data,
1.134526 +** it is always safe to read up to two varints from it without risking an
1.134527 +** overread, even if the node data is corrupted.
1.134528 +*/
1.134529 +#define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
1.134530 +
1.134531 +/*
1.134532 +** Under certain circumstances, b-tree nodes (doclists) can be loaded into
1.134533 +** memory incrementally instead of all at once. This can be a big performance
1.134534 +** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
1.134535 +** method before retrieving all query results (as may happen, for example,
1.134536 +** if a query has a LIMIT clause).
1.134537 +**
1.134538 +** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD 
1.134539 +** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
1.134540 +** The code is written so that the hard lower-limit for each of these values 
1.134541 +** is 1. Clearly such small values would be inefficient, but can be useful 
1.134542 +** for testing purposes.
1.134543 +**
1.134544 +** If this module is built with SQLITE_TEST defined, these constants may
1.134545 +** be overridden at runtime for testing purposes. File fts3_test.c contains
1.134546 +** a Tcl interface to read and write the values.
1.134547 +*/
1.134548 +#ifdef SQLITE_TEST
1.134549 +int test_fts3_node_chunksize = (4*1024);
1.134550 +int test_fts3_node_chunk_threshold = (4*1024)*4;
1.134551 +# define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
1.134552 +# define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
1.134553 +#else
1.134554 +# define FTS3_NODE_CHUNKSIZE (4*1024) 
1.134555 +# define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
1.134556 +#endif
1.134557 +
1.134558 +/*
1.134559 +** The two values that may be meaningfully bound to the :1 parameter in
1.134560 +** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
1.134561 +*/
1.134562 +#define FTS_STAT_DOCTOTAL      0
1.134563 +#define FTS_STAT_INCRMERGEHINT 1
1.134564 +#define FTS_STAT_AUTOINCRMERGE 2
1.134565 +
1.134566 +/*
1.134567 +** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
1.134568 +** and incremental merge operation that takes place. This is used for 
1.134569 +** debugging FTS only, it should not usually be turned on in production
1.134570 +** systems.
1.134571 +*/
1.134572 +#ifdef FTS3_LOG_MERGES
1.134573 +static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
1.134574 +  sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
1.134575 +}
1.134576 +#else
1.134577 +#define fts3LogMerge(x, y)
1.134578 +#endif
1.134579 +
1.134580 +
1.134581 +typedef struct PendingList PendingList;
1.134582 +typedef struct SegmentNode SegmentNode;
1.134583 +typedef struct SegmentWriter SegmentWriter;
1.134584 +
1.134585 +/*
1.134586 +** An instance of the following data structure is used to build doclists
1.134587 +** incrementally. See function fts3PendingListAppend() for details.
1.134588 +*/
1.134589 +struct PendingList {
1.134590 +  int nData;
1.134591 +  char *aData;
1.134592 +  int nSpace;
1.134593 +  sqlite3_int64 iLastDocid;
1.134594 +  sqlite3_int64 iLastCol;
1.134595 +  sqlite3_int64 iLastPos;
1.134596 +};
1.134597 +
1.134598 +
1.134599 +/*
1.134600 +** Each cursor has a (possibly empty) linked list of the following objects.
1.134601 +*/
1.134602 +struct Fts3DeferredToken {
1.134603 +  Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
1.134604 +  int iCol;                       /* Column token must occur in */
1.134605 +  Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
1.134606 +  PendingList *pList;             /* Doclist is assembled here */
1.134607 +};
1.134608 +
1.134609 +/*
1.134610 +** An instance of this structure is used to iterate through the terms on
1.134611 +** a contiguous set of segment b-tree leaf nodes. Although the details of
1.134612 +** this structure are only manipulated by code in this file, opaque handles
1.134613 +** of type Fts3SegReader* are also used by code in fts3.c to iterate through
1.134614 +** terms when querying the full-text index. See functions:
1.134615 +**
1.134616 +**   sqlite3Fts3SegReaderNew()
1.134617 +**   sqlite3Fts3SegReaderFree()
1.134618 +**   sqlite3Fts3SegReaderIterate()
1.134619 +**
1.134620 +** Methods used to manipulate Fts3SegReader structures:
1.134621 +**
1.134622 +**   fts3SegReaderNext()
1.134623 +**   fts3SegReaderFirstDocid()
1.134624 +**   fts3SegReaderNextDocid()
1.134625 +*/
1.134626 +struct Fts3SegReader {
1.134627 +  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
1.134628 +  u8 bLookup;                     /* True for a lookup only */
1.134629 +  u8 rootOnly;                    /* True for a root-only reader */
1.134630 +
1.134631 +  sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
1.134632 +  sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
1.134633 +  sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
1.134634 +  sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
1.134635 +
1.134636 +  char *aNode;                    /* Pointer to node data (or NULL) */
1.134637 +  int nNode;                      /* Size of buffer at aNode (or 0) */
1.134638 +  int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
1.134639 +  sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
1.134640 +
1.134641 +  Fts3HashElem **ppNextElem;
1.134642 +
1.134643 +  /* Variables set by fts3SegReaderNext(). These may be read directly
1.134644 +  ** by the caller. They are valid from the time SegmentReaderNew() returns
1.134645 +  ** until SegmentReaderNext() returns something other than SQLITE_OK
1.134646 +  ** (i.e. SQLITE_DONE).
1.134647 +  */
1.134648 +  int nTerm;                      /* Number of bytes in current term */
1.134649 +  char *zTerm;                    /* Pointer to current term */
1.134650 +  int nTermAlloc;                 /* Allocated size of zTerm buffer */
1.134651 +  char *aDoclist;                 /* Pointer to doclist of current entry */
1.134652 +  int nDoclist;                   /* Size of doclist in current entry */
1.134653 +
1.134654 +  /* The following variables are used by fts3SegReaderNextDocid() to iterate 
1.134655 +  ** through the current doclist (aDoclist/nDoclist).
1.134656 +  */
1.134657 +  char *pOffsetList;
1.134658 +  int nOffsetList;                /* For descending pending seg-readers only */
1.134659 +  sqlite3_int64 iDocid;
1.134660 +};
1.134661 +
1.134662 +#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
1.134663 +#define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
1.134664 +
1.134665 +/*
1.134666 +** An instance of this structure is used to create a segment b-tree in the
1.134667 +** database. The internal details of this type are only accessed by the
1.134668 +** following functions:
1.134669 +**
1.134670 +**   fts3SegWriterAdd()
1.134671 +**   fts3SegWriterFlush()
1.134672 +**   fts3SegWriterFree()
1.134673 +*/
1.134674 +struct SegmentWriter {
1.134675 +  SegmentNode *pTree;             /* Pointer to interior tree structure */
1.134676 +  sqlite3_int64 iFirst;           /* First slot in %_segments written */
1.134677 +  sqlite3_int64 iFree;            /* Next free slot in %_segments */
1.134678 +  char *zTerm;                    /* Pointer to previous term buffer */
1.134679 +  int nTerm;                      /* Number of bytes in zTerm */
1.134680 +  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
1.134681 +  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
1.134682 +  int nSize;                      /* Size of allocation at aData */
1.134683 +  int nData;                      /* Bytes of data in aData */
1.134684 +  char *aData;                    /* Pointer to block from malloc() */
1.134685 +};
1.134686 +
1.134687 +/*
1.134688 +** Type SegmentNode is used by the following three functions to create
1.134689 +** the interior part of the segment b+-tree structures (everything except
1.134690 +** the leaf nodes). These functions and type are only ever used by code
1.134691 +** within the fts3SegWriterXXX() family of functions described above.
1.134692 +**
1.134693 +**   fts3NodeAddTerm()
1.134694 +**   fts3NodeWrite()
1.134695 +**   fts3NodeFree()
1.134696 +**
1.134697 +** When a b+tree is written to the database (either as a result of a merge
1.134698 +** or the pending-terms table being flushed), leaves are written into the 
1.134699 +** database file as soon as they are completely populated. The interior of
1.134700 +** the tree is assembled in memory and written out only once all leaves have
1.134701 +** been populated and stored. This is Ok, as the b+-tree fanout is usually
1.134702 +** very large, meaning that the interior of the tree consumes relatively 
1.134703 +** little memory.
1.134704 +*/
1.134705 +struct SegmentNode {
1.134706 +  SegmentNode *pParent;           /* Parent node (or NULL for root node) */
1.134707 +  SegmentNode *pRight;            /* Pointer to right-sibling */
1.134708 +  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
1.134709 +  int nEntry;                     /* Number of terms written to node so far */
1.134710 +  char *zTerm;                    /* Pointer to previous term buffer */
1.134711 +  int nTerm;                      /* Number of bytes in zTerm */
1.134712 +  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
1.134713 +  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
1.134714 +  int nData;                      /* Bytes of valid data so far */
1.134715 +  char *aData;                    /* Node data */
1.134716 +};
1.134717 +
1.134718 +/*
1.134719 +** Valid values for the second argument to fts3SqlStmt().
1.134720 +*/
1.134721 +#define SQL_DELETE_CONTENT             0
1.134722 +#define SQL_IS_EMPTY                   1
1.134723 +#define SQL_DELETE_ALL_CONTENT         2 
1.134724 +#define SQL_DELETE_ALL_SEGMENTS        3
1.134725 +#define SQL_DELETE_ALL_SEGDIR          4
1.134726 +#define SQL_DELETE_ALL_DOCSIZE         5
1.134727 +#define SQL_DELETE_ALL_STAT            6
1.134728 +#define SQL_SELECT_CONTENT_BY_ROWID    7
1.134729 +#define SQL_NEXT_SEGMENT_INDEX         8
1.134730 +#define SQL_INSERT_SEGMENTS            9
1.134731 +#define SQL_NEXT_SEGMENTS_ID          10
1.134732 +#define SQL_INSERT_SEGDIR             11
1.134733 +#define SQL_SELECT_LEVEL              12
1.134734 +#define SQL_SELECT_LEVEL_RANGE        13
1.134735 +#define SQL_SELECT_LEVEL_COUNT        14
1.134736 +#define SQL_SELECT_SEGDIR_MAX_LEVEL   15
1.134737 +#define SQL_DELETE_SEGDIR_LEVEL       16
1.134738 +#define SQL_DELETE_SEGMENTS_RANGE     17
1.134739 +#define SQL_CONTENT_INSERT            18
1.134740 +#define SQL_DELETE_DOCSIZE            19
1.134741 +#define SQL_REPLACE_DOCSIZE           20
1.134742 +#define SQL_SELECT_DOCSIZE            21
1.134743 +#define SQL_SELECT_STAT               22
1.134744 +#define SQL_REPLACE_STAT              23
1.134745 +
1.134746 +#define SQL_SELECT_ALL_PREFIX_LEVEL   24
1.134747 +#define SQL_DELETE_ALL_TERMS_SEGDIR   25
1.134748 +#define SQL_DELETE_SEGDIR_RANGE       26
1.134749 +#define SQL_SELECT_ALL_LANGID         27
1.134750 +#define SQL_FIND_MERGE_LEVEL          28
1.134751 +#define SQL_MAX_LEAF_NODE_ESTIMATE    29
1.134752 +#define SQL_DELETE_SEGDIR_ENTRY       30
1.134753 +#define SQL_SHIFT_SEGDIR_ENTRY        31
1.134754 +#define SQL_SELECT_SEGDIR             32
1.134755 +#define SQL_CHOMP_SEGDIR              33
1.134756 +#define SQL_SEGMENT_IS_APPENDABLE     34
1.134757 +#define SQL_SELECT_INDEXES            35
1.134758 +#define SQL_SELECT_MXLEVEL            36
1.134759 +
1.134760 +/*
1.134761 +** This function is used to obtain an SQLite prepared statement handle
1.134762 +** for the statement identified by the second argument. If successful,
1.134763 +** *pp is set to the requested statement handle and SQLITE_OK returned.
1.134764 +** Otherwise, an SQLite error code is returned and *pp is set to 0.
1.134765 +**
1.134766 +** If argument apVal is not NULL, then it must point to an array with
1.134767 +** at least as many entries as the requested statement has bound 
1.134768 +** parameters. The values are bound to the statements parameters before
1.134769 +** returning.
1.134770 +*/
1.134771 +static int fts3SqlStmt(
1.134772 +  Fts3Table *p,                   /* Virtual table handle */
1.134773 +  int eStmt,                      /* One of the SQL_XXX constants above */
1.134774 +  sqlite3_stmt **pp,              /* OUT: Statement handle */
1.134775 +  sqlite3_value **apVal           /* Values to bind to statement */
1.134776 +){
1.134777 +  const char *azSql[] = {
1.134778 +/* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
1.134779 +/* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
1.134780 +/* 2  */  "DELETE FROM %Q.'%q_content'",
1.134781 +/* 3  */  "DELETE FROM %Q.'%q_segments'",
1.134782 +/* 4  */  "DELETE FROM %Q.'%q_segdir'",
1.134783 +/* 5  */  "DELETE FROM %Q.'%q_docsize'",
1.134784 +/* 6  */  "DELETE FROM %Q.'%q_stat'",
1.134785 +/* 7  */  "SELECT %s WHERE rowid=?",
1.134786 +/* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
1.134787 +/* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
1.134788 +/* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
1.134789 +/* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
1.134790 +
1.134791 +          /* Return segments in order from oldest to newest.*/ 
1.134792 +/* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
1.134793 +            "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
1.134794 +/* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
1.134795 +            "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
1.134796 +            "ORDER BY level DESC, idx ASC",
1.134797 +
1.134798 +/* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
1.134799 +/* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
1.134800 +
1.134801 +/* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
1.134802 +/* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
1.134803 +/* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
1.134804 +/* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
1.134805 +/* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
1.134806 +/* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
1.134807 +/* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
1.134808 +/* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
1.134809 +/* 24 */  "",
1.134810 +/* 25 */  "",
1.134811 +
1.134812 +/* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
1.134813 +/* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
1.134814 +
1.134815 +/* This statement is used to determine which level to read the input from
1.134816 +** when performing an incremental merge. It returns the absolute level number
1.134817 +** of the oldest level in the db that contains at least ? segments. Or,
1.134818 +** if no level in the FTS index contains more than ? segments, the statement
1.134819 +** returns zero rows.  */
1.134820 +/* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
1.134821 +         "  ORDER BY (level %% 1024) ASC LIMIT 1",
1.134822 +
1.134823 +/* Estimate the upper limit on the number of leaf nodes in a new segment
1.134824 +** created by merging the oldest :2 segments from absolute level :1. See 
1.134825 +** function sqlite3Fts3Incrmerge() for details.  */
1.134826 +/* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
1.134827 +         "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
1.134828 +
1.134829 +/* SQL_DELETE_SEGDIR_ENTRY
1.134830 +**   Delete the %_segdir entry on absolute level :1 with index :2.  */
1.134831 +/* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
1.134832 +
1.134833 +/* SQL_SHIFT_SEGDIR_ENTRY
1.134834 +**   Modify the idx value for the segment with idx=:3 on absolute level :2
1.134835 +**   to :1.  */
1.134836 +/* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
1.134837 +
1.134838 +/* SQL_SELECT_SEGDIR
1.134839 +**   Read a single entry from the %_segdir table. The entry from absolute 
1.134840 +**   level :1 with index value :2.  */
1.134841 +/* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
1.134842 +            "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
1.134843 +
1.134844 +/* SQL_CHOMP_SEGDIR
1.134845 +**   Update the start_block (:1) and root (:2) fields of the %_segdir
1.134846 +**   entry located on absolute level :3 with index :4.  */
1.134847 +/* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
1.134848 +            "WHERE level = ? AND idx = ?",
1.134849 +
1.134850 +/* SQL_SEGMENT_IS_APPENDABLE
1.134851 +**   Return a single row if the segment with end_block=? is appendable. Or
1.134852 +**   no rows otherwise.  */
1.134853 +/* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
1.134854 +
1.134855 +/* SQL_SELECT_INDEXES
1.134856 +**   Return the list of valid segment indexes for absolute level ?  */
1.134857 +/* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
1.134858 +
1.134859 +/* SQL_SELECT_MXLEVEL
1.134860 +**   Return the largest relative level in the FTS index or indexes.  */
1.134861 +/* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'"
1.134862 +  };
1.134863 +  int rc = SQLITE_OK;
1.134864 +  sqlite3_stmt *pStmt;
1.134865 +
1.134866 +  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
1.134867 +  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
1.134868 +  
1.134869 +  pStmt = p->aStmt[eStmt];
1.134870 +  if( !pStmt ){
1.134871 +    char *zSql;
1.134872 +    if( eStmt==SQL_CONTENT_INSERT ){
1.134873 +      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
1.134874 +    }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
1.134875 +      zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
1.134876 +    }else{
1.134877 +      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
1.134878 +    }
1.134879 +    if( !zSql ){
1.134880 +      rc = SQLITE_NOMEM;
1.134881 +    }else{
1.134882 +      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
1.134883 +      sqlite3_free(zSql);
1.134884 +      assert( rc==SQLITE_OK || pStmt==0 );
1.134885 +      p->aStmt[eStmt] = pStmt;
1.134886 +    }
1.134887 +  }
1.134888 +  if( apVal ){
1.134889 +    int i;
1.134890 +    int nParam = sqlite3_bind_parameter_count(pStmt);
1.134891 +    for(i=0; rc==SQLITE_OK && i<nParam; i++){
1.134892 +      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
1.134893 +    }
1.134894 +  }
1.134895 +  *pp = pStmt;
1.134896 +  return rc;
1.134897 +}
1.134898 +
1.134899 +
1.134900 +static int fts3SelectDocsize(
1.134901 +  Fts3Table *pTab,                /* FTS3 table handle */
1.134902 +  sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
1.134903 +  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
1.134904 +){
1.134905 +  sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
1.134906 +  int rc;                         /* Return code */
1.134907 +
1.134908 +  rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
1.134909 +  if( rc==SQLITE_OK ){
1.134910 +    sqlite3_bind_int64(pStmt, 1, iDocid);
1.134911 +    rc = sqlite3_step(pStmt);
1.134912 +    if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
1.134913 +      rc = sqlite3_reset(pStmt);
1.134914 +      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
1.134915 +      pStmt = 0;
1.134916 +    }else{
1.134917 +      rc = SQLITE_OK;
1.134918 +    }
1.134919 +  }
1.134920 +
1.134921 +  *ppStmt = pStmt;
1.134922 +  return rc;
1.134923 +}
1.134924 +
1.134925 +SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
1.134926 +  Fts3Table *pTab,                /* Fts3 table handle */
1.134927 +  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
1.134928 +){
1.134929 +  sqlite3_stmt *pStmt = 0;
1.134930 +  int rc;
1.134931 +  rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
1.134932 +  if( rc==SQLITE_OK ){
1.134933 +    sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
1.134934 +    if( sqlite3_step(pStmt)!=SQLITE_ROW
1.134935 +     || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
1.134936 +    ){
1.134937 +      rc = sqlite3_reset(pStmt);
1.134938 +      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
1.134939 +      pStmt = 0;
1.134940 +    }
1.134941 +  }
1.134942 +  *ppStmt = pStmt;
1.134943 +  return rc;
1.134944 +}
1.134945 +
1.134946 +SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
1.134947 +  Fts3Table *pTab,                /* Fts3 table handle */
1.134948 +  sqlite3_int64 iDocid,           /* Docid to read size data for */
1.134949 +  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
1.134950 +){
1.134951 +  return fts3SelectDocsize(pTab, iDocid, ppStmt);
1.134952 +}
1.134953 +
1.134954 +/*
1.134955 +** Similar to fts3SqlStmt(). Except, after binding the parameters in
1.134956 +** array apVal[] to the SQL statement identified by eStmt, the statement
1.134957 +** is executed.
1.134958 +**
1.134959 +** Returns SQLITE_OK if the statement is successfully executed, or an
1.134960 +** SQLite error code otherwise.
1.134961 +*/
1.134962 +static void fts3SqlExec(
1.134963 +  int *pRC,                /* Result code */
1.134964 +  Fts3Table *p,            /* The FTS3 table */
1.134965 +  int eStmt,               /* Index of statement to evaluate */
1.134966 +  sqlite3_value **apVal    /* Parameters to bind */
1.134967 +){
1.134968 +  sqlite3_stmt *pStmt;
1.134969 +  int rc;
1.134970 +  if( *pRC ) return;
1.134971 +  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
1.134972 +  if( rc==SQLITE_OK ){
1.134973 +    sqlite3_step(pStmt);
1.134974 +    rc = sqlite3_reset(pStmt);
1.134975 +  }
1.134976 +  *pRC = rc;
1.134977 +}
1.134978 +
1.134979 +
1.134980 +/*
1.134981 +** This function ensures that the caller has obtained an exclusive 
1.134982 +** shared-cache table-lock on the %_segdir table. This is required before 
1.134983 +** writing data to the fts3 table. If this lock is not acquired first, then
1.134984 +** the caller may end up attempting to take this lock as part of committing
1.134985 +** a transaction, causing SQLite to return SQLITE_LOCKED or 
1.134986 +** LOCKED_SHAREDCACHEto a COMMIT command.
1.134987 +**
1.134988 +** It is best to avoid this because if FTS3 returns any error when 
1.134989 +** committing a transaction, the whole transaction will be rolled back. 
1.134990 +** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. 
1.134991 +** It can still happen if the user locks the underlying tables directly 
1.134992 +** instead of accessing them via FTS.
1.134993 +*/
1.134994 +static int fts3Writelock(Fts3Table *p){
1.134995 +  int rc = SQLITE_OK;
1.134996 +  
1.134997 +  if( p->nPendingData==0 ){
1.134998 +    sqlite3_stmt *pStmt;
1.134999 +    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
1.135000 +    if( rc==SQLITE_OK ){
1.135001 +      sqlite3_bind_null(pStmt, 1);
1.135002 +      sqlite3_step(pStmt);
1.135003 +      rc = sqlite3_reset(pStmt);
1.135004 +    }
1.135005 +  }
1.135006 +
1.135007 +  return rc;
1.135008 +}
1.135009 +
1.135010 +/*
1.135011 +** FTS maintains a separate indexes for each language-id (a 32-bit integer).
1.135012 +** Within each language id, a separate index is maintained to store the
1.135013 +** document terms, and each configured prefix size (configured the FTS 
1.135014 +** "prefix=" option). And each index consists of multiple levels ("relative
1.135015 +** levels").
1.135016 +**
1.135017 +** All three of these values (the language id, the specific index and the
1.135018 +** level within the index) are encoded in 64-bit integer values stored
1.135019 +** in the %_segdir table on disk. This function is used to convert three
1.135020 +** separate component values into the single 64-bit integer value that
1.135021 +** can be used to query the %_segdir table.
1.135022 +**
1.135023 +** Specifically, each language-id/index combination is allocated 1024 
1.135024 +** 64-bit integer level values ("absolute levels"). The main terms index
1.135025 +** for language-id 0 is allocate values 0-1023. The first prefix index
1.135026 +** (if any) for language-id 0 is allocated values 1024-2047. And so on.
1.135027 +** Language 1 indexes are allocated immediately following language 0.
1.135028 +**
1.135029 +** So, for a system with nPrefix prefix indexes configured, the block of
1.135030 +** absolute levels that corresponds to language-id iLangid and index 
1.135031 +** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
1.135032 +*/
1.135033 +static sqlite3_int64 getAbsoluteLevel(
1.135034 +  Fts3Table *p,                   /* FTS3 table handle */
1.135035 +  int iLangid,                    /* Language id */
1.135036 +  int iIndex,                     /* Index in p->aIndex[] */
1.135037 +  int iLevel                      /* Level of segments */
1.135038 +){
1.135039 +  sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
1.135040 +  assert( iLangid>=0 );
1.135041 +  assert( p->nIndex>0 );
1.135042 +  assert( iIndex>=0 && iIndex<p->nIndex );
1.135043 +
1.135044 +  iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
1.135045 +  return iBase + iLevel;
1.135046 +}
1.135047 +
1.135048 +/*
1.135049 +** Set *ppStmt to a statement handle that may be used to iterate through
1.135050 +** all rows in the %_segdir table, from oldest to newest. If successful,
1.135051 +** return SQLITE_OK. If an error occurs while preparing the statement, 
1.135052 +** return an SQLite error code.
1.135053 +**
1.135054 +** There is only ever one instance of this SQL statement compiled for
1.135055 +** each FTS3 table.
1.135056 +**
1.135057 +** The statement returns the following columns from the %_segdir table:
1.135058 +**
1.135059 +**   0: idx
1.135060 +**   1: start_block
1.135061 +**   2: leaves_end_block
1.135062 +**   3: end_block
1.135063 +**   4: root
1.135064 +*/
1.135065 +SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
1.135066 +  Fts3Table *p,                   /* FTS3 table */
1.135067 +  int iLangid,                    /* Language being queried */
1.135068 +  int iIndex,                     /* Index for p->aIndex[] */
1.135069 +  int iLevel,                     /* Level to select (relative level) */
1.135070 +  sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
1.135071 +){
1.135072 +  int rc;
1.135073 +  sqlite3_stmt *pStmt = 0;
1.135074 +
1.135075 +  assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
1.135076 +  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
1.135077 +  assert( iIndex>=0 && iIndex<p->nIndex );
1.135078 +
1.135079 +  if( iLevel<0 ){
1.135080 +    /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
1.135081 +    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
1.135082 +    if( rc==SQLITE_OK ){ 
1.135083 +      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
1.135084 +      sqlite3_bind_int64(pStmt, 2, 
1.135085 +          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
1.135086 +      );
1.135087 +    }
1.135088 +  }else{
1.135089 +    /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
1.135090 +    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
1.135091 +    if( rc==SQLITE_OK ){ 
1.135092 +      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
1.135093 +    }
1.135094 +  }
1.135095 +  *ppStmt = pStmt;
1.135096 +  return rc;
1.135097 +}
1.135098 +
1.135099 +
1.135100 +/*
1.135101 +** Append a single varint to a PendingList buffer. SQLITE_OK is returned
1.135102 +** if successful, or an SQLite error code otherwise.
1.135103 +**
1.135104 +** This function also serves to allocate the PendingList structure itself.
1.135105 +** For example, to create a new PendingList structure containing two
1.135106 +** varints:
1.135107 +**
1.135108 +**   PendingList *p = 0;
1.135109 +**   fts3PendingListAppendVarint(&p, 1);
1.135110 +**   fts3PendingListAppendVarint(&p, 2);
1.135111 +*/
1.135112 +static int fts3PendingListAppendVarint(
1.135113 +  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
1.135114 +  sqlite3_int64 i                 /* Value to append to data */
1.135115 +){
1.135116 +  PendingList *p = *pp;
1.135117 +
1.135118 +  /* Allocate or grow the PendingList as required. */
1.135119 +  if( !p ){
1.135120 +    p = sqlite3_malloc(sizeof(*p) + 100);
1.135121 +    if( !p ){
1.135122 +      return SQLITE_NOMEM;
1.135123 +    }
1.135124 +    p->nSpace = 100;
1.135125 +    p->aData = (char *)&p[1];
1.135126 +    p->nData = 0;
1.135127 +  }
1.135128 +  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
1.135129 +    int nNew = p->nSpace * 2;
1.135130 +    p = sqlite3_realloc(p, sizeof(*p) + nNew);
1.135131 +    if( !p ){
1.135132 +      sqlite3_free(*pp);
1.135133 +      *pp = 0;
1.135134 +      return SQLITE_NOMEM;
1.135135 +    }
1.135136 +    p->nSpace = nNew;
1.135137 +    p->aData = (char *)&p[1];
1.135138 +  }
1.135139 +
1.135140 +  /* Append the new serialized varint to the end of the list. */
1.135141 +  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
1.135142 +  p->aData[p->nData] = '\0';
1.135143 +  *pp = p;
1.135144 +  return SQLITE_OK;
1.135145 +}
1.135146 +
1.135147 +/*
1.135148 +** Add a docid/column/position entry to a PendingList structure. Non-zero
1.135149 +** is returned if the structure is sqlite3_realloced as part of adding
1.135150 +** the entry. Otherwise, zero.
1.135151 +**
1.135152 +** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
1.135153 +** Zero is always returned in this case. Otherwise, if no OOM error occurs,
1.135154 +** it is set to SQLITE_OK.
1.135155 +*/
1.135156 +static int fts3PendingListAppend(
1.135157 +  PendingList **pp,               /* IN/OUT: PendingList structure */
1.135158 +  sqlite3_int64 iDocid,           /* Docid for entry to add */
1.135159 +  sqlite3_int64 iCol,             /* Column for entry to add */
1.135160 +  sqlite3_int64 iPos,             /* Position of term for entry to add */
1.135161 +  int *pRc                        /* OUT: Return code */
1.135162 +){
1.135163 +  PendingList *p = *pp;
1.135164 +  int rc = SQLITE_OK;
1.135165 +
1.135166 +  assert( !p || p->iLastDocid<=iDocid );
1.135167 +
1.135168 +  if( !p || p->iLastDocid!=iDocid ){
1.135169 +    sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
1.135170 +    if( p ){
1.135171 +      assert( p->nData<p->nSpace );
1.135172 +      assert( p->aData[p->nData]==0 );
1.135173 +      p->nData++;
1.135174 +    }
1.135175 +    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
1.135176 +      goto pendinglistappend_out;
1.135177 +    }
1.135178 +    p->iLastCol = -1;
1.135179 +    p->iLastPos = 0;
1.135180 +    p->iLastDocid = iDocid;
1.135181 +  }
1.135182 +  if( iCol>0 && p->iLastCol!=iCol ){
1.135183 +    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
1.135184 +     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
1.135185 +    ){
1.135186 +      goto pendinglistappend_out;
1.135187 +    }
1.135188 +    p->iLastCol = iCol;
1.135189 +    p->iLastPos = 0;
1.135190 +  }
1.135191 +  if( iCol>=0 ){
1.135192 +    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
1.135193 +    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
1.135194 +    if( rc==SQLITE_OK ){
1.135195 +      p->iLastPos = iPos;
1.135196 +    }
1.135197 +  }
1.135198 +
1.135199 + pendinglistappend_out:
1.135200 +  *pRc = rc;
1.135201 +  if( p!=*pp ){
1.135202 +    *pp = p;
1.135203 +    return 1;
1.135204 +  }
1.135205 +  return 0;
1.135206 +}
1.135207 +
1.135208 +/*
1.135209 +** Free a PendingList object allocated by fts3PendingListAppend().
1.135210 +*/
1.135211 +static void fts3PendingListDelete(PendingList *pList){
1.135212 +  sqlite3_free(pList);
1.135213 +}
1.135214 +
1.135215 +/*
1.135216 +** Add an entry to one of the pending-terms hash tables.
1.135217 +*/
1.135218 +static int fts3PendingTermsAddOne(
1.135219 +  Fts3Table *p,
1.135220 +  int iCol,
1.135221 +  int iPos,
1.135222 +  Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
1.135223 +  const char *zToken,
1.135224 +  int nToken
1.135225 +){
1.135226 +  PendingList *pList;
1.135227 +  int rc = SQLITE_OK;
1.135228 +
1.135229 +  pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
1.135230 +  if( pList ){
1.135231 +    p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
1.135232 +  }
1.135233 +  if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
1.135234 +    if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
1.135235 +      /* Malloc failed while inserting the new entry. This can only 
1.135236 +      ** happen if there was no previous entry for this token.
1.135237 +      */
1.135238 +      assert( 0==fts3HashFind(pHash, zToken, nToken) );
1.135239 +      sqlite3_free(pList);
1.135240 +      rc = SQLITE_NOMEM;
1.135241 +    }
1.135242 +  }
1.135243 +  if( rc==SQLITE_OK ){
1.135244 +    p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
1.135245 +  }
1.135246 +  return rc;
1.135247 +}
1.135248 +
1.135249 +/*
1.135250 +** Tokenize the nul-terminated string zText and add all tokens to the
1.135251 +** pending-terms hash-table. The docid used is that currently stored in
1.135252 +** p->iPrevDocid, and the column is specified by argument iCol.
1.135253 +**
1.135254 +** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
1.135255 +*/
1.135256 +static int fts3PendingTermsAdd(
1.135257 +  Fts3Table *p,                   /* Table into which text will be inserted */
1.135258 +  int iLangid,                    /* Language id to use */
1.135259 +  const char *zText,              /* Text of document to be inserted */
1.135260 +  int iCol,                       /* Column into which text is being inserted */
1.135261 +  u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
1.135262 +){
1.135263 +  int rc;
1.135264 +  int iStart = 0;
1.135265 +  int iEnd = 0;
1.135266 +  int iPos = 0;
1.135267 +  int nWord = 0;
1.135268 +
1.135269 +  char const *zToken;
1.135270 +  int nToken = 0;
1.135271 +
1.135272 +  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
1.135273 +  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
1.135274 +  sqlite3_tokenizer_cursor *pCsr;
1.135275 +  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
1.135276 +      const char**,int*,int*,int*,int*);
1.135277 +
1.135278 +  assert( pTokenizer && pModule );
1.135279 +
1.135280 +  /* If the user has inserted a NULL value, this function may be called with
1.135281 +  ** zText==0. In this case, add zero token entries to the hash table and 
1.135282 +  ** return early. */
1.135283 +  if( zText==0 ){
1.135284 +    *pnWord = 0;
1.135285 +    return SQLITE_OK;
1.135286 +  }
1.135287 +
1.135288 +  rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
1.135289 +  if( rc!=SQLITE_OK ){
1.135290 +    return rc;
1.135291 +  }
1.135292 +
1.135293 +  xNext = pModule->xNext;
1.135294 +  while( SQLITE_OK==rc
1.135295 +      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
1.135296 +  ){
1.135297 +    int i;
1.135298 +    if( iPos>=nWord ) nWord = iPos+1;
1.135299 +
1.135300 +    /* Positions cannot be negative; we use -1 as a terminator internally.
1.135301 +    ** Tokens must have a non-zero length.
1.135302 +    */
1.135303 +    if( iPos<0 || !zToken || nToken<=0 ){
1.135304 +      rc = SQLITE_ERROR;
1.135305 +      break;
1.135306 +    }
1.135307 +
1.135308 +    /* Add the term to the terms index */
1.135309 +    rc = fts3PendingTermsAddOne(
1.135310 +        p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
1.135311 +    );
1.135312 +    
1.135313 +    /* Add the term to each of the prefix indexes that it is not too 
1.135314 +    ** short for. */
1.135315 +    for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
1.135316 +      struct Fts3Index *pIndex = &p->aIndex[i];
1.135317 +      if( nToken<pIndex->nPrefix ) continue;
1.135318 +      rc = fts3PendingTermsAddOne(
1.135319 +          p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
1.135320 +      );
1.135321 +    }
1.135322 +  }
1.135323 +
1.135324 +  pModule->xClose(pCsr);
1.135325 +  *pnWord += nWord;
1.135326 +  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
1.135327 +}
1.135328 +
1.135329 +/* 
1.135330 +** Calling this function indicates that subsequent calls to 
1.135331 +** fts3PendingTermsAdd() are to add term/position-list pairs for the
1.135332 +** contents of the document with docid iDocid.
1.135333 +*/
1.135334 +static int fts3PendingTermsDocid(
1.135335 +  Fts3Table *p,                   /* Full-text table handle */
1.135336 +  int iLangid,                    /* Language id of row being written */
1.135337 +  sqlite_int64 iDocid             /* Docid of row being written */
1.135338 +){
1.135339 +  assert( iLangid>=0 );
1.135340 +
1.135341 +  /* TODO(shess) Explore whether partially flushing the buffer on
1.135342 +  ** forced-flush would provide better performance.  I suspect that if
1.135343 +  ** we ordered the doclists by size and flushed the largest until the
1.135344 +  ** buffer was half empty, that would let the less frequent terms
1.135345 +  ** generate longer doclists.
1.135346 +  */
1.135347 +  if( iDocid<=p->iPrevDocid 
1.135348 +   || p->iPrevLangid!=iLangid
1.135349 +   || p->nPendingData>p->nMaxPendingData 
1.135350 +  ){
1.135351 +    int rc = sqlite3Fts3PendingTermsFlush(p);
1.135352 +    if( rc!=SQLITE_OK ) return rc;
1.135353 +  }
1.135354 +  p->iPrevDocid = iDocid;
1.135355 +  p->iPrevLangid = iLangid;
1.135356 +  return SQLITE_OK;
1.135357 +}
1.135358 +
1.135359 +/*
1.135360 +** Discard the contents of the pending-terms hash tables. 
1.135361 +*/
1.135362 +SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
1.135363 +  int i;
1.135364 +  for(i=0; i<p->nIndex; i++){
1.135365 +    Fts3HashElem *pElem;
1.135366 +    Fts3Hash *pHash = &p->aIndex[i].hPending;
1.135367 +    for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
1.135368 +      PendingList *pList = (PendingList *)fts3HashData(pElem);
1.135369 +      fts3PendingListDelete(pList);
1.135370 +    }
1.135371 +    fts3HashClear(pHash);
1.135372 +  }
1.135373 +  p->nPendingData = 0;
1.135374 +}
1.135375 +
1.135376 +/*
1.135377 +** This function is called by the xUpdate() method as part of an INSERT
1.135378 +** operation. It adds entries for each term in the new record to the
1.135379 +** pendingTerms hash table.
1.135380 +**
1.135381 +** Argument apVal is the same as the similarly named argument passed to
1.135382 +** fts3InsertData(). Parameter iDocid is the docid of the new row.
1.135383 +*/
1.135384 +static int fts3InsertTerms(
1.135385 +  Fts3Table *p, 
1.135386 +  int iLangid, 
1.135387 +  sqlite3_value **apVal, 
1.135388 +  u32 *aSz
1.135389 +){
1.135390 +  int i;                          /* Iterator variable */
1.135391 +  for(i=2; i<p->nColumn+2; i++){
1.135392 +    int iCol = i-2;
1.135393 +    if( p->abNotindexed[iCol]==0 ){
1.135394 +      const char *zText = (const char *)sqlite3_value_text(apVal[i]);
1.135395 +      int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
1.135396 +      if( rc!=SQLITE_OK ){
1.135397 +        return rc;
1.135398 +      }
1.135399 +      aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
1.135400 +    }
1.135401 +  }
1.135402 +  return SQLITE_OK;
1.135403 +}
1.135404 +
1.135405 +/*
1.135406 +** This function is called by the xUpdate() method for an INSERT operation.
1.135407 +** The apVal parameter is passed a copy of the apVal argument passed by
1.135408 +** SQLite to the xUpdate() method. i.e:
1.135409 +**
1.135410 +**   apVal[0]                Not used for INSERT.
1.135411 +**   apVal[1]                rowid
1.135412 +**   apVal[2]                Left-most user-defined column
1.135413 +**   ...
1.135414 +**   apVal[p->nColumn+1]     Right-most user-defined column
1.135415 +**   apVal[p->nColumn+2]     Hidden column with same name as table
1.135416 +**   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
1.135417 +**   apVal[p->nColumn+4]     Hidden languageid column
1.135418 +*/
1.135419 +static int fts3InsertData(
1.135420 +  Fts3Table *p,                   /* Full-text table */
1.135421 +  sqlite3_value **apVal,          /* Array of values to insert */
1.135422 +  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
1.135423 +){
1.135424 +  int rc;                         /* Return code */
1.135425 +  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
1.135426 +
1.135427 +  if( p->zContentTbl ){
1.135428 +    sqlite3_value *pRowid = apVal[p->nColumn+3];
1.135429 +    if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
1.135430 +      pRowid = apVal[1];
1.135431 +    }
1.135432 +    if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
1.135433 +      return SQLITE_CONSTRAINT;
1.135434 +    }
1.135435 +    *piDocid = sqlite3_value_int64(pRowid);
1.135436 +    return SQLITE_OK;
1.135437 +  }
1.135438 +
1.135439 +  /* Locate the statement handle used to insert data into the %_content
1.135440 +  ** table. The SQL for this statement is:
1.135441 +  **
1.135442 +  **   INSERT INTO %_content VALUES(?, ?, ?, ...)
1.135443 +  **
1.135444 +  ** The statement features N '?' variables, where N is the number of user
1.135445 +  ** defined columns in the FTS3 table, plus one for the docid field.
1.135446 +  */
1.135447 +  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
1.135448 +  if( rc==SQLITE_OK && p->zLanguageid ){
1.135449 +    rc = sqlite3_bind_int(
1.135450 +        pContentInsert, p->nColumn+2, 
1.135451 +        sqlite3_value_int(apVal[p->nColumn+4])
1.135452 +    );
1.135453 +  }
1.135454 +  if( rc!=SQLITE_OK ) return rc;
1.135455 +
1.135456 +  /* There is a quirk here. The users INSERT statement may have specified
1.135457 +  ** a value for the "rowid" field, for the "docid" field, or for both.
1.135458 +  ** Which is a problem, since "rowid" and "docid" are aliases for the
1.135459 +  ** same value. For example:
1.135460 +  **
1.135461 +  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
1.135462 +  **
1.135463 +  ** In FTS3, this is an error. It is an error to specify non-NULL values
1.135464 +  ** for both docid and some other rowid alias.
1.135465 +  */
1.135466 +  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
1.135467 +    if( SQLITE_NULL==sqlite3_value_type(apVal[0])
1.135468 +     && SQLITE_NULL!=sqlite3_value_type(apVal[1])
1.135469 +    ){
1.135470 +      /* A rowid/docid conflict. */
1.135471 +      return SQLITE_ERROR;
1.135472 +    }
1.135473 +    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
1.135474 +    if( rc!=SQLITE_OK ) return rc;
1.135475 +  }
1.135476 +
1.135477 +  /* Execute the statement to insert the record. Set *piDocid to the 
1.135478 +  ** new docid value. 
1.135479 +  */
1.135480 +  sqlite3_step(pContentInsert);
1.135481 +  rc = sqlite3_reset(pContentInsert);
1.135482 +
1.135483 +  *piDocid = sqlite3_last_insert_rowid(p->db);
1.135484 +  return rc;
1.135485 +}
1.135486 +
1.135487 +
1.135488 +
1.135489 +/*
1.135490 +** Remove all data from the FTS3 table. Clear the hash table containing
1.135491 +** pending terms.
1.135492 +*/
1.135493 +static int fts3DeleteAll(Fts3Table *p, int bContent){
1.135494 +  int rc = SQLITE_OK;             /* Return code */
1.135495 +
1.135496 +  /* Discard the contents of the pending-terms hash table. */
1.135497 +  sqlite3Fts3PendingTermsClear(p);
1.135498 +
1.135499 +  /* Delete everything from the shadow tables. Except, leave %_content as
1.135500 +  ** is if bContent is false.  */
1.135501 +  assert( p->zContentTbl==0 || bContent==0 );
1.135502 +  if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
1.135503 +  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
1.135504 +  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
1.135505 +  if( p->bHasDocsize ){
1.135506 +    fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
1.135507 +  }
1.135508 +  if( p->bHasStat ){
1.135509 +    fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
1.135510 +  }
1.135511 +  return rc;
1.135512 +}
1.135513 +
1.135514 +/*
1.135515 +**
1.135516 +*/
1.135517 +static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
1.135518 +  int iLangid = 0;
1.135519 +  if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
1.135520 +  return iLangid;
1.135521 +}
1.135522 +
1.135523 +/*
1.135524 +** The first element in the apVal[] array is assumed to contain the docid
1.135525 +** (an integer) of a row about to be deleted. Remove all terms from the
1.135526 +** full-text index.
1.135527 +*/
1.135528 +static void fts3DeleteTerms( 
1.135529 +  int *pRC,               /* Result code */
1.135530 +  Fts3Table *p,           /* The FTS table to delete from */
1.135531 +  sqlite3_value *pRowid,  /* The docid to be deleted */
1.135532 +  u32 *aSz,               /* Sizes of deleted document written here */
1.135533 +  int *pbFound            /* OUT: Set to true if row really does exist */
1.135534 +){
1.135535 +  int rc;
1.135536 +  sqlite3_stmt *pSelect;
1.135537 +
1.135538 +  assert( *pbFound==0 );
1.135539 +  if( *pRC ) return;
1.135540 +  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
1.135541 +  if( rc==SQLITE_OK ){
1.135542 +    if( SQLITE_ROW==sqlite3_step(pSelect) ){
1.135543 +      int i;
1.135544 +      int iLangid = langidFromSelect(p, pSelect);
1.135545 +      rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
1.135546 +      for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
1.135547 +        int iCol = i-1;
1.135548 +        if( p->abNotindexed[iCol]==0 ){
1.135549 +          const char *zText = (const char *)sqlite3_column_text(pSelect, i);
1.135550 +          rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
1.135551 +          aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
1.135552 +        }
1.135553 +      }
1.135554 +      if( rc!=SQLITE_OK ){
1.135555 +        sqlite3_reset(pSelect);
1.135556 +        *pRC = rc;
1.135557 +        return;
1.135558 +      }
1.135559 +      *pbFound = 1;
1.135560 +    }
1.135561 +    rc = sqlite3_reset(pSelect);
1.135562 +  }else{
1.135563 +    sqlite3_reset(pSelect);
1.135564 +  }
1.135565 +  *pRC = rc;
1.135566 +}
1.135567 +
1.135568 +/*
1.135569 +** Forward declaration to account for the circular dependency between
1.135570 +** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
1.135571 +*/
1.135572 +static int fts3SegmentMerge(Fts3Table *, int, int, int);
1.135573 +
1.135574 +/* 
1.135575 +** This function allocates a new level iLevel index in the segdir table.
1.135576 +** Usually, indexes are allocated within a level sequentially starting
1.135577 +** with 0, so the allocated index is one greater than the value returned
1.135578 +** by:
1.135579 +**
1.135580 +**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
1.135581 +**
1.135582 +** However, if there are already FTS3_MERGE_COUNT indexes at the requested
1.135583 +** level, they are merged into a single level (iLevel+1) segment and the 
1.135584 +** allocated index is 0.
1.135585 +**
1.135586 +** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
1.135587 +** returned. Otherwise, an SQLite error code is returned.
1.135588 +*/
1.135589 +static int fts3AllocateSegdirIdx(
1.135590 +  Fts3Table *p, 
1.135591 +  int iLangid,                    /* Language id */
1.135592 +  int iIndex,                     /* Index for p->aIndex */
1.135593 +  int iLevel, 
1.135594 +  int *piIdx
1.135595 +){
1.135596 +  int rc;                         /* Return Code */
1.135597 +  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
1.135598 +  int iNext = 0;                  /* Result of query pNextIdx */
1.135599 +
1.135600 +  assert( iLangid>=0 );
1.135601 +  assert( p->nIndex>=1 );
1.135602 +
1.135603 +  /* Set variable iNext to the next available segdir index at level iLevel. */
1.135604 +  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
1.135605 +  if( rc==SQLITE_OK ){
1.135606 +    sqlite3_bind_int64(
1.135607 +        pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
1.135608 +    );
1.135609 +    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
1.135610 +      iNext = sqlite3_column_int(pNextIdx, 0);
1.135611 +    }
1.135612 +    rc = sqlite3_reset(pNextIdx);
1.135613 +  }
1.135614 +
1.135615 +  if( rc==SQLITE_OK ){
1.135616 +    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
1.135617 +    ** full, merge all segments in level iLevel into a single iLevel+1
1.135618 +    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
1.135619 +    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
1.135620 +    */
1.135621 +    if( iNext>=FTS3_MERGE_COUNT ){
1.135622 +      fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
1.135623 +      rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
1.135624 +      *piIdx = 0;
1.135625 +    }else{
1.135626 +      *piIdx = iNext;
1.135627 +    }
1.135628 +  }
1.135629 +
1.135630 +  return rc;
1.135631 +}
1.135632 +
1.135633 +/*
1.135634 +** The %_segments table is declared as follows:
1.135635 +**
1.135636 +**   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
1.135637 +**
1.135638 +** This function reads data from a single row of the %_segments table. The
1.135639 +** specific row is identified by the iBlockid parameter. If paBlob is not
1.135640 +** NULL, then a buffer is allocated using sqlite3_malloc() and populated
1.135641 +** with the contents of the blob stored in the "block" column of the 
1.135642 +** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
1.135643 +** to the size of the blob in bytes before returning.
1.135644 +**
1.135645 +** If an error occurs, or the table does not contain the specified row,
1.135646 +** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
1.135647 +** paBlob is non-NULL, then it is the responsibility of the caller to
1.135648 +** eventually free the returned buffer.
1.135649 +**
1.135650 +** This function may leave an open sqlite3_blob* handle in the
1.135651 +** Fts3Table.pSegments variable. This handle is reused by subsequent calls
1.135652 +** to this function. The handle may be closed by calling the
1.135653 +** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
1.135654 +** performance improvement, but the blob handle should always be closed
1.135655 +** before control is returned to the user (to prevent a lock being held
1.135656 +** on the database file for longer than necessary). Thus, any virtual table
1.135657 +** method (xFilter etc.) that may directly or indirectly call this function
1.135658 +** must call sqlite3Fts3SegmentsClose() before returning.
1.135659 +*/
1.135660 +SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
1.135661 +  Fts3Table *p,                   /* FTS3 table handle */
1.135662 +  sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
1.135663 +  char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
1.135664 +  int *pnBlob,                    /* OUT: Size of blob data */
1.135665 +  int *pnLoad                     /* OUT: Bytes actually loaded */
1.135666 +){
1.135667 +  int rc;                         /* Return code */
1.135668 +
1.135669 +  /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
1.135670 +  assert( pnBlob );
1.135671 +
1.135672 +  if( p->pSegments ){
1.135673 +    rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
1.135674 +  }else{
1.135675 +    if( 0==p->zSegmentsTbl ){
1.135676 +      p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
1.135677 +      if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
1.135678 +    }
1.135679 +    rc = sqlite3_blob_open(
1.135680 +       p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
1.135681 +    );
1.135682 +  }
1.135683 +
1.135684 +  if( rc==SQLITE_OK ){
1.135685 +    int nByte = sqlite3_blob_bytes(p->pSegments);
1.135686 +    *pnBlob = nByte;
1.135687 +    if( paBlob ){
1.135688 +      char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
1.135689 +      if( !aByte ){
1.135690 +        rc = SQLITE_NOMEM;
1.135691 +      }else{
1.135692 +        if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
1.135693 +          nByte = FTS3_NODE_CHUNKSIZE;
1.135694 +          *pnLoad = nByte;
1.135695 +        }
1.135696 +        rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
1.135697 +        memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
1.135698 +        if( rc!=SQLITE_OK ){
1.135699 +          sqlite3_free(aByte);
1.135700 +          aByte = 0;
1.135701 +        }
1.135702 +      }
1.135703 +      *paBlob = aByte;
1.135704 +    }
1.135705 +  }
1.135706 +
1.135707 +  return rc;
1.135708 +}
1.135709 +
1.135710 +/*
1.135711 +** Close the blob handle at p->pSegments, if it is open. See comments above
1.135712 +** the sqlite3Fts3ReadBlock() function for details.
1.135713 +*/
1.135714 +SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
1.135715 +  sqlite3_blob_close(p->pSegments);
1.135716 +  p->pSegments = 0;
1.135717 +}
1.135718 +    
1.135719 +static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
1.135720 +  int nRead;                      /* Number of bytes to read */
1.135721 +  int rc;                         /* Return code */
1.135722 +
1.135723 +  nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
1.135724 +  rc = sqlite3_blob_read(
1.135725 +      pReader->pBlob, 
1.135726 +      &pReader->aNode[pReader->nPopulate],
1.135727 +      nRead,
1.135728 +      pReader->nPopulate
1.135729 +  );
1.135730 +
1.135731 +  if( rc==SQLITE_OK ){
1.135732 +    pReader->nPopulate += nRead;
1.135733 +    memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
1.135734 +    if( pReader->nPopulate==pReader->nNode ){
1.135735 +      sqlite3_blob_close(pReader->pBlob);
1.135736 +      pReader->pBlob = 0;
1.135737 +      pReader->nPopulate = 0;
1.135738 +    }
1.135739 +  }
1.135740 +  return rc;
1.135741 +}
1.135742 +
1.135743 +static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
1.135744 +  int rc = SQLITE_OK;
1.135745 +  assert( !pReader->pBlob 
1.135746 +       || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
1.135747 +  );
1.135748 +  while( pReader->pBlob && rc==SQLITE_OK 
1.135749 +     &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
1.135750 +  ){
1.135751 +    rc = fts3SegReaderIncrRead(pReader);
1.135752 +  }
1.135753 +  return rc;
1.135754 +}
1.135755 +
1.135756 +/*
1.135757 +** Set an Fts3SegReader cursor to point at EOF.
1.135758 +*/
1.135759 +static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
1.135760 +  if( !fts3SegReaderIsRootOnly(pSeg) ){
1.135761 +    sqlite3_free(pSeg->aNode);
1.135762 +    sqlite3_blob_close(pSeg->pBlob);
1.135763 +    pSeg->pBlob = 0;
1.135764 +  }
1.135765 +  pSeg->aNode = 0;
1.135766 +}
1.135767 +
1.135768 +/*
1.135769 +** Move the iterator passed as the first argument to the next term in the
1.135770 +** segment. If successful, SQLITE_OK is returned. If there is no next term,
1.135771 +** SQLITE_DONE. Otherwise, an SQLite error code.
1.135772 +*/
1.135773 +static int fts3SegReaderNext(
1.135774 +  Fts3Table *p, 
1.135775 +  Fts3SegReader *pReader,
1.135776 +  int bIncr
1.135777 +){
1.135778 +  int rc;                         /* Return code of various sub-routines */
1.135779 +  char *pNext;                    /* Cursor variable */
1.135780 +  int nPrefix;                    /* Number of bytes in term prefix */
1.135781 +  int nSuffix;                    /* Number of bytes in term suffix */
1.135782 +
1.135783 +  if( !pReader->aDoclist ){
1.135784 +    pNext = pReader->aNode;
1.135785 +  }else{
1.135786 +    pNext = &pReader->aDoclist[pReader->nDoclist];
1.135787 +  }
1.135788 +
1.135789 +  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
1.135790 +
1.135791 +    if( fts3SegReaderIsPending(pReader) ){
1.135792 +      Fts3HashElem *pElem = *(pReader->ppNextElem);
1.135793 +      if( pElem==0 ){
1.135794 +        pReader->aNode = 0;
1.135795 +      }else{
1.135796 +        PendingList *pList = (PendingList *)fts3HashData(pElem);
1.135797 +        pReader->zTerm = (char *)fts3HashKey(pElem);
1.135798 +        pReader->nTerm = fts3HashKeysize(pElem);
1.135799 +        pReader->nNode = pReader->nDoclist = pList->nData + 1;
1.135800 +        pReader->aNode = pReader->aDoclist = pList->aData;
1.135801 +        pReader->ppNextElem++;
1.135802 +        assert( pReader->aNode );
1.135803 +      }
1.135804 +      return SQLITE_OK;
1.135805 +    }
1.135806 +
1.135807 +    fts3SegReaderSetEof(pReader);
1.135808 +
1.135809 +    /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf 
1.135810 +    ** blocks have already been traversed.  */
1.135811 +    assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
1.135812 +    if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
1.135813 +      return SQLITE_OK;
1.135814 +    }
1.135815 +
1.135816 +    rc = sqlite3Fts3ReadBlock(
1.135817 +        p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, 
1.135818 +        (bIncr ? &pReader->nPopulate : 0)
1.135819 +    );
1.135820 +    if( rc!=SQLITE_OK ) return rc;
1.135821 +    assert( pReader->pBlob==0 );
1.135822 +    if( bIncr && pReader->nPopulate<pReader->nNode ){
1.135823 +      pReader->pBlob = p->pSegments;
1.135824 +      p->pSegments = 0;
1.135825 +    }
1.135826 +    pNext = pReader->aNode;
1.135827 +  }
1.135828 +
1.135829 +  assert( !fts3SegReaderIsPending(pReader) );
1.135830 +
1.135831 +  rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
1.135832 +  if( rc!=SQLITE_OK ) return rc;
1.135833 +  
1.135834 +  /* Because of the FTS3_NODE_PADDING bytes of padding, the following is 
1.135835 +  ** safe (no risk of overread) even if the node data is corrupted. */
1.135836 +  pNext += fts3GetVarint32(pNext, &nPrefix);
1.135837 +  pNext += fts3GetVarint32(pNext, &nSuffix);
1.135838 +  if( nPrefix<0 || nSuffix<=0 
1.135839 +   || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] 
1.135840 +  ){
1.135841 +    return FTS_CORRUPT_VTAB;
1.135842 +  }
1.135843 +
1.135844 +  if( nPrefix+nSuffix>pReader->nTermAlloc ){
1.135845 +    int nNew = (nPrefix+nSuffix)*2;
1.135846 +    char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
1.135847 +    if( !zNew ){
1.135848 +      return SQLITE_NOMEM;
1.135849 +    }
1.135850 +    pReader->zTerm = zNew;
1.135851 +    pReader->nTermAlloc = nNew;
1.135852 +  }
1.135853 +
1.135854 +  rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
1.135855 +  if( rc!=SQLITE_OK ) return rc;
1.135856 +
1.135857 +  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
1.135858 +  pReader->nTerm = nPrefix+nSuffix;
1.135859 +  pNext += nSuffix;
1.135860 +  pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
1.135861 +  pReader->aDoclist = pNext;
1.135862 +  pReader->pOffsetList = 0;
1.135863 +
1.135864 +  /* Check that the doclist does not appear to extend past the end of the
1.135865 +  ** b-tree node. And that the final byte of the doclist is 0x00. If either 
1.135866 +  ** of these statements is untrue, then the data structure is corrupt.
1.135867 +  */
1.135868 +  if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] 
1.135869 +   || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
1.135870 +  ){
1.135871 +    return FTS_CORRUPT_VTAB;
1.135872 +  }
1.135873 +  return SQLITE_OK;
1.135874 +}
1.135875 +
1.135876 +/*
1.135877 +** Set the SegReader to point to the first docid in the doclist associated
1.135878 +** with the current term.
1.135879 +*/
1.135880 +static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
1.135881 +  int rc = SQLITE_OK;
1.135882 +  assert( pReader->aDoclist );
1.135883 +  assert( !pReader->pOffsetList );
1.135884 +  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
1.135885 +    u8 bEof = 0;
1.135886 +    pReader->iDocid = 0;
1.135887 +    pReader->nOffsetList = 0;
1.135888 +    sqlite3Fts3DoclistPrev(0,
1.135889 +        pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, 
1.135890 +        &pReader->iDocid, &pReader->nOffsetList, &bEof
1.135891 +    );
1.135892 +  }else{
1.135893 +    rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
1.135894 +    if( rc==SQLITE_OK ){
1.135895 +      int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
1.135896 +      pReader->pOffsetList = &pReader->aDoclist[n];
1.135897 +    }
1.135898 +  }
1.135899 +  return rc;
1.135900 +}
1.135901 +
1.135902 +/*
1.135903 +** Advance the SegReader to point to the next docid in the doclist
1.135904 +** associated with the current term.
1.135905 +** 
1.135906 +** If arguments ppOffsetList and pnOffsetList are not NULL, then 
1.135907 +** *ppOffsetList is set to point to the first column-offset list
1.135908 +** in the doclist entry (i.e. immediately past the docid varint).
1.135909 +** *pnOffsetList is set to the length of the set of column-offset
1.135910 +** lists, not including the nul-terminator byte. For example:
1.135911 +*/
1.135912 +static int fts3SegReaderNextDocid(
1.135913 +  Fts3Table *pTab,
1.135914 +  Fts3SegReader *pReader,         /* Reader to advance to next docid */
1.135915 +  char **ppOffsetList,            /* OUT: Pointer to current position-list */
1.135916 +  int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
1.135917 +){
1.135918 +  int rc = SQLITE_OK;
1.135919 +  char *p = pReader->pOffsetList;
1.135920 +  char c = 0;
1.135921 +
1.135922 +  assert( p );
1.135923 +
1.135924 +  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
1.135925 +    /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
1.135926 +    ** Pending-terms doclists are always built up in ascending order, so
1.135927 +    ** we have to iterate through them backwards here. */
1.135928 +    u8 bEof = 0;
1.135929 +    if( ppOffsetList ){
1.135930 +      *ppOffsetList = pReader->pOffsetList;
1.135931 +      *pnOffsetList = pReader->nOffsetList - 1;
1.135932 +    }
1.135933 +    sqlite3Fts3DoclistPrev(0,
1.135934 +        pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
1.135935 +        &pReader->nOffsetList, &bEof
1.135936 +    );
1.135937 +    if( bEof ){
1.135938 +      pReader->pOffsetList = 0;
1.135939 +    }else{
1.135940 +      pReader->pOffsetList = p;
1.135941 +    }
1.135942 +  }else{
1.135943 +    char *pEnd = &pReader->aDoclist[pReader->nDoclist];
1.135944 +
1.135945 +    /* Pointer p currently points at the first byte of an offset list. The
1.135946 +    ** following block advances it to point one byte past the end of
1.135947 +    ** the same offset list. */
1.135948 +    while( 1 ){
1.135949 +  
1.135950 +      /* The following line of code (and the "p++" below the while() loop) is
1.135951 +      ** normally all that is required to move pointer p to the desired 
1.135952 +      ** position. The exception is if this node is being loaded from disk
1.135953 +      ** incrementally and pointer "p" now points to the first byte past
1.135954 +      ** the populated part of pReader->aNode[].
1.135955 +      */
1.135956 +      while( *p | c ) c = *p++ & 0x80;
1.135957 +      assert( *p==0 );
1.135958 +  
1.135959 +      if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
1.135960 +      rc = fts3SegReaderIncrRead(pReader);
1.135961 +      if( rc!=SQLITE_OK ) return rc;
1.135962 +    }
1.135963 +    p++;
1.135964 +  
1.135965 +    /* If required, populate the output variables with a pointer to and the
1.135966 +    ** size of the previous offset-list.
1.135967 +    */
1.135968 +    if( ppOffsetList ){
1.135969 +      *ppOffsetList = pReader->pOffsetList;
1.135970 +      *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
1.135971 +    }
1.135972 +
1.135973 +    /* List may have been edited in place by fts3EvalNearTrim() */
1.135974 +    while( p<pEnd && *p==0 ) p++;
1.135975 +  
1.135976 +    /* If there are no more entries in the doclist, set pOffsetList to
1.135977 +    ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
1.135978 +    ** Fts3SegReader.pOffsetList to point to the next offset list before
1.135979 +    ** returning.
1.135980 +    */
1.135981 +    if( p>=pEnd ){
1.135982 +      pReader->pOffsetList = 0;
1.135983 +    }else{
1.135984 +      rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
1.135985 +      if( rc==SQLITE_OK ){
1.135986 +        sqlite3_int64 iDelta;
1.135987 +        pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
1.135988 +        if( pTab->bDescIdx ){
1.135989 +          pReader->iDocid -= iDelta;
1.135990 +        }else{
1.135991 +          pReader->iDocid += iDelta;
1.135992 +        }
1.135993 +      }
1.135994 +    }
1.135995 +  }
1.135996 +
1.135997 +  return SQLITE_OK;
1.135998 +}
1.135999 +
1.136000 +
1.136001 +SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
1.136002 +  Fts3Cursor *pCsr, 
1.136003 +  Fts3MultiSegReader *pMsr,
1.136004 +  int *pnOvfl
1.136005 +){
1.136006 +  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
1.136007 +  int nOvfl = 0;
1.136008 +  int ii;
1.136009 +  int rc = SQLITE_OK;
1.136010 +  int pgsz = p->nPgsz;
1.136011 +
1.136012 +  assert( p->bFts4 );
1.136013 +  assert( pgsz>0 );
1.136014 +
1.136015 +  for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
1.136016 +    Fts3SegReader *pReader = pMsr->apSegment[ii];
1.136017 +    if( !fts3SegReaderIsPending(pReader) 
1.136018 +     && !fts3SegReaderIsRootOnly(pReader) 
1.136019 +    ){
1.136020 +      sqlite3_int64 jj;
1.136021 +      for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
1.136022 +        int nBlob;
1.136023 +        rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
1.136024 +        if( rc!=SQLITE_OK ) break;
1.136025 +        if( (nBlob+35)>pgsz ){
1.136026 +          nOvfl += (nBlob + 34)/pgsz;
1.136027 +        }
1.136028 +      }
1.136029 +    }
1.136030 +  }
1.136031 +  *pnOvfl = nOvfl;
1.136032 +  return rc;
1.136033 +}
1.136034 +
1.136035 +/*
1.136036 +** Free all allocations associated with the iterator passed as the 
1.136037 +** second argument.
1.136038 +*/
1.136039 +SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
1.136040 +  if( pReader && !fts3SegReaderIsPending(pReader) ){
1.136041 +    sqlite3_free(pReader->zTerm);
1.136042 +    if( !fts3SegReaderIsRootOnly(pReader) ){
1.136043 +      sqlite3_free(pReader->aNode);
1.136044 +      sqlite3_blob_close(pReader->pBlob);
1.136045 +    }
1.136046 +  }
1.136047 +  sqlite3_free(pReader);
1.136048 +}
1.136049 +
1.136050 +/*
1.136051 +** Allocate a new SegReader object.
1.136052 +*/
1.136053 +SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
1.136054 +  int iAge,                       /* Segment "age". */
1.136055 +  int bLookup,                    /* True for a lookup only */
1.136056 +  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
1.136057 +  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
1.136058 +  sqlite3_int64 iEndBlock,        /* Final block of segment */
1.136059 +  const char *zRoot,              /* Buffer containing root node */
1.136060 +  int nRoot,                      /* Size of buffer containing root node */
1.136061 +  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
1.136062 +){
1.136063 +  Fts3SegReader *pReader;         /* Newly allocated SegReader object */
1.136064 +  int nExtra = 0;                 /* Bytes to allocate segment root node */
1.136065 +
1.136066 +  assert( iStartLeaf<=iEndLeaf );
1.136067 +  if( iStartLeaf==0 ){
1.136068 +    nExtra = nRoot + FTS3_NODE_PADDING;
1.136069 +  }
1.136070 +
1.136071 +  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
1.136072 +  if( !pReader ){
1.136073 +    return SQLITE_NOMEM;
1.136074 +  }
1.136075 +  memset(pReader, 0, sizeof(Fts3SegReader));
1.136076 +  pReader->iIdx = iAge;
1.136077 +  pReader->bLookup = bLookup!=0;
1.136078 +  pReader->iStartBlock = iStartLeaf;
1.136079 +  pReader->iLeafEndBlock = iEndLeaf;
1.136080 +  pReader->iEndBlock = iEndBlock;
1.136081 +
1.136082 +  if( nExtra ){
1.136083 +    /* The entire segment is stored in the root node. */
1.136084 +    pReader->aNode = (char *)&pReader[1];
1.136085 +    pReader->rootOnly = 1;
1.136086 +    pReader->nNode = nRoot;
1.136087 +    memcpy(pReader->aNode, zRoot, nRoot);
1.136088 +    memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
1.136089 +  }else{
1.136090 +    pReader->iCurrentBlock = iStartLeaf-1;
1.136091 +  }
1.136092 +  *ppReader = pReader;
1.136093 +  return SQLITE_OK;
1.136094 +}
1.136095 +
1.136096 +/*
1.136097 +** This is a comparison function used as a qsort() callback when sorting
1.136098 +** an array of pending terms by term. This occurs as part of flushing
1.136099 +** the contents of the pending-terms hash table to the database.
1.136100 +*/
1.136101 +static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
1.136102 +  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
1.136103 +  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
1.136104 +  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
1.136105 +  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
1.136106 +
1.136107 +  int n = (n1<n2 ? n1 : n2);
1.136108 +  int c = memcmp(z1, z2, n);
1.136109 +  if( c==0 ){
1.136110 +    c = n1 - n2;
1.136111 +  }
1.136112 +  return c;
1.136113 +}
1.136114 +
1.136115 +/*
1.136116 +** This function is used to allocate an Fts3SegReader that iterates through
1.136117 +** a subset of the terms stored in the Fts3Table.pendingTerms array.
1.136118 +**
1.136119 +** If the isPrefixIter parameter is zero, then the returned SegReader iterates
1.136120 +** through each term in the pending-terms table. Or, if isPrefixIter is
1.136121 +** non-zero, it iterates through each term and its prefixes. For example, if
1.136122 +** the pending terms hash table contains the terms "sqlite", "mysql" and
1.136123 +** "firebird", then the iterator visits the following 'terms' (in the order
1.136124 +** shown):
1.136125 +**
1.136126 +**   f fi fir fire fireb firebi firebir firebird
1.136127 +**   m my mys mysq mysql
1.136128 +**   s sq sql sqli sqlit sqlite
1.136129 +**
1.136130 +** Whereas if isPrefixIter is zero, the terms visited are:
1.136131 +**
1.136132 +**   firebird mysql sqlite
1.136133 +*/
1.136134 +SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
1.136135 +  Fts3Table *p,                   /* Virtual table handle */
1.136136 +  int iIndex,                     /* Index for p->aIndex */
1.136137 +  const char *zTerm,              /* Term to search for */
1.136138 +  int nTerm,                      /* Size of buffer zTerm */
1.136139 +  int bPrefix,                    /* True for a prefix iterator */
1.136140 +  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
1.136141 +){
1.136142 +  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
1.136143 +  Fts3HashElem *pE;               /* Iterator variable */
1.136144 +  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
1.136145 +  int nElem = 0;                  /* Size of array at aElem */
1.136146 +  int rc = SQLITE_OK;             /* Return Code */
1.136147 +  Fts3Hash *pHash;
1.136148 +
1.136149 +  pHash = &p->aIndex[iIndex].hPending;
1.136150 +  if( bPrefix ){
1.136151 +    int nAlloc = 0;               /* Size of allocated array at aElem */
1.136152 +
1.136153 +    for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
1.136154 +      char *zKey = (char *)fts3HashKey(pE);
1.136155 +      int nKey = fts3HashKeysize(pE);
1.136156 +      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
1.136157 +        if( nElem==nAlloc ){
1.136158 +          Fts3HashElem **aElem2;
1.136159 +          nAlloc += 16;
1.136160 +          aElem2 = (Fts3HashElem **)sqlite3_realloc(
1.136161 +              aElem, nAlloc*sizeof(Fts3HashElem *)
1.136162 +          );
1.136163 +          if( !aElem2 ){
1.136164 +            rc = SQLITE_NOMEM;
1.136165 +            nElem = 0;
1.136166 +            break;
1.136167 +          }
1.136168 +          aElem = aElem2;
1.136169 +        }
1.136170 +
1.136171 +        aElem[nElem++] = pE;
1.136172 +      }
1.136173 +    }
1.136174 +
1.136175 +    /* If more than one term matches the prefix, sort the Fts3HashElem
1.136176 +    ** objects in term order using qsort(). This uses the same comparison
1.136177 +    ** callback as is used when flushing terms to disk.
1.136178 +    */
1.136179 +    if( nElem>1 ){
1.136180 +      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
1.136181 +    }
1.136182 +
1.136183 +  }else{
1.136184 +    /* The query is a simple term lookup that matches at most one term in
1.136185 +    ** the index. All that is required is a straight hash-lookup. 
1.136186 +    **
1.136187 +    ** Because the stack address of pE may be accessed via the aElem pointer
1.136188 +    ** below, the "Fts3HashElem *pE" must be declared so that it is valid
1.136189 +    ** within this entire function, not just this "else{...}" block.
1.136190 +    */
1.136191 +    pE = fts3HashFindElem(pHash, zTerm, nTerm);
1.136192 +    if( pE ){
1.136193 +      aElem = &pE;
1.136194 +      nElem = 1;
1.136195 +    }
1.136196 +  }
1.136197 +
1.136198 +  if( nElem>0 ){
1.136199 +    int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
1.136200 +    pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
1.136201 +    if( !pReader ){
1.136202 +      rc = SQLITE_NOMEM;
1.136203 +    }else{
1.136204 +      memset(pReader, 0, nByte);
1.136205 +      pReader->iIdx = 0x7FFFFFFF;
1.136206 +      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
1.136207 +      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
1.136208 +    }
1.136209 +  }
1.136210 +
1.136211 +  if( bPrefix ){
1.136212 +    sqlite3_free(aElem);
1.136213 +  }
1.136214 +  *ppReader = pReader;
1.136215 +  return rc;
1.136216 +}
1.136217 +
1.136218 +/*
1.136219 +** Compare the entries pointed to by two Fts3SegReader structures. 
1.136220 +** Comparison is as follows:
1.136221 +**
1.136222 +**   1) EOF is greater than not EOF.
1.136223 +**
1.136224 +**   2) The current terms (if any) are compared using memcmp(). If one
1.136225 +**      term is a prefix of another, the longer term is considered the
1.136226 +**      larger.
1.136227 +**
1.136228 +**   3) By segment age. An older segment is considered larger.
1.136229 +*/
1.136230 +static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
1.136231 +  int rc;
1.136232 +  if( pLhs->aNode && pRhs->aNode ){
1.136233 +    int rc2 = pLhs->nTerm - pRhs->nTerm;
1.136234 +    if( rc2<0 ){
1.136235 +      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
1.136236 +    }else{
1.136237 +      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
1.136238 +    }
1.136239 +    if( rc==0 ){
1.136240 +      rc = rc2;
1.136241 +    }
1.136242 +  }else{
1.136243 +    rc = (pLhs->aNode==0) - (pRhs->aNode==0);
1.136244 +  }
1.136245 +  if( rc==0 ){
1.136246 +    rc = pRhs->iIdx - pLhs->iIdx;
1.136247 +  }
1.136248 +  assert( rc!=0 );
1.136249 +  return rc;
1.136250 +}
1.136251 +
1.136252 +/*
1.136253 +** A different comparison function for SegReader structures. In this
1.136254 +** version, it is assumed that each SegReader points to an entry in
1.136255 +** a doclist for identical terms. Comparison is made as follows:
1.136256 +**
1.136257 +**   1) EOF (end of doclist in this case) is greater than not EOF.
1.136258 +**
1.136259 +**   2) By current docid.
1.136260 +**
1.136261 +**   3) By segment age. An older segment is considered larger.
1.136262 +*/
1.136263 +static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
1.136264 +  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
1.136265 +  if( rc==0 ){
1.136266 +    if( pLhs->iDocid==pRhs->iDocid ){
1.136267 +      rc = pRhs->iIdx - pLhs->iIdx;
1.136268 +    }else{
1.136269 +      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
1.136270 +    }
1.136271 +  }
1.136272 +  assert( pLhs->aNode && pRhs->aNode );
1.136273 +  return rc;
1.136274 +}
1.136275 +static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
1.136276 +  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
1.136277 +  if( rc==0 ){
1.136278 +    if( pLhs->iDocid==pRhs->iDocid ){
1.136279 +      rc = pRhs->iIdx - pLhs->iIdx;
1.136280 +    }else{
1.136281 +      rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
1.136282 +    }
1.136283 +  }
1.136284 +  assert( pLhs->aNode && pRhs->aNode );
1.136285 +  return rc;
1.136286 +}
1.136287 +
1.136288 +/*
1.136289 +** Compare the term that the Fts3SegReader object passed as the first argument
1.136290 +** points to with the term specified by arguments zTerm and nTerm. 
1.136291 +**
1.136292 +** If the pSeg iterator is already at EOF, return 0. Otherwise, return
1.136293 +** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
1.136294 +** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
1.136295 +*/
1.136296 +static int fts3SegReaderTermCmp(
1.136297 +  Fts3SegReader *pSeg,            /* Segment reader object */
1.136298 +  const char *zTerm,              /* Term to compare to */
1.136299 +  int nTerm                       /* Size of term zTerm in bytes */
1.136300 +){
1.136301 +  int res = 0;
1.136302 +  if( pSeg->aNode ){
1.136303 +    if( pSeg->nTerm>nTerm ){
1.136304 +      res = memcmp(pSeg->zTerm, zTerm, nTerm);
1.136305 +    }else{
1.136306 +      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
1.136307 +    }
1.136308 +    if( res==0 ){
1.136309 +      res = pSeg->nTerm-nTerm;
1.136310 +    }
1.136311 +  }
1.136312 +  return res;
1.136313 +}
1.136314 +
1.136315 +/*
1.136316 +** Argument apSegment is an array of nSegment elements. It is known that
1.136317 +** the final (nSegment-nSuspect) members are already in sorted order
1.136318 +** (according to the comparison function provided). This function shuffles
1.136319 +** the array around until all entries are in sorted order.
1.136320 +*/
1.136321 +static void fts3SegReaderSort(
1.136322 +  Fts3SegReader **apSegment,                     /* Array to sort entries of */
1.136323 +  int nSegment,                                  /* Size of apSegment array */
1.136324 +  int nSuspect,                                  /* Unsorted entry count */
1.136325 +  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
1.136326 +){
1.136327 +  int i;                          /* Iterator variable */
1.136328 +
1.136329 +  assert( nSuspect<=nSegment );
1.136330 +
1.136331 +  if( nSuspect==nSegment ) nSuspect--;
1.136332 +  for(i=nSuspect-1; i>=0; i--){
1.136333 +    int j;
1.136334 +    for(j=i; j<(nSegment-1); j++){
1.136335 +      Fts3SegReader *pTmp;
1.136336 +      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
1.136337 +      pTmp = apSegment[j+1];
1.136338 +      apSegment[j+1] = apSegment[j];
1.136339 +      apSegment[j] = pTmp;
1.136340 +    }
1.136341 +  }
1.136342 +
1.136343 +#ifndef NDEBUG
1.136344 +  /* Check that the list really is sorted now. */
1.136345 +  for(i=0; i<(nSuspect-1); i++){
1.136346 +    assert( xCmp(apSegment[i], apSegment[i+1])<0 );
1.136347 +  }
1.136348 +#endif
1.136349 +}
1.136350 +
1.136351 +/* 
1.136352 +** Insert a record into the %_segments table.
1.136353 +*/
1.136354 +static int fts3WriteSegment(
1.136355 +  Fts3Table *p,                   /* Virtual table handle */
1.136356 +  sqlite3_int64 iBlock,           /* Block id for new block */
1.136357 +  char *z,                        /* Pointer to buffer containing block data */
1.136358 +  int n                           /* Size of buffer z in bytes */
1.136359 +){
1.136360 +  sqlite3_stmt *pStmt;
1.136361 +  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
1.136362 +  if( rc==SQLITE_OK ){
1.136363 +    sqlite3_bind_int64(pStmt, 1, iBlock);
1.136364 +    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
1.136365 +    sqlite3_step(pStmt);
1.136366 +    rc = sqlite3_reset(pStmt);
1.136367 +  }
1.136368 +  return rc;
1.136369 +}
1.136370 +
1.136371 +/*
1.136372 +** Find the largest relative level number in the table. If successful, set
1.136373 +** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
1.136374 +** set *pnMax to zero and return an SQLite error code.
1.136375 +*/
1.136376 +SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
1.136377 +  int rc;
1.136378 +  int mxLevel = 0;
1.136379 +  sqlite3_stmt *pStmt = 0;
1.136380 +
1.136381 +  rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
1.136382 +  if( rc==SQLITE_OK ){
1.136383 +    if( SQLITE_ROW==sqlite3_step(pStmt) ){
1.136384 +      mxLevel = sqlite3_column_int(pStmt, 0);
1.136385 +    }
1.136386 +    rc = sqlite3_reset(pStmt);
1.136387 +  }
1.136388 +  *pnMax = mxLevel;
1.136389 +  return rc;
1.136390 +}
1.136391 +
1.136392 +/* 
1.136393 +** Insert a record into the %_segdir table.
1.136394 +*/
1.136395 +static int fts3WriteSegdir(
1.136396 +  Fts3Table *p,                   /* Virtual table handle */
1.136397 +  sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
1.136398 +  int iIdx,                       /* Value for "idx" field */
1.136399 +  sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
1.136400 +  sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
1.136401 +  sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
1.136402 +  char *zRoot,                    /* Blob value for "root" field */
1.136403 +  int nRoot                       /* Number of bytes in buffer zRoot */
1.136404 +){
1.136405 +  sqlite3_stmt *pStmt;
1.136406 +  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
1.136407 +  if( rc==SQLITE_OK ){
1.136408 +    sqlite3_bind_int64(pStmt, 1, iLevel);
1.136409 +    sqlite3_bind_int(pStmt, 2, iIdx);
1.136410 +    sqlite3_bind_int64(pStmt, 3, iStartBlock);
1.136411 +    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
1.136412 +    sqlite3_bind_int64(pStmt, 5, iEndBlock);
1.136413 +    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
1.136414 +    sqlite3_step(pStmt);
1.136415 +    rc = sqlite3_reset(pStmt);
1.136416 +  }
1.136417 +  return rc;
1.136418 +}
1.136419 +
1.136420 +/*
1.136421 +** Return the size of the common prefix (if any) shared by zPrev and
1.136422 +** zNext, in bytes. For example, 
1.136423 +**
1.136424 +**   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
1.136425 +**   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
1.136426 +**   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
1.136427 +*/
1.136428 +static int fts3PrefixCompress(
1.136429 +  const char *zPrev,              /* Buffer containing previous term */
1.136430 +  int nPrev,                      /* Size of buffer zPrev in bytes */
1.136431 +  const char *zNext,              /* Buffer containing next term */
1.136432 +  int nNext                       /* Size of buffer zNext in bytes */
1.136433 +){
1.136434 +  int n;
1.136435 +  UNUSED_PARAMETER(nNext);
1.136436 +  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
1.136437 +  return n;
1.136438 +}
1.136439 +
1.136440 +/*
1.136441 +** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
1.136442 +** (according to memcmp) than the previous term.
1.136443 +*/
1.136444 +static int fts3NodeAddTerm(
1.136445 +  Fts3Table *p,                   /* Virtual table handle */
1.136446 +  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
1.136447 +  int isCopyTerm,                 /* True if zTerm/nTerm is transient */
1.136448 +  const char *zTerm,              /* Pointer to buffer containing term */
1.136449 +  int nTerm                       /* Size of term in bytes */
1.136450 +){
1.136451 +  SegmentNode *pTree = *ppTree;
1.136452 +  int rc;
1.136453 +  SegmentNode *pNew;
1.136454 +
1.136455 +  /* First try to append the term to the current node. Return early if 
1.136456 +  ** this is possible.
1.136457 +  */
1.136458 +  if( pTree ){
1.136459 +    int nData = pTree->nData;     /* Current size of node in bytes */
1.136460 +    int nReq = nData;             /* Required space after adding zTerm */
1.136461 +    int nPrefix;                  /* Number of bytes of prefix compression */
1.136462 +    int nSuffix;                  /* Suffix length */
1.136463 +
1.136464 +    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
1.136465 +    nSuffix = nTerm-nPrefix;
1.136466 +
1.136467 +    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
1.136468 +    if( nReq<=p->nNodeSize || !pTree->zTerm ){
1.136469 +
1.136470 +      if( nReq>p->nNodeSize ){
1.136471 +        /* An unusual case: this is the first term to be added to the node
1.136472 +        ** and the static node buffer (p->nNodeSize bytes) is not large
1.136473 +        ** enough. Use a separately malloced buffer instead This wastes
1.136474 +        ** p->nNodeSize bytes, but since this scenario only comes about when
1.136475 +        ** the database contain two terms that share a prefix of almost 2KB, 
1.136476 +        ** this is not expected to be a serious problem. 
1.136477 +        */
1.136478 +        assert( pTree->aData==(char *)&pTree[1] );
1.136479 +        pTree->aData = (char *)sqlite3_malloc(nReq);
1.136480 +        if( !pTree->aData ){
1.136481 +          return SQLITE_NOMEM;
1.136482 +        }
1.136483 +      }
1.136484 +
1.136485 +      if( pTree->zTerm ){
1.136486 +        /* There is no prefix-length field for first term in a node */
1.136487 +        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
1.136488 +      }
1.136489 +
1.136490 +      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
1.136491 +      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
1.136492 +      pTree->nData = nData + nSuffix;
1.136493 +      pTree->nEntry++;
1.136494 +
1.136495 +      if( isCopyTerm ){
1.136496 +        if( pTree->nMalloc<nTerm ){
1.136497 +          char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
1.136498 +          if( !zNew ){
1.136499 +            return SQLITE_NOMEM;
1.136500 +          }
1.136501 +          pTree->nMalloc = nTerm*2;
1.136502 +          pTree->zMalloc = zNew;
1.136503 +        }
1.136504 +        pTree->zTerm = pTree->zMalloc;
1.136505 +        memcpy(pTree->zTerm, zTerm, nTerm);
1.136506 +        pTree->nTerm = nTerm;
1.136507 +      }else{
1.136508 +        pTree->zTerm = (char *)zTerm;
1.136509 +        pTree->nTerm = nTerm;
1.136510 +      }
1.136511 +      return SQLITE_OK;
1.136512 +    }
1.136513 +  }
1.136514 +
1.136515 +  /* If control flows to here, it was not possible to append zTerm to the
1.136516 +  ** current node. Create a new node (a right-sibling of the current node).
1.136517 +  ** If this is the first node in the tree, the term is added to it.
1.136518 +  **
1.136519 +  ** Otherwise, the term is not added to the new node, it is left empty for
1.136520 +  ** now. Instead, the term is inserted into the parent of pTree. If pTree 
1.136521 +  ** has no parent, one is created here.
1.136522 +  */
1.136523 +  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
1.136524 +  if( !pNew ){
1.136525 +    return SQLITE_NOMEM;
1.136526 +  }
1.136527 +  memset(pNew, 0, sizeof(SegmentNode));
1.136528 +  pNew->nData = 1 + FTS3_VARINT_MAX;
1.136529 +  pNew->aData = (char *)&pNew[1];
1.136530 +
1.136531 +  if( pTree ){
1.136532 +    SegmentNode *pParent = pTree->pParent;
1.136533 +    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
1.136534 +    if( pTree->pParent==0 ){
1.136535 +      pTree->pParent = pParent;
1.136536 +    }
1.136537 +    pTree->pRight = pNew;
1.136538 +    pNew->pLeftmost = pTree->pLeftmost;
1.136539 +    pNew->pParent = pParent;
1.136540 +    pNew->zMalloc = pTree->zMalloc;
1.136541 +    pNew->nMalloc = pTree->nMalloc;
1.136542 +    pTree->zMalloc = 0;
1.136543 +  }else{
1.136544 +    pNew->pLeftmost = pNew;
1.136545 +    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
1.136546 +  }
1.136547 +
1.136548 +  *ppTree = pNew;
1.136549 +  return rc;
1.136550 +}
1.136551 +
1.136552 +/*
1.136553 +** Helper function for fts3NodeWrite().
1.136554 +*/
1.136555 +static int fts3TreeFinishNode(
1.136556 +  SegmentNode *pTree, 
1.136557 +  int iHeight, 
1.136558 +  sqlite3_int64 iLeftChild
1.136559 +){
1.136560 +  int nStart;
1.136561 +  assert( iHeight>=1 && iHeight<128 );
1.136562 +  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
1.136563 +  pTree->aData[nStart] = (char)iHeight;
1.136564 +  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
1.136565 +  return nStart;
1.136566 +}
1.136567 +
1.136568 +/*
1.136569 +** Write the buffer for the segment node pTree and all of its peers to the
1.136570 +** database. Then call this function recursively to write the parent of 
1.136571 +** pTree and its peers to the database. 
1.136572 +**
1.136573 +** Except, if pTree is a root node, do not write it to the database. Instead,
1.136574 +** set output variables *paRoot and *pnRoot to contain the root node.
1.136575 +**
1.136576 +** If successful, SQLITE_OK is returned and output variable *piLast is
1.136577 +** set to the largest blockid written to the database (or zero if no
1.136578 +** blocks were written to the db). Otherwise, an SQLite error code is 
1.136579 +** returned.
1.136580 +*/
1.136581 +static int fts3NodeWrite(
1.136582 +  Fts3Table *p,                   /* Virtual table handle */
1.136583 +  SegmentNode *pTree,             /* SegmentNode handle */
1.136584 +  int iHeight,                    /* Height of this node in tree */
1.136585 +  sqlite3_int64 iLeaf,            /* Block id of first leaf node */
1.136586 +  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
1.136587 +  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
1.136588 +  char **paRoot,                  /* OUT: Data for root node */
1.136589 +  int *pnRoot                     /* OUT: Size of root node in bytes */
1.136590 +){
1.136591 +  int rc = SQLITE_OK;
1.136592 +
1.136593 +  if( !pTree->pParent ){
1.136594 +    /* Root node of the tree. */
1.136595 +    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
1.136596 +    *piLast = iFree-1;
1.136597 +    *pnRoot = pTree->nData - nStart;
1.136598 +    *paRoot = &pTree->aData[nStart];
1.136599 +  }else{
1.136600 +    SegmentNode *pIter;
1.136601 +    sqlite3_int64 iNextFree = iFree;
1.136602 +    sqlite3_int64 iNextLeaf = iLeaf;
1.136603 +    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
1.136604 +      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
1.136605 +      int nWrite = pIter->nData - nStart;
1.136606 +  
1.136607 +      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
1.136608 +      iNextFree++;
1.136609 +      iNextLeaf += (pIter->nEntry+1);
1.136610 +    }
1.136611 +    if( rc==SQLITE_OK ){
1.136612 +      assert( iNextLeaf==iFree );
1.136613 +      rc = fts3NodeWrite(
1.136614 +          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
1.136615 +      );
1.136616 +    }
1.136617 +  }
1.136618 +
1.136619 +  return rc;
1.136620 +}
1.136621 +
1.136622 +/*
1.136623 +** Free all memory allocations associated with the tree pTree.
1.136624 +*/
1.136625 +static void fts3NodeFree(SegmentNode *pTree){
1.136626 +  if( pTree ){
1.136627 +    SegmentNode *p = pTree->pLeftmost;
1.136628 +    fts3NodeFree(p->pParent);
1.136629 +    while( p ){
1.136630 +      SegmentNode *pRight = p->pRight;
1.136631 +      if( p->aData!=(char *)&p[1] ){
1.136632 +        sqlite3_free(p->aData);
1.136633 +      }
1.136634 +      assert( pRight==0 || p->zMalloc==0 );
1.136635 +      sqlite3_free(p->zMalloc);
1.136636 +      sqlite3_free(p);
1.136637 +      p = pRight;
1.136638 +    }
1.136639 +  }
1.136640 +}
1.136641 +
1.136642 +/*
1.136643 +** Add a term to the segment being constructed by the SegmentWriter object
1.136644 +** *ppWriter. When adding the first term to a segment, *ppWriter should
1.136645 +** be passed NULL. This function will allocate a new SegmentWriter object
1.136646 +** and return it via the input/output variable *ppWriter in this case.
1.136647 +**
1.136648 +** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
1.136649 +*/
1.136650 +static int fts3SegWriterAdd(
1.136651 +  Fts3Table *p,                   /* Virtual table handle */
1.136652 +  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
1.136653 +  int isCopyTerm,                 /* True if buffer zTerm must be copied */
1.136654 +  const char *zTerm,              /* Pointer to buffer containing term */
1.136655 +  int nTerm,                      /* Size of term in bytes */
1.136656 +  const char *aDoclist,           /* Pointer to buffer containing doclist */
1.136657 +  int nDoclist                    /* Size of doclist in bytes */
1.136658 +){
1.136659 +  int nPrefix;                    /* Size of term prefix in bytes */
1.136660 +  int nSuffix;                    /* Size of term suffix in bytes */
1.136661 +  int nReq;                       /* Number of bytes required on leaf page */
1.136662 +  int nData;
1.136663 +  SegmentWriter *pWriter = *ppWriter;
1.136664 +
1.136665 +  if( !pWriter ){
1.136666 +    int rc;
1.136667 +    sqlite3_stmt *pStmt;
1.136668 +
1.136669 +    /* Allocate the SegmentWriter structure */
1.136670 +    pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
1.136671 +    if( !pWriter ) return SQLITE_NOMEM;
1.136672 +    memset(pWriter, 0, sizeof(SegmentWriter));
1.136673 +    *ppWriter = pWriter;
1.136674 +
1.136675 +    /* Allocate a buffer in which to accumulate data */
1.136676 +    pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
1.136677 +    if( !pWriter->aData ) return SQLITE_NOMEM;
1.136678 +    pWriter->nSize = p->nNodeSize;
1.136679 +
1.136680 +    /* Find the next free blockid in the %_segments table */
1.136681 +    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
1.136682 +    if( rc!=SQLITE_OK ) return rc;
1.136683 +    if( SQLITE_ROW==sqlite3_step(pStmt) ){
1.136684 +      pWriter->iFree = sqlite3_column_int64(pStmt, 0);
1.136685 +      pWriter->iFirst = pWriter->iFree;
1.136686 +    }
1.136687 +    rc = sqlite3_reset(pStmt);
1.136688 +    if( rc!=SQLITE_OK ) return rc;
1.136689 +  }
1.136690 +  nData = pWriter->nData;
1.136691 +
1.136692 +  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
1.136693 +  nSuffix = nTerm-nPrefix;
1.136694 +
1.136695 +  /* Figure out how many bytes are required by this new entry */
1.136696 +  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
1.136697 +    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
1.136698 +    nSuffix +                               /* Term suffix */
1.136699 +    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
1.136700 +    nDoclist;                               /* Doclist data */
1.136701 +
1.136702 +  if( nData>0 && nData+nReq>p->nNodeSize ){
1.136703 +    int rc;
1.136704 +
1.136705 +    /* The current leaf node is full. Write it out to the database. */
1.136706 +    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
1.136707 +    if( rc!=SQLITE_OK ) return rc;
1.136708 +    p->nLeafAdd++;
1.136709 +
1.136710 +    /* Add the current term to the interior node tree. The term added to
1.136711 +    ** the interior tree must:
1.136712 +    **
1.136713 +    **   a) be greater than the largest term on the leaf node just written
1.136714 +    **      to the database (still available in pWriter->zTerm), and
1.136715 +    **
1.136716 +    **   b) be less than or equal to the term about to be added to the new
1.136717 +    **      leaf node (zTerm/nTerm).
1.136718 +    **
1.136719 +    ** In other words, it must be the prefix of zTerm 1 byte longer than
1.136720 +    ** the common prefix (if any) of zTerm and pWriter->zTerm.
1.136721 +    */
1.136722 +    assert( nPrefix<nTerm );
1.136723 +    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
1.136724 +    if( rc!=SQLITE_OK ) return rc;
1.136725 +
1.136726 +    nData = 0;
1.136727 +    pWriter->nTerm = 0;
1.136728 +
1.136729 +    nPrefix = 0;
1.136730 +    nSuffix = nTerm;
1.136731 +    nReq = 1 +                              /* varint containing prefix size */
1.136732 +      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
1.136733 +      nTerm +                               /* Term suffix */
1.136734 +      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
1.136735 +      nDoclist;                             /* Doclist data */
1.136736 +  }
1.136737 +
1.136738 +  /* If the buffer currently allocated is too small for this entry, realloc
1.136739 +  ** the buffer to make it large enough.
1.136740 +  */
1.136741 +  if( nReq>pWriter->nSize ){
1.136742 +    char *aNew = sqlite3_realloc(pWriter->aData, nReq);
1.136743 +    if( !aNew ) return SQLITE_NOMEM;
1.136744 +    pWriter->aData = aNew;
1.136745 +    pWriter->nSize = nReq;
1.136746 +  }
1.136747 +  assert( nData+nReq<=pWriter->nSize );
1.136748 +
1.136749 +  /* Append the prefix-compressed term and doclist to the buffer. */
1.136750 +  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
1.136751 +  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
1.136752 +  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
1.136753 +  nData += nSuffix;
1.136754 +  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
1.136755 +  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
1.136756 +  pWriter->nData = nData + nDoclist;
1.136757 +
1.136758 +  /* Save the current term so that it can be used to prefix-compress the next.
1.136759 +  ** If the isCopyTerm parameter is true, then the buffer pointed to by
1.136760 +  ** zTerm is transient, so take a copy of the term data. Otherwise, just
1.136761 +  ** store a copy of the pointer.
1.136762 +  */
1.136763 +  if( isCopyTerm ){
1.136764 +    if( nTerm>pWriter->nMalloc ){
1.136765 +      char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
1.136766 +      if( !zNew ){
1.136767 +        return SQLITE_NOMEM;
1.136768 +      }
1.136769 +      pWriter->nMalloc = nTerm*2;
1.136770 +      pWriter->zMalloc = zNew;
1.136771 +      pWriter->zTerm = zNew;
1.136772 +    }
1.136773 +    assert( pWriter->zTerm==pWriter->zMalloc );
1.136774 +    memcpy(pWriter->zTerm, zTerm, nTerm);
1.136775 +  }else{
1.136776 +    pWriter->zTerm = (char *)zTerm;
1.136777 +  }
1.136778 +  pWriter->nTerm = nTerm;
1.136779 +
1.136780 +  return SQLITE_OK;
1.136781 +}
1.136782 +
1.136783 +/*
1.136784 +** Flush all data associated with the SegmentWriter object pWriter to the
1.136785 +** database. This function must be called after all terms have been added
1.136786 +** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
1.136787 +** returned. Otherwise, an SQLite error code.
1.136788 +*/
1.136789 +static int fts3SegWriterFlush(
1.136790 +  Fts3Table *p,                   /* Virtual table handle */
1.136791 +  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
1.136792 +  sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
1.136793 +  int iIdx                        /* Value for 'idx' column of %_segdir */
1.136794 +){
1.136795 +  int rc;                         /* Return code */
1.136796 +  if( pWriter->pTree ){
1.136797 +    sqlite3_int64 iLast = 0;      /* Largest block id written to database */
1.136798 +    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
1.136799 +    char *zRoot = NULL;           /* Pointer to buffer containing root node */
1.136800 +    int nRoot = 0;                /* Size of buffer zRoot */
1.136801 +
1.136802 +    iLastLeaf = pWriter->iFree;
1.136803 +    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
1.136804 +    if( rc==SQLITE_OK ){
1.136805 +      rc = fts3NodeWrite(p, pWriter->pTree, 1,
1.136806 +          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
1.136807 +    }
1.136808 +    if( rc==SQLITE_OK ){
1.136809 +      rc = fts3WriteSegdir(
1.136810 +          p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
1.136811 +    }
1.136812 +  }else{
1.136813 +    /* The entire tree fits on the root node. Write it to the segdir table. */
1.136814 +    rc = fts3WriteSegdir(
1.136815 +        p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
1.136816 +  }
1.136817 +  p->nLeafAdd++;
1.136818 +  return rc;
1.136819 +}
1.136820 +
1.136821 +/*
1.136822 +** Release all memory held by the SegmentWriter object passed as the 
1.136823 +** first argument.
1.136824 +*/
1.136825 +static void fts3SegWriterFree(SegmentWriter *pWriter){
1.136826 +  if( pWriter ){
1.136827 +    sqlite3_free(pWriter->aData);
1.136828 +    sqlite3_free(pWriter->zMalloc);
1.136829 +    fts3NodeFree(pWriter->pTree);
1.136830 +    sqlite3_free(pWriter);
1.136831 +  }
1.136832 +}
1.136833 +
1.136834 +/*
1.136835 +** The first value in the apVal[] array is assumed to contain an integer.
1.136836 +** This function tests if there exist any documents with docid values that
1.136837 +** are different from that integer. i.e. if deleting the document with docid
1.136838 +** pRowid would mean the FTS3 table were empty.
1.136839 +**
1.136840 +** If successful, *pisEmpty is set to true if the table is empty except for
1.136841 +** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
1.136842 +** error occurs, an SQLite error code is returned.
1.136843 +*/
1.136844 +static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
1.136845 +  sqlite3_stmt *pStmt;
1.136846 +  int rc;
1.136847 +  if( p->zContentTbl ){
1.136848 +    /* If using the content=xxx option, assume the table is never empty */
1.136849 +    *pisEmpty = 0;
1.136850 +    rc = SQLITE_OK;
1.136851 +  }else{
1.136852 +    rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
1.136853 +    if( rc==SQLITE_OK ){
1.136854 +      if( SQLITE_ROW==sqlite3_step(pStmt) ){
1.136855 +        *pisEmpty = sqlite3_column_int(pStmt, 0);
1.136856 +      }
1.136857 +      rc = sqlite3_reset(pStmt);
1.136858 +    }
1.136859 +  }
1.136860 +  return rc;
1.136861 +}
1.136862 +
1.136863 +/*
1.136864 +** Set *pnMax to the largest segment level in the database for the index
1.136865 +** iIndex.
1.136866 +**
1.136867 +** Segment levels are stored in the 'level' column of the %_segdir table.
1.136868 +**
1.136869 +** Return SQLITE_OK if successful, or an SQLite error code if not.
1.136870 +*/
1.136871 +static int fts3SegmentMaxLevel(
1.136872 +  Fts3Table *p, 
1.136873 +  int iLangid,
1.136874 +  int iIndex, 
1.136875 +  sqlite3_int64 *pnMax
1.136876 +){
1.136877 +  sqlite3_stmt *pStmt;
1.136878 +  int rc;
1.136879 +  assert( iIndex>=0 && iIndex<p->nIndex );
1.136880 +
1.136881 +  /* Set pStmt to the compiled version of:
1.136882 +  **
1.136883 +  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
1.136884 +  **
1.136885 +  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
1.136886 +  */
1.136887 +  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
1.136888 +  if( rc!=SQLITE_OK ) return rc;
1.136889 +  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
1.136890 +  sqlite3_bind_int64(pStmt, 2, 
1.136891 +      getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
1.136892 +  );
1.136893 +  if( SQLITE_ROW==sqlite3_step(pStmt) ){
1.136894 +    *pnMax = sqlite3_column_int64(pStmt, 0);
1.136895 +  }
1.136896 +  return sqlite3_reset(pStmt);
1.136897 +}
1.136898 +
1.136899 +/*
1.136900 +** Delete all entries in the %_segments table associated with the segment
1.136901 +** opened with seg-reader pSeg. This function does not affect the contents
1.136902 +** of the %_segdir table.
1.136903 +*/
1.136904 +static int fts3DeleteSegment(
1.136905 +  Fts3Table *p,                   /* FTS table handle */
1.136906 +  Fts3SegReader *pSeg             /* Segment to delete */
1.136907 +){
1.136908 +  int rc = SQLITE_OK;             /* Return code */
1.136909 +  if( pSeg->iStartBlock ){
1.136910 +    sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
1.136911 +    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
1.136912 +    if( rc==SQLITE_OK ){
1.136913 +      sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
1.136914 +      sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
1.136915 +      sqlite3_step(pDelete);
1.136916 +      rc = sqlite3_reset(pDelete);
1.136917 +    }
1.136918 +  }
1.136919 +  return rc;
1.136920 +}
1.136921 +
1.136922 +/*
1.136923 +** This function is used after merging multiple segments into a single large
1.136924 +** segment to delete the old, now redundant, segment b-trees. Specifically,
1.136925 +** it:
1.136926 +** 
1.136927 +**   1) Deletes all %_segments entries for the segments associated with 
1.136928 +**      each of the SegReader objects in the array passed as the third 
1.136929 +**      argument, and
1.136930 +**
1.136931 +**   2) deletes all %_segdir entries with level iLevel, or all %_segdir
1.136932 +**      entries regardless of level if (iLevel<0).
1.136933 +**
1.136934 +** SQLITE_OK is returned if successful, otherwise an SQLite error code.
1.136935 +*/
1.136936 +static int fts3DeleteSegdir(
1.136937 +  Fts3Table *p,                   /* Virtual table handle */
1.136938 +  int iLangid,                    /* Language id */
1.136939 +  int iIndex,                     /* Index for p->aIndex */
1.136940 +  int iLevel,                     /* Level of %_segdir entries to delete */
1.136941 +  Fts3SegReader **apSegment,      /* Array of SegReader objects */
1.136942 +  int nReader                     /* Size of array apSegment */
1.136943 +){
1.136944 +  int rc = SQLITE_OK;             /* Return Code */
1.136945 +  int i;                          /* Iterator variable */
1.136946 +  sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
1.136947 +
1.136948 +  for(i=0; rc==SQLITE_OK && i<nReader; i++){
1.136949 +    rc = fts3DeleteSegment(p, apSegment[i]);
1.136950 +  }
1.136951 +  if( rc!=SQLITE_OK ){
1.136952 +    return rc;
1.136953 +  }
1.136954 +
1.136955 +  assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
1.136956 +  if( iLevel==FTS3_SEGCURSOR_ALL ){
1.136957 +    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
1.136958 +    if( rc==SQLITE_OK ){
1.136959 +      sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
1.136960 +      sqlite3_bind_int64(pDelete, 2, 
1.136961 +          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
1.136962 +      );
1.136963 +    }
1.136964 +  }else{
1.136965 +    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
1.136966 +    if( rc==SQLITE_OK ){
1.136967 +      sqlite3_bind_int64(
1.136968 +          pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
1.136969 +      );
1.136970 +    }
1.136971 +  }
1.136972 +
1.136973 +  if( rc==SQLITE_OK ){
1.136974 +    sqlite3_step(pDelete);
1.136975 +    rc = sqlite3_reset(pDelete);
1.136976 +  }
1.136977 +
1.136978 +  return rc;
1.136979 +}
1.136980 +
1.136981 +/*
1.136982 +** When this function is called, buffer *ppList (size *pnList bytes) contains 
1.136983 +** a position list that may (or may not) feature multiple columns. This
1.136984 +** function adjusts the pointer *ppList and the length *pnList so that they
1.136985 +** identify the subset of the position list that corresponds to column iCol.
1.136986 +**
1.136987 +** If there are no entries in the input position list for column iCol, then
1.136988 +** *pnList is set to zero before returning.
1.136989 +**
1.136990 +** If parameter bZero is non-zero, then any part of the input list following
1.136991 +** the end of the output list is zeroed before returning.
1.136992 +*/
1.136993 +static void fts3ColumnFilter(
1.136994 +  int iCol,                       /* Column to filter on */
1.136995 +  int bZero,                      /* Zero out anything following *ppList */
1.136996 +  char **ppList,                  /* IN/OUT: Pointer to position list */
1.136997 +  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
1.136998 +){
1.136999 +  char *pList = *ppList;
1.137000 +  int nList = *pnList;
1.137001 +  char *pEnd = &pList[nList];
1.137002 +  int iCurrent = 0;
1.137003 +  char *p = pList;
1.137004 +
1.137005 +  assert( iCol>=0 );
1.137006 +  while( 1 ){
1.137007 +    char c = 0;
1.137008 +    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
1.137009 +  
1.137010 +    if( iCol==iCurrent ){
1.137011 +      nList = (int)(p - pList);
1.137012 +      break;
1.137013 +    }
1.137014 +
1.137015 +    nList -= (int)(p - pList);
1.137016 +    pList = p;
1.137017 +    if( nList==0 ){
1.137018 +      break;
1.137019 +    }
1.137020 +    p = &pList[1];
1.137021 +    p += fts3GetVarint32(p, &iCurrent);
1.137022 +  }
1.137023 +
1.137024 +  if( bZero && &pList[nList]!=pEnd ){
1.137025 +    memset(&pList[nList], 0, pEnd - &pList[nList]);
1.137026 +  }
1.137027 +  *ppList = pList;
1.137028 +  *pnList = nList;
1.137029 +}
1.137030 +
1.137031 +/*
1.137032 +** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
1.137033 +** existing data). Grow the buffer if required.
1.137034 +**
1.137035 +** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
1.137036 +** trying to resize the buffer, return SQLITE_NOMEM.
1.137037 +*/
1.137038 +static int fts3MsrBufferData(
1.137039 +  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
1.137040 +  char *pList,
1.137041 +  int nList
1.137042 +){
1.137043 +  if( nList>pMsr->nBuffer ){
1.137044 +    char *pNew;
1.137045 +    pMsr->nBuffer = nList*2;
1.137046 +    pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
1.137047 +    if( !pNew ) return SQLITE_NOMEM;
1.137048 +    pMsr->aBuffer = pNew;
1.137049 +  }
1.137050 +
1.137051 +  memcpy(pMsr->aBuffer, pList, nList);
1.137052 +  return SQLITE_OK;
1.137053 +}
1.137054 +
1.137055 +SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
1.137056 +  Fts3Table *p,                   /* Virtual table handle */
1.137057 +  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
1.137058 +  sqlite3_int64 *piDocid,         /* OUT: Docid value */
1.137059 +  char **paPoslist,               /* OUT: Pointer to position list */
1.137060 +  int *pnPoslist                  /* OUT: Size of position list in bytes */
1.137061 +){
1.137062 +  int nMerge = pMsr->nAdvance;
1.137063 +  Fts3SegReader **apSegment = pMsr->apSegment;
1.137064 +  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
1.137065 +    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
1.137066 +  );
1.137067 +
1.137068 +  if( nMerge==0 ){
1.137069 +    *paPoslist = 0;
1.137070 +    return SQLITE_OK;
1.137071 +  }
1.137072 +
1.137073 +  while( 1 ){
1.137074 +    Fts3SegReader *pSeg;
1.137075 +    pSeg = pMsr->apSegment[0];
1.137076 +
1.137077 +    if( pSeg->pOffsetList==0 ){
1.137078 +      *paPoslist = 0;
1.137079 +      break;
1.137080 +    }else{
1.137081 +      int rc;
1.137082 +      char *pList;
1.137083 +      int nList;
1.137084 +      int j;
1.137085 +      sqlite3_int64 iDocid = apSegment[0]->iDocid;
1.137086 +
1.137087 +      rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
1.137088 +      j = 1;
1.137089 +      while( rc==SQLITE_OK 
1.137090 +        && j<nMerge
1.137091 +        && apSegment[j]->pOffsetList
1.137092 +        && apSegment[j]->iDocid==iDocid
1.137093 +      ){
1.137094 +        rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
1.137095 +        j++;
1.137096 +      }
1.137097 +      if( rc!=SQLITE_OK ) return rc;
1.137098 +      fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
1.137099 +
1.137100 +      if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
1.137101 +        rc = fts3MsrBufferData(pMsr, pList, nList+1);
1.137102 +        if( rc!=SQLITE_OK ) return rc;
1.137103 +        assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
1.137104 +        pList = pMsr->aBuffer;
1.137105 +      }
1.137106 +
1.137107 +      if( pMsr->iColFilter>=0 ){
1.137108 +        fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
1.137109 +      }
1.137110 +
1.137111 +      if( nList>0 ){
1.137112 +        *paPoslist = pList;
1.137113 +        *piDocid = iDocid;
1.137114 +        *pnPoslist = nList;
1.137115 +        break;
1.137116 +      }
1.137117 +    }
1.137118 +  }
1.137119 +
1.137120 +  return SQLITE_OK;
1.137121 +}
1.137122 +
1.137123 +static int fts3SegReaderStart(
1.137124 +  Fts3Table *p,                   /* Virtual table handle */
1.137125 +  Fts3MultiSegReader *pCsr,       /* Cursor object */
1.137126 +  const char *zTerm,              /* Term searched for (or NULL) */
1.137127 +  int nTerm                       /* Length of zTerm in bytes */
1.137128 +){
1.137129 +  int i;
1.137130 +  int nSeg = pCsr->nSegment;
1.137131 +
1.137132 +  /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
1.137133 +  ** for, then advance each segment iterator until it points to a term of
1.137134 +  ** equal or greater value than the specified term. This prevents many
1.137135 +  ** unnecessary merge/sort operations for the case where single segment
1.137136 +  ** b-tree leaf nodes contain more than one term.
1.137137 +  */
1.137138 +  for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
1.137139 +    int res = 0;
1.137140 +    Fts3SegReader *pSeg = pCsr->apSegment[i];
1.137141 +    do {
1.137142 +      int rc = fts3SegReaderNext(p, pSeg, 0);
1.137143 +      if( rc!=SQLITE_OK ) return rc;
1.137144 +    }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
1.137145 +
1.137146 +    if( pSeg->bLookup && res!=0 ){
1.137147 +      fts3SegReaderSetEof(pSeg);
1.137148 +    }
1.137149 +  }
1.137150 +  fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
1.137151 +
1.137152 +  return SQLITE_OK;
1.137153 +}
1.137154 +
1.137155 +SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
1.137156 +  Fts3Table *p,                   /* Virtual table handle */
1.137157 +  Fts3MultiSegReader *pCsr,       /* Cursor object */
1.137158 +  Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
1.137159 +){
1.137160 +  pCsr->pFilter = pFilter;
1.137161 +  return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
1.137162 +}
1.137163 +
1.137164 +SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
1.137165 +  Fts3Table *p,                   /* Virtual table handle */
1.137166 +  Fts3MultiSegReader *pCsr,       /* Cursor object */
1.137167 +  int iCol,                       /* Column to match on. */
1.137168 +  const char *zTerm,              /* Term to iterate through a doclist for */
1.137169 +  int nTerm                       /* Number of bytes in zTerm */
1.137170 +){
1.137171 +  int i;
1.137172 +  int rc;
1.137173 +  int nSegment = pCsr->nSegment;
1.137174 +  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
1.137175 +    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
1.137176 +  );
1.137177 +
1.137178 +  assert( pCsr->pFilter==0 );
1.137179 +  assert( zTerm && nTerm>0 );
1.137180 +
1.137181 +  /* Advance each segment iterator until it points to the term zTerm/nTerm. */
1.137182 +  rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
1.137183 +  if( rc!=SQLITE_OK ) return rc;
1.137184 +
1.137185 +  /* Determine how many of the segments actually point to zTerm/nTerm. */
1.137186 +  for(i=0; i<nSegment; i++){
1.137187 +    Fts3SegReader *pSeg = pCsr->apSegment[i];
1.137188 +    if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
1.137189 +      break;
1.137190 +    }
1.137191 +  }
1.137192 +  pCsr->nAdvance = i;
1.137193 +
1.137194 +  /* Advance each of the segments to point to the first docid. */
1.137195 +  for(i=0; i<pCsr->nAdvance; i++){
1.137196 +    rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
1.137197 +    if( rc!=SQLITE_OK ) return rc;
1.137198 +  }
1.137199 +  fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
1.137200 +
1.137201 +  assert( iCol<0 || iCol<p->nColumn );
1.137202 +  pCsr->iColFilter = iCol;
1.137203 +
1.137204 +  return SQLITE_OK;
1.137205 +}
1.137206 +
1.137207 +/*
1.137208 +** This function is called on a MultiSegReader that has been started using
1.137209 +** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
1.137210 +** have been made. Calling this function puts the MultiSegReader in such
1.137211 +** a state that if the next two calls are:
1.137212 +**
1.137213 +**   sqlite3Fts3SegReaderStart()
1.137214 +**   sqlite3Fts3SegReaderStep()
1.137215 +**
1.137216 +** then the entire doclist for the term is available in 
1.137217 +** MultiSegReader.aDoclist/nDoclist.
1.137218 +*/
1.137219 +SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
1.137220 +  int i;                          /* Used to iterate through segment-readers */
1.137221 +
1.137222 +  assert( pCsr->zTerm==0 );
1.137223 +  assert( pCsr->nTerm==0 );
1.137224 +  assert( pCsr->aDoclist==0 );
1.137225 +  assert( pCsr->nDoclist==0 );
1.137226 +
1.137227 +  pCsr->nAdvance = 0;
1.137228 +  pCsr->bRestart = 1;
1.137229 +  for(i=0; i<pCsr->nSegment; i++){
1.137230 +    pCsr->apSegment[i]->pOffsetList = 0;
1.137231 +    pCsr->apSegment[i]->nOffsetList = 0;
1.137232 +    pCsr->apSegment[i]->iDocid = 0;
1.137233 +  }
1.137234 +
1.137235 +  return SQLITE_OK;
1.137236 +}
1.137237 +
1.137238 +
1.137239 +SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
1.137240 +  Fts3Table *p,                   /* Virtual table handle */
1.137241 +  Fts3MultiSegReader *pCsr        /* Cursor object */
1.137242 +){
1.137243 +  int rc = SQLITE_OK;
1.137244 +
1.137245 +  int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
1.137246 +  int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
1.137247 +  int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
1.137248 +  int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
1.137249 +  int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
1.137250 +  int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
1.137251 +
1.137252 +  Fts3SegReader **apSegment = pCsr->apSegment;
1.137253 +  int nSegment = pCsr->nSegment;
1.137254 +  Fts3SegFilter *pFilter = pCsr->pFilter;
1.137255 +  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
1.137256 +    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
1.137257 +  );
1.137258 +
1.137259 +  if( pCsr->nSegment==0 ) return SQLITE_OK;
1.137260 +
1.137261 +  do {
1.137262 +    int nMerge;
1.137263 +    int i;
1.137264 +  
1.137265 +    /* Advance the first pCsr->nAdvance entries in the apSegment[] array
1.137266 +    ** forward. Then sort the list in order of current term again.  
1.137267 +    */
1.137268 +    for(i=0; i<pCsr->nAdvance; i++){
1.137269 +      Fts3SegReader *pSeg = apSegment[i];
1.137270 +      if( pSeg->bLookup ){
1.137271 +        fts3SegReaderSetEof(pSeg);
1.137272 +      }else{
1.137273 +        rc = fts3SegReaderNext(p, pSeg, 0);
1.137274 +      }
1.137275 +      if( rc!=SQLITE_OK ) return rc;
1.137276 +    }
1.137277 +    fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
1.137278 +    pCsr->nAdvance = 0;
1.137279 +
1.137280 +    /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
1.137281 +    assert( rc==SQLITE_OK );
1.137282 +    if( apSegment[0]->aNode==0 ) break;
1.137283 +
1.137284 +    pCsr->nTerm = apSegment[0]->nTerm;
1.137285 +    pCsr->zTerm = apSegment[0]->zTerm;
1.137286 +
1.137287 +    /* If this is a prefix-search, and if the term that apSegment[0] points
1.137288 +    ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
1.137289 +    ** required callbacks have been made. In this case exit early.
1.137290 +    **
1.137291 +    ** Similarly, if this is a search for an exact match, and the first term
1.137292 +    ** of segment apSegment[0] is not a match, exit early.
1.137293 +    */
1.137294 +    if( pFilter->zTerm && !isScan ){
1.137295 +      if( pCsr->nTerm<pFilter->nTerm 
1.137296 +       || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
1.137297 +       || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) 
1.137298 +      ){
1.137299 +        break;
1.137300 +      }
1.137301 +    }
1.137302 +
1.137303 +    nMerge = 1;
1.137304 +    while( nMerge<nSegment 
1.137305 +        && apSegment[nMerge]->aNode
1.137306 +        && apSegment[nMerge]->nTerm==pCsr->nTerm 
1.137307 +        && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
1.137308 +    ){
1.137309 +      nMerge++;
1.137310 +    }
1.137311 +
1.137312 +    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
1.137313 +    if( nMerge==1 
1.137314 +     && !isIgnoreEmpty 
1.137315 +     && !isFirst 
1.137316 +     && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
1.137317 +    ){
1.137318 +      pCsr->nDoclist = apSegment[0]->nDoclist;
1.137319 +      if( fts3SegReaderIsPending(apSegment[0]) ){
1.137320 +        rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
1.137321 +        pCsr->aDoclist = pCsr->aBuffer;
1.137322 +      }else{
1.137323 +        pCsr->aDoclist = apSegment[0]->aDoclist;
1.137324 +      }
1.137325 +      if( rc==SQLITE_OK ) rc = SQLITE_ROW;
1.137326 +    }else{
1.137327 +      int nDoclist = 0;           /* Size of doclist */
1.137328 +      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
1.137329 +
1.137330 +      /* The current term of the first nMerge entries in the array
1.137331 +      ** of Fts3SegReader objects is the same. The doclists must be merged
1.137332 +      ** and a single term returned with the merged doclist.
1.137333 +      */
1.137334 +      for(i=0; i<nMerge; i++){
1.137335 +        fts3SegReaderFirstDocid(p, apSegment[i]);
1.137336 +      }
1.137337 +      fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
1.137338 +      while( apSegment[0]->pOffsetList ){
1.137339 +        int j;                    /* Number of segments that share a docid */
1.137340 +        char *pList = 0;
1.137341 +        int nList = 0;
1.137342 +        int nByte;
1.137343 +        sqlite3_int64 iDocid = apSegment[0]->iDocid;
1.137344 +        fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
1.137345 +        j = 1;
1.137346 +        while( j<nMerge
1.137347 +            && apSegment[j]->pOffsetList
1.137348 +            && apSegment[j]->iDocid==iDocid
1.137349 +        ){
1.137350 +          fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
1.137351 +          j++;
1.137352 +        }
1.137353 +
1.137354 +        if( isColFilter ){
1.137355 +          fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
1.137356 +        }
1.137357 +
1.137358 +        if( !isIgnoreEmpty || nList>0 ){
1.137359 +
1.137360 +          /* Calculate the 'docid' delta value to write into the merged 
1.137361 +          ** doclist. */
1.137362 +          sqlite3_int64 iDelta;
1.137363 +          if( p->bDescIdx && nDoclist>0 ){
1.137364 +            iDelta = iPrev - iDocid;
1.137365 +          }else{
1.137366 +            iDelta = iDocid - iPrev;
1.137367 +          }
1.137368 +          assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
1.137369 +          assert( nDoclist>0 || iDelta==iDocid );
1.137370 +
1.137371 +          nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
1.137372 +          if( nDoclist+nByte>pCsr->nBuffer ){
1.137373 +            char *aNew;
1.137374 +            pCsr->nBuffer = (nDoclist+nByte)*2;
1.137375 +            aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
1.137376 +            if( !aNew ){
1.137377 +              return SQLITE_NOMEM;
1.137378 +            }
1.137379 +            pCsr->aBuffer = aNew;
1.137380 +          }
1.137381 +
1.137382 +          if( isFirst ){
1.137383 +            char *a = &pCsr->aBuffer[nDoclist];
1.137384 +            int nWrite;
1.137385 +           
1.137386 +            nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
1.137387 +            if( nWrite ){
1.137388 +              iPrev = iDocid;
1.137389 +              nDoclist += nWrite;
1.137390 +            }
1.137391 +          }else{
1.137392 +            nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
1.137393 +            iPrev = iDocid;
1.137394 +            if( isRequirePos ){
1.137395 +              memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
1.137396 +              nDoclist += nList;
1.137397 +              pCsr->aBuffer[nDoclist++] = '\0';
1.137398 +            }
1.137399 +          }
1.137400 +        }
1.137401 +
1.137402 +        fts3SegReaderSort(apSegment, nMerge, j, xCmp);
1.137403 +      }
1.137404 +      if( nDoclist>0 ){
1.137405 +        pCsr->aDoclist = pCsr->aBuffer;
1.137406 +        pCsr->nDoclist = nDoclist;
1.137407 +        rc = SQLITE_ROW;
1.137408 +      }
1.137409 +    }
1.137410 +    pCsr->nAdvance = nMerge;
1.137411 +  }while( rc==SQLITE_OK );
1.137412 +
1.137413 +  return rc;
1.137414 +}
1.137415 +
1.137416 +
1.137417 +SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
1.137418 +  Fts3MultiSegReader *pCsr       /* Cursor object */
1.137419 +){
1.137420 +  if( pCsr ){
1.137421 +    int i;
1.137422 +    for(i=0; i<pCsr->nSegment; i++){
1.137423 +      sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
1.137424 +    }
1.137425 +    sqlite3_free(pCsr->apSegment);
1.137426 +    sqlite3_free(pCsr->aBuffer);
1.137427 +
1.137428 +    pCsr->nSegment = 0;
1.137429 +    pCsr->apSegment = 0;
1.137430 +    pCsr->aBuffer = 0;
1.137431 +  }
1.137432 +}
1.137433 +
1.137434 +/*
1.137435 +** Merge all level iLevel segments in the database into a single 
1.137436 +** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
1.137437 +** single segment with a level equal to the numerically largest level 
1.137438 +** currently present in the database.
1.137439 +**
1.137440 +** If this function is called with iLevel<0, but there is only one
1.137441 +** segment in the database, SQLITE_DONE is returned immediately. 
1.137442 +** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
1.137443 +** an SQLite error code is returned.
1.137444 +*/
1.137445 +static int fts3SegmentMerge(
1.137446 +  Fts3Table *p, 
1.137447 +  int iLangid,                    /* Language id to merge */
1.137448 +  int iIndex,                     /* Index in p->aIndex[] to merge */
1.137449 +  int iLevel                      /* Level to merge */
1.137450 +){
1.137451 +  int rc;                         /* Return code */
1.137452 +  int iIdx = 0;                   /* Index of new segment */
1.137453 +  sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
1.137454 +  SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
1.137455 +  Fts3SegFilter filter;           /* Segment term filter condition */
1.137456 +  Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
1.137457 +  int bIgnoreEmpty = 0;           /* True to ignore empty segments */
1.137458 +
1.137459 +  assert( iLevel==FTS3_SEGCURSOR_ALL
1.137460 +       || iLevel==FTS3_SEGCURSOR_PENDING
1.137461 +       || iLevel>=0
1.137462 +  );
1.137463 +  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
1.137464 +  assert( iIndex>=0 && iIndex<p->nIndex );
1.137465 +
1.137466 +  rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
1.137467 +  if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
1.137468 +
1.137469 +  if( iLevel==FTS3_SEGCURSOR_ALL ){
1.137470 +    /* This call is to merge all segments in the database to a single
1.137471 +    ** segment. The level of the new segment is equal to the numerically
1.137472 +    ** greatest segment level currently present in the database for this
1.137473 +    ** index. The idx of the new segment is always 0.  */
1.137474 +    if( csr.nSegment==1 ){
1.137475 +      rc = SQLITE_DONE;
1.137476 +      goto finished;
1.137477 +    }
1.137478 +    rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
1.137479 +    bIgnoreEmpty = 1;
1.137480 +
1.137481 +  }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
1.137482 +    iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
1.137483 +    rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
1.137484 +  }else{
1.137485 +    /* This call is to merge all segments at level iLevel. find the next
1.137486 +    ** available segment index at level iLevel+1. The call to
1.137487 +    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
1.137488 +    ** a single iLevel+2 segment if necessary.  */
1.137489 +    rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
1.137490 +    iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
1.137491 +  }
1.137492 +  if( rc!=SQLITE_OK ) goto finished;
1.137493 +  assert( csr.nSegment>0 );
1.137494 +  assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
1.137495 +  assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
1.137496 +
1.137497 +  memset(&filter, 0, sizeof(Fts3SegFilter));
1.137498 +  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
1.137499 +  filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
1.137500 +
1.137501 +  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
1.137502 +  while( SQLITE_OK==rc ){
1.137503 +    rc = sqlite3Fts3SegReaderStep(p, &csr);
1.137504 +    if( rc!=SQLITE_ROW ) break;
1.137505 +    rc = fts3SegWriterAdd(p, &pWriter, 1, 
1.137506 +        csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
1.137507 +  }
1.137508 +  if( rc!=SQLITE_OK ) goto finished;
1.137509 +  assert( pWriter );
1.137510 +
1.137511 +  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
1.137512 +    rc = fts3DeleteSegdir(
1.137513 +        p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
1.137514 +    );
1.137515 +    if( rc!=SQLITE_OK ) goto finished;
1.137516 +  }
1.137517 +  rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
1.137518 +
1.137519 + finished:
1.137520 +  fts3SegWriterFree(pWriter);
1.137521 +  sqlite3Fts3SegReaderFinish(&csr);
1.137522 +  return rc;
1.137523 +}
1.137524 +
1.137525 +
1.137526 +/* 
1.137527 +** Flush the contents of pendingTerms to level 0 segments.
1.137528 +*/
1.137529 +SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
1.137530 +  int rc = SQLITE_OK;
1.137531 +  int i;
1.137532 +        
1.137533 +  for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
1.137534 +    rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
1.137535 +    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
1.137536 +  }
1.137537 +  sqlite3Fts3PendingTermsClear(p);
1.137538 +
1.137539 +  /* Determine the auto-incr-merge setting if unknown.  If enabled,
1.137540 +  ** estimate the number of leaf blocks of content to be written
1.137541 +  */
1.137542 +  if( rc==SQLITE_OK && p->bHasStat
1.137543 +   && p->bAutoincrmerge==0xff && p->nLeafAdd>0
1.137544 +  ){
1.137545 +    sqlite3_stmt *pStmt = 0;
1.137546 +    rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
1.137547 +    if( rc==SQLITE_OK ){
1.137548 +      sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
1.137549 +      rc = sqlite3_step(pStmt);
1.137550 +      p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0));
1.137551 +      rc = sqlite3_reset(pStmt);
1.137552 +    }
1.137553 +  }
1.137554 +  return rc;
1.137555 +}
1.137556 +
1.137557 +/*
1.137558 +** Encode N integers as varints into a blob.
1.137559 +*/
1.137560 +static void fts3EncodeIntArray(
1.137561 +  int N,             /* The number of integers to encode */
1.137562 +  u32 *a,            /* The integer values */
1.137563 +  char *zBuf,        /* Write the BLOB here */
1.137564 +  int *pNBuf         /* Write number of bytes if zBuf[] used here */
1.137565 +){
1.137566 +  int i, j;
1.137567 +  for(i=j=0; i<N; i++){
1.137568 +    j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
1.137569 +  }
1.137570 +  *pNBuf = j;
1.137571 +}
1.137572 +
1.137573 +/*
1.137574 +** Decode a blob of varints into N integers
1.137575 +*/
1.137576 +static void fts3DecodeIntArray(
1.137577 +  int N,             /* The number of integers to decode */
1.137578 +  u32 *a,            /* Write the integer values */
1.137579 +  const char *zBuf,  /* The BLOB containing the varints */
1.137580 +  int nBuf           /* size of the BLOB */
1.137581 +){
1.137582 +  int i, j;
1.137583 +  UNUSED_PARAMETER(nBuf);
1.137584 +  for(i=j=0; i<N; i++){
1.137585 +    sqlite3_int64 x;
1.137586 +    j += sqlite3Fts3GetVarint(&zBuf[j], &x);
1.137587 +    assert(j<=nBuf);
1.137588 +    a[i] = (u32)(x & 0xffffffff);
1.137589 +  }
1.137590 +}
1.137591 +
1.137592 +/*
1.137593 +** Insert the sizes (in tokens) for each column of the document
1.137594 +** with docid equal to p->iPrevDocid.  The sizes are encoded as
1.137595 +** a blob of varints.
1.137596 +*/
1.137597 +static void fts3InsertDocsize(
1.137598 +  int *pRC,                       /* Result code */
1.137599 +  Fts3Table *p,                   /* Table into which to insert */
1.137600 +  u32 *aSz                        /* Sizes of each column, in tokens */
1.137601 +){
1.137602 +  char *pBlob;             /* The BLOB encoding of the document size */
1.137603 +  int nBlob;               /* Number of bytes in the BLOB */
1.137604 +  sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
1.137605 +  int rc;                  /* Result code from subfunctions */
1.137606 +
1.137607 +  if( *pRC ) return;
1.137608 +  pBlob = sqlite3_malloc( 10*p->nColumn );
1.137609 +  if( pBlob==0 ){
1.137610 +    *pRC = SQLITE_NOMEM;
1.137611 +    return;
1.137612 +  }
1.137613 +  fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
1.137614 +  rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
1.137615 +  if( rc ){
1.137616 +    sqlite3_free(pBlob);
1.137617 +    *pRC = rc;
1.137618 +    return;
1.137619 +  }
1.137620 +  sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
1.137621 +  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
1.137622 +  sqlite3_step(pStmt);
1.137623 +  *pRC = sqlite3_reset(pStmt);
1.137624 +}
1.137625 +
1.137626 +/*
1.137627 +** Record 0 of the %_stat table contains a blob consisting of N varints,
1.137628 +** where N is the number of user defined columns in the fts3 table plus
1.137629 +** two. If nCol is the number of user defined columns, then values of the 
1.137630 +** varints are set as follows:
1.137631 +**
1.137632 +**   Varint 0:       Total number of rows in the table.
1.137633 +**
1.137634 +**   Varint 1..nCol: For each column, the total number of tokens stored in
1.137635 +**                   the column for all rows of the table.
1.137636 +**
1.137637 +**   Varint 1+nCol:  The total size, in bytes, of all text values in all
1.137638 +**                   columns of all rows of the table.
1.137639 +**
1.137640 +*/
1.137641 +static void fts3UpdateDocTotals(
1.137642 +  int *pRC,                       /* The result code */
1.137643 +  Fts3Table *p,                   /* Table being updated */
1.137644 +  u32 *aSzIns,                    /* Size increases */
1.137645 +  u32 *aSzDel,                    /* Size decreases */
1.137646 +  int nChng                       /* Change in the number of documents */
1.137647 +){
1.137648 +  char *pBlob;             /* Storage for BLOB written into %_stat */
1.137649 +  int nBlob;               /* Size of BLOB written into %_stat */
1.137650 +  u32 *a;                  /* Array of integers that becomes the BLOB */
1.137651 +  sqlite3_stmt *pStmt;     /* Statement for reading and writing */
1.137652 +  int i;                   /* Loop counter */
1.137653 +  int rc;                  /* Result code from subfunctions */
1.137654 +
1.137655 +  const int nStat = p->nColumn+2;
1.137656 +
1.137657 +  if( *pRC ) return;
1.137658 +  a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
1.137659 +  if( a==0 ){
1.137660 +    *pRC = SQLITE_NOMEM;
1.137661 +    return;
1.137662 +  }
1.137663 +  pBlob = (char*)&a[nStat];
1.137664 +  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
1.137665 +  if( rc ){
1.137666 +    sqlite3_free(a);
1.137667 +    *pRC = rc;
1.137668 +    return;
1.137669 +  }
1.137670 +  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
1.137671 +  if( sqlite3_step(pStmt)==SQLITE_ROW ){
1.137672 +    fts3DecodeIntArray(nStat, a,
1.137673 +         sqlite3_column_blob(pStmt, 0),
1.137674 +         sqlite3_column_bytes(pStmt, 0));
1.137675 +  }else{
1.137676 +    memset(a, 0, sizeof(u32)*(nStat) );
1.137677 +  }
1.137678 +  rc = sqlite3_reset(pStmt);
1.137679 +  if( rc!=SQLITE_OK ){
1.137680 +    sqlite3_free(a);
1.137681 +    *pRC = rc;
1.137682 +    return;
1.137683 +  }
1.137684 +  if( nChng<0 && a[0]<(u32)(-nChng) ){
1.137685 +    a[0] = 0;
1.137686 +  }else{
1.137687 +    a[0] += nChng;
1.137688 +  }
1.137689 +  for(i=0; i<p->nColumn+1; i++){
1.137690 +    u32 x = a[i+1];
1.137691 +    if( x+aSzIns[i] < aSzDel[i] ){
1.137692 +      x = 0;
1.137693 +    }else{
1.137694 +      x = x + aSzIns[i] - aSzDel[i];
1.137695 +    }
1.137696 +    a[i+1] = x;
1.137697 +  }
1.137698 +  fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
1.137699 +  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
1.137700 +  if( rc ){
1.137701 +    sqlite3_free(a);
1.137702 +    *pRC = rc;
1.137703 +    return;
1.137704 +  }
1.137705 +  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
1.137706 +  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
1.137707 +  sqlite3_step(pStmt);
1.137708 +  *pRC = sqlite3_reset(pStmt);
1.137709 +  sqlite3_free(a);
1.137710 +}
1.137711 +
1.137712 +/*
1.137713 +** Merge the entire database so that there is one segment for each 
1.137714 +** iIndex/iLangid combination.
1.137715 +*/
1.137716 +static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
1.137717 +  int bSeenDone = 0;
1.137718 +  int rc;
1.137719 +  sqlite3_stmt *pAllLangid = 0;
1.137720 +
1.137721 +  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
1.137722 +  if( rc==SQLITE_OK ){
1.137723 +    int rc2;
1.137724 +    sqlite3_bind_int(pAllLangid, 1, p->nIndex);
1.137725 +    while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
1.137726 +      int i;
1.137727 +      int iLangid = sqlite3_column_int(pAllLangid, 0);
1.137728 +      for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
1.137729 +        rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
1.137730 +        if( rc==SQLITE_DONE ){
1.137731 +          bSeenDone = 1;
1.137732 +          rc = SQLITE_OK;
1.137733 +        }
1.137734 +      }
1.137735 +    }
1.137736 +    rc2 = sqlite3_reset(pAllLangid);
1.137737 +    if( rc==SQLITE_OK ) rc = rc2;
1.137738 +  }
1.137739 +
1.137740 +  sqlite3Fts3SegmentsClose(p);
1.137741 +  sqlite3Fts3PendingTermsClear(p);
1.137742 +
1.137743 +  return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
1.137744 +}
1.137745 +
1.137746 +/*
1.137747 +** This function is called when the user executes the following statement:
1.137748 +**
1.137749 +**     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
1.137750 +**
1.137751 +** The entire FTS index is discarded and rebuilt. If the table is one 
1.137752 +** created using the content=xxx option, then the new index is based on
1.137753 +** the current contents of the xxx table. Otherwise, it is rebuilt based
1.137754 +** on the contents of the %_content table.
1.137755 +*/
1.137756 +static int fts3DoRebuild(Fts3Table *p){
1.137757 +  int rc;                         /* Return Code */
1.137758 +
1.137759 +  rc = fts3DeleteAll(p, 0);
1.137760 +  if( rc==SQLITE_OK ){
1.137761 +    u32 *aSz = 0;
1.137762 +    u32 *aSzIns = 0;
1.137763 +    u32 *aSzDel = 0;
1.137764 +    sqlite3_stmt *pStmt = 0;
1.137765 +    int nEntry = 0;
1.137766 +
1.137767 +    /* Compose and prepare an SQL statement to loop through the content table */
1.137768 +    char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
1.137769 +    if( !zSql ){
1.137770 +      rc = SQLITE_NOMEM;
1.137771 +    }else{
1.137772 +      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
1.137773 +      sqlite3_free(zSql);
1.137774 +    }
1.137775 +
1.137776 +    if( rc==SQLITE_OK ){
1.137777 +      int nByte = sizeof(u32) * (p->nColumn+1)*3;
1.137778 +      aSz = (u32 *)sqlite3_malloc(nByte);
1.137779 +      if( aSz==0 ){
1.137780 +        rc = SQLITE_NOMEM;
1.137781 +      }else{
1.137782 +        memset(aSz, 0, nByte);
1.137783 +        aSzIns = &aSz[p->nColumn+1];
1.137784 +        aSzDel = &aSzIns[p->nColumn+1];
1.137785 +      }
1.137786 +    }
1.137787 +
1.137788 +    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
1.137789 +      int iCol;
1.137790 +      int iLangid = langidFromSelect(p, pStmt);
1.137791 +      rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
1.137792 +      memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
1.137793 +      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
1.137794 +        if( p->abNotindexed[iCol]==0 ){
1.137795 +          const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
1.137796 +          rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
1.137797 +          aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
1.137798 +        }
1.137799 +      }
1.137800 +      if( p->bHasDocsize ){
1.137801 +        fts3InsertDocsize(&rc, p, aSz);
1.137802 +      }
1.137803 +      if( rc!=SQLITE_OK ){
1.137804 +        sqlite3_finalize(pStmt);
1.137805 +        pStmt = 0;
1.137806 +      }else{
1.137807 +        nEntry++;
1.137808 +        for(iCol=0; iCol<=p->nColumn; iCol++){
1.137809 +          aSzIns[iCol] += aSz[iCol];
1.137810 +        }
1.137811 +      }
1.137812 +    }
1.137813 +    if( p->bFts4 ){
1.137814 +      fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
1.137815 +    }
1.137816 +    sqlite3_free(aSz);
1.137817 +
1.137818 +    if( pStmt ){
1.137819 +      int rc2 = sqlite3_finalize(pStmt);
1.137820 +      if( rc==SQLITE_OK ){
1.137821 +        rc = rc2;
1.137822 +      }
1.137823 +    }
1.137824 +  }
1.137825 +
1.137826 +  return rc;
1.137827 +}
1.137828 +
1.137829 +
1.137830 +/*
1.137831 +** This function opens a cursor used to read the input data for an 
1.137832 +** incremental merge operation. Specifically, it opens a cursor to scan
1.137833 +** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute 
1.137834 +** level iAbsLevel.
1.137835 +*/
1.137836 +static int fts3IncrmergeCsr(
1.137837 +  Fts3Table *p,                   /* FTS3 table handle */
1.137838 +  sqlite3_int64 iAbsLevel,        /* Absolute level to open */
1.137839 +  int nSeg,                       /* Number of segments to merge */
1.137840 +  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
1.137841 +){
1.137842 +  int rc;                         /* Return Code */
1.137843 +  sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */  
1.137844 +  int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
1.137845 +
1.137846 +  /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
1.137847 +  memset(pCsr, 0, sizeof(*pCsr));
1.137848 +  nByte = sizeof(Fts3SegReader *) * nSeg;
1.137849 +  pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
1.137850 +
1.137851 +  if( pCsr->apSegment==0 ){
1.137852 +    rc = SQLITE_NOMEM;
1.137853 +  }else{
1.137854 +    memset(pCsr->apSegment, 0, nByte);
1.137855 +    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
1.137856 +  }
1.137857 +  if( rc==SQLITE_OK ){
1.137858 +    int i;
1.137859 +    int rc2;
1.137860 +    sqlite3_bind_int64(pStmt, 1, iAbsLevel);
1.137861 +    assert( pCsr->nSegment==0 );
1.137862 +    for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
1.137863 +      rc = sqlite3Fts3SegReaderNew(i, 0,
1.137864 +          sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
1.137865 +          sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
1.137866 +          sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
1.137867 +          sqlite3_column_blob(pStmt, 4),         /* segdir.root */
1.137868 +          sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
1.137869 +          &pCsr->apSegment[i]
1.137870 +      );
1.137871 +      pCsr->nSegment++;
1.137872 +    }
1.137873 +    rc2 = sqlite3_reset(pStmt);
1.137874 +    if( rc==SQLITE_OK ) rc = rc2;
1.137875 +  }
1.137876 +
1.137877 +  return rc;
1.137878 +}
1.137879 +
1.137880 +typedef struct IncrmergeWriter IncrmergeWriter;
1.137881 +typedef struct NodeWriter NodeWriter;
1.137882 +typedef struct Blob Blob;
1.137883 +typedef struct NodeReader NodeReader;
1.137884 +
1.137885 +/*
1.137886 +** An instance of the following structure is used as a dynamic buffer
1.137887 +** to build up nodes or other blobs of data in.
1.137888 +**
1.137889 +** The function blobGrowBuffer() is used to extend the allocation.
1.137890 +*/
1.137891 +struct Blob {
1.137892 +  char *a;                        /* Pointer to allocation */
1.137893 +  int n;                          /* Number of valid bytes of data in a[] */
1.137894 +  int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
1.137895 +};
1.137896 +
1.137897 +/*
1.137898 +** This structure is used to build up buffers containing segment b-tree 
1.137899 +** nodes (blocks).
1.137900 +*/
1.137901 +struct NodeWriter {
1.137902 +  sqlite3_int64 iBlock;           /* Current block id */
1.137903 +  Blob key;                       /* Last key written to the current block */
1.137904 +  Blob block;                     /* Current block image */
1.137905 +};
1.137906 +
1.137907 +/*
1.137908 +** An object of this type contains the state required to create or append
1.137909 +** to an appendable b-tree segment.
1.137910 +*/
1.137911 +struct IncrmergeWriter {
1.137912 +  int nLeafEst;                   /* Space allocated for leaf blocks */
1.137913 +  int nWork;                      /* Number of leaf pages flushed */
1.137914 +  sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
1.137915 +  int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
1.137916 +  sqlite3_int64 iStart;           /* Block number of first allocated block */
1.137917 +  sqlite3_int64 iEnd;             /* Block number of last allocated block */
1.137918 +  NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
1.137919 +};
1.137920 +
1.137921 +/*
1.137922 +** An object of the following type is used to read data from a single
1.137923 +** FTS segment node. See the following functions:
1.137924 +**
1.137925 +**     nodeReaderInit()
1.137926 +**     nodeReaderNext()
1.137927 +**     nodeReaderRelease()
1.137928 +*/
1.137929 +struct NodeReader {
1.137930 +  const char *aNode;
1.137931 +  int nNode;
1.137932 +  int iOff;                       /* Current offset within aNode[] */
1.137933 +
1.137934 +  /* Output variables. Containing the current node entry. */
1.137935 +  sqlite3_int64 iChild;           /* Pointer to child node */
1.137936 +  Blob term;                      /* Current term */
1.137937 +  const char *aDoclist;           /* Pointer to doclist */
1.137938 +  int nDoclist;                   /* Size of doclist in bytes */
1.137939 +};
1.137940 +
1.137941 +/*
1.137942 +** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
1.137943 +** Otherwise, if the allocation at pBlob->a is not already at least nMin
1.137944 +** bytes in size, extend (realloc) it to be so.
1.137945 +**
1.137946 +** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
1.137947 +** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
1.137948 +** to reflect the new size of the pBlob->a[] buffer.
1.137949 +*/
1.137950 +static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
1.137951 +  if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
1.137952 +    int nAlloc = nMin;
1.137953 +    char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
1.137954 +    if( a ){
1.137955 +      pBlob->nAlloc = nAlloc;
1.137956 +      pBlob->a = a;
1.137957 +    }else{
1.137958 +      *pRc = SQLITE_NOMEM;
1.137959 +    }
1.137960 +  }
1.137961 +}
1.137962 +
1.137963 +/*
1.137964 +** Attempt to advance the node-reader object passed as the first argument to
1.137965 +** the next entry on the node. 
1.137966 +**
1.137967 +** Return an error code if an error occurs (SQLITE_NOMEM is possible). 
1.137968 +** Otherwise return SQLITE_OK. If there is no next entry on the node
1.137969 +** (e.g. because the current entry is the last) set NodeReader->aNode to
1.137970 +** NULL to indicate EOF. Otherwise, populate the NodeReader structure output 
1.137971 +** variables for the new entry.
1.137972 +*/
1.137973 +static int nodeReaderNext(NodeReader *p){
1.137974 +  int bFirst = (p->term.n==0);    /* True for first term on the node */
1.137975 +  int nPrefix = 0;                /* Bytes to copy from previous term */
1.137976 +  int nSuffix = 0;                /* Bytes to append to the prefix */
1.137977 +  int rc = SQLITE_OK;             /* Return code */
1.137978 +
1.137979 +  assert( p->aNode );
1.137980 +  if( p->iChild && bFirst==0 ) p->iChild++;
1.137981 +  if( p->iOff>=p->nNode ){
1.137982 +    /* EOF */
1.137983 +    p->aNode = 0;
1.137984 +  }else{
1.137985 +    if( bFirst==0 ){
1.137986 +      p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
1.137987 +    }
1.137988 +    p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
1.137989 +
1.137990 +    blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
1.137991 +    if( rc==SQLITE_OK ){
1.137992 +      memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
1.137993 +      p->term.n = nPrefix+nSuffix;
1.137994 +      p->iOff += nSuffix;
1.137995 +      if( p->iChild==0 ){
1.137996 +        p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
1.137997 +        p->aDoclist = &p->aNode[p->iOff];
1.137998 +        p->iOff += p->nDoclist;
1.137999 +      }
1.138000 +    }
1.138001 +  }
1.138002 +
1.138003 +  assert( p->iOff<=p->nNode );
1.138004 +
1.138005 +  return rc;
1.138006 +}
1.138007 +
1.138008 +/*
1.138009 +** Release all dynamic resources held by node-reader object *p.
1.138010 +*/
1.138011 +static void nodeReaderRelease(NodeReader *p){
1.138012 +  sqlite3_free(p->term.a);
1.138013 +}
1.138014 +
1.138015 +/*
1.138016 +** Initialize a node-reader object to read the node in buffer aNode/nNode.
1.138017 +**
1.138018 +** If successful, SQLITE_OK is returned and the NodeReader object set to 
1.138019 +** point to the first entry on the node (if any). Otherwise, an SQLite
1.138020 +** error code is returned.
1.138021 +*/
1.138022 +static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
1.138023 +  memset(p, 0, sizeof(NodeReader));
1.138024 +  p->aNode = aNode;
1.138025 +  p->nNode = nNode;
1.138026 +
1.138027 +  /* Figure out if this is a leaf or an internal node. */
1.138028 +  if( p->aNode[0] ){
1.138029 +    /* An internal node. */
1.138030 +    p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
1.138031 +  }else{
1.138032 +    p->iOff = 1;
1.138033 +  }
1.138034 +
1.138035 +  return nodeReaderNext(p);
1.138036 +}
1.138037 +
1.138038 +/*
1.138039 +** This function is called while writing an FTS segment each time a leaf o
1.138040 +** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
1.138041 +** to be greater than the largest key on the node just written, but smaller
1.138042 +** than or equal to the first key that will be written to the next leaf
1.138043 +** node.
1.138044 +**
1.138045 +** The block id of the leaf node just written to disk may be found in
1.138046 +** (pWriter->aNodeWriter[0].iBlock) when this function is called.
1.138047 +*/
1.138048 +static int fts3IncrmergePush(
1.138049 +  Fts3Table *p,                   /* Fts3 table handle */
1.138050 +  IncrmergeWriter *pWriter,       /* Writer object */
1.138051 +  const char *zTerm,              /* Term to write to internal node */
1.138052 +  int nTerm                       /* Bytes at zTerm */
1.138053 +){
1.138054 +  sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
1.138055 +  int iLayer;
1.138056 +
1.138057 +  assert( nTerm>0 );
1.138058 +  for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
1.138059 +    sqlite3_int64 iNextPtr = 0;
1.138060 +    NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
1.138061 +    int rc = SQLITE_OK;
1.138062 +    int nPrefix;
1.138063 +    int nSuffix;
1.138064 +    int nSpace;
1.138065 +
1.138066 +    /* Figure out how much space the key will consume if it is written to
1.138067 +    ** the current node of layer iLayer. Due to the prefix compression, 
1.138068 +    ** the space required changes depending on which node the key is to
1.138069 +    ** be added to.  */
1.138070 +    nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
1.138071 +    nSuffix = nTerm - nPrefix;
1.138072 +    nSpace  = sqlite3Fts3VarintLen(nPrefix);
1.138073 +    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
1.138074 +
1.138075 +    if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){ 
1.138076 +      /* If the current node of layer iLayer contains zero keys, or if adding
1.138077 +      ** the key to it will not cause it to grow to larger than nNodeSize 
1.138078 +      ** bytes in size, write the key here.  */
1.138079 +
1.138080 +      Blob *pBlk = &pNode->block;
1.138081 +      if( pBlk->n==0 ){
1.138082 +        blobGrowBuffer(pBlk, p->nNodeSize, &rc);
1.138083 +        if( rc==SQLITE_OK ){
1.138084 +          pBlk->a[0] = (char)iLayer;
1.138085 +          pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
1.138086 +        }
1.138087 +      }
1.138088 +      blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
1.138089 +      blobGrowBuffer(&pNode->key, nTerm, &rc);
1.138090 +
1.138091 +      if( rc==SQLITE_OK ){
1.138092 +        if( pNode->key.n ){
1.138093 +          pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
1.138094 +        }
1.138095 +        pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
1.138096 +        memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
1.138097 +        pBlk->n += nSuffix;
1.138098 +
1.138099 +        memcpy(pNode->key.a, zTerm, nTerm);
1.138100 +        pNode->key.n = nTerm;
1.138101 +      }
1.138102 +    }else{
1.138103 +      /* Otherwise, flush the current node of layer iLayer to disk.
1.138104 +      ** Then allocate a new, empty sibling node. The key will be written
1.138105 +      ** into the parent of this node. */
1.138106 +      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
1.138107 +
1.138108 +      assert( pNode->block.nAlloc>=p->nNodeSize );
1.138109 +      pNode->block.a[0] = (char)iLayer;
1.138110 +      pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
1.138111 +
1.138112 +      iNextPtr = pNode->iBlock;
1.138113 +      pNode->iBlock++;
1.138114 +      pNode->key.n = 0;
1.138115 +    }
1.138116 +
1.138117 +    if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
1.138118 +    iPtr = iNextPtr;
1.138119 +  }
1.138120 +
1.138121 +  assert( 0 );
1.138122 +  return 0;
1.138123 +}
1.138124 +
1.138125 +/*
1.138126 +** Append a term and (optionally) doclist to the FTS segment node currently
1.138127 +** stored in blob *pNode. The node need not contain any terms, but the
1.138128 +** header must be written before this function is called.
1.138129 +**
1.138130 +** A node header is a single 0x00 byte for a leaf node, or a height varint
1.138131 +** followed by the left-hand-child varint for an internal node.
1.138132 +**
1.138133 +** The term to be appended is passed via arguments zTerm/nTerm. For a 
1.138134 +** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
1.138135 +** node, both aDoclist and nDoclist must be passed 0.
1.138136 +**
1.138137 +** If the size of the value in blob pPrev is zero, then this is the first
1.138138 +** term written to the node. Otherwise, pPrev contains a copy of the 
1.138139 +** previous term. Before this function returns, it is updated to contain a
1.138140 +** copy of zTerm/nTerm.
1.138141 +**
1.138142 +** It is assumed that the buffer associated with pNode is already large
1.138143 +** enough to accommodate the new entry. The buffer associated with pPrev
1.138144 +** is extended by this function if requrired.
1.138145 +**
1.138146 +** If an error (i.e. OOM condition) occurs, an SQLite error code is
1.138147 +** returned. Otherwise, SQLITE_OK.
1.138148 +*/
1.138149 +static int fts3AppendToNode(
1.138150 +  Blob *pNode,                    /* Current node image to append to */
1.138151 +  Blob *pPrev,                    /* Buffer containing previous term written */
1.138152 +  const char *zTerm,              /* New term to write */
1.138153 +  int nTerm,                      /* Size of zTerm in bytes */
1.138154 +  const char *aDoclist,           /* Doclist (or NULL) to write */
1.138155 +  int nDoclist                    /* Size of aDoclist in bytes */ 
1.138156 +){
1.138157 +  int rc = SQLITE_OK;             /* Return code */
1.138158 +  int bFirst = (pPrev->n==0);     /* True if this is the first term written */
1.138159 +  int nPrefix;                    /* Size of term prefix in bytes */
1.138160 +  int nSuffix;                    /* Size of term suffix in bytes */
1.138161 +
1.138162 +  /* Node must have already been started. There must be a doclist for a
1.138163 +  ** leaf node, and there must not be a doclist for an internal node.  */
1.138164 +  assert( pNode->n>0 );
1.138165 +  assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
1.138166 +
1.138167 +  blobGrowBuffer(pPrev, nTerm, &rc);
1.138168 +  if( rc!=SQLITE_OK ) return rc;
1.138169 +
1.138170 +  nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
1.138171 +  nSuffix = nTerm - nPrefix;
1.138172 +  memcpy(pPrev->a, zTerm, nTerm);
1.138173 +  pPrev->n = nTerm;
1.138174 +
1.138175 +  if( bFirst==0 ){
1.138176 +    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
1.138177 +  }
1.138178 +  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
1.138179 +  memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
1.138180 +  pNode->n += nSuffix;
1.138181 +
1.138182 +  if( aDoclist ){
1.138183 +    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
1.138184 +    memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
1.138185 +    pNode->n += nDoclist;
1.138186 +  }
1.138187 +
1.138188 +  assert( pNode->n<=pNode->nAlloc );
1.138189 +
1.138190 +  return SQLITE_OK;
1.138191 +}
1.138192 +
1.138193 +/*
1.138194 +** Append the current term and doclist pointed to by cursor pCsr to the
1.138195 +** appendable b-tree segment opened for writing by pWriter.
1.138196 +**
1.138197 +** Return SQLITE_OK if successful, or an SQLite error code otherwise.
1.138198 +*/
1.138199 +static int fts3IncrmergeAppend(
1.138200 +  Fts3Table *p,                   /* Fts3 table handle */
1.138201 +  IncrmergeWriter *pWriter,       /* Writer object */
1.138202 +  Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
1.138203 +){
1.138204 +  const char *zTerm = pCsr->zTerm;
1.138205 +  int nTerm = pCsr->nTerm;
1.138206 +  const char *aDoclist = pCsr->aDoclist;
1.138207 +  int nDoclist = pCsr->nDoclist;
1.138208 +  int rc = SQLITE_OK;           /* Return code */
1.138209 +  int nSpace;                   /* Total space in bytes required on leaf */
1.138210 +  int nPrefix;                  /* Size of prefix shared with previous term */
1.138211 +  int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
1.138212 +  NodeWriter *pLeaf;            /* Object used to write leaf nodes */
1.138213 +
1.138214 +  pLeaf = &pWriter->aNodeWriter[0];
1.138215 +  nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
1.138216 +  nSuffix = nTerm - nPrefix;
1.138217 +
1.138218 +  nSpace  = sqlite3Fts3VarintLen(nPrefix);
1.138219 +  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
1.138220 +  nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
1.138221 +
1.138222 +  /* If the current block is not empty, and if adding this term/doclist
1.138223 +  ** to the current block would make it larger than Fts3Table.nNodeSize
1.138224 +  ** bytes, write this block out to the database. */
1.138225 +  if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
1.138226 +    rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
1.138227 +    pWriter->nWork++;
1.138228 +
1.138229 +    /* Add the current term to the parent node. The term added to the 
1.138230 +    ** parent must:
1.138231 +    **
1.138232 +    **   a) be greater than the largest term on the leaf node just written
1.138233 +    **      to the database (still available in pLeaf->key), and
1.138234 +    **
1.138235 +    **   b) be less than or equal to the term about to be added to the new
1.138236 +    **      leaf node (zTerm/nTerm).
1.138237 +    **
1.138238 +    ** In other words, it must be the prefix of zTerm 1 byte longer than
1.138239 +    ** the common prefix (if any) of zTerm and pWriter->zTerm.
1.138240 +    */
1.138241 +    if( rc==SQLITE_OK ){
1.138242 +      rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
1.138243 +    }
1.138244 +
1.138245 +    /* Advance to the next output block */
1.138246 +    pLeaf->iBlock++;
1.138247 +    pLeaf->key.n = 0;
1.138248 +    pLeaf->block.n = 0;
1.138249 +
1.138250 +    nSuffix = nTerm;
1.138251 +    nSpace  = 1;
1.138252 +    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
1.138253 +    nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
1.138254 +  }
1.138255 +
1.138256 +  blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
1.138257 +
1.138258 +  if( rc==SQLITE_OK ){
1.138259 +    if( pLeaf->block.n==0 ){
1.138260 +      pLeaf->block.n = 1;
1.138261 +      pLeaf->block.a[0] = '\0';
1.138262 +    }
1.138263 +    rc = fts3AppendToNode(
1.138264 +        &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
1.138265 +    );
1.138266 +  }
1.138267 +
1.138268 +  return rc;
1.138269 +}
1.138270 +
1.138271 +/*
1.138272 +** This function is called to release all dynamic resources held by the
1.138273 +** merge-writer object pWriter, and if no error has occurred, to flush
1.138274 +** all outstanding node buffers held by pWriter to disk.
1.138275 +**
1.138276 +** If *pRc is not SQLITE_OK when this function is called, then no attempt
1.138277 +** is made to write any data to disk. Instead, this function serves only
1.138278 +** to release outstanding resources.
1.138279 +**
1.138280 +** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
1.138281 +** flushing buffers to disk, *pRc is set to an SQLite error code before
1.138282 +** returning.
1.138283 +*/
1.138284 +static void fts3IncrmergeRelease(
1.138285 +  Fts3Table *p,                   /* FTS3 table handle */
1.138286 +  IncrmergeWriter *pWriter,       /* Merge-writer object */
1.138287 +  int *pRc                        /* IN/OUT: Error code */
1.138288 +){
1.138289 +  int i;                          /* Used to iterate through non-root layers */
1.138290 +  int iRoot;                      /* Index of root in pWriter->aNodeWriter */
1.138291 +  NodeWriter *pRoot;              /* NodeWriter for root node */
1.138292 +  int rc = *pRc;                  /* Error code */
1.138293 +
1.138294 +  /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment 
1.138295 +  ** root node. If the segment fits entirely on a single leaf node, iRoot
1.138296 +  ** will be set to 0. If the root node is the parent of the leaves, iRoot
1.138297 +  ** will be 1. And so on.  */
1.138298 +  for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
1.138299 +    NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
1.138300 +    if( pNode->block.n>0 ) break;
1.138301 +    assert( *pRc || pNode->block.nAlloc==0 );
1.138302 +    assert( *pRc || pNode->key.nAlloc==0 );
1.138303 +    sqlite3_free(pNode->block.a);
1.138304 +    sqlite3_free(pNode->key.a);
1.138305 +  }
1.138306 +
1.138307 +  /* Empty output segment. This is a no-op. */
1.138308 +  if( iRoot<0 ) return;
1.138309 +
1.138310 +  /* The entire output segment fits on a single node. Normally, this means
1.138311 +  ** the node would be stored as a blob in the "root" column of the %_segdir
1.138312 +  ** table. However, this is not permitted in this case. The problem is that 
1.138313 +  ** space has already been reserved in the %_segments table, and so the 
1.138314 +  ** start_block and end_block fields of the %_segdir table must be populated. 
1.138315 +  ** And, by design or by accident, released versions of FTS cannot handle 
1.138316 +  ** segments that fit entirely on the root node with start_block!=0.
1.138317 +  **
1.138318 +  ** Instead, create a synthetic root node that contains nothing but a 
1.138319 +  ** pointer to the single content node. So that the segment consists of a
1.138320 +  ** single leaf and a single interior (root) node.
1.138321 +  **
1.138322 +  ** Todo: Better might be to defer allocating space in the %_segments 
1.138323 +  ** table until we are sure it is needed.
1.138324 +  */
1.138325 +  if( iRoot==0 ){
1.138326 +    Blob *pBlock = &pWriter->aNodeWriter[1].block;
1.138327 +    blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
1.138328 +    if( rc==SQLITE_OK ){
1.138329 +      pBlock->a[0] = 0x01;
1.138330 +      pBlock->n = 1 + sqlite3Fts3PutVarint(
1.138331 +          &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
1.138332 +      );
1.138333 +    }
1.138334 +    iRoot = 1;
1.138335 +  }
1.138336 +  pRoot = &pWriter->aNodeWriter[iRoot];
1.138337 +
1.138338 +  /* Flush all currently outstanding nodes to disk. */
1.138339 +  for(i=0; i<iRoot; i++){
1.138340 +    NodeWriter *pNode = &pWriter->aNodeWriter[i];
1.138341 +    if( pNode->block.n>0 && rc==SQLITE_OK ){
1.138342 +      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
1.138343 +    }
1.138344 +    sqlite3_free(pNode->block.a);
1.138345 +    sqlite3_free(pNode->key.a);
1.138346 +  }
1.138347 +
1.138348 +  /* Write the %_segdir record. */
1.138349 +  if( rc==SQLITE_OK ){
1.138350 +    rc = fts3WriteSegdir(p, 
1.138351 +        pWriter->iAbsLevel+1,               /* level */
1.138352 +        pWriter->iIdx,                      /* idx */
1.138353 +        pWriter->iStart,                    /* start_block */
1.138354 +        pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
1.138355 +        pWriter->iEnd,                      /* end_block */
1.138356 +        pRoot->block.a, pRoot->block.n      /* root */
1.138357 +    );
1.138358 +  }
1.138359 +  sqlite3_free(pRoot->block.a);
1.138360 +  sqlite3_free(pRoot->key.a);
1.138361 +
1.138362 +  *pRc = rc;
1.138363 +}
1.138364 +
1.138365 +/*
1.138366 +** Compare the term in buffer zLhs (size in bytes nLhs) with that in
1.138367 +** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
1.138368 +** the other, it is considered to be smaller than the other.
1.138369 +**
1.138370 +** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
1.138371 +** if it is greater.
1.138372 +*/
1.138373 +static int fts3TermCmp(
1.138374 +  const char *zLhs, int nLhs,     /* LHS of comparison */
1.138375 +  const char *zRhs, int nRhs      /* RHS of comparison */
1.138376 +){
1.138377 +  int nCmp = MIN(nLhs, nRhs);
1.138378 +  int res;
1.138379 +
1.138380 +  res = memcmp(zLhs, zRhs, nCmp);
1.138381 +  if( res==0 ) res = nLhs - nRhs;
1.138382 +
1.138383 +  return res;
1.138384 +}
1.138385 +
1.138386 +
1.138387 +/*
1.138388 +** Query to see if the entry in the %_segments table with blockid iEnd is 
1.138389 +** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
1.138390 +** returning. Otherwise, set *pbRes to 0. 
1.138391 +**
1.138392 +** Or, if an error occurs while querying the database, return an SQLite 
1.138393 +** error code. The final value of *pbRes is undefined in this case.
1.138394 +**
1.138395 +** This is used to test if a segment is an "appendable" segment. If it
1.138396 +** is, then a NULL entry has been inserted into the %_segments table
1.138397 +** with blockid %_segdir.end_block.
1.138398 +*/
1.138399 +static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
1.138400 +  int bRes = 0;                   /* Result to set *pbRes to */
1.138401 +  sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
1.138402 +  int rc;                         /* Return code */
1.138403 +
1.138404 +  rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
1.138405 +  if( rc==SQLITE_OK ){
1.138406 +    sqlite3_bind_int64(pCheck, 1, iEnd);
1.138407 +    if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
1.138408 +    rc = sqlite3_reset(pCheck);
1.138409 +  }
1.138410 +  
1.138411 +  *pbRes = bRes;
1.138412 +  return rc;
1.138413 +}
1.138414 +
1.138415 +/*
1.138416 +** This function is called when initializing an incremental-merge operation.
1.138417 +** It checks if the existing segment with index value iIdx at absolute level 
1.138418 +** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
1.138419 +** merge-writer object *pWriter is initialized to write to it.
1.138420 +**
1.138421 +** An existing segment can be appended to by an incremental merge if:
1.138422 +**
1.138423 +**   * It was initially created as an appendable segment (with all required
1.138424 +**     space pre-allocated), and
1.138425 +**
1.138426 +**   * The first key read from the input (arguments zKey and nKey) is 
1.138427 +**     greater than the largest key currently stored in the potential
1.138428 +**     output segment.
1.138429 +*/
1.138430 +static int fts3IncrmergeLoad(
1.138431 +  Fts3Table *p,                   /* Fts3 table handle */
1.138432 +  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
1.138433 +  int iIdx,                       /* Index of candidate output segment */
1.138434 +  const char *zKey,               /* First key to write */
1.138435 +  int nKey,                       /* Number of bytes in nKey */
1.138436 +  IncrmergeWriter *pWriter        /* Populate this object */
1.138437 +){
1.138438 +  int rc;                         /* Return code */
1.138439 +  sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
1.138440 +
1.138441 +  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
1.138442 +  if( rc==SQLITE_OK ){
1.138443 +    sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
1.138444 +    sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
1.138445 +    sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
1.138446 +    const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
1.138447 +    int nRoot = 0;                /* Size of aRoot[] in bytes */
1.138448 +    int rc2;                      /* Return code from sqlite3_reset() */
1.138449 +    int bAppendable = 0;          /* Set to true if segment is appendable */
1.138450 +
1.138451 +    /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
1.138452 +    sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
1.138453 +    sqlite3_bind_int(pSelect, 2, iIdx);
1.138454 +    if( sqlite3_step(pSelect)==SQLITE_ROW ){
1.138455 +      iStart = sqlite3_column_int64(pSelect, 1);
1.138456 +      iLeafEnd = sqlite3_column_int64(pSelect, 2);
1.138457 +      iEnd = sqlite3_column_int64(pSelect, 3);
1.138458 +      nRoot = sqlite3_column_bytes(pSelect, 4);
1.138459 +      aRoot = sqlite3_column_blob(pSelect, 4);
1.138460 +    }else{
1.138461 +      return sqlite3_reset(pSelect);
1.138462 +    }
1.138463 +
1.138464 +    /* Check for the zero-length marker in the %_segments table */
1.138465 +    rc = fts3IsAppendable(p, iEnd, &bAppendable);
1.138466 +
1.138467 +    /* Check that zKey/nKey is larger than the largest key the candidate */
1.138468 +    if( rc==SQLITE_OK && bAppendable ){
1.138469 +      char *aLeaf = 0;
1.138470 +      int nLeaf = 0;
1.138471 +
1.138472 +      rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
1.138473 +      if( rc==SQLITE_OK ){
1.138474 +        NodeReader reader;
1.138475 +        for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
1.138476 +            rc==SQLITE_OK && reader.aNode;
1.138477 +            rc = nodeReaderNext(&reader)
1.138478 +        ){
1.138479 +          assert( reader.aNode );
1.138480 +        }
1.138481 +        if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
1.138482 +          bAppendable = 0;
1.138483 +        }
1.138484 +        nodeReaderRelease(&reader);
1.138485 +      }
1.138486 +      sqlite3_free(aLeaf);
1.138487 +    }
1.138488 +
1.138489 +    if( rc==SQLITE_OK && bAppendable ){
1.138490 +      /* It is possible to append to this segment. Set up the IncrmergeWriter
1.138491 +      ** object to do so.  */
1.138492 +      int i;
1.138493 +      int nHeight = (int)aRoot[0];
1.138494 +      NodeWriter *pNode;
1.138495 +
1.138496 +      pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
1.138497 +      pWriter->iStart = iStart;
1.138498 +      pWriter->iEnd = iEnd;
1.138499 +      pWriter->iAbsLevel = iAbsLevel;
1.138500 +      pWriter->iIdx = iIdx;
1.138501 +
1.138502 +      for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
1.138503 +        pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
1.138504 +      }
1.138505 +
1.138506 +      pNode = &pWriter->aNodeWriter[nHeight];
1.138507 +      pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
1.138508 +      blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
1.138509 +      if( rc==SQLITE_OK ){
1.138510 +        memcpy(pNode->block.a, aRoot, nRoot);
1.138511 +        pNode->block.n = nRoot;
1.138512 +      }
1.138513 +
1.138514 +      for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
1.138515 +        NodeReader reader;
1.138516 +        pNode = &pWriter->aNodeWriter[i];
1.138517 +
1.138518 +        rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
1.138519 +        while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
1.138520 +        blobGrowBuffer(&pNode->key, reader.term.n, &rc);
1.138521 +        if( rc==SQLITE_OK ){
1.138522 +          memcpy(pNode->key.a, reader.term.a, reader.term.n);
1.138523 +          pNode->key.n = reader.term.n;
1.138524 +          if( i>0 ){
1.138525 +            char *aBlock = 0;
1.138526 +            int nBlock = 0;
1.138527 +            pNode = &pWriter->aNodeWriter[i-1];
1.138528 +            pNode->iBlock = reader.iChild;
1.138529 +            rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
1.138530 +            blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
1.138531 +            if( rc==SQLITE_OK ){
1.138532 +              memcpy(pNode->block.a, aBlock, nBlock);
1.138533 +              pNode->block.n = nBlock;
1.138534 +            }
1.138535 +            sqlite3_free(aBlock);
1.138536 +          }
1.138537 +        }
1.138538 +        nodeReaderRelease(&reader);
1.138539 +      }
1.138540 +    }
1.138541 +
1.138542 +    rc2 = sqlite3_reset(pSelect);
1.138543 +    if( rc==SQLITE_OK ) rc = rc2;
1.138544 +  }
1.138545 +
1.138546 +  return rc;
1.138547 +}
1.138548 +
1.138549 +/*
1.138550 +** Determine the largest segment index value that exists within absolute
1.138551 +** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
1.138552 +** one before returning SQLITE_OK. Or, if there are no segments at all 
1.138553 +** within level iAbsLevel, set *piIdx to zero.
1.138554 +**
1.138555 +** If an error occurs, return an SQLite error code. The final value of
1.138556 +** *piIdx is undefined in this case.
1.138557 +*/
1.138558 +static int fts3IncrmergeOutputIdx( 
1.138559 +  Fts3Table *p,                   /* FTS Table handle */
1.138560 +  sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
1.138561 +  int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
1.138562 +){
1.138563 +  int rc;
1.138564 +  sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
1.138565 +
1.138566 +  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
1.138567 +  if( rc==SQLITE_OK ){
1.138568 +    sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
1.138569 +    sqlite3_step(pOutputIdx);
1.138570 +    *piIdx = sqlite3_column_int(pOutputIdx, 0);
1.138571 +    rc = sqlite3_reset(pOutputIdx);
1.138572 +  }
1.138573 +
1.138574 +  return rc;
1.138575 +}
1.138576 +
1.138577 +/* 
1.138578 +** Allocate an appendable output segment on absolute level iAbsLevel+1
1.138579 +** with idx value iIdx.
1.138580 +**
1.138581 +** In the %_segdir table, a segment is defined by the values in three
1.138582 +** columns:
1.138583 +**
1.138584 +**     start_block
1.138585 +**     leaves_end_block
1.138586 +**     end_block
1.138587 +**
1.138588 +** When an appendable segment is allocated, it is estimated that the
1.138589 +** maximum number of leaf blocks that may be required is the sum of the
1.138590 +** number of leaf blocks consumed by the input segments, plus the number
1.138591 +** of input segments, multiplied by two. This value is stored in stack 
1.138592 +** variable nLeafEst.
1.138593 +**
1.138594 +** A total of 16*nLeafEst blocks are allocated when an appendable segment
1.138595 +** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
1.138596 +** array of leaf nodes starts at the first block allocated. The array
1.138597 +** of interior nodes that are parents of the leaf nodes start at block
1.138598 +** (start_block + (1 + end_block - start_block) / 16). And so on.
1.138599 +**
1.138600 +** In the actual code below, the value "16" is replaced with the 
1.138601 +** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
1.138602 +*/
1.138603 +static int fts3IncrmergeWriter( 
1.138604 +  Fts3Table *p,                   /* Fts3 table handle */
1.138605 +  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
1.138606 +  int iIdx,                       /* Index of new output segment */
1.138607 +  Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
1.138608 +  IncrmergeWriter *pWriter        /* Populate this object */
1.138609 +){
1.138610 +  int rc;                         /* Return Code */
1.138611 +  int i;                          /* Iterator variable */
1.138612 +  int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
1.138613 +  sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
1.138614 +  sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
1.138615 +
1.138616 +  /* Calculate nLeafEst. */
1.138617 +  rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
1.138618 +  if( rc==SQLITE_OK ){
1.138619 +    sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
1.138620 +    sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
1.138621 +    if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
1.138622 +      nLeafEst = sqlite3_column_int(pLeafEst, 0);
1.138623 +    }
1.138624 +    rc = sqlite3_reset(pLeafEst);
1.138625 +  }
1.138626 +  if( rc!=SQLITE_OK ) return rc;
1.138627 +
1.138628 +  /* Calculate the first block to use in the output segment */
1.138629 +  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
1.138630 +  if( rc==SQLITE_OK ){
1.138631 +    if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
1.138632 +      pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
1.138633 +      pWriter->iEnd = pWriter->iStart - 1;
1.138634 +      pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
1.138635 +    }
1.138636 +    rc = sqlite3_reset(pFirstBlock);
1.138637 +  }
1.138638 +  if( rc!=SQLITE_OK ) return rc;
1.138639 +
1.138640 +  /* Insert the marker in the %_segments table to make sure nobody tries
1.138641 +  ** to steal the space just allocated. This is also used to identify 
1.138642 +  ** appendable segments.  */
1.138643 +  rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
1.138644 +  if( rc!=SQLITE_OK ) return rc;
1.138645 +
1.138646 +  pWriter->iAbsLevel = iAbsLevel;
1.138647 +  pWriter->nLeafEst = nLeafEst;
1.138648 +  pWriter->iIdx = iIdx;
1.138649 +
1.138650 +  /* Set up the array of NodeWriter objects */
1.138651 +  for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
1.138652 +    pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
1.138653 +  }
1.138654 +  return SQLITE_OK;
1.138655 +}
1.138656 +
1.138657 +/*
1.138658 +** Remove an entry from the %_segdir table. This involves running the 
1.138659 +** following two statements:
1.138660 +**
1.138661 +**   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
1.138662 +**   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
1.138663 +**
1.138664 +** The DELETE statement removes the specific %_segdir level. The UPDATE 
1.138665 +** statement ensures that the remaining segments have contiguously allocated
1.138666 +** idx values.
1.138667 +*/
1.138668 +static int fts3RemoveSegdirEntry(
1.138669 +  Fts3Table *p,                   /* FTS3 table handle */
1.138670 +  sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
1.138671 +  int iIdx                        /* Index of %_segdir entry to delete */
1.138672 +){
1.138673 +  int rc;                         /* Return code */
1.138674 +  sqlite3_stmt *pDelete = 0;      /* DELETE statement */
1.138675 +
1.138676 +  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
1.138677 +  if( rc==SQLITE_OK ){
1.138678 +    sqlite3_bind_int64(pDelete, 1, iAbsLevel);
1.138679 +    sqlite3_bind_int(pDelete, 2, iIdx);
1.138680 +    sqlite3_step(pDelete);
1.138681 +    rc = sqlite3_reset(pDelete);
1.138682 +  }
1.138683 +
1.138684 +  return rc;
1.138685 +}
1.138686 +
1.138687 +/*
1.138688 +** One or more segments have just been removed from absolute level iAbsLevel.
1.138689 +** Update the 'idx' values of the remaining segments in the level so that
1.138690 +** the idx values are a contiguous sequence starting from 0.
1.138691 +*/
1.138692 +static int fts3RepackSegdirLevel(
1.138693 +  Fts3Table *p,                   /* FTS3 table handle */
1.138694 +  sqlite3_int64 iAbsLevel         /* Absolute level to repack */
1.138695 +){
1.138696 +  int rc;                         /* Return code */
1.138697 +  int *aIdx = 0;                  /* Array of remaining idx values */
1.138698 +  int nIdx = 0;                   /* Valid entries in aIdx[] */
1.138699 +  int nAlloc = 0;                 /* Allocated size of aIdx[] */
1.138700 +  int i;                          /* Iterator variable */
1.138701 +  sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
1.138702 +  sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
1.138703 +
1.138704 +  rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
1.138705 +  if( rc==SQLITE_OK ){
1.138706 +    int rc2;
1.138707 +    sqlite3_bind_int64(pSelect, 1, iAbsLevel);
1.138708 +    while( SQLITE_ROW==sqlite3_step(pSelect) ){
1.138709 +      if( nIdx>=nAlloc ){
1.138710 +        int *aNew;
1.138711 +        nAlloc += 16;
1.138712 +        aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
1.138713 +        if( !aNew ){
1.138714 +          rc = SQLITE_NOMEM;
1.138715 +          break;
1.138716 +        }
1.138717 +        aIdx = aNew;
1.138718 +      }
1.138719 +      aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
1.138720 +    }
1.138721 +    rc2 = sqlite3_reset(pSelect);
1.138722 +    if( rc==SQLITE_OK ) rc = rc2;
1.138723 +  }
1.138724 +
1.138725 +  if( rc==SQLITE_OK ){
1.138726 +    rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
1.138727 +  }
1.138728 +  if( rc==SQLITE_OK ){
1.138729 +    sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
1.138730 +  }
1.138731 +
1.138732 +  assert( p->bIgnoreSavepoint==0 );
1.138733 +  p->bIgnoreSavepoint = 1;
1.138734 +  for(i=0; rc==SQLITE_OK && i<nIdx; i++){
1.138735 +    if( aIdx[i]!=i ){
1.138736 +      sqlite3_bind_int(pUpdate, 3, aIdx[i]);
1.138737 +      sqlite3_bind_int(pUpdate, 1, i);
1.138738 +      sqlite3_step(pUpdate);
1.138739 +      rc = sqlite3_reset(pUpdate);
1.138740 +    }
1.138741 +  }
1.138742 +  p->bIgnoreSavepoint = 0;
1.138743 +
1.138744 +  sqlite3_free(aIdx);
1.138745 +  return rc;
1.138746 +}
1.138747 +
1.138748 +static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
1.138749 +  pNode->a[0] = (char)iHeight;
1.138750 +  if( iChild ){
1.138751 +    assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
1.138752 +    pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
1.138753 +  }else{
1.138754 +    assert( pNode->nAlloc>=1 );
1.138755 +    pNode->n = 1;
1.138756 +  }
1.138757 +}
1.138758 +
1.138759 +/*
1.138760 +** The first two arguments are a pointer to and the size of a segment b-tree
1.138761 +** node. The node may be a leaf or an internal node.
1.138762 +**
1.138763 +** This function creates a new node image in blob object *pNew by copying
1.138764 +** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
1.138765 +** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
1.138766 +*/
1.138767 +static int fts3TruncateNode(
1.138768 +  const char *aNode,              /* Current node image */
1.138769 +  int nNode,                      /* Size of aNode in bytes */
1.138770 +  Blob *pNew,                     /* OUT: Write new node image here */
1.138771 +  const char *zTerm,              /* Omit all terms smaller than this */
1.138772 +  int nTerm,                      /* Size of zTerm in bytes */
1.138773 +  sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
1.138774 +){
1.138775 +  NodeReader reader;              /* Reader object */
1.138776 +  Blob prev = {0, 0, 0};          /* Previous term written to new node */
1.138777 +  int rc = SQLITE_OK;             /* Return code */
1.138778 +  int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
1.138779 +
1.138780 +  /* Allocate required output space */
1.138781 +  blobGrowBuffer(pNew, nNode, &rc);
1.138782 +  if( rc!=SQLITE_OK ) return rc;
1.138783 +  pNew->n = 0;
1.138784 +
1.138785 +  /* Populate new node buffer */
1.138786 +  for(rc = nodeReaderInit(&reader, aNode, nNode); 
1.138787 +      rc==SQLITE_OK && reader.aNode; 
1.138788 +      rc = nodeReaderNext(&reader)
1.138789 +  ){
1.138790 +    if( pNew->n==0 ){
1.138791 +      int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
1.138792 +      if( res<0 || (bLeaf==0 && res==0) ) continue;
1.138793 +      fts3StartNode(pNew, (int)aNode[0], reader.iChild);
1.138794 +      *piBlock = reader.iChild;
1.138795 +    }
1.138796 +    rc = fts3AppendToNode(
1.138797 +        pNew, &prev, reader.term.a, reader.term.n,
1.138798 +        reader.aDoclist, reader.nDoclist
1.138799 +    );
1.138800 +    if( rc!=SQLITE_OK ) break;
1.138801 +  }
1.138802 +  if( pNew->n==0 ){
1.138803 +    fts3StartNode(pNew, (int)aNode[0], reader.iChild);
1.138804 +    *piBlock = reader.iChild;
1.138805 +  }
1.138806 +  assert( pNew->n<=pNew->nAlloc );
1.138807 +
1.138808 +  nodeReaderRelease(&reader);
1.138809 +  sqlite3_free(prev.a);
1.138810 +  return rc;
1.138811 +}
1.138812 +
1.138813 +/*
1.138814 +** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute 
1.138815 +** level iAbsLevel. This may involve deleting entries from the %_segments
1.138816 +** table, and modifying existing entries in both the %_segments and %_segdir
1.138817 +** tables.
1.138818 +**
1.138819 +** SQLITE_OK is returned if the segment is updated successfully. Or an
1.138820 +** SQLite error code otherwise.
1.138821 +*/
1.138822 +static int fts3TruncateSegment(
1.138823 +  Fts3Table *p,                   /* FTS3 table handle */
1.138824 +  sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
1.138825 +  int iIdx,                       /* Index within level of segment to modify */
1.138826 +  const char *zTerm,              /* Remove terms smaller than this */
1.138827 +  int nTerm                      /* Number of bytes in buffer zTerm */
1.138828 +){
1.138829 +  int rc = SQLITE_OK;             /* Return code */
1.138830 +  Blob root = {0,0,0};            /* New root page image */
1.138831 +  Blob block = {0,0,0};           /* Buffer used for any other block */
1.138832 +  sqlite3_int64 iBlock = 0;       /* Block id */
1.138833 +  sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
1.138834 +  sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
1.138835 +  sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
1.138836 +
1.138837 +  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
1.138838 +  if( rc==SQLITE_OK ){
1.138839 +    int rc2;                      /* sqlite3_reset() return code */
1.138840 +    sqlite3_bind_int64(pFetch, 1, iAbsLevel);
1.138841 +    sqlite3_bind_int(pFetch, 2, iIdx);
1.138842 +    if( SQLITE_ROW==sqlite3_step(pFetch) ){
1.138843 +      const char *aRoot = sqlite3_column_blob(pFetch, 4);
1.138844 +      int nRoot = sqlite3_column_bytes(pFetch, 4);
1.138845 +      iOldStart = sqlite3_column_int64(pFetch, 1);
1.138846 +      rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
1.138847 +    }
1.138848 +    rc2 = sqlite3_reset(pFetch);
1.138849 +    if( rc==SQLITE_OK ) rc = rc2;
1.138850 +  }
1.138851 +
1.138852 +  while( rc==SQLITE_OK && iBlock ){
1.138853 +    char *aBlock = 0;
1.138854 +    int nBlock = 0;
1.138855 +    iNewStart = iBlock;
1.138856 +
1.138857 +    rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
1.138858 +    if( rc==SQLITE_OK ){
1.138859 +      rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
1.138860 +    }
1.138861 +    if( rc==SQLITE_OK ){
1.138862 +      rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
1.138863 +    }
1.138864 +    sqlite3_free(aBlock);
1.138865 +  }
1.138866 +
1.138867 +  /* Variable iNewStart now contains the first valid leaf node. */
1.138868 +  if( rc==SQLITE_OK && iNewStart ){
1.138869 +    sqlite3_stmt *pDel = 0;
1.138870 +    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
1.138871 +    if( rc==SQLITE_OK ){
1.138872 +      sqlite3_bind_int64(pDel, 1, iOldStart);
1.138873 +      sqlite3_bind_int64(pDel, 2, iNewStart-1);
1.138874 +      sqlite3_step(pDel);
1.138875 +      rc = sqlite3_reset(pDel);
1.138876 +    }
1.138877 +  }
1.138878 +
1.138879 +  if( rc==SQLITE_OK ){
1.138880 +    sqlite3_stmt *pChomp = 0;
1.138881 +    rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
1.138882 +    if( rc==SQLITE_OK ){
1.138883 +      sqlite3_bind_int64(pChomp, 1, iNewStart);
1.138884 +      sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
1.138885 +      sqlite3_bind_int64(pChomp, 3, iAbsLevel);
1.138886 +      sqlite3_bind_int(pChomp, 4, iIdx);
1.138887 +      sqlite3_step(pChomp);
1.138888 +      rc = sqlite3_reset(pChomp);
1.138889 +    }
1.138890 +  }
1.138891 +
1.138892 +  sqlite3_free(root.a);
1.138893 +  sqlite3_free(block.a);
1.138894 +  return rc;
1.138895 +}
1.138896 +
1.138897 +/*
1.138898 +** This function is called after an incrmental-merge operation has run to
1.138899 +** merge (or partially merge) two or more segments from absolute level
1.138900 +** iAbsLevel.
1.138901 +**
1.138902 +** Each input segment is either removed from the db completely (if all of
1.138903 +** its data was copied to the output segment by the incrmerge operation)
1.138904 +** or modified in place so that it no longer contains those entries that
1.138905 +** have been duplicated in the output segment.
1.138906 +*/
1.138907 +static int fts3IncrmergeChomp(
1.138908 +  Fts3Table *p,                   /* FTS table handle */
1.138909 +  sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
1.138910 +  Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
1.138911 +  int *pnRem                      /* Number of segments not deleted */
1.138912 +){
1.138913 +  int i;
1.138914 +  int nRem = 0;
1.138915 +  int rc = SQLITE_OK;
1.138916 +
1.138917 +  for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
1.138918 +    Fts3SegReader *pSeg = 0;
1.138919 +    int j;
1.138920 +
1.138921 +    /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
1.138922 +    ** somewhere in the pCsr->apSegment[] array.  */
1.138923 +    for(j=0; ALWAYS(j<pCsr->nSegment); j++){
1.138924 +      pSeg = pCsr->apSegment[j];
1.138925 +      if( pSeg->iIdx==i ) break;
1.138926 +    }
1.138927 +    assert( j<pCsr->nSegment && pSeg->iIdx==i );
1.138928 +
1.138929 +    if( pSeg->aNode==0 ){
1.138930 +      /* Seg-reader is at EOF. Remove the entire input segment. */
1.138931 +      rc = fts3DeleteSegment(p, pSeg);
1.138932 +      if( rc==SQLITE_OK ){
1.138933 +        rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
1.138934 +      }
1.138935 +      *pnRem = 0;
1.138936 +    }else{
1.138937 +      /* The incremental merge did not copy all the data from this 
1.138938 +      ** segment to the upper level. The segment is modified in place
1.138939 +      ** so that it contains no keys smaller than zTerm/nTerm. */ 
1.138940 +      const char *zTerm = pSeg->zTerm;
1.138941 +      int nTerm = pSeg->nTerm;
1.138942 +      rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
1.138943 +      nRem++;
1.138944 +    }
1.138945 +  }
1.138946 +
1.138947 +  if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
1.138948 +    rc = fts3RepackSegdirLevel(p, iAbsLevel);
1.138949 +  }
1.138950 +
1.138951 +  *pnRem = nRem;
1.138952 +  return rc;
1.138953 +}
1.138954 +
1.138955 +/*
1.138956 +** Store an incr-merge hint in the database.
1.138957 +*/
1.138958 +static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
1.138959 +  sqlite3_stmt *pReplace = 0;
1.138960 +  int rc;                         /* Return code */
1.138961 +
1.138962 +  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
1.138963 +  if( rc==SQLITE_OK ){
1.138964 +    sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
1.138965 +    sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
1.138966 +    sqlite3_step(pReplace);
1.138967 +    rc = sqlite3_reset(pReplace);
1.138968 +  }
1.138969 +
1.138970 +  return rc;
1.138971 +}
1.138972 +
1.138973 +/*
1.138974 +** Load an incr-merge hint from the database. The incr-merge hint, if one 
1.138975 +** exists, is stored in the rowid==1 row of the %_stat table.
1.138976 +**
1.138977 +** If successful, populate blob *pHint with the value read from the %_stat
1.138978 +** table and return SQLITE_OK. Otherwise, if an error occurs, return an
1.138979 +** SQLite error code.
1.138980 +*/
1.138981 +static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
1.138982 +  sqlite3_stmt *pSelect = 0;
1.138983 +  int rc;
1.138984 +
1.138985 +  pHint->n = 0;
1.138986 +  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
1.138987 +  if( rc==SQLITE_OK ){
1.138988 +    int rc2;
1.138989 +    sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
1.138990 +    if( SQLITE_ROW==sqlite3_step(pSelect) ){
1.138991 +      const char *aHint = sqlite3_column_blob(pSelect, 0);
1.138992 +      int nHint = sqlite3_column_bytes(pSelect, 0);
1.138993 +      if( aHint ){
1.138994 +        blobGrowBuffer(pHint, nHint, &rc);
1.138995 +        if( rc==SQLITE_OK ){
1.138996 +          memcpy(pHint->a, aHint, nHint);
1.138997 +          pHint->n = nHint;
1.138998 +        }
1.138999 +      }
1.139000 +    }
1.139001 +    rc2 = sqlite3_reset(pSelect);
1.139002 +    if( rc==SQLITE_OK ) rc = rc2;
1.139003 +  }
1.139004 +
1.139005 +  return rc;
1.139006 +}
1.139007 +
1.139008 +/*
1.139009 +** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
1.139010 +** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
1.139011 +** consists of two varints, the absolute level number of the input segments 
1.139012 +** and the number of input segments.
1.139013 +**
1.139014 +** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
1.139015 +** set *pRc to an SQLite error code before returning.
1.139016 +*/
1.139017 +static void fts3IncrmergeHintPush(
1.139018 +  Blob *pHint,                    /* Hint blob to append to */
1.139019 +  i64 iAbsLevel,                  /* First varint to store in hint */
1.139020 +  int nInput,                     /* Second varint to store in hint */
1.139021 +  int *pRc                        /* IN/OUT: Error code */
1.139022 +){
1.139023 +  blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
1.139024 +  if( *pRc==SQLITE_OK ){
1.139025 +    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
1.139026 +    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
1.139027 +  }
1.139028 +}
1.139029 +
1.139030 +/*
1.139031 +** Read the last entry (most recently pushed) from the hint blob *pHint
1.139032 +** and then remove the entry. Write the two values read to *piAbsLevel and 
1.139033 +** *pnInput before returning.
1.139034 +**
1.139035 +** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
1.139036 +** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
1.139037 +*/
1.139038 +static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
1.139039 +  const int nHint = pHint->n;
1.139040 +  int i;
1.139041 +
1.139042 +  i = pHint->n-2;
1.139043 +  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
1.139044 +  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
1.139045 +
1.139046 +  pHint->n = i;
1.139047 +  i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
1.139048 +  i += fts3GetVarint32(&pHint->a[i], pnInput);
1.139049 +  if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
1.139050 +
1.139051 +  return SQLITE_OK;
1.139052 +}
1.139053 +
1.139054 +
1.139055 +/*
1.139056 +** Attempt an incremental merge that writes nMerge leaf blocks.
1.139057 +**
1.139058 +** Incremental merges happen nMin segments at a time. The two
1.139059 +** segments to be merged are the nMin oldest segments (the ones with
1.139060 +** the smallest indexes) in the highest level that contains at least
1.139061 +** nMin segments. Multiple merges might occur in an attempt to write the 
1.139062 +** quota of nMerge leaf blocks.
1.139063 +*/
1.139064 +SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
1.139065 +  int rc;                         /* Return code */
1.139066 +  int nRem = nMerge;              /* Number of leaf pages yet to  be written */
1.139067 +  Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
1.139068 +  Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
1.139069 +  IncrmergeWriter *pWriter;       /* Writer object */
1.139070 +  int nSeg = 0;                   /* Number of input segments */
1.139071 +  sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
1.139072 +  Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
1.139073 +  int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
1.139074 +
1.139075 +  /* Allocate space for the cursor, filter and writer objects */
1.139076 +  const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
1.139077 +  pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
1.139078 +  if( !pWriter ) return SQLITE_NOMEM;
1.139079 +  pFilter = (Fts3SegFilter *)&pWriter[1];
1.139080 +  pCsr = (Fts3MultiSegReader *)&pFilter[1];
1.139081 +
1.139082 +  rc = fts3IncrmergeHintLoad(p, &hint);
1.139083 +  while( rc==SQLITE_OK && nRem>0 ){
1.139084 +    const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
1.139085 +    sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
1.139086 +    int bUseHint = 0;             /* True if attempting to append */
1.139087 +
1.139088 +    /* Search the %_segdir table for the absolute level with the smallest
1.139089 +    ** relative level number that contains at least nMin segments, if any.
1.139090 +    ** If one is found, set iAbsLevel to the absolute level number and
1.139091 +    ** nSeg to nMin. If no level with at least nMin segments can be found, 
1.139092 +    ** set nSeg to -1.
1.139093 +    */
1.139094 +    rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
1.139095 +    sqlite3_bind_int(pFindLevel, 1, nMin);
1.139096 +    if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
1.139097 +      iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
1.139098 +      nSeg = nMin;
1.139099 +    }else{
1.139100 +      nSeg = -1;
1.139101 +    }
1.139102 +    rc = sqlite3_reset(pFindLevel);
1.139103 +
1.139104 +    /* If the hint read from the %_stat table is not empty, check if the
1.139105 +    ** last entry in it specifies a relative level smaller than or equal
1.139106 +    ** to the level identified by the block above (if any). If so, this 
1.139107 +    ** iteration of the loop will work on merging at the hinted level.
1.139108 +    */
1.139109 +    if( rc==SQLITE_OK && hint.n ){
1.139110 +      int nHint = hint.n;
1.139111 +      sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
1.139112 +      int nHintSeg = 0;                     /* Hint number of segments */
1.139113 +
1.139114 +      rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
1.139115 +      if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
1.139116 +        iAbsLevel = iHintAbsLevel;
1.139117 +        nSeg = nHintSeg;
1.139118 +        bUseHint = 1;
1.139119 +        bDirtyHint = 1;
1.139120 +      }else{
1.139121 +        /* This undoes the effect of the HintPop() above - so that no entry
1.139122 +        ** is removed from the hint blob.  */
1.139123 +        hint.n = nHint;
1.139124 +      }
1.139125 +    }
1.139126 +
1.139127 +    /* If nSeg is less that zero, then there is no level with at least
1.139128 +    ** nMin segments and no hint in the %_stat table. No work to do.
1.139129 +    ** Exit early in this case.  */
1.139130 +    if( nSeg<0 ) break;
1.139131 +
1.139132 +    /* Open a cursor to iterate through the contents of the oldest nSeg 
1.139133 +    ** indexes of absolute level iAbsLevel. If this cursor is opened using 
1.139134 +    ** the 'hint' parameters, it is possible that there are less than nSeg
1.139135 +    ** segments available in level iAbsLevel. In this case, no work is
1.139136 +    ** done on iAbsLevel - fall through to the next iteration of the loop 
1.139137 +    ** to start work on some other level.  */
1.139138 +    memset(pWriter, 0, nAlloc);
1.139139 +    pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
1.139140 +    if( rc==SQLITE_OK ){
1.139141 +      rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
1.139142 +    }
1.139143 +    if( SQLITE_OK==rc && pCsr->nSegment==nSeg
1.139144 +     && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
1.139145 +     && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
1.139146 +    ){
1.139147 +      int iIdx = 0;               /* Largest idx in level (iAbsLevel+1) */
1.139148 +      rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
1.139149 +      if( rc==SQLITE_OK ){
1.139150 +        if( bUseHint && iIdx>0 ){
1.139151 +          const char *zKey = pCsr->zTerm;
1.139152 +          int nKey = pCsr->nTerm;
1.139153 +          rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
1.139154 +        }else{
1.139155 +          rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
1.139156 +        }
1.139157 +      }
1.139158 +
1.139159 +      if( rc==SQLITE_OK && pWriter->nLeafEst ){
1.139160 +        fts3LogMerge(nSeg, iAbsLevel);
1.139161 +        do {
1.139162 +          rc = fts3IncrmergeAppend(p, pWriter, pCsr);
1.139163 +          if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
1.139164 +          if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
1.139165 +        }while( rc==SQLITE_ROW );
1.139166 +
1.139167 +        /* Update or delete the input segments */
1.139168 +        if( rc==SQLITE_OK ){
1.139169 +          nRem -= (1 + pWriter->nWork);
1.139170 +          rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
1.139171 +          if( nSeg!=0 ){
1.139172 +            bDirtyHint = 1;
1.139173 +            fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
1.139174 +          }
1.139175 +        }
1.139176 +      }
1.139177 +
1.139178 +      fts3IncrmergeRelease(p, pWriter, &rc);
1.139179 +    }
1.139180 +
1.139181 +    sqlite3Fts3SegReaderFinish(pCsr);
1.139182 +  }
1.139183 +
1.139184 +  /* Write the hint values into the %_stat table for the next incr-merger */
1.139185 +  if( bDirtyHint && rc==SQLITE_OK ){
1.139186 +    rc = fts3IncrmergeHintStore(p, &hint);
1.139187 +  }
1.139188 +
1.139189 +  sqlite3_free(pWriter);
1.139190 +  sqlite3_free(hint.a);
1.139191 +  return rc;
1.139192 +}
1.139193 +
1.139194 +/*
1.139195 +** Convert the text beginning at *pz into an integer and return
1.139196 +** its value.  Advance *pz to point to the first character past
1.139197 +** the integer.
1.139198 +*/
1.139199 +static int fts3Getint(const char **pz){
1.139200 +  const char *z = *pz;
1.139201 +  int i = 0;
1.139202 +  while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
1.139203 +  *pz = z;
1.139204 +  return i;
1.139205 +}
1.139206 +
1.139207 +/*
1.139208 +** Process statements of the form:
1.139209 +**
1.139210 +**    INSERT INTO table(table) VALUES('merge=A,B');
1.139211 +**
1.139212 +** A and B are integers that decode to be the number of leaf pages
1.139213 +** written for the merge, and the minimum number of segments on a level
1.139214 +** before it will be selected for a merge, respectively.
1.139215 +*/
1.139216 +static int fts3DoIncrmerge(
1.139217 +  Fts3Table *p,                   /* FTS3 table handle */
1.139218 +  const char *zParam              /* Nul-terminated string containing "A,B" */
1.139219 +){
1.139220 +  int rc;
1.139221 +  int nMin = (FTS3_MERGE_COUNT / 2);
1.139222 +  int nMerge = 0;
1.139223 +  const char *z = zParam;
1.139224 +
1.139225 +  /* Read the first integer value */
1.139226 +  nMerge = fts3Getint(&z);
1.139227 +
1.139228 +  /* If the first integer value is followed by a ',',  read the second
1.139229 +  ** integer value. */
1.139230 +  if( z[0]==',' && z[1]!='\0' ){
1.139231 +    z++;
1.139232 +    nMin = fts3Getint(&z);
1.139233 +  }
1.139234 +
1.139235 +  if( z[0]!='\0' || nMin<2 ){
1.139236 +    rc = SQLITE_ERROR;
1.139237 +  }else{
1.139238 +    rc = SQLITE_OK;
1.139239 +    if( !p->bHasStat ){
1.139240 +      assert( p->bFts4==0 );
1.139241 +      sqlite3Fts3CreateStatTable(&rc, p);
1.139242 +    }
1.139243 +    if( rc==SQLITE_OK ){
1.139244 +      rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
1.139245 +    }
1.139246 +    sqlite3Fts3SegmentsClose(p);
1.139247 +  }
1.139248 +  return rc;
1.139249 +}
1.139250 +
1.139251 +/*
1.139252 +** Process statements of the form:
1.139253 +**
1.139254 +**    INSERT INTO table(table) VALUES('automerge=X');
1.139255 +**
1.139256 +** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
1.139257 +** turn it on.  The setting is persistent.
1.139258 +*/
1.139259 +static int fts3DoAutoincrmerge(
1.139260 +  Fts3Table *p,                   /* FTS3 table handle */
1.139261 +  const char *zParam              /* Nul-terminated string containing boolean */
1.139262 +){
1.139263 +  int rc = SQLITE_OK;
1.139264 +  sqlite3_stmt *pStmt = 0;
1.139265 +  p->bAutoincrmerge = fts3Getint(&zParam)!=0;
1.139266 +  if( !p->bHasStat ){
1.139267 +    assert( p->bFts4==0 );
1.139268 +    sqlite3Fts3CreateStatTable(&rc, p);
1.139269 +    if( rc ) return rc;
1.139270 +  }
1.139271 +  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
1.139272 +  if( rc ) return rc;
1.139273 +  sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
1.139274 +  sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);
1.139275 +  sqlite3_step(pStmt);
1.139276 +  rc = sqlite3_reset(pStmt);
1.139277 +  return rc;
1.139278 +}
1.139279 +
1.139280 +/*
1.139281 +** Return a 64-bit checksum for the FTS index entry specified by the
1.139282 +** arguments to this function.
1.139283 +*/
1.139284 +static u64 fts3ChecksumEntry(
1.139285 +  const char *zTerm,              /* Pointer to buffer containing term */
1.139286 +  int nTerm,                      /* Size of zTerm in bytes */
1.139287 +  int iLangid,                    /* Language id for current row */
1.139288 +  int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
1.139289 +  i64 iDocid,                     /* Docid for current row. */
1.139290 +  int iCol,                       /* Column number */
1.139291 +  int iPos                        /* Position */
1.139292 +){
1.139293 +  int i;
1.139294 +  u64 ret = (u64)iDocid;
1.139295 +
1.139296 +  ret += (ret<<3) + iLangid;
1.139297 +  ret += (ret<<3) + iIndex;
1.139298 +  ret += (ret<<3) + iCol;
1.139299 +  ret += (ret<<3) + iPos;
1.139300 +  for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
1.139301 +
1.139302 +  return ret;
1.139303 +}
1.139304 +
1.139305 +/*
1.139306 +** Return a checksum of all entries in the FTS index that correspond to
1.139307 +** language id iLangid. The checksum is calculated by XORing the checksums
1.139308 +** of each individual entry (see fts3ChecksumEntry()) together.
1.139309 +**
1.139310 +** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
1.139311 +** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
1.139312 +** return value is undefined in this case.
1.139313 +*/
1.139314 +static u64 fts3ChecksumIndex(
1.139315 +  Fts3Table *p,                   /* FTS3 table handle */
1.139316 +  int iLangid,                    /* Language id to return cksum for */
1.139317 +  int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
1.139318 +  int *pRc                        /* OUT: Return code */
1.139319 +){
1.139320 +  Fts3SegFilter filter;
1.139321 +  Fts3MultiSegReader csr;
1.139322 +  int rc;
1.139323 +  u64 cksum = 0;
1.139324 +
1.139325 +  assert( *pRc==SQLITE_OK );
1.139326 +
1.139327 +  memset(&filter, 0, sizeof(filter));
1.139328 +  memset(&csr, 0, sizeof(csr));
1.139329 +  filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
1.139330 +  filter.flags |= FTS3_SEGMENT_SCAN;
1.139331 +
1.139332 +  rc = sqlite3Fts3SegReaderCursor(
1.139333 +      p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
1.139334 +  );
1.139335 +  if( rc==SQLITE_OK ){
1.139336 +    rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
1.139337 +  }
1.139338 +
1.139339 +  if( rc==SQLITE_OK ){
1.139340 +    while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
1.139341 +      char *pCsr = csr.aDoclist;
1.139342 +      char *pEnd = &pCsr[csr.nDoclist];
1.139343 +
1.139344 +      i64 iDocid = 0;
1.139345 +      i64 iCol = 0;
1.139346 +      i64 iPos = 0;
1.139347 +
1.139348 +      pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
1.139349 +      while( pCsr<pEnd ){
1.139350 +        i64 iVal = 0;
1.139351 +        pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
1.139352 +        if( pCsr<pEnd ){
1.139353 +          if( iVal==0 || iVal==1 ){
1.139354 +            iCol = 0;
1.139355 +            iPos = 0;
1.139356 +            if( iVal ){
1.139357 +              pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
1.139358 +            }else{
1.139359 +              pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
1.139360 +              iDocid += iVal;
1.139361 +            }
1.139362 +          }else{
1.139363 +            iPos += (iVal - 2);
1.139364 +            cksum = cksum ^ fts3ChecksumEntry(
1.139365 +                csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
1.139366 +                (int)iCol, (int)iPos
1.139367 +            );
1.139368 +          }
1.139369 +        }
1.139370 +      }
1.139371 +    }
1.139372 +  }
1.139373 +  sqlite3Fts3SegReaderFinish(&csr);
1.139374 +
1.139375 +  *pRc = rc;
1.139376 +  return cksum;
1.139377 +}
1.139378 +
1.139379 +/*
1.139380 +** Check if the contents of the FTS index match the current contents of the
1.139381 +** content table. If no error occurs and the contents do match, set *pbOk
1.139382 +** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
1.139383 +** to false before returning.
1.139384 +**
1.139385 +** If an error occurs (e.g. an OOM or IO error), return an SQLite error 
1.139386 +** code. The final value of *pbOk is undefined in this case.
1.139387 +*/
1.139388 +static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
1.139389 +  int rc = SQLITE_OK;             /* Return code */
1.139390 +  u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
1.139391 +  u64 cksum2 = 0;                 /* Checksum based on %_content contents */
1.139392 +  sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
1.139393 +
1.139394 +  /* This block calculates the checksum according to the FTS index. */
1.139395 +  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
1.139396 +  if( rc==SQLITE_OK ){
1.139397 +    int rc2;
1.139398 +    sqlite3_bind_int(pAllLangid, 1, p->nIndex);
1.139399 +    while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
1.139400 +      int iLangid = sqlite3_column_int(pAllLangid, 0);
1.139401 +      int i;
1.139402 +      for(i=0; i<p->nIndex; i++){
1.139403 +        cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
1.139404 +      }
1.139405 +    }
1.139406 +    rc2 = sqlite3_reset(pAllLangid);
1.139407 +    if( rc==SQLITE_OK ) rc = rc2;
1.139408 +  }
1.139409 +
1.139410 +  /* This block calculates the checksum according to the %_content table */
1.139411 +  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
1.139412 +  if( rc==SQLITE_OK ){
1.139413 +    sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
1.139414 +    sqlite3_stmt *pStmt = 0;
1.139415 +    char *zSql;
1.139416 +   
1.139417 +    zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
1.139418 +    if( !zSql ){
1.139419 +      rc = SQLITE_NOMEM;
1.139420 +    }else{
1.139421 +      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
1.139422 +      sqlite3_free(zSql);
1.139423 +    }
1.139424 +
1.139425 +    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
1.139426 +      i64 iDocid = sqlite3_column_int64(pStmt, 0);
1.139427 +      int iLang = langidFromSelect(p, pStmt);
1.139428 +      int iCol;
1.139429 +
1.139430 +      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
1.139431 +        const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
1.139432 +        int nText = sqlite3_column_bytes(pStmt, iCol+1);
1.139433 +        sqlite3_tokenizer_cursor *pT = 0;
1.139434 +
1.139435 +        rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);
1.139436 +        while( rc==SQLITE_OK ){
1.139437 +          char const *zToken;       /* Buffer containing token */
1.139438 +          int nToken = 0;           /* Number of bytes in token */
1.139439 +          int iDum1 = 0, iDum2 = 0; /* Dummy variables */
1.139440 +          int iPos = 0;             /* Position of token in zText */
1.139441 +
1.139442 +          rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
1.139443 +          if( rc==SQLITE_OK ){
1.139444 +            int i;
1.139445 +            cksum2 = cksum2 ^ fts3ChecksumEntry(
1.139446 +                zToken, nToken, iLang, 0, iDocid, iCol, iPos
1.139447 +            );
1.139448 +            for(i=1; i<p->nIndex; i++){
1.139449 +              if( p->aIndex[i].nPrefix<=nToken ){
1.139450 +                cksum2 = cksum2 ^ fts3ChecksumEntry(
1.139451 +                  zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
1.139452 +                );
1.139453 +              }
1.139454 +            }
1.139455 +          }
1.139456 +        }
1.139457 +        if( pT ) pModule->xClose(pT);
1.139458 +        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
1.139459 +      }
1.139460 +    }
1.139461 +
1.139462 +    sqlite3_finalize(pStmt);
1.139463 +  }
1.139464 +
1.139465 +  *pbOk = (cksum1==cksum2);
1.139466 +  return rc;
1.139467 +}
1.139468 +
1.139469 +/*
1.139470 +** Run the integrity-check. If no error occurs and the current contents of
1.139471 +** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
1.139472 +** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
1.139473 +**
1.139474 +** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite 
1.139475 +** error code.
1.139476 +**
1.139477 +** The integrity-check works as follows. For each token and indexed token
1.139478 +** prefix in the document set, a 64-bit checksum is calculated (by code
1.139479 +** in fts3ChecksumEntry()) based on the following:
1.139480 +**
1.139481 +**     + The index number (0 for the main index, 1 for the first prefix
1.139482 +**       index etc.),
1.139483 +**     + The token (or token prefix) text itself, 
1.139484 +**     + The language-id of the row it appears in,
1.139485 +**     + The docid of the row it appears in,
1.139486 +**     + The column it appears in, and
1.139487 +**     + The tokens position within that column.
1.139488 +**
1.139489 +** The checksums for all entries in the index are XORed together to create
1.139490 +** a single checksum for the entire index.
1.139491 +**
1.139492 +** The integrity-check code calculates the same checksum in two ways:
1.139493 +**
1.139494 +**     1. By scanning the contents of the FTS index, and 
1.139495 +**     2. By scanning and tokenizing the content table.
1.139496 +**
1.139497 +** If the two checksums are identical, the integrity-check is deemed to have
1.139498 +** passed.
1.139499 +*/
1.139500 +static int fts3DoIntegrityCheck(
1.139501 +  Fts3Table *p                    /* FTS3 table handle */
1.139502 +){
1.139503 +  int rc;
1.139504 +  int bOk = 0;
1.139505 +  rc = fts3IntegrityCheck(p, &bOk);
1.139506 +  if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
1.139507 +  return rc;
1.139508 +}
1.139509 +
1.139510 +/*
1.139511 +** Handle a 'special' INSERT of the form:
1.139512 +**
1.139513 +**   "INSERT INTO tbl(tbl) VALUES(<expr>)"
1.139514 +**
1.139515 +** Argument pVal contains the result of <expr>. Currently the only 
1.139516 +** meaningful value to insert is the text 'optimize'.
1.139517 +*/
1.139518 +static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
1.139519 +  int rc;                         /* Return Code */
1.139520 +  const char *zVal = (const char *)sqlite3_value_text(pVal);
1.139521 +  int nVal = sqlite3_value_bytes(pVal);
1.139522 +
1.139523 +  if( !zVal ){
1.139524 +    return SQLITE_NOMEM;
1.139525 +  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
1.139526 +    rc = fts3DoOptimize(p, 0);
1.139527 +  }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
1.139528 +    rc = fts3DoRebuild(p);
1.139529 +  }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
1.139530 +    rc = fts3DoIntegrityCheck(p);
1.139531 +  }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
1.139532 +    rc = fts3DoIncrmerge(p, &zVal[6]);
1.139533 +  }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
1.139534 +    rc = fts3DoAutoincrmerge(p, &zVal[10]);
1.139535 +#ifdef SQLITE_TEST
1.139536 +  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
1.139537 +    p->nNodeSize = atoi(&zVal[9]);
1.139538 +    rc = SQLITE_OK;
1.139539 +  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
1.139540 +    p->nMaxPendingData = atoi(&zVal[11]);
1.139541 +    rc = SQLITE_OK;
1.139542 +  }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
1.139543 +    p->bNoIncrDoclist = atoi(&zVal[21]);
1.139544 +    rc = SQLITE_OK;
1.139545 +#endif
1.139546 +  }else{
1.139547 +    rc = SQLITE_ERROR;
1.139548 +  }
1.139549 +
1.139550 +  return rc;
1.139551 +}
1.139552 +
1.139553 +#ifndef SQLITE_DISABLE_FTS4_DEFERRED
1.139554 +/*
1.139555 +** Delete all cached deferred doclists. Deferred doclists are cached
1.139556 +** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
1.139557 +*/
1.139558 +SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
1.139559 +  Fts3DeferredToken *pDef;
1.139560 +  for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
1.139561 +    fts3PendingListDelete(pDef->pList);
1.139562 +    pDef->pList = 0;
1.139563 +  }
1.139564 +}
1.139565 +
1.139566 +/*
1.139567 +** Free all entries in the pCsr->pDeffered list. Entries are added to 
1.139568 +** this list using sqlite3Fts3DeferToken().
1.139569 +*/
1.139570 +SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
1.139571 +  Fts3DeferredToken *pDef;
1.139572 +  Fts3DeferredToken *pNext;
1.139573 +  for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
1.139574 +    pNext = pDef->pNext;
1.139575 +    fts3PendingListDelete(pDef->pList);
1.139576 +    sqlite3_free(pDef);
1.139577 +  }
1.139578 +  pCsr->pDeferred = 0;
1.139579 +}
1.139580 +
1.139581 +/*
1.139582 +** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
1.139583 +** based on the row that pCsr currently points to.
1.139584 +**
1.139585 +** A deferred-doclist is like any other doclist with position information
1.139586 +** included, except that it only contains entries for a single row of the
1.139587 +** table, not for all rows.
1.139588 +*/
1.139589 +SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
1.139590 +  int rc = SQLITE_OK;             /* Return code */
1.139591 +  if( pCsr->pDeferred ){
1.139592 +    int i;                        /* Used to iterate through table columns */
1.139593 +    sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
1.139594 +    Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
1.139595 +  
1.139596 +    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
1.139597 +    sqlite3_tokenizer *pT = p->pTokenizer;
1.139598 +    sqlite3_tokenizer_module const *pModule = pT->pModule;
1.139599 +   
1.139600 +    assert( pCsr->isRequireSeek==0 );
1.139601 +    iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
1.139602 +  
1.139603 +    for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
1.139604 +      if( p->abNotindexed[i]==0 ){
1.139605 +        const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
1.139606 +        sqlite3_tokenizer_cursor *pTC = 0;
1.139607 +
1.139608 +        rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
1.139609 +        while( rc==SQLITE_OK ){
1.139610 +          char const *zToken;       /* Buffer containing token */
1.139611 +          int nToken = 0;           /* Number of bytes in token */
1.139612 +          int iDum1 = 0, iDum2 = 0; /* Dummy variables */
1.139613 +          int iPos = 0;             /* Position of token in zText */
1.139614 +
1.139615 +          rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
1.139616 +          for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
1.139617 +            Fts3PhraseToken *pPT = pDef->pToken;
1.139618 +            if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
1.139619 +                && (pPT->bFirst==0 || iPos==0)
1.139620 +                && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
1.139621 +                && (0==memcmp(zToken, pPT->z, pPT->n))
1.139622 +              ){
1.139623 +              fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
1.139624 +            }
1.139625 +          }
1.139626 +        }
1.139627 +        if( pTC ) pModule->xClose(pTC);
1.139628 +        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
1.139629 +      }
1.139630 +    }
1.139631 +
1.139632 +    for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
1.139633 +      if( pDef->pList ){
1.139634 +        rc = fts3PendingListAppendVarint(&pDef->pList, 0);
1.139635 +      }
1.139636 +    }
1.139637 +  }
1.139638 +
1.139639 +  return rc;
1.139640 +}
1.139641 +
1.139642 +SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
1.139643 +  Fts3DeferredToken *p, 
1.139644 +  char **ppData, 
1.139645 +  int *pnData
1.139646 +){
1.139647 +  char *pRet;
1.139648 +  int nSkip;
1.139649 +  sqlite3_int64 dummy;
1.139650 +
1.139651 +  *ppData = 0;
1.139652 +  *pnData = 0;
1.139653 +
1.139654 +  if( p->pList==0 ){
1.139655 +    return SQLITE_OK;
1.139656 +  }
1.139657 +
1.139658 +  pRet = (char *)sqlite3_malloc(p->pList->nData);
1.139659 +  if( !pRet ) return SQLITE_NOMEM;
1.139660 +
1.139661 +  nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
1.139662 +  *pnData = p->pList->nData - nSkip;
1.139663 +  *ppData = pRet;
1.139664 +  
1.139665 +  memcpy(pRet, &p->pList->aData[nSkip], *pnData);
1.139666 +  return SQLITE_OK;
1.139667 +}
1.139668 +
1.139669 +/*
1.139670 +** Add an entry for token pToken to the pCsr->pDeferred list.
1.139671 +*/
1.139672 +SQLITE_PRIVATE int sqlite3Fts3DeferToken(
1.139673 +  Fts3Cursor *pCsr,               /* Fts3 table cursor */
1.139674 +  Fts3PhraseToken *pToken,        /* Token to defer */
1.139675 +  int iCol                        /* Column that token must appear in (or -1) */
1.139676 +){
1.139677 +  Fts3DeferredToken *pDeferred;
1.139678 +  pDeferred = sqlite3_malloc(sizeof(*pDeferred));
1.139679 +  if( !pDeferred ){
1.139680 +    return SQLITE_NOMEM;
1.139681 +  }
1.139682 +  memset(pDeferred, 0, sizeof(*pDeferred));
1.139683 +  pDeferred->pToken = pToken;
1.139684 +  pDeferred->pNext = pCsr->pDeferred; 
1.139685 +  pDeferred->iCol = iCol;
1.139686 +  pCsr->pDeferred = pDeferred;
1.139687 +
1.139688 +  assert( pToken->pDeferred==0 );
1.139689 +  pToken->pDeferred = pDeferred;
1.139690 +
1.139691 +  return SQLITE_OK;
1.139692 +}
1.139693 +#endif
1.139694 +
1.139695 +/*
1.139696 +** SQLite value pRowid contains the rowid of a row that may or may not be
1.139697 +** present in the FTS3 table. If it is, delete it and adjust the contents
1.139698 +** of subsiduary data structures accordingly.
1.139699 +*/
1.139700 +static int fts3DeleteByRowid(
1.139701 +  Fts3Table *p, 
1.139702 +  sqlite3_value *pRowid, 
1.139703 +  int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
1.139704 +  u32 *aSzDel
1.139705 +){
1.139706 +  int rc = SQLITE_OK;             /* Return code */
1.139707 +  int bFound = 0;                 /* True if *pRowid really is in the table */
1.139708 +
1.139709 +  fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
1.139710 +  if( bFound && rc==SQLITE_OK ){
1.139711 +    int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
1.139712 +    rc = fts3IsEmpty(p, pRowid, &isEmpty);
1.139713 +    if( rc==SQLITE_OK ){
1.139714 +      if( isEmpty ){
1.139715 +        /* Deleting this row means the whole table is empty. In this case
1.139716 +        ** delete the contents of all three tables and throw away any
1.139717 +        ** data in the pendingTerms hash table.  */
1.139718 +        rc = fts3DeleteAll(p, 1);
1.139719 +        *pnChng = 0;
1.139720 +        memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
1.139721 +      }else{
1.139722 +        *pnChng = *pnChng - 1;
1.139723 +        if( p->zContentTbl==0 ){
1.139724 +          fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
1.139725 +        }
1.139726 +        if( p->bHasDocsize ){
1.139727 +          fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
1.139728 +        }
1.139729 +      }
1.139730 +    }
1.139731 +  }
1.139732 +
1.139733 +  return rc;
1.139734 +}
1.139735 +
1.139736 +/*
1.139737 +** This function does the work for the xUpdate method of FTS3 virtual
1.139738 +** tables. The schema of the virtual table being:
1.139739 +**
1.139740 +**     CREATE TABLE <table name>( 
1.139741 +**       <user columns>,
1.139742 +**       <table name> HIDDEN, 
1.139743 +**       docid HIDDEN, 
1.139744 +**       <langid> HIDDEN
1.139745 +**     );
1.139746 +**
1.139747 +** 
1.139748 +*/
1.139749 +SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
1.139750 +  sqlite3_vtab *pVtab,            /* FTS3 vtab object */
1.139751 +  int nArg,                       /* Size of argument array */
1.139752 +  sqlite3_value **apVal,          /* Array of arguments */
1.139753 +  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
1.139754 +){
1.139755 +  Fts3Table *p = (Fts3Table *)pVtab;
1.139756 +  int rc = SQLITE_OK;             /* Return Code */
1.139757 +  int isRemove = 0;               /* True for an UPDATE or DELETE */
1.139758 +  u32 *aSzIns = 0;                /* Sizes of inserted documents */
1.139759 +  u32 *aSzDel = 0;                /* Sizes of deleted documents */
1.139760 +  int nChng = 0;                  /* Net change in number of documents */
1.139761 +  int bInsertDone = 0;
1.139762 +
1.139763 +  assert( p->pSegments==0 );
1.139764 +  assert( 
1.139765 +      nArg==1                     /* DELETE operations */
1.139766 +   || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
1.139767 +  );
1.139768 +
1.139769 +  /* Check for a "special" INSERT operation. One of the form:
1.139770 +  **
1.139771 +  **   INSERT INTO xyz(xyz) VALUES('command');
1.139772 +  */
1.139773 +  if( nArg>1 
1.139774 +   && sqlite3_value_type(apVal[0])==SQLITE_NULL 
1.139775 +   && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL 
1.139776 +  ){
1.139777 +    rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
1.139778 +    goto update_out;
1.139779 +  }
1.139780 +
1.139781 +  if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
1.139782 +    rc = SQLITE_CONSTRAINT;
1.139783 +    goto update_out;
1.139784 +  }
1.139785 +
1.139786 +  /* Allocate space to hold the change in document sizes */
1.139787 +  aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
1.139788 +  if( aSzDel==0 ){
1.139789 +    rc = SQLITE_NOMEM;
1.139790 +    goto update_out;
1.139791 +  }
1.139792 +  aSzIns = &aSzDel[p->nColumn+1];
1.139793 +  memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
1.139794 +
1.139795 +  rc = fts3Writelock(p);
1.139796 +  if( rc!=SQLITE_OK ) goto update_out;
1.139797 +
1.139798 +  /* If this is an INSERT operation, or an UPDATE that modifies the rowid
1.139799 +  ** value, then this operation requires constraint handling.
1.139800 +  **
1.139801 +  ** If the on-conflict mode is REPLACE, this means that the existing row
1.139802 +  ** should be deleted from the database before inserting the new row. Or,
1.139803 +  ** if the on-conflict mode is other than REPLACE, then this method must
1.139804 +  ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
1.139805 +  ** modify the database file.
1.139806 +  */
1.139807 +  if( nArg>1 && p->zContentTbl==0 ){
1.139808 +    /* Find the value object that holds the new rowid value. */
1.139809 +    sqlite3_value *pNewRowid = apVal[3+p->nColumn];
1.139810 +    if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
1.139811 +      pNewRowid = apVal[1];
1.139812 +    }
1.139813 +
1.139814 +    if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( 
1.139815 +        sqlite3_value_type(apVal[0])==SQLITE_NULL
1.139816 +     || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
1.139817 +    )){
1.139818 +      /* The new rowid is not NULL (in this case the rowid will be
1.139819 +      ** automatically assigned and there is no chance of a conflict), and 
1.139820 +      ** the statement is either an INSERT or an UPDATE that modifies the
1.139821 +      ** rowid column. So if the conflict mode is REPLACE, then delete any
1.139822 +      ** existing row with rowid=pNewRowid. 
1.139823 +      **
1.139824 +      ** Or, if the conflict mode is not REPLACE, insert the new record into 
1.139825 +      ** the %_content table. If we hit the duplicate rowid constraint (or any
1.139826 +      ** other error) while doing so, return immediately.
1.139827 +      **
1.139828 +      ** This branch may also run if pNewRowid contains a value that cannot
1.139829 +      ** be losslessly converted to an integer. In this case, the eventual 
1.139830 +      ** call to fts3InsertData() (either just below or further on in this
1.139831 +      ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is 
1.139832 +      ** invoked, it will delete zero rows (since no row will have
1.139833 +      ** docid=$pNewRowid if $pNewRowid is not an integer value).
1.139834 +      */
1.139835 +      if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
1.139836 +        rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
1.139837 +      }else{
1.139838 +        rc = fts3InsertData(p, apVal, pRowid);
1.139839 +        bInsertDone = 1;
1.139840 +      }
1.139841 +    }
1.139842 +  }
1.139843 +  if( rc!=SQLITE_OK ){
1.139844 +    goto update_out;
1.139845 +  }
1.139846 +
1.139847 +  /* If this is a DELETE or UPDATE operation, remove the old record. */
1.139848 +  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
1.139849 +    assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
1.139850 +    rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
1.139851 +    isRemove = 1;
1.139852 +  }
1.139853 +  
1.139854 +  /* If this is an INSERT or UPDATE operation, insert the new record. */
1.139855 +  if( nArg>1 && rc==SQLITE_OK ){
1.139856 +    int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
1.139857 +    if( bInsertDone==0 ){
1.139858 +      rc = fts3InsertData(p, apVal, pRowid);
1.139859 +      if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
1.139860 +        rc = FTS_CORRUPT_VTAB;
1.139861 +      }
1.139862 +    }
1.139863 +    if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
1.139864 +      rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
1.139865 +    }
1.139866 +    if( rc==SQLITE_OK ){
1.139867 +      assert( p->iPrevDocid==*pRowid );
1.139868 +      rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
1.139869 +    }
1.139870 +    if( p->bHasDocsize ){
1.139871 +      fts3InsertDocsize(&rc, p, aSzIns);
1.139872 +    }
1.139873 +    nChng++;
1.139874 +  }
1.139875 +
1.139876 +  if( p->bFts4 ){
1.139877 +    fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
1.139878 +  }
1.139879 +
1.139880 + update_out:
1.139881 +  sqlite3_free(aSzDel);
1.139882 +  sqlite3Fts3SegmentsClose(p);
1.139883 +  return rc;
1.139884 +}
1.139885 +
1.139886 +/* 
1.139887 +** Flush any data in the pending-terms hash table to disk. If successful,
1.139888 +** merge all segments in the database (including the new segment, if 
1.139889 +** there was any data to flush) into a single segment. 
1.139890 +*/
1.139891 +SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
1.139892 +  int rc;
1.139893 +  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
1.139894 +  if( rc==SQLITE_OK ){
1.139895 +    rc = fts3DoOptimize(p, 1);
1.139896 +    if( rc==SQLITE_OK || rc==SQLITE_DONE ){
1.139897 +      int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
1.139898 +      if( rc2!=SQLITE_OK ) rc = rc2;
1.139899 +    }else{
1.139900 +      sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
1.139901 +      sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
1.139902 +    }
1.139903 +  }
1.139904 +  sqlite3Fts3SegmentsClose(p);
1.139905 +  return rc;
1.139906 +}
1.139907 +
1.139908 +#endif
1.139909 +
1.139910 +/************** End of fts3_write.c ******************************************/
1.139911 +/************** Begin file fts3_snippet.c ************************************/
1.139912 +/*
1.139913 +** 2009 Oct 23
1.139914 +**
1.139915 +** The author disclaims copyright to this source code.  In place of
1.139916 +** a legal notice, here is a blessing:
1.139917 +**
1.139918 +**    May you do good and not evil.
1.139919 +**    May you find forgiveness for yourself and forgive others.
1.139920 +**    May you share freely, never taking more than you give.
1.139921 +**
1.139922 +******************************************************************************
1.139923 +*/
1.139924 +
1.139925 +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
1.139926 +
1.139927 +/* #include <string.h> */
1.139928 +/* #include <assert.h> */
1.139929 +
1.139930 +/*
1.139931 +** Characters that may appear in the second argument to matchinfo().
1.139932 +*/
1.139933 +#define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
1.139934 +#define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
1.139935 +#define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
1.139936 +#define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
1.139937 +#define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
1.139938 +#define FTS3_MATCHINFO_LCS       's'        /* nCol values */
1.139939 +#define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
1.139940 +
1.139941 +/*
1.139942 +** The default value for the second argument to matchinfo(). 
1.139943 +*/
1.139944 +#define FTS3_MATCHINFO_DEFAULT   "pcx"
1.139945 +
1.139946 +
1.139947 +/*
1.139948 +** Used as an fts3ExprIterate() context when loading phrase doclists to
1.139949 +** Fts3Expr.aDoclist[]/nDoclist.
1.139950 +*/
1.139951 +typedef struct LoadDoclistCtx LoadDoclistCtx;
1.139952 +struct LoadDoclistCtx {
1.139953 +  Fts3Cursor *pCsr;               /* FTS3 Cursor */
1.139954 +  int nPhrase;                    /* Number of phrases seen so far */
1.139955 +  int nToken;                     /* Number of tokens seen so far */
1.139956 +};
1.139957 +
1.139958 +/*
1.139959 +** The following types are used as part of the implementation of the 
1.139960 +** fts3BestSnippet() routine.
1.139961 +*/
1.139962 +typedef struct SnippetIter SnippetIter;
1.139963 +typedef struct SnippetPhrase SnippetPhrase;
1.139964 +typedef struct SnippetFragment SnippetFragment;
1.139965 +
1.139966 +struct SnippetIter {
1.139967 +  Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
1.139968 +  int iCol;                       /* Extract snippet from this column */
1.139969 +  int nSnippet;                   /* Requested snippet length (in tokens) */
1.139970 +  int nPhrase;                    /* Number of phrases in query */
1.139971 +  SnippetPhrase *aPhrase;         /* Array of size nPhrase */
1.139972 +  int iCurrent;                   /* First token of current snippet */
1.139973 +};
1.139974 +
1.139975 +struct SnippetPhrase {
1.139976 +  int nToken;                     /* Number of tokens in phrase */
1.139977 +  char *pList;                    /* Pointer to start of phrase position list */
1.139978 +  int iHead;                      /* Next value in position list */
1.139979 +  char *pHead;                    /* Position list data following iHead */
1.139980 +  int iTail;                      /* Next value in trailing position list */
1.139981 +  char *pTail;                    /* Position list data following iTail */
1.139982 +};
1.139983 +
1.139984 +struct SnippetFragment {
1.139985 +  int iCol;                       /* Column snippet is extracted from */
1.139986 +  int iPos;                       /* Index of first token in snippet */
1.139987 +  u64 covered;                    /* Mask of query phrases covered */
1.139988 +  u64 hlmask;                     /* Mask of snippet terms to highlight */
1.139989 +};
1.139990 +
1.139991 +/*
1.139992 +** This type is used as an fts3ExprIterate() context object while 
1.139993 +** accumulating the data returned by the matchinfo() function.
1.139994 +*/
1.139995 +typedef struct MatchInfo MatchInfo;
1.139996 +struct MatchInfo {
1.139997 +  Fts3Cursor *pCursor;            /* FTS3 Cursor */
1.139998 +  int nCol;                       /* Number of columns in table */
1.139999 +  int nPhrase;                    /* Number of matchable phrases in query */
1.140000 +  sqlite3_int64 nDoc;             /* Number of docs in database */
1.140001 +  u32 *aMatchinfo;                /* Pre-allocated buffer */
1.140002 +};
1.140003 +
1.140004 +
1.140005 +
1.140006 +/*
1.140007 +** The snippet() and offsets() functions both return text values. An instance
1.140008 +** of the following structure is used to accumulate those values while the
1.140009 +** functions are running. See fts3StringAppend() for details.
1.140010 +*/
1.140011 +typedef struct StrBuffer StrBuffer;
1.140012 +struct StrBuffer {
1.140013 +  char *z;                        /* Pointer to buffer containing string */
1.140014 +  int n;                          /* Length of z in bytes (excl. nul-term) */
1.140015 +  int nAlloc;                     /* Allocated size of buffer z in bytes */
1.140016 +};
1.140017 +
1.140018 +
1.140019 +/*
1.140020 +** This function is used to help iterate through a position-list. A position
1.140021 +** list is a list of unique integers, sorted from smallest to largest. Each
1.140022 +** element of the list is represented by an FTS3 varint that takes the value
1.140023 +** of the difference between the current element and the previous one plus
1.140024 +** two. For example, to store the position-list:
1.140025 +**
1.140026 +**     4 9 113
1.140027 +**
1.140028 +** the three varints:
1.140029 +**
1.140030 +**     6 7 106
1.140031 +**
1.140032 +** are encoded.
1.140033 +**
1.140034 +** When this function is called, *pp points to the start of an element of
1.140035 +** the list. *piPos contains the value of the previous entry in the list.
1.140036 +** After it returns, *piPos contains the value of the next element of the
1.140037 +** list and *pp is advanced to the following varint.
1.140038 +*/
1.140039 +static void fts3GetDeltaPosition(char **pp, int *piPos){
1.140040 +  int iVal;
1.140041 +  *pp += fts3GetVarint32(*pp, &iVal);
1.140042 +  *piPos += (iVal-2);
1.140043 +}
1.140044 +
1.140045 +/*
1.140046 +** Helper function for fts3ExprIterate() (see below).
1.140047 +*/
1.140048 +static int fts3ExprIterate2(
1.140049 +  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
1.140050 +  int *piPhrase,                  /* Pointer to phrase counter */
1.140051 +  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
1.140052 +  void *pCtx                      /* Second argument to pass to callback */
1.140053 +){
1.140054 +  int rc;                         /* Return code */
1.140055 +  int eType = pExpr->eType;       /* Type of expression node pExpr */
1.140056 +
1.140057 +  if( eType!=FTSQUERY_PHRASE ){
1.140058 +    assert( pExpr->pLeft && pExpr->pRight );
1.140059 +    rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
1.140060 +    if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
1.140061 +      rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
1.140062 +    }
1.140063 +  }else{
1.140064 +    rc = x(pExpr, *piPhrase, pCtx);
1.140065 +    (*piPhrase)++;
1.140066 +  }
1.140067 +  return rc;
1.140068 +}
1.140069 +
1.140070 +/*
1.140071 +** Iterate through all phrase nodes in an FTS3 query, except those that
1.140072 +** are part of a sub-tree that is the right-hand-side of a NOT operator.
1.140073 +** For each phrase node found, the supplied callback function is invoked.
1.140074 +**
1.140075 +** If the callback function returns anything other than SQLITE_OK, 
1.140076 +** the iteration is abandoned and the error code returned immediately.
1.140077 +** Otherwise, SQLITE_OK is returned after a callback has been made for
1.140078 +** all eligible phrase nodes.
1.140079 +*/
1.140080 +static int fts3ExprIterate(
1.140081 +  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
1.140082 +  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
1.140083 +  void *pCtx                      /* Second argument to pass to callback */
1.140084 +){
1.140085 +  int iPhrase = 0;                /* Variable used as the phrase counter */
1.140086 +  return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
1.140087 +}
1.140088 +
1.140089 +/*
1.140090 +** This is an fts3ExprIterate() callback used while loading the doclists
1.140091 +** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
1.140092 +** fts3ExprLoadDoclists().
1.140093 +*/
1.140094 +static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
1.140095 +  int rc = SQLITE_OK;
1.140096 +  Fts3Phrase *pPhrase = pExpr->pPhrase;
1.140097 +  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
1.140098 +
1.140099 +  UNUSED_PARAMETER(iPhrase);
1.140100 +
1.140101 +  p->nPhrase++;
1.140102 +  p->nToken += pPhrase->nToken;
1.140103 +
1.140104 +  return rc;
1.140105 +}
1.140106 +
1.140107 +/*
1.140108 +** Load the doclists for each phrase in the query associated with FTS3 cursor
1.140109 +** pCsr. 
1.140110 +**
1.140111 +** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
1.140112 +** phrases in the expression (all phrases except those directly or 
1.140113 +** indirectly descended from the right-hand-side of a NOT operator). If 
1.140114 +** pnToken is not NULL, then it is set to the number of tokens in all
1.140115 +** matchable phrases of the expression.
1.140116 +*/
1.140117 +static int fts3ExprLoadDoclists(
1.140118 +  Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
1.140119 +  int *pnPhrase,                  /* OUT: Number of phrases in query */
1.140120 +  int *pnToken                    /* OUT: Number of tokens in query */
1.140121 +){
1.140122 +  int rc;                         /* Return Code */
1.140123 +  LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
1.140124 +  sCtx.pCsr = pCsr;
1.140125 +  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
1.140126 +  if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
1.140127 +  if( pnToken ) *pnToken = sCtx.nToken;
1.140128 +  return rc;
1.140129 +}
1.140130 +
1.140131 +static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
1.140132 +  (*(int *)ctx)++;
1.140133 +  UNUSED_PARAMETER(pExpr);
1.140134 +  UNUSED_PARAMETER(iPhrase);
1.140135 +  return SQLITE_OK;
1.140136 +}
1.140137 +static int fts3ExprPhraseCount(Fts3Expr *pExpr){
1.140138 +  int nPhrase = 0;
1.140139 +  (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
1.140140 +  return nPhrase;
1.140141 +}
1.140142 +
1.140143 +/*
1.140144 +** Advance the position list iterator specified by the first two 
1.140145 +** arguments so that it points to the first element with a value greater
1.140146 +** than or equal to parameter iNext.
1.140147 +*/
1.140148 +static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
1.140149 +  char *pIter = *ppIter;
1.140150 +  if( pIter ){
1.140151 +    int iIter = *piIter;
1.140152 +
1.140153 +    while( iIter<iNext ){
1.140154 +      if( 0==(*pIter & 0xFE) ){
1.140155 +        iIter = -1;
1.140156 +        pIter = 0;
1.140157 +        break;
1.140158 +      }
1.140159 +      fts3GetDeltaPosition(&pIter, &iIter);
1.140160 +    }
1.140161 +
1.140162 +    *piIter = iIter;
1.140163 +    *ppIter = pIter;
1.140164 +  }
1.140165 +}
1.140166 +
1.140167 +/*
1.140168 +** Advance the snippet iterator to the next candidate snippet.
1.140169 +*/
1.140170 +static int fts3SnippetNextCandidate(SnippetIter *pIter){
1.140171 +  int i;                          /* Loop counter */
1.140172 +
1.140173 +  if( pIter->iCurrent<0 ){
1.140174 +    /* The SnippetIter object has just been initialized. The first snippet
1.140175 +    ** candidate always starts at offset 0 (even if this candidate has a
1.140176 +    ** score of 0.0).
1.140177 +    */
1.140178 +    pIter->iCurrent = 0;
1.140179 +
1.140180 +    /* Advance the 'head' iterator of each phrase to the first offset that
1.140181 +    ** is greater than or equal to (iNext+nSnippet).
1.140182 +    */
1.140183 +    for(i=0; i<pIter->nPhrase; i++){
1.140184 +      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
1.140185 +      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
1.140186 +    }
1.140187 +  }else{
1.140188 +    int iStart;
1.140189 +    int iEnd = 0x7FFFFFFF;
1.140190 +
1.140191 +    for(i=0; i<pIter->nPhrase; i++){
1.140192 +      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
1.140193 +      if( pPhrase->pHead && pPhrase->iHead<iEnd ){
1.140194 +        iEnd = pPhrase->iHead;
1.140195 +      }
1.140196 +    }
1.140197 +    if( iEnd==0x7FFFFFFF ){
1.140198 +      return 1;
1.140199 +    }
1.140200 +
1.140201 +    pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
1.140202 +    for(i=0; i<pIter->nPhrase; i++){
1.140203 +      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
1.140204 +      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
1.140205 +      fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
1.140206 +    }
1.140207 +  }
1.140208 +
1.140209 +  return 0;
1.140210 +}
1.140211 +
1.140212 +/*
1.140213 +** Retrieve information about the current candidate snippet of snippet 
1.140214 +** iterator pIter.
1.140215 +*/
1.140216 +static void fts3SnippetDetails(
1.140217 +  SnippetIter *pIter,             /* Snippet iterator */
1.140218 +  u64 mCovered,                   /* Bitmask of phrases already covered */
1.140219 +  int *piToken,                   /* OUT: First token of proposed snippet */
1.140220 +  int *piScore,                   /* OUT: "Score" for this snippet */
1.140221 +  u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
1.140222 +  u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
1.140223 +){
1.140224 +  int iStart = pIter->iCurrent;   /* First token of snippet */
1.140225 +  int iScore = 0;                 /* Score of this snippet */
1.140226 +  int i;                          /* Loop counter */
1.140227 +  u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
1.140228 +  u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
1.140229 +
1.140230 +  for(i=0; i<pIter->nPhrase; i++){
1.140231 +    SnippetPhrase *pPhrase = &pIter->aPhrase[i];
1.140232 +    if( pPhrase->pTail ){
1.140233 +      char *pCsr = pPhrase->pTail;
1.140234 +      int iCsr = pPhrase->iTail;
1.140235 +
1.140236 +      while( iCsr<(iStart+pIter->nSnippet) ){
1.140237 +        int j;
1.140238 +        u64 mPhrase = (u64)1 << i;
1.140239 +        u64 mPos = (u64)1 << (iCsr - iStart);
1.140240 +        assert( iCsr>=iStart );
1.140241 +        if( (mCover|mCovered)&mPhrase ){
1.140242 +          iScore++;
1.140243 +        }else{
1.140244 +          iScore += 1000;
1.140245 +        }
1.140246 +        mCover |= mPhrase;
1.140247 +
1.140248 +        for(j=0; j<pPhrase->nToken; j++){
1.140249 +          mHighlight |= (mPos>>j);
1.140250 +        }
1.140251 +
1.140252 +        if( 0==(*pCsr & 0x0FE) ) break;
1.140253 +        fts3GetDeltaPosition(&pCsr, &iCsr);
1.140254 +      }
1.140255 +    }
1.140256 +  }
1.140257 +
1.140258 +  /* Set the output variables before returning. */
1.140259 +  *piToken = iStart;
1.140260 +  *piScore = iScore;
1.140261 +  *pmCover = mCover;
1.140262 +  *pmHighlight = mHighlight;
1.140263 +}
1.140264 +
1.140265 +/*
1.140266 +** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
1.140267 +** Each invocation populates an element of the SnippetIter.aPhrase[] array.
1.140268 +*/
1.140269 +static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
1.140270 +  SnippetIter *p = (SnippetIter *)ctx;
1.140271 +  SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
1.140272 +  char *pCsr;
1.140273 +  int rc;
1.140274 +
1.140275 +  pPhrase->nToken = pExpr->pPhrase->nToken;
1.140276 +  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
1.140277 +  assert( rc==SQLITE_OK || pCsr==0 );
1.140278 +  if( pCsr ){
1.140279 +    int iFirst = 0;
1.140280 +    pPhrase->pList = pCsr;
1.140281 +    fts3GetDeltaPosition(&pCsr, &iFirst);
1.140282 +    assert( iFirst>=0 );
1.140283 +    pPhrase->pHead = pCsr;
1.140284 +    pPhrase->pTail = pCsr;
1.140285 +    pPhrase->iHead = iFirst;
1.140286 +    pPhrase->iTail = iFirst;
1.140287 +  }else{
1.140288 +    assert( rc!=SQLITE_OK || (
1.140289 +       pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 
1.140290 +    ));
1.140291 +  }
1.140292 +
1.140293 +  return rc;
1.140294 +}
1.140295 +
1.140296 +/*
1.140297 +** Select the fragment of text consisting of nFragment contiguous tokens 
1.140298 +** from column iCol that represent the "best" snippet. The best snippet
1.140299 +** is the snippet with the highest score, where scores are calculated
1.140300 +** by adding:
1.140301 +**
1.140302 +**   (a) +1 point for each occurrence of a matchable phrase in the snippet.
1.140303 +**
1.140304 +**   (b) +1000 points for the first occurrence of each matchable phrase in 
1.140305 +**       the snippet for which the corresponding mCovered bit is not set.
1.140306 +**
1.140307 +** The selected snippet parameters are stored in structure *pFragment before
1.140308 +** returning. The score of the selected snippet is stored in *piScore
1.140309 +** before returning.
1.140310 +*/
1.140311 +static int fts3BestSnippet(
1.140312 +  int nSnippet,                   /* Desired snippet length */
1.140313 +  Fts3Cursor *pCsr,               /* Cursor to create snippet for */
1.140314 +  int iCol,                       /* Index of column to create snippet from */
1.140315 +  u64 mCovered,                   /* Mask of phrases already covered */
1.140316 +  u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
1.140317 +  SnippetFragment *pFragment,     /* OUT: Best snippet found */
1.140318 +  int *piScore                    /* OUT: Score of snippet pFragment */
1.140319 +){
1.140320 +  int rc;                         /* Return Code */
1.140321 +  int nList;                      /* Number of phrases in expression */
1.140322 +  SnippetIter sIter;              /* Iterates through snippet candidates */
1.140323 +  int nByte;                      /* Number of bytes of space to allocate */
1.140324 +  int iBestScore = -1;            /* Best snippet score found so far */
1.140325 +  int i;                          /* Loop counter */
1.140326 +
1.140327 +  memset(&sIter, 0, sizeof(sIter));
1.140328 +
1.140329 +  /* Iterate through the phrases in the expression to count them. The same
1.140330 +  ** callback makes sure the doclists are loaded for each phrase.
1.140331 +  */
1.140332 +  rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
1.140333 +  if( rc!=SQLITE_OK ){
1.140334 +    return rc;
1.140335 +  }
1.140336 +
1.140337 +  /* Now that it is known how many phrases there are, allocate and zero
1.140338 +  ** the required space using malloc().
1.140339 +  */
1.140340 +  nByte = sizeof(SnippetPhrase) * nList;
1.140341 +  sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
1.140342 +  if( !sIter.aPhrase ){
1.140343 +    return SQLITE_NOMEM;
1.140344 +  }
1.140345 +  memset(sIter.aPhrase, 0, nByte);
1.140346 +
1.140347 +  /* Initialize the contents of the SnippetIter object. Then iterate through
1.140348 +  ** the set of phrases in the expression to populate the aPhrase[] array.
1.140349 +  */
1.140350 +  sIter.pCsr = pCsr;
1.140351 +  sIter.iCol = iCol;
1.140352 +  sIter.nSnippet = nSnippet;
1.140353 +  sIter.nPhrase = nList;
1.140354 +  sIter.iCurrent = -1;
1.140355 +  (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
1.140356 +
1.140357 +  /* Set the *pmSeen output variable. */
1.140358 +  for(i=0; i<nList; i++){
1.140359 +    if( sIter.aPhrase[i].pHead ){
1.140360 +      *pmSeen |= (u64)1 << i;
1.140361 +    }
1.140362 +  }
1.140363 +
1.140364 +  /* Loop through all candidate snippets. Store the best snippet in 
1.140365 +  ** *pFragment. Store its associated 'score' in iBestScore.
1.140366 +  */
1.140367 +  pFragment->iCol = iCol;
1.140368 +  while( !fts3SnippetNextCandidate(&sIter) ){
1.140369 +    int iPos;
1.140370 +    int iScore;
1.140371 +    u64 mCover;
1.140372 +    u64 mHighlight;
1.140373 +    fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
1.140374 +    assert( iScore>=0 );
1.140375 +    if( iScore>iBestScore ){
1.140376 +      pFragment->iPos = iPos;
1.140377 +      pFragment->hlmask = mHighlight;
1.140378 +      pFragment->covered = mCover;
1.140379 +      iBestScore = iScore;
1.140380 +    }
1.140381 +  }
1.140382 +
1.140383 +  sqlite3_free(sIter.aPhrase);
1.140384 +  *piScore = iBestScore;
1.140385 +  return SQLITE_OK;
1.140386 +}
1.140387 +
1.140388 +
1.140389 +/*
1.140390 +** Append a string to the string-buffer passed as the first argument.
1.140391 +**
1.140392 +** If nAppend is negative, then the length of the string zAppend is
1.140393 +** determined using strlen().
1.140394 +*/
1.140395 +static int fts3StringAppend(
1.140396 +  StrBuffer *pStr,                /* Buffer to append to */
1.140397 +  const char *zAppend,            /* Pointer to data to append to buffer */
1.140398 +  int nAppend                     /* Size of zAppend in bytes (or -1) */
1.140399 +){
1.140400 +  if( nAppend<0 ){
1.140401 +    nAppend = (int)strlen(zAppend);
1.140402 +  }
1.140403 +
1.140404 +  /* If there is insufficient space allocated at StrBuffer.z, use realloc()
1.140405 +  ** to grow the buffer until so that it is big enough to accomadate the
1.140406 +  ** appended data.
1.140407 +  */
1.140408 +  if( pStr->n+nAppend+1>=pStr->nAlloc ){
1.140409 +    int nAlloc = pStr->nAlloc+nAppend+100;
1.140410 +    char *zNew = sqlite3_realloc(pStr->z, nAlloc);
1.140411 +    if( !zNew ){
1.140412 +      return SQLITE_NOMEM;
1.140413 +    }
1.140414 +    pStr->z = zNew;
1.140415 +    pStr->nAlloc = nAlloc;
1.140416 +  }
1.140417 +  assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
1.140418 +
1.140419 +  /* Append the data to the string buffer. */
1.140420 +  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
1.140421 +  pStr->n += nAppend;
1.140422 +  pStr->z[pStr->n] = '\0';
1.140423 +
1.140424 +  return SQLITE_OK;
1.140425 +}
1.140426 +
1.140427 +/*
1.140428 +** The fts3BestSnippet() function often selects snippets that end with a
1.140429 +** query term. That is, the final term of the snippet is always a term
1.140430 +** that requires highlighting. For example, if 'X' is a highlighted term
1.140431 +** and '.' is a non-highlighted term, BestSnippet() may select:
1.140432 +**
1.140433 +**     ........X.....X
1.140434 +**
1.140435 +** This function "shifts" the beginning of the snippet forward in the 
1.140436 +** document so that there are approximately the same number of 
1.140437 +** non-highlighted terms to the right of the final highlighted term as there
1.140438 +** are to the left of the first highlighted term. For example, to this:
1.140439 +**
1.140440 +**     ....X.....X....
1.140441 +**
1.140442 +** This is done as part of extracting the snippet text, not when selecting
1.140443 +** the snippet. Snippet selection is done based on doclists only, so there
1.140444 +** is no way for fts3BestSnippet() to know whether or not the document 
1.140445 +** actually contains terms that follow the final highlighted term. 
1.140446 +*/
1.140447 +static int fts3SnippetShift(
1.140448 +  Fts3Table *pTab,                /* FTS3 table snippet comes from */
1.140449 +  int iLangid,                    /* Language id to use in tokenizing */
1.140450 +  int nSnippet,                   /* Number of tokens desired for snippet */
1.140451 +  const char *zDoc,               /* Document text to extract snippet from */
1.140452 +  int nDoc,                       /* Size of buffer zDoc in bytes */
1.140453 +  int *piPos,                     /* IN/OUT: First token of snippet */
1.140454 +  u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
1.140455 +){
1.140456 +  u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
1.140457 +
1.140458 +  if( hlmask ){
1.140459 +    int nLeft;                    /* Tokens to the left of first highlight */
1.140460 +    int nRight;                   /* Tokens to the right of last highlight */
1.140461 +    int nDesired;                 /* Ideal number of tokens to shift forward */
1.140462 +
1.140463 +    for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
1.140464 +    for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
1.140465 +    nDesired = (nLeft-nRight)/2;
1.140466 +
1.140467 +    /* Ideally, the start of the snippet should be pushed forward in the
1.140468 +    ** document nDesired tokens. This block checks if there are actually
1.140469 +    ** nDesired tokens to the right of the snippet. If so, *piPos and
1.140470 +    ** *pHlMask are updated to shift the snippet nDesired tokens to the
1.140471 +    ** right. Otherwise, the snippet is shifted by the number of tokens
1.140472 +    ** available.
1.140473 +    */
1.140474 +    if( nDesired>0 ){
1.140475 +      int nShift;                 /* Number of tokens to shift snippet by */
1.140476 +      int iCurrent = 0;           /* Token counter */
1.140477 +      int rc;                     /* Return Code */
1.140478 +      sqlite3_tokenizer_module *pMod;
1.140479 +      sqlite3_tokenizer_cursor *pC;
1.140480 +      pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
1.140481 +
1.140482 +      /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
1.140483 +      ** or more tokens in zDoc/nDoc.
1.140484 +      */
1.140485 +      rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
1.140486 +      if( rc!=SQLITE_OK ){
1.140487 +        return rc;
1.140488 +      }
1.140489 +      while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
1.140490 +        const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
1.140491 +        rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
1.140492 +      }
1.140493 +      pMod->xClose(pC);
1.140494 +      if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
1.140495 +
1.140496 +      nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
1.140497 +      assert( nShift<=nDesired );
1.140498 +      if( nShift>0 ){
1.140499 +        *piPos += nShift;
1.140500 +        *pHlmask = hlmask >> nShift;
1.140501 +      }
1.140502 +    }
1.140503 +  }
1.140504 +  return SQLITE_OK;
1.140505 +}
1.140506 +
1.140507 +/*
1.140508 +** Extract the snippet text for fragment pFragment from cursor pCsr and
1.140509 +** append it to string buffer pOut.
1.140510 +*/
1.140511 +static int fts3SnippetText(
1.140512 +  Fts3Cursor *pCsr,               /* FTS3 Cursor */
1.140513 +  SnippetFragment *pFragment,     /* Snippet to extract */
1.140514 +  int iFragment,                  /* Fragment number */
1.140515 +  int isLast,                     /* True for final fragment in snippet */
1.140516 +  int nSnippet,                   /* Number of tokens in extracted snippet */
1.140517 +  const char *zOpen,              /* String inserted before highlighted term */
1.140518 +  const char *zClose,             /* String inserted after highlighted term */
1.140519 +  const char *zEllipsis,          /* String inserted between snippets */
1.140520 +  StrBuffer *pOut                 /* Write output here */
1.140521 +){
1.140522 +  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
1.140523 +  int rc;                         /* Return code */
1.140524 +  const char *zDoc;               /* Document text to extract snippet from */
1.140525 +  int nDoc;                       /* Size of zDoc in bytes */
1.140526 +  int iCurrent = 0;               /* Current token number of document */
1.140527 +  int iEnd = 0;                   /* Byte offset of end of current token */
1.140528 +  int isShiftDone = 0;            /* True after snippet is shifted */
1.140529 +  int iPos = pFragment->iPos;     /* First token of snippet */
1.140530 +  u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
1.140531 +  int iCol = pFragment->iCol+1;   /* Query column to extract text from */
1.140532 +  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
1.140533 +  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
1.140534 +  
1.140535 +  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
1.140536 +  if( zDoc==0 ){
1.140537 +    if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
1.140538 +      return SQLITE_NOMEM;
1.140539 +    }
1.140540 +    return SQLITE_OK;
1.140541 +  }
1.140542 +  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
1.140543 +
1.140544 +  /* Open a token cursor on the document. */
1.140545 +  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
1.140546 +  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
1.140547 +  if( rc!=SQLITE_OK ){
1.140548 +    return rc;
1.140549 +  }
1.140550 +
1.140551 +  while( rc==SQLITE_OK ){
1.140552 +    const char *ZDUMMY;           /* Dummy argument used with tokenizer */
1.140553 +    int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
1.140554 +    int iBegin = 0;               /* Offset in zDoc of start of token */
1.140555 +    int iFin = 0;                 /* Offset in zDoc of end of token */
1.140556 +    int isHighlight = 0;          /* True for highlighted terms */
1.140557 +
1.140558 +    /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
1.140559 +    ** in the FTS code the variable that the third argument to xNext points to
1.140560 +    ** is initialized to zero before the first (*but not necessarily
1.140561 +    ** subsequent*) call to xNext(). This is done for a particular application
1.140562 +    ** that needs to know whether or not the tokenizer is being used for
1.140563 +    ** snippet generation or for some other purpose.
1.140564 +    **
1.140565 +    ** Extreme care is required when writing code to depend on this
1.140566 +    ** initialization. It is not a documented part of the tokenizer interface.
1.140567 +    ** If a tokenizer is used directly by any code outside of FTS, this
1.140568 +    ** convention might not be respected.  */
1.140569 +    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
1.140570 +    if( rc!=SQLITE_OK ){
1.140571 +      if( rc==SQLITE_DONE ){
1.140572 +        /* Special case - the last token of the snippet is also the last token
1.140573 +        ** of the column. Append any punctuation that occurred between the end
1.140574 +        ** of the previous token and the end of the document to the output. 
1.140575 +        ** Then break out of the loop. */
1.140576 +        rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
1.140577 +      }
1.140578 +      break;
1.140579 +    }
1.140580 +    if( iCurrent<iPos ){ continue; }
1.140581 +
1.140582 +    if( !isShiftDone ){
1.140583 +      int n = nDoc - iBegin;
1.140584 +      rc = fts3SnippetShift(
1.140585 +          pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
1.140586 +      );
1.140587 +      isShiftDone = 1;
1.140588 +
1.140589 +      /* Now that the shift has been done, check if the initial "..." are
1.140590 +      ** required. They are required if (a) this is not the first fragment,
1.140591 +      ** or (b) this fragment does not begin at position 0 of its column. 
1.140592 +      */
1.140593 +      if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
1.140594 +        rc = fts3StringAppend(pOut, zEllipsis, -1);
1.140595 +      }
1.140596 +      if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
1.140597 +    }
1.140598 +
1.140599 +    if( iCurrent>=(iPos+nSnippet) ){
1.140600 +      if( isLast ){
1.140601 +        rc = fts3StringAppend(pOut, zEllipsis, -1);
1.140602 +      }
1.140603 +      break;
1.140604 +    }
1.140605 +
1.140606 +    /* Set isHighlight to true if this term should be highlighted. */
1.140607 +    isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
1.140608 +
1.140609 +    if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
1.140610 +    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
1.140611 +    if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
1.140612 +    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
1.140613 +
1.140614 +    iEnd = iFin;
1.140615 +  }
1.140616 +
1.140617 +  pMod->xClose(pC);
1.140618 +  return rc;
1.140619 +}
1.140620 +
1.140621 +
1.140622 +/*
1.140623 +** This function is used to count the entries in a column-list (a 
1.140624 +** delta-encoded list of term offsets within a single column of a single 
1.140625 +** row). When this function is called, *ppCollist should point to the
1.140626 +** beginning of the first varint in the column-list (the varint that
1.140627 +** contains the position of the first matching term in the column data).
1.140628 +** Before returning, *ppCollist is set to point to the first byte after
1.140629 +** the last varint in the column-list (either the 0x00 signifying the end
1.140630 +** of the position-list, or the 0x01 that precedes the column number of
1.140631 +** the next column in the position-list).
1.140632 +**
1.140633 +** The number of elements in the column-list is returned.
1.140634 +*/
1.140635 +static int fts3ColumnlistCount(char **ppCollist){
1.140636 +  char *pEnd = *ppCollist;
1.140637 +  char c = 0;
1.140638 +  int nEntry = 0;
1.140639 +
1.140640 +  /* A column-list is terminated by either a 0x01 or 0x00. */
1.140641 +  while( 0xFE & (*pEnd | c) ){
1.140642 +    c = *pEnd++ & 0x80;
1.140643 +    if( !c ) nEntry++;
1.140644 +  }
1.140645 +
1.140646 +  *ppCollist = pEnd;
1.140647 +  return nEntry;
1.140648 +}
1.140649 +
1.140650 +/*
1.140651 +** fts3ExprIterate() callback used to collect the "global" matchinfo stats
1.140652 +** for a single query. 
1.140653 +**
1.140654 +** fts3ExprIterate() callback to load the 'global' elements of a
1.140655 +** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements 
1.140656 +** of the matchinfo array that are constant for all rows returned by the 
1.140657 +** current query.
1.140658 +**
1.140659 +** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
1.140660 +** function populates Matchinfo.aMatchinfo[] as follows:
1.140661 +**
1.140662 +**   for(iCol=0; iCol<nCol; iCol++){
1.140663 +**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
1.140664 +**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
1.140665 +**   }
1.140666 +**
1.140667 +** where X is the number of matches for phrase iPhrase is column iCol of all
1.140668 +** rows of the table. Y is the number of rows for which column iCol contains
1.140669 +** at least one instance of phrase iPhrase.
1.140670 +**
1.140671 +** If the phrase pExpr consists entirely of deferred tokens, then all X and
1.140672 +** Y values are set to nDoc, where nDoc is the number of documents in the 
1.140673 +** file system. This is done because the full-text index doclist is required
1.140674 +** to calculate these values properly, and the full-text index doclist is
1.140675 +** not available for deferred tokens.
1.140676 +*/
1.140677 +static int fts3ExprGlobalHitsCb(
1.140678 +  Fts3Expr *pExpr,                /* Phrase expression node */
1.140679 +  int iPhrase,                    /* Phrase number (numbered from zero) */
1.140680 +  void *pCtx                      /* Pointer to MatchInfo structure */
1.140681 +){
1.140682 +  MatchInfo *p = (MatchInfo *)pCtx;
1.140683 +  return sqlite3Fts3EvalPhraseStats(
1.140684 +      p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
1.140685 +  );
1.140686 +}
1.140687 +
1.140688 +/*
1.140689 +** fts3ExprIterate() callback used to collect the "local" part of the
1.140690 +** FTS3_MATCHINFO_HITS array. The local stats are those elements of the 
1.140691 +** array that are different for each row returned by the query.
1.140692 +*/
1.140693 +static int fts3ExprLocalHitsCb(
1.140694 +  Fts3Expr *pExpr,                /* Phrase expression node */
1.140695 +  int iPhrase,                    /* Phrase number */
1.140696 +  void *pCtx                      /* Pointer to MatchInfo structure */
1.140697 +){
1.140698 +  int rc = SQLITE_OK;
1.140699 +  MatchInfo *p = (MatchInfo *)pCtx;
1.140700 +  int iStart = iPhrase * p->nCol * 3;
1.140701 +  int i;
1.140702 +
1.140703 +  for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
1.140704 +    char *pCsr;
1.140705 +    rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
1.140706 +    if( pCsr ){
1.140707 +      p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
1.140708 +    }else{
1.140709 +      p->aMatchinfo[iStart+i*3] = 0;
1.140710 +    }
1.140711 +  }
1.140712 +
1.140713 +  return rc;
1.140714 +}
1.140715 +
1.140716 +static int fts3MatchinfoCheck(
1.140717 +  Fts3Table *pTab, 
1.140718 +  char cArg,
1.140719 +  char **pzErr
1.140720 +){
1.140721 +  if( (cArg==FTS3_MATCHINFO_NPHRASE)
1.140722 +   || (cArg==FTS3_MATCHINFO_NCOL)
1.140723 +   || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
1.140724 +   || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
1.140725 +   || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
1.140726 +   || (cArg==FTS3_MATCHINFO_LCS)
1.140727 +   || (cArg==FTS3_MATCHINFO_HITS)
1.140728 +  ){
1.140729 +    return SQLITE_OK;
1.140730 +  }
1.140731 +  *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
1.140732 +  return SQLITE_ERROR;
1.140733 +}
1.140734 +
1.140735 +static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
1.140736 +  int nVal;                       /* Number of integers output by cArg */
1.140737 +
1.140738 +  switch( cArg ){
1.140739 +    case FTS3_MATCHINFO_NDOC:
1.140740 +    case FTS3_MATCHINFO_NPHRASE: 
1.140741 +    case FTS3_MATCHINFO_NCOL: 
1.140742 +      nVal = 1;
1.140743 +      break;
1.140744 +
1.140745 +    case FTS3_MATCHINFO_AVGLENGTH:
1.140746 +    case FTS3_MATCHINFO_LENGTH:
1.140747 +    case FTS3_MATCHINFO_LCS:
1.140748 +      nVal = pInfo->nCol;
1.140749 +      break;
1.140750 +
1.140751 +    default:
1.140752 +      assert( cArg==FTS3_MATCHINFO_HITS );
1.140753 +      nVal = pInfo->nCol * pInfo->nPhrase * 3;
1.140754 +      break;
1.140755 +  }
1.140756 +
1.140757 +  return nVal;
1.140758 +}
1.140759 +
1.140760 +static int fts3MatchinfoSelectDoctotal(
1.140761 +  Fts3Table *pTab,
1.140762 +  sqlite3_stmt **ppStmt,
1.140763 +  sqlite3_int64 *pnDoc,
1.140764 +  const char **paLen
1.140765 +){
1.140766 +  sqlite3_stmt *pStmt;
1.140767 +  const char *a;
1.140768 +  sqlite3_int64 nDoc;
1.140769 +
1.140770 +  if( !*ppStmt ){
1.140771 +    int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
1.140772 +    if( rc!=SQLITE_OK ) return rc;
1.140773 +  }
1.140774 +  pStmt = *ppStmt;
1.140775 +  assert( sqlite3_data_count(pStmt)==1 );
1.140776 +
1.140777 +  a = sqlite3_column_blob(pStmt, 0);
1.140778 +  a += sqlite3Fts3GetVarint(a, &nDoc);
1.140779 +  if( nDoc==0 ) return FTS_CORRUPT_VTAB;
1.140780 +  *pnDoc = (u32)nDoc;
1.140781 +
1.140782 +  if( paLen ) *paLen = a;
1.140783 +  return SQLITE_OK;
1.140784 +}
1.140785 +
1.140786 +/*
1.140787 +** An instance of the following structure is used to store state while 
1.140788 +** iterating through a multi-column position-list corresponding to the
1.140789 +** hits for a single phrase on a single row in order to calculate the
1.140790 +** values for a matchinfo() FTS3_MATCHINFO_LCS request.
1.140791 +*/
1.140792 +typedef struct LcsIterator LcsIterator;
1.140793 +struct LcsIterator {
1.140794 +  Fts3Expr *pExpr;                /* Pointer to phrase expression */
1.140795 +  int iPosOffset;                 /* Tokens count up to end of this phrase */
1.140796 +  char *pRead;                    /* Cursor used to iterate through aDoclist */
1.140797 +  int iPos;                       /* Current position */
1.140798 +};
1.140799 +
1.140800 +/* 
1.140801 +** If LcsIterator.iCol is set to the following value, the iterator has
1.140802 +** finished iterating through all offsets for all columns.
1.140803 +*/
1.140804 +#define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
1.140805 +
1.140806 +static int fts3MatchinfoLcsCb(
1.140807 +  Fts3Expr *pExpr,                /* Phrase expression node */
1.140808 +  int iPhrase,                    /* Phrase number (numbered from zero) */
1.140809 +  void *pCtx                      /* Pointer to MatchInfo structure */
1.140810 +){
1.140811 +  LcsIterator *aIter = (LcsIterator *)pCtx;
1.140812 +  aIter[iPhrase].pExpr = pExpr;
1.140813 +  return SQLITE_OK;
1.140814 +}
1.140815 +
1.140816 +/*
1.140817 +** Advance the iterator passed as an argument to the next position. Return
1.140818 +** 1 if the iterator is at EOF or if it now points to the start of the
1.140819 +** position list for the next column.
1.140820 +*/
1.140821 +static int fts3LcsIteratorAdvance(LcsIterator *pIter){
1.140822 +  char *pRead = pIter->pRead;
1.140823 +  sqlite3_int64 iRead;
1.140824 +  int rc = 0;
1.140825 +
1.140826 +  pRead += sqlite3Fts3GetVarint(pRead, &iRead);
1.140827 +  if( iRead==0 || iRead==1 ){
1.140828 +    pRead = 0;
1.140829 +    rc = 1;
1.140830 +  }else{
1.140831 +    pIter->iPos += (int)(iRead-2);
1.140832 +  }
1.140833 +
1.140834 +  pIter->pRead = pRead;
1.140835 +  return rc;
1.140836 +}
1.140837 +  
1.140838 +/*
1.140839 +** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. 
1.140840 +**
1.140841 +** If the call is successful, the longest-common-substring lengths for each
1.140842 +** column are written into the first nCol elements of the pInfo->aMatchinfo[] 
1.140843 +** array before returning. SQLITE_OK is returned in this case.
1.140844 +**
1.140845 +** Otherwise, if an error occurs, an SQLite error code is returned and the
1.140846 +** data written to the first nCol elements of pInfo->aMatchinfo[] is 
1.140847 +** undefined.
1.140848 +*/
1.140849 +static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
1.140850 +  LcsIterator *aIter;
1.140851 +  int i;
1.140852 +  int iCol;
1.140853 +  int nToken = 0;
1.140854 +
1.140855 +  /* Allocate and populate the array of LcsIterator objects. The array
1.140856 +  ** contains one element for each matchable phrase in the query.
1.140857 +  **/
1.140858 +  aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
1.140859 +  if( !aIter ) return SQLITE_NOMEM;
1.140860 +  memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
1.140861 +  (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
1.140862 +
1.140863 +  for(i=0; i<pInfo->nPhrase; i++){
1.140864 +    LcsIterator *pIter = &aIter[i];
1.140865 +    nToken -= pIter->pExpr->pPhrase->nToken;
1.140866 +    pIter->iPosOffset = nToken;
1.140867 +  }
1.140868 +
1.140869 +  for(iCol=0; iCol<pInfo->nCol; iCol++){
1.140870 +    int nLcs = 0;                 /* LCS value for this column */
1.140871 +    int nLive = 0;                /* Number of iterators in aIter not at EOF */
1.140872 +
1.140873 +    for(i=0; i<pInfo->nPhrase; i++){
1.140874 +      int rc;
1.140875 +      LcsIterator *pIt = &aIter[i];
1.140876 +      rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
1.140877 +      if( rc!=SQLITE_OK ) return rc;
1.140878 +      if( pIt->pRead ){
1.140879 +        pIt->iPos = pIt->iPosOffset;
1.140880 +        fts3LcsIteratorAdvance(&aIter[i]);
1.140881 +        nLive++;
1.140882 +      }
1.140883 +    }
1.140884 +
1.140885 +    while( nLive>0 ){
1.140886 +      LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
1.140887 +      int nThisLcs = 0;           /* LCS for the current iterator positions */
1.140888 +
1.140889 +      for(i=0; i<pInfo->nPhrase; i++){
1.140890 +        LcsIterator *pIter = &aIter[i];
1.140891 +        if( pIter->pRead==0 ){
1.140892 +          /* This iterator is already at EOF for this column. */
1.140893 +          nThisLcs = 0;
1.140894 +        }else{
1.140895 +          if( pAdv==0 || pIter->iPos<pAdv->iPos ){
1.140896 +            pAdv = pIter;
1.140897 +          }
1.140898 +          if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
1.140899 +            nThisLcs++;
1.140900 +          }else{
1.140901 +            nThisLcs = 1;
1.140902 +          }
1.140903 +          if( nThisLcs>nLcs ) nLcs = nThisLcs;
1.140904 +        }
1.140905 +      }
1.140906 +      if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
1.140907 +    }
1.140908 +
1.140909 +    pInfo->aMatchinfo[iCol] = nLcs;
1.140910 +  }
1.140911 +
1.140912 +  sqlite3_free(aIter);
1.140913 +  return SQLITE_OK;
1.140914 +}
1.140915 +
1.140916 +/*
1.140917 +** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
1.140918 +** be returned by the matchinfo() function. Argument zArg contains the 
1.140919 +** format string passed as the second argument to matchinfo (or the
1.140920 +** default value "pcx" if no second argument was specified). The format
1.140921 +** string has already been validated and the pInfo->aMatchinfo[] array
1.140922 +** is guaranteed to be large enough for the output.
1.140923 +**
1.140924 +** If bGlobal is true, then populate all fields of the matchinfo() output.
1.140925 +** If it is false, then assume that those fields that do not change between
1.140926 +** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
1.140927 +** have already been populated.
1.140928 +**
1.140929 +** Return SQLITE_OK if successful, or an SQLite error code if an error 
1.140930 +** occurs. If a value other than SQLITE_OK is returned, the state the
1.140931 +** pInfo->aMatchinfo[] buffer is left in is undefined.
1.140932 +*/
1.140933 +static int fts3MatchinfoValues(
1.140934 +  Fts3Cursor *pCsr,               /* FTS3 cursor object */
1.140935 +  int bGlobal,                    /* True to grab the global stats */
1.140936 +  MatchInfo *pInfo,               /* Matchinfo context object */
1.140937 +  const char *zArg                /* Matchinfo format string */
1.140938 +){
1.140939 +  int rc = SQLITE_OK;
1.140940 +  int i;
1.140941 +  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
1.140942 +  sqlite3_stmt *pSelect = 0;
1.140943 +
1.140944 +  for(i=0; rc==SQLITE_OK && zArg[i]; i++){
1.140945 +
1.140946 +    switch( zArg[i] ){
1.140947 +      case FTS3_MATCHINFO_NPHRASE:
1.140948 +        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
1.140949 +        break;
1.140950 +
1.140951 +      case FTS3_MATCHINFO_NCOL:
1.140952 +        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
1.140953 +        break;
1.140954 +        
1.140955 +      case FTS3_MATCHINFO_NDOC:
1.140956 +        if( bGlobal ){
1.140957 +          sqlite3_int64 nDoc = 0;
1.140958 +          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
1.140959 +          pInfo->aMatchinfo[0] = (u32)nDoc;
1.140960 +        }
1.140961 +        break;
1.140962 +
1.140963 +      case FTS3_MATCHINFO_AVGLENGTH: 
1.140964 +        if( bGlobal ){
1.140965 +          sqlite3_int64 nDoc;     /* Number of rows in table */
1.140966 +          const char *a;          /* Aggregate column length array */
1.140967 +
1.140968 +          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
1.140969 +          if( rc==SQLITE_OK ){
1.140970 +            int iCol;
1.140971 +            for(iCol=0; iCol<pInfo->nCol; iCol++){
1.140972 +              u32 iVal;
1.140973 +              sqlite3_int64 nToken;
1.140974 +              a += sqlite3Fts3GetVarint(a, &nToken);
1.140975 +              iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
1.140976 +              pInfo->aMatchinfo[iCol] = iVal;
1.140977 +            }
1.140978 +          }
1.140979 +        }
1.140980 +        break;
1.140981 +
1.140982 +      case FTS3_MATCHINFO_LENGTH: {
1.140983 +        sqlite3_stmt *pSelectDocsize = 0;
1.140984 +        rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
1.140985 +        if( rc==SQLITE_OK ){
1.140986 +          int iCol;
1.140987 +          const char *a = sqlite3_column_blob(pSelectDocsize, 0);
1.140988 +          for(iCol=0; iCol<pInfo->nCol; iCol++){
1.140989 +            sqlite3_int64 nToken;
1.140990 +            a += sqlite3Fts3GetVarint(a, &nToken);
1.140991 +            pInfo->aMatchinfo[iCol] = (u32)nToken;
1.140992 +          }
1.140993 +        }
1.140994 +        sqlite3_reset(pSelectDocsize);
1.140995 +        break;
1.140996 +      }
1.140997 +
1.140998 +      case FTS3_MATCHINFO_LCS:
1.140999 +        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
1.141000 +        if( rc==SQLITE_OK ){
1.141001 +          rc = fts3MatchinfoLcs(pCsr, pInfo);
1.141002 +        }
1.141003 +        break;
1.141004 +
1.141005 +      default: {
1.141006 +        Fts3Expr *pExpr;
1.141007 +        assert( zArg[i]==FTS3_MATCHINFO_HITS );
1.141008 +        pExpr = pCsr->pExpr;
1.141009 +        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
1.141010 +        if( rc!=SQLITE_OK ) break;
1.141011 +        if( bGlobal ){
1.141012 +          if( pCsr->pDeferred ){
1.141013 +            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
1.141014 +            if( rc!=SQLITE_OK ) break;
1.141015 +          }
1.141016 +          rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
1.141017 +          if( rc!=SQLITE_OK ) break;
1.141018 +        }
1.141019 +        (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
1.141020 +        break;
1.141021 +      }
1.141022 +    }
1.141023 +
1.141024 +    pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
1.141025 +  }
1.141026 +
1.141027 +  sqlite3_reset(pSelect);
1.141028 +  return rc;
1.141029 +}
1.141030 +
1.141031 +
1.141032 +/*
1.141033 +** Populate pCsr->aMatchinfo[] with data for the current row. The 
1.141034 +** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
1.141035 +*/
1.141036 +static int fts3GetMatchinfo(
1.141037 +  Fts3Cursor *pCsr,               /* FTS3 Cursor object */
1.141038 +  const char *zArg                /* Second argument to matchinfo() function */
1.141039 +){
1.141040 +  MatchInfo sInfo;
1.141041 +  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
1.141042 +  int rc = SQLITE_OK;
1.141043 +  int bGlobal = 0;                /* Collect 'global' stats as well as local */
1.141044 +
1.141045 +  memset(&sInfo, 0, sizeof(MatchInfo));
1.141046 +  sInfo.pCursor = pCsr;
1.141047 +  sInfo.nCol = pTab->nColumn;
1.141048 +
1.141049 +  /* If there is cached matchinfo() data, but the format string for the 
1.141050 +  ** cache does not match the format string for this request, discard 
1.141051 +  ** the cached data. */
1.141052 +  if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
1.141053 +    assert( pCsr->aMatchinfo );
1.141054 +    sqlite3_free(pCsr->aMatchinfo);
1.141055 +    pCsr->zMatchinfo = 0;
1.141056 +    pCsr->aMatchinfo = 0;
1.141057 +  }
1.141058 +
1.141059 +  /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
1.141060 +  ** matchinfo function has been called for this query. In this case 
1.141061 +  ** allocate the array used to accumulate the matchinfo data and
1.141062 +  ** initialize those elements that are constant for every row.
1.141063 +  */
1.141064 +  if( pCsr->aMatchinfo==0 ){
1.141065 +    int nMatchinfo = 0;           /* Number of u32 elements in match-info */
1.141066 +    int nArg;                     /* Bytes in zArg */
1.141067 +    int i;                        /* Used to iterate through zArg */
1.141068 +
1.141069 +    /* Determine the number of phrases in the query */
1.141070 +    pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
1.141071 +    sInfo.nPhrase = pCsr->nPhrase;
1.141072 +
1.141073 +    /* Determine the number of integers in the buffer returned by this call. */
1.141074 +    for(i=0; zArg[i]; i++){
1.141075 +      nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
1.141076 +    }
1.141077 +
1.141078 +    /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
1.141079 +    nArg = (int)strlen(zArg);
1.141080 +    pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
1.141081 +    if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
1.141082 +
1.141083 +    pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
1.141084 +    pCsr->nMatchinfo = nMatchinfo;
1.141085 +    memcpy(pCsr->zMatchinfo, zArg, nArg+1);
1.141086 +    memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
1.141087 +    pCsr->isMatchinfoNeeded = 1;
1.141088 +    bGlobal = 1;
1.141089 +  }
1.141090 +
1.141091 +  sInfo.aMatchinfo = pCsr->aMatchinfo;
1.141092 +  sInfo.nPhrase = pCsr->nPhrase;
1.141093 +  if( pCsr->isMatchinfoNeeded ){
1.141094 +    rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
1.141095 +    pCsr->isMatchinfoNeeded = 0;
1.141096 +  }
1.141097 +
1.141098 +  return rc;
1.141099 +}
1.141100 +
1.141101 +/*
1.141102 +** Implementation of snippet() function.
1.141103 +*/
1.141104 +SQLITE_PRIVATE void sqlite3Fts3Snippet(
1.141105 +  sqlite3_context *pCtx,          /* SQLite function call context */
1.141106 +  Fts3Cursor *pCsr,               /* Cursor object */
1.141107 +  const char *zStart,             /* Snippet start text - "<b>" */
1.141108 +  const char *zEnd,               /* Snippet end text - "</b>" */
1.141109 +  const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
1.141110 +  int iCol,                       /* Extract snippet from this column */
1.141111 +  int nToken                      /* Approximate number of tokens in snippet */
1.141112 +){
1.141113 +  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
1.141114 +  int rc = SQLITE_OK;
1.141115 +  int i;
1.141116 +  StrBuffer res = {0, 0, 0};
1.141117 +
1.141118 +  /* The returned text includes up to four fragments of text extracted from
1.141119 +  ** the data in the current row. The first iteration of the for(...) loop
1.141120 +  ** below attempts to locate a single fragment of text nToken tokens in 
1.141121 +  ** size that contains at least one instance of all phrases in the query
1.141122 +  ** expression that appear in the current row. If such a fragment of text
1.141123 +  ** cannot be found, the second iteration of the loop attempts to locate
1.141124 +  ** a pair of fragments, and so on.
1.141125 +  */
1.141126 +  int nSnippet = 0;               /* Number of fragments in this snippet */
1.141127 +  SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
1.141128 +  int nFToken = -1;               /* Number of tokens in each fragment */
1.141129 +
1.141130 +  if( !pCsr->pExpr ){
1.141131 +    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
1.141132 +    return;
1.141133 +  }
1.141134 +
1.141135 +  for(nSnippet=1; 1; nSnippet++){
1.141136 +
1.141137 +    int iSnip;                    /* Loop counter 0..nSnippet-1 */
1.141138 +    u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
1.141139 +    u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
1.141140 +
1.141141 +    if( nToken>=0 ){
1.141142 +      nFToken = (nToken+nSnippet-1) / nSnippet;
1.141143 +    }else{
1.141144 +      nFToken = -1 * nToken;
1.141145 +    }
1.141146 +
1.141147 +    for(iSnip=0; iSnip<nSnippet; iSnip++){
1.141148 +      int iBestScore = -1;        /* Best score of columns checked so far */
1.141149 +      int iRead;                  /* Used to iterate through columns */
1.141150 +      SnippetFragment *pFragment = &aSnippet[iSnip];
1.141151 +
1.141152 +      memset(pFragment, 0, sizeof(*pFragment));
1.141153 +
1.141154 +      /* Loop through all columns of the table being considered for snippets.
1.141155 +      ** If the iCol argument to this function was negative, this means all
1.141156 +      ** columns of the FTS3 table. Otherwise, only column iCol is considered.
1.141157 +      */
1.141158 +      for(iRead=0; iRead<pTab->nColumn; iRead++){
1.141159 +        SnippetFragment sF = {0, 0, 0, 0};
1.141160 +        int iS;
1.141161 +        if( iCol>=0 && iRead!=iCol ) continue;
1.141162 +
1.141163 +        /* Find the best snippet of nFToken tokens in column iRead. */
1.141164 +        rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
1.141165 +        if( rc!=SQLITE_OK ){
1.141166 +          goto snippet_out;
1.141167 +        }
1.141168 +        if( iS>iBestScore ){
1.141169 +          *pFragment = sF;
1.141170 +          iBestScore = iS;
1.141171 +        }
1.141172 +      }
1.141173 +
1.141174 +      mCovered |= pFragment->covered;
1.141175 +    }
1.141176 +
1.141177 +    /* If all query phrases seen by fts3BestSnippet() are present in at least
1.141178 +    ** one of the nSnippet snippet fragments, break out of the loop.
1.141179 +    */
1.141180 +    assert( (mCovered&mSeen)==mCovered );
1.141181 +    if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
1.141182 +  }
1.141183 +
1.141184 +  assert( nFToken>0 );
1.141185 +
1.141186 +  for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
1.141187 +    rc = fts3SnippetText(pCsr, &aSnippet[i], 
1.141188 +        i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
1.141189 +    );
1.141190 +  }
1.141191 +
1.141192 + snippet_out:
1.141193 +  sqlite3Fts3SegmentsClose(pTab);
1.141194 +  if( rc!=SQLITE_OK ){
1.141195 +    sqlite3_result_error_code(pCtx, rc);
1.141196 +    sqlite3_free(res.z);
1.141197 +  }else{
1.141198 +    sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
1.141199 +  }
1.141200 +}
1.141201 +
1.141202 +
1.141203 +typedef struct TermOffset TermOffset;
1.141204 +typedef struct TermOffsetCtx TermOffsetCtx;
1.141205 +
1.141206 +struct TermOffset {
1.141207 +  char *pList;                    /* Position-list */
1.141208 +  int iPos;                       /* Position just read from pList */
1.141209 +  int iOff;                       /* Offset of this term from read positions */
1.141210 +};
1.141211 +
1.141212 +struct TermOffsetCtx {
1.141213 +  Fts3Cursor *pCsr;
1.141214 +  int iCol;                       /* Column of table to populate aTerm for */
1.141215 +  int iTerm;
1.141216 +  sqlite3_int64 iDocid;
1.141217 +  TermOffset *aTerm;
1.141218 +};
1.141219 +
1.141220 +/*
1.141221 +** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
1.141222 +*/
1.141223 +static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
1.141224 +  TermOffsetCtx *p = (TermOffsetCtx *)ctx;
1.141225 +  int nTerm;                      /* Number of tokens in phrase */
1.141226 +  int iTerm;                      /* For looping through nTerm phrase terms */
1.141227 +  char *pList;                    /* Pointer to position list for phrase */
1.141228 +  int iPos = 0;                   /* First position in position-list */
1.141229 +  int rc;
1.141230 +
1.141231 +  UNUSED_PARAMETER(iPhrase);
1.141232 +  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
1.141233 +  nTerm = pExpr->pPhrase->nToken;
1.141234 +  if( pList ){
1.141235 +    fts3GetDeltaPosition(&pList, &iPos);
1.141236 +    assert( iPos>=0 );
1.141237 +  }
1.141238 +
1.141239 +  for(iTerm=0; iTerm<nTerm; iTerm++){
1.141240 +    TermOffset *pT = &p->aTerm[p->iTerm++];
1.141241 +    pT->iOff = nTerm-iTerm-1;
1.141242 +    pT->pList = pList;
1.141243 +    pT->iPos = iPos;
1.141244 +  }
1.141245 +
1.141246 +  return rc;
1.141247 +}
1.141248 +
1.141249 +/*
1.141250 +** Implementation of offsets() function.
1.141251 +*/
1.141252 +SQLITE_PRIVATE void sqlite3Fts3Offsets(
1.141253 +  sqlite3_context *pCtx,          /* SQLite function call context */
1.141254 +  Fts3Cursor *pCsr                /* Cursor object */
1.141255 +){
1.141256 +  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
1.141257 +  sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
1.141258 +  int rc;                         /* Return Code */
1.141259 +  int nToken;                     /* Number of tokens in query */
1.141260 +  int iCol;                       /* Column currently being processed */
1.141261 +  StrBuffer res = {0, 0, 0};      /* Result string */
1.141262 +  TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
1.141263 +
1.141264 +  if( !pCsr->pExpr ){
1.141265 +    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
1.141266 +    return;
1.141267 +  }
1.141268 +
1.141269 +  memset(&sCtx, 0, sizeof(sCtx));
1.141270 +  assert( pCsr->isRequireSeek==0 );
1.141271 +
1.141272 +  /* Count the number of terms in the query */
1.141273 +  rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
1.141274 +  if( rc!=SQLITE_OK ) goto offsets_out;
1.141275 +
1.141276 +  /* Allocate the array of TermOffset iterators. */
1.141277 +  sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
1.141278 +  if( 0==sCtx.aTerm ){
1.141279 +    rc = SQLITE_NOMEM;
1.141280 +    goto offsets_out;
1.141281 +  }
1.141282 +  sCtx.iDocid = pCsr->iPrevId;
1.141283 +  sCtx.pCsr = pCsr;
1.141284 +
1.141285 +  /* Loop through the table columns, appending offset information to 
1.141286 +  ** string-buffer res for each column.
1.141287 +  */
1.141288 +  for(iCol=0; iCol<pTab->nColumn; iCol++){
1.141289 +    sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
1.141290 +    const char *ZDUMMY;           /* Dummy argument used with xNext() */
1.141291 +    int NDUMMY = 0;               /* Dummy argument used with xNext() */
1.141292 +    int iStart = 0;
1.141293 +    int iEnd = 0;
1.141294 +    int iCurrent = 0;
1.141295 +    const char *zDoc;
1.141296 +    int nDoc;
1.141297 +
1.141298 +    /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
1.141299 +    ** no way that this operation can fail, so the return code from
1.141300 +    ** fts3ExprIterate() can be discarded.
1.141301 +    */
1.141302 +    sCtx.iCol = iCol;
1.141303 +    sCtx.iTerm = 0;
1.141304 +    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
1.141305 +
1.141306 +    /* Retreive the text stored in column iCol. If an SQL NULL is stored 
1.141307 +    ** in column iCol, jump immediately to the next iteration of the loop.
1.141308 +    ** If an OOM occurs while retrieving the data (this can happen if SQLite
1.141309 +    ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 
1.141310 +    ** to the caller. 
1.141311 +    */
1.141312 +    zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
1.141313 +    nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
1.141314 +    if( zDoc==0 ){
1.141315 +      if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
1.141316 +        continue;
1.141317 +      }
1.141318 +      rc = SQLITE_NOMEM;
1.141319 +      goto offsets_out;
1.141320 +    }
1.141321 +
1.141322 +    /* Initialize a tokenizer iterator to iterate through column iCol. */
1.141323 +    rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
1.141324 +        zDoc, nDoc, &pC
1.141325 +    );
1.141326 +    if( rc!=SQLITE_OK ) goto offsets_out;
1.141327 +
1.141328 +    rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
1.141329 +    while( rc==SQLITE_OK ){
1.141330 +      int i;                      /* Used to loop through terms */
1.141331 +      int iMinPos = 0x7FFFFFFF;   /* Position of next token */
1.141332 +      TermOffset *pTerm = 0;      /* TermOffset associated with next token */
1.141333 +
1.141334 +      for(i=0; i<nToken; i++){
1.141335 +        TermOffset *pT = &sCtx.aTerm[i];
1.141336 +        if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
1.141337 +          iMinPos = pT->iPos-pT->iOff;
1.141338 +          pTerm = pT;
1.141339 +        }
1.141340 +      }
1.141341 +
1.141342 +      if( !pTerm ){
1.141343 +        /* All offsets for this column have been gathered. */
1.141344 +        rc = SQLITE_DONE;
1.141345 +      }else{
1.141346 +        assert( iCurrent<=iMinPos );
1.141347 +        if( 0==(0xFE&*pTerm->pList) ){
1.141348 +          pTerm->pList = 0;
1.141349 +        }else{
1.141350 +          fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
1.141351 +        }
1.141352 +        while( rc==SQLITE_OK && iCurrent<iMinPos ){
1.141353 +          rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
1.141354 +        }
1.141355 +        if( rc==SQLITE_OK ){
1.141356 +          char aBuffer[64];
1.141357 +          sqlite3_snprintf(sizeof(aBuffer), aBuffer, 
1.141358 +              "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
1.141359 +          );
1.141360 +          rc = fts3StringAppend(&res, aBuffer, -1);
1.141361 +        }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
1.141362 +          rc = FTS_CORRUPT_VTAB;
1.141363 +        }
1.141364 +      }
1.141365 +    }
1.141366 +    if( rc==SQLITE_DONE ){
1.141367 +      rc = SQLITE_OK;
1.141368 +    }
1.141369 +
1.141370 +    pMod->xClose(pC);
1.141371 +    if( rc!=SQLITE_OK ) goto offsets_out;
1.141372 +  }
1.141373 +
1.141374 + offsets_out:
1.141375 +  sqlite3_free(sCtx.aTerm);
1.141376 +  assert( rc!=SQLITE_DONE );
1.141377 +  sqlite3Fts3SegmentsClose(pTab);
1.141378 +  if( rc!=SQLITE_OK ){
1.141379 +    sqlite3_result_error_code(pCtx,  rc);
1.141380 +    sqlite3_free(res.z);
1.141381 +  }else{
1.141382 +    sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
1.141383 +  }
1.141384 +  return;
1.141385 +}
1.141386 +
1.141387 +/*
1.141388 +** Implementation of matchinfo() function.
1.141389 +*/
1.141390 +SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
1.141391 +  sqlite3_context *pContext,      /* Function call context */
1.141392 +  Fts3Cursor *pCsr,               /* FTS3 table cursor */
1.141393 +  const char *zArg                /* Second arg to matchinfo() function */
1.141394 +){
1.141395 +  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
1.141396 +  int rc;
1.141397 +  int i;
1.141398 +  const char *zFormat;
1.141399 +
1.141400 +  if( zArg ){
1.141401 +    for(i=0; zArg[i]; i++){
1.141402 +      char *zErr = 0;
1.141403 +      if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
1.141404 +        sqlite3_result_error(pContext, zErr, -1);
1.141405 +        sqlite3_free(zErr);
1.141406 +        return;
1.141407 +      }
1.141408 +    }
1.141409 +    zFormat = zArg;
1.141410 +  }else{
1.141411 +    zFormat = FTS3_MATCHINFO_DEFAULT;
1.141412 +  }
1.141413 +
1.141414 +  if( !pCsr->pExpr ){
1.141415 +    sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
1.141416 +    return;
1.141417 +  }
1.141418 +
1.141419 +  /* Retrieve matchinfo() data. */
1.141420 +  rc = fts3GetMatchinfo(pCsr, zFormat);
1.141421 +  sqlite3Fts3SegmentsClose(pTab);
1.141422 +
1.141423 +  if( rc!=SQLITE_OK ){
1.141424 +    sqlite3_result_error_code(pContext, rc);
1.141425 +  }else{
1.141426 +    int n = pCsr->nMatchinfo * sizeof(u32);
1.141427 +    sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
1.141428 +  }
1.141429 +}
1.141430 +
1.141431 +#endif
1.141432 +
1.141433 +/************** End of fts3_snippet.c ****************************************/
1.141434 +/************** Begin file fts3_unicode.c ************************************/
1.141435 +/*
1.141436 +** 2012 May 24
1.141437 +**
1.141438 +** The author disclaims copyright to this source code.  In place of
1.141439 +** a legal notice, here is a blessing:
1.141440 +**
1.141441 +**    May you do good and not evil.
1.141442 +**    May you find forgiveness for yourself and forgive others.
1.141443 +**    May you share freely, never taking more than you give.
1.141444 +**
1.141445 +******************************************************************************
1.141446 +**
1.141447 +** Implementation of the "unicode" full-text-search tokenizer.
1.141448 +*/
1.141449 +
1.141450 +#ifdef SQLITE_ENABLE_FTS4_UNICODE61
1.141451 +
1.141452 +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
1.141453 +
1.141454 +/* #include <assert.h> */
1.141455 +/* #include <stdlib.h> */
1.141456 +/* #include <stdio.h> */
1.141457 +/* #include <string.h> */
1.141458 +
1.141459 +
1.141460 +/*
1.141461 +** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
1.141462 +** from the sqlite3 source file utf.c. If this file is compiled as part
1.141463 +** of the amalgamation, they are not required.
1.141464 +*/
1.141465 +#ifndef SQLITE_AMALGAMATION
1.141466 +
1.141467 +static const unsigned char sqlite3Utf8Trans1[] = {
1.141468 +  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
1.141469 +  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
1.141470 +  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
1.141471 +  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
1.141472 +  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
1.141473 +  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
1.141474 +  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
1.141475 +  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
1.141476 +};
1.141477 +
1.141478 +#define READ_UTF8(zIn, zTerm, c)                           \
1.141479 +  c = *(zIn++);                                            \
1.141480 +  if( c>=0xc0 ){                                           \
1.141481 +    c = sqlite3Utf8Trans1[c-0xc0];                         \
1.141482 +    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
1.141483 +      c = (c<<6) + (0x3f & *(zIn++));                      \
1.141484 +    }                                                      \
1.141485 +    if( c<0x80                                             \
1.141486 +        || (c&0xFFFFF800)==0xD800                          \
1.141487 +        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
1.141488 +  }
1.141489 +
1.141490 +#define WRITE_UTF8(zOut, c) {                          \
1.141491 +  if( c<0x00080 ){                                     \
1.141492 +    *zOut++ = (u8)(c&0xFF);                            \
1.141493 +  }                                                    \
1.141494 +  else if( c<0x00800 ){                                \
1.141495 +    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
1.141496 +    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
1.141497 +  }                                                    \
1.141498 +  else if( c<0x10000 ){                                \
1.141499 +    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
1.141500 +    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
1.141501 +    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
1.141502 +  }else{                                               \
1.141503 +    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
1.141504 +    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
1.141505 +    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
1.141506 +    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
1.141507 +  }                                                    \
1.141508 +}
1.141509 +
1.141510 +#endif /* ifndef SQLITE_AMALGAMATION */
1.141511 +
1.141512 +typedef struct unicode_tokenizer unicode_tokenizer;
1.141513 +typedef struct unicode_cursor unicode_cursor;
1.141514 +
1.141515 +struct unicode_tokenizer {
1.141516 +  sqlite3_tokenizer base;
1.141517 +  int bRemoveDiacritic;
1.141518 +  int nException;
1.141519 +  int *aiException;
1.141520 +};
1.141521 +
1.141522 +struct unicode_cursor {
1.141523 +  sqlite3_tokenizer_cursor base;
1.141524 +  const unsigned char *aInput;    /* Input text being tokenized */
1.141525 +  int nInput;                     /* Size of aInput[] in bytes */
1.141526 +  int iOff;                       /* Current offset within aInput[] */
1.141527 +  int iToken;                     /* Index of next token to be returned */
1.141528 +  char *zToken;                   /* storage for current token */
1.141529 +  int nAlloc;                     /* space allocated at zToken */
1.141530 +};
1.141531 +
1.141532 +
1.141533 +/*
1.141534 +** Destroy a tokenizer allocated by unicodeCreate().
1.141535 +*/
1.141536 +static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
1.141537 +  if( pTokenizer ){
1.141538 +    unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
1.141539 +    sqlite3_free(p->aiException);
1.141540 +    sqlite3_free(p);
1.141541 +  }
1.141542 +  return SQLITE_OK;
1.141543 +}
1.141544 +
1.141545 +/*
1.141546 +** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
1.141547 +** statement has specified that the tokenizer for this table shall consider
1.141548 +** all characters in string zIn/nIn to be separators (if bAlnum==0) or
1.141549 +** token characters (if bAlnum==1).
1.141550 +**
1.141551 +** For each codepoint in the zIn/nIn string, this function checks if the
1.141552 +** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
1.141553 +** If so, no action is taken. Otherwise, the codepoint is added to the 
1.141554 +** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
1.141555 +** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
1.141556 +** codepoints in the aiException[] array.
1.141557 +**
1.141558 +** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
1.141559 +** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
1.141560 +** It is not possible to change the behavior of the tokenizer with respect
1.141561 +** to these codepoints.
1.141562 +*/
1.141563 +static int unicodeAddExceptions(
1.141564 +  unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
1.141565 +  int bAlnum,                     /* Replace Isalnum() return value with this */
1.141566 +  const char *zIn,                /* Array of characters to make exceptions */
1.141567 +  int nIn                         /* Length of z in bytes */
1.141568 +){
1.141569 +  const unsigned char *z = (const unsigned char *)zIn;
1.141570 +  const unsigned char *zTerm = &z[nIn];
1.141571 +  int iCode;
1.141572 +  int nEntry = 0;
1.141573 +
1.141574 +  assert( bAlnum==0 || bAlnum==1 );
1.141575 +
1.141576 +  while( z<zTerm ){
1.141577 +    READ_UTF8(z, zTerm, iCode);
1.141578 +    assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
1.141579 +    if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum 
1.141580 +     && sqlite3FtsUnicodeIsdiacritic(iCode)==0 
1.141581 +    ){
1.141582 +      nEntry++;
1.141583 +    }
1.141584 +  }
1.141585 +
1.141586 +  if( nEntry ){
1.141587 +    int *aNew;                    /* New aiException[] array */
1.141588 +    int nNew;                     /* Number of valid entries in array aNew[] */
1.141589 +
1.141590 +    aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
1.141591 +    if( aNew==0 ) return SQLITE_NOMEM;
1.141592 +    nNew = p->nException;
1.141593 +
1.141594 +    z = (const unsigned char *)zIn;
1.141595 +    while( z<zTerm ){
1.141596 +      READ_UTF8(z, zTerm, iCode);
1.141597 +      if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum 
1.141598 +       && sqlite3FtsUnicodeIsdiacritic(iCode)==0
1.141599 +      ){
1.141600 +        int i, j;
1.141601 +        for(i=0; i<nNew && aNew[i]<iCode; i++);
1.141602 +        for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
1.141603 +        aNew[i] = iCode;
1.141604 +        nNew++;
1.141605 +      }
1.141606 +    }
1.141607 +    p->aiException = aNew;
1.141608 +    p->nException = nNew;
1.141609 +  }
1.141610 +
1.141611 +  return SQLITE_OK;
1.141612 +}
1.141613 +
1.141614 +/*
1.141615 +** Return true if the p->aiException[] array contains the value iCode.
1.141616 +*/
1.141617 +static int unicodeIsException(unicode_tokenizer *p, int iCode){
1.141618 +  if( p->nException>0 ){
1.141619 +    int *a = p->aiException;
1.141620 +    int iLo = 0;
1.141621 +    int iHi = p->nException-1;
1.141622 +
1.141623 +    while( iHi>=iLo ){
1.141624 +      int iTest = (iHi + iLo) / 2;
1.141625 +      if( iCode==a[iTest] ){
1.141626 +        return 1;
1.141627 +      }else if( iCode>a[iTest] ){
1.141628 +        iLo = iTest+1;
1.141629 +      }else{
1.141630 +        iHi = iTest-1;
1.141631 +      }
1.141632 +    }
1.141633 +  }
1.141634 +
1.141635 +  return 0;
1.141636 +}
1.141637 +
1.141638 +/*
1.141639 +** Return true if, for the purposes of tokenization, codepoint iCode is
1.141640 +** considered a token character (not a separator).
1.141641 +*/
1.141642 +static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
1.141643 +  assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
1.141644 +  return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
1.141645 +}
1.141646 +
1.141647 +/*
1.141648 +** Create a new tokenizer instance.
1.141649 +*/
1.141650 +static int unicodeCreate(
1.141651 +  int nArg,                       /* Size of array argv[] */
1.141652 +  const char * const *azArg,      /* Tokenizer creation arguments */
1.141653 +  sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
1.141654 +){
1.141655 +  unicode_tokenizer *pNew;        /* New tokenizer object */
1.141656 +  int i;
1.141657 +  int rc = SQLITE_OK;
1.141658 +
1.141659 +  pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
1.141660 +  if( pNew==NULL ) return SQLITE_NOMEM;
1.141661 +  memset(pNew, 0, sizeof(unicode_tokenizer));
1.141662 +  pNew->bRemoveDiacritic = 1;
1.141663 +
1.141664 +  for(i=0; rc==SQLITE_OK && i<nArg; i++){
1.141665 +    const char *z = azArg[i];
1.141666 +    int n = strlen(z);
1.141667 +
1.141668 +    if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
1.141669 +      pNew->bRemoveDiacritic = 1;
1.141670 +    }
1.141671 +    else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
1.141672 +      pNew->bRemoveDiacritic = 0;
1.141673 +    }
1.141674 +    else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
1.141675 +      rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
1.141676 +    }
1.141677 +    else if( n>=11 && memcmp("separators=", z, 11)==0 ){
1.141678 +      rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
1.141679 +    }
1.141680 +    else{
1.141681 +      /* Unrecognized argument */
1.141682 +      rc  = SQLITE_ERROR;
1.141683 +    }
1.141684 +  }
1.141685 +
1.141686 +  if( rc!=SQLITE_OK ){
1.141687 +    unicodeDestroy((sqlite3_tokenizer *)pNew);
1.141688 +    pNew = 0;
1.141689 +  }
1.141690 +  *pp = (sqlite3_tokenizer *)pNew;
1.141691 +  return rc;
1.141692 +}
1.141693 +
1.141694 +/*
1.141695 +** Prepare to begin tokenizing a particular string.  The input
1.141696 +** string to be tokenized is pInput[0..nBytes-1].  A cursor
1.141697 +** used to incrementally tokenize this string is returned in 
1.141698 +** *ppCursor.
1.141699 +*/
1.141700 +static int unicodeOpen(
1.141701 +  sqlite3_tokenizer *p,           /* The tokenizer */
1.141702 +  const char *aInput,             /* Input string */
1.141703 +  int nInput,                     /* Size of string aInput in bytes */
1.141704 +  sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
1.141705 +){
1.141706 +  unicode_cursor *pCsr;
1.141707 +
1.141708 +  pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
1.141709 +  if( pCsr==0 ){
1.141710 +    return SQLITE_NOMEM;
1.141711 +  }
1.141712 +  memset(pCsr, 0, sizeof(unicode_cursor));
1.141713 +
1.141714 +  pCsr->aInput = (const unsigned char *)aInput;
1.141715 +  if( aInput==0 ){
1.141716 +    pCsr->nInput = 0;
1.141717 +  }else if( nInput<0 ){
1.141718 +    pCsr->nInput = (int)strlen(aInput);
1.141719 +  }else{
1.141720 +    pCsr->nInput = nInput;
1.141721 +  }
1.141722 +
1.141723 +  *pp = &pCsr->base;
1.141724 +  UNUSED_PARAMETER(p);
1.141725 +  return SQLITE_OK;
1.141726 +}
1.141727 +
1.141728 +/*
1.141729 +** Close a tokenization cursor previously opened by a call to
1.141730 +** simpleOpen() above.
1.141731 +*/
1.141732 +static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
1.141733 +  unicode_cursor *pCsr = (unicode_cursor *) pCursor;
1.141734 +  sqlite3_free(pCsr->zToken);
1.141735 +  sqlite3_free(pCsr);
1.141736 +  return SQLITE_OK;
1.141737 +}
1.141738 +
1.141739 +/*
1.141740 +** Extract the next token from a tokenization cursor.  The cursor must
1.141741 +** have been opened by a prior call to simpleOpen().
1.141742 +*/
1.141743 +static int unicodeNext(
1.141744 +  sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
1.141745 +  const char **paToken,           /* OUT: Token text */
1.141746 +  int *pnToken,                   /* OUT: Number of bytes at *paToken */
1.141747 +  int *piStart,                   /* OUT: Starting offset of token */
1.141748 +  int *piEnd,                     /* OUT: Ending offset of token */
1.141749 +  int *piPos                      /* OUT: Position integer of token */
1.141750 +){
1.141751 +  unicode_cursor *pCsr = (unicode_cursor *)pC;
1.141752 +  unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
1.141753 +  int iCode;
1.141754 +  char *zOut;
1.141755 +  const unsigned char *z = &pCsr->aInput[pCsr->iOff];
1.141756 +  const unsigned char *zStart = z;
1.141757 +  const unsigned char *zEnd;
1.141758 +  const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
1.141759 +
1.141760 +  /* Scan past any delimiter characters before the start of the next token.
1.141761 +  ** Return SQLITE_DONE early if this takes us all the way to the end of 
1.141762 +  ** the input.  */
1.141763 +  while( z<zTerm ){
1.141764 +    READ_UTF8(z, zTerm, iCode);
1.141765 +    if( unicodeIsAlnum(p, iCode) ) break;
1.141766 +    zStart = z;
1.141767 +  }
1.141768 +  if( zStart>=zTerm ) return SQLITE_DONE;
1.141769 +
1.141770 +  zOut = pCsr->zToken;
1.141771 +  do {
1.141772 +    int iOut;
1.141773 +
1.141774 +    /* Grow the output buffer if required. */
1.141775 +    if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
1.141776 +      char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
1.141777 +      if( !zNew ) return SQLITE_NOMEM;
1.141778 +      zOut = &zNew[zOut - pCsr->zToken];
1.141779 +      pCsr->zToken = zNew;
1.141780 +      pCsr->nAlloc += 64;
1.141781 +    }
1.141782 +
1.141783 +    /* Write the folded case of the last character read to the output */
1.141784 +    zEnd = z;
1.141785 +    iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
1.141786 +    if( iOut ){
1.141787 +      WRITE_UTF8(zOut, iOut);
1.141788 +    }
1.141789 +
1.141790 +    /* If the cursor is not at EOF, read the next character */
1.141791 +    if( z>=zTerm ) break;
1.141792 +    READ_UTF8(z, zTerm, iCode);
1.141793 +  }while( unicodeIsAlnum(p, iCode) 
1.141794 +       || sqlite3FtsUnicodeIsdiacritic(iCode)
1.141795 +  );
1.141796 +
1.141797 +  /* Set the output variables and return. */
1.141798 +  pCsr->iOff = (z - pCsr->aInput);
1.141799 +  *paToken = pCsr->zToken;
1.141800 +  *pnToken = zOut - pCsr->zToken;
1.141801 +  *piStart = (zStart - pCsr->aInput);
1.141802 +  *piEnd = (zEnd - pCsr->aInput);
1.141803 +  *piPos = pCsr->iToken++;
1.141804 +  return SQLITE_OK;
1.141805 +}
1.141806 +
1.141807 +/*
1.141808 +** Set *ppModule to a pointer to the sqlite3_tokenizer_module 
1.141809 +** structure for the unicode tokenizer.
1.141810 +*/
1.141811 +SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
1.141812 +  static const sqlite3_tokenizer_module module = {
1.141813 +    0,
1.141814 +    unicodeCreate,
1.141815 +    unicodeDestroy,
1.141816 +    unicodeOpen,
1.141817 +    unicodeClose,
1.141818 +    unicodeNext,
1.141819 +    0,
1.141820 +  };
1.141821 +  *ppModule = &module;
1.141822 +}
1.141823 +
1.141824 +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
1.141825 +#endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */
1.141826 +
1.141827 +/************** End of fts3_unicode.c ****************************************/
1.141828 +/************** Begin file fts3_unicode2.c ***********************************/
1.141829 +/*
1.141830 +** 2012 May 25
1.141831 +**
1.141832 +** The author disclaims copyright to this source code.  In place of
1.141833 +** a legal notice, here is a blessing:
1.141834 +**
1.141835 +**    May you do good and not evil.
1.141836 +**    May you find forgiveness for yourself and forgive others.
1.141837 +**    May you share freely, never taking more than you give.
1.141838 +**
1.141839 +******************************************************************************
1.141840 +*/
1.141841 +
1.141842 +/*
1.141843 +** DO NOT EDIT THIS MACHINE GENERATED FILE.
1.141844 +*/
1.141845 +
1.141846 +#if defined(SQLITE_ENABLE_FTS4_UNICODE61)
1.141847 +#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
1.141848 +
1.141849 +/* #include <assert.h> */
1.141850 +
1.141851 +/*
1.141852 +** Return true if the argument corresponds to a unicode codepoint
1.141853 +** classified as either a letter or a number. Otherwise false.
1.141854 +**
1.141855 +** The results are undefined if the value passed to this function
1.141856 +** is less than zero.
1.141857 +*/
1.141858 +SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
1.141859 +  /* Each unsigned integer in the following array corresponds to a contiguous
1.141860 +  ** range of unicode codepoints that are not either letters or numbers (i.e.
1.141861 +  ** codepoints for which this function should return 0).
1.141862 +  **
1.141863 +  ** The most significant 22 bits in each 32-bit value contain the first 
1.141864 +  ** codepoint in the range. The least significant 10 bits are used to store
1.141865 +  ** the size of the range (always at least 1). In other words, the value 
1.141866 +  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint 
1.141867 +  ** C. It is not possible to represent a range larger than 1023 codepoints 
1.141868 +  ** using this format.
1.141869 +  */
1.141870 +  const static unsigned int aEntry[] = {
1.141871 +    0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
1.141872 +    0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
1.141873 +    0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
1.141874 +    0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
1.141875 +    0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
1.141876 +    0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
1.141877 +    0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
1.141878 +    0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
1.141879 +    0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
1.141880 +    0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
1.141881 +    0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
1.141882 +    0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
1.141883 +    0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
1.141884 +    0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
1.141885 +    0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
1.141886 +    0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
1.141887 +    0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
1.141888 +    0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
1.141889 +    0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
1.141890 +    0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
1.141891 +    0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
1.141892 +    0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
1.141893 +    0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
1.141894 +    0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
1.141895 +    0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
1.141896 +    0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
1.141897 +    0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
1.141898 +    0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
1.141899 +    0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
1.141900 +    0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
1.141901 +    0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
1.141902 +    0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
1.141903 +    0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
1.141904 +    0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
1.141905 +    0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
1.141906 +    0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
1.141907 +    0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
1.141908 +    0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
1.141909 +    0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
1.141910 +    0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
1.141911 +    0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
1.141912 +    0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
1.141913 +    0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
1.141914 +    0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
1.141915 +    0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
1.141916 +    0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
1.141917 +    0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
1.141918 +    0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
1.141919 +    0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
1.141920 +    0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
1.141921 +    0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
1.141922 +    0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
1.141923 +    0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
1.141924 +    0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
1.141925 +    0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
1.141926 +    0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
1.141927 +    0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
1.141928 +    0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
1.141929 +    0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
1.141930 +    0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
1.141931 +    0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
1.141932 +    0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
1.141933 +    0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
1.141934 +    0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
1.141935 +    0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
1.141936 +    0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
1.141937 +    0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
1.141938 +    0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
1.141939 +    0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
1.141940 +    0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
1.141941 +    0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
1.141942 +    0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
1.141943 +    0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
1.141944 +    0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
1.141945 +    0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
1.141946 +    0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
1.141947 +    0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
1.141948 +    0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
1.141949 +    0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
1.141950 +    0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
1.141951 +    0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
1.141952 +    0x380400F0,
1.141953 +  };
1.141954 +  static const unsigned int aAscii[4] = {
1.141955 +    0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
1.141956 +  };
1.141957 +
1.141958 +  if( c<128 ){
1.141959 +    return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
1.141960 +  }else if( c<(1<<22) ){
1.141961 +    unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
1.141962 +    int iRes;
1.141963 +    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
1.141964 +    int iLo = 0;
1.141965 +    while( iHi>=iLo ){
1.141966 +      int iTest = (iHi + iLo) / 2;
1.141967 +      if( key >= aEntry[iTest] ){
1.141968 +        iRes = iTest;
1.141969 +        iLo = iTest+1;
1.141970 +      }else{
1.141971 +        iHi = iTest-1;
1.141972 +      }
1.141973 +    }
1.141974 +    assert( aEntry[0]<key );
1.141975 +    assert( key>=aEntry[iRes] );
1.141976 +    return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
1.141977 +  }
1.141978 +  return 1;
1.141979 +}
1.141980 +
1.141981 +
1.141982 +/*
1.141983 +** If the argument is a codepoint corresponding to a lowercase letter
1.141984 +** in the ASCII range with a diacritic added, return the codepoint
1.141985 +** of the ASCII letter only. For example, if passed 235 - "LATIN
1.141986 +** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
1.141987 +** E"). The resuls of passing a codepoint that corresponds to an
1.141988 +** uppercase letter are undefined.
1.141989 +*/
1.141990 +static int remove_diacritic(int c){
1.141991 +  unsigned short aDia[] = {
1.141992 +        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995, 
1.141993 +     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286, 
1.141994 +     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732, 
1.141995 +     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336, 
1.141996 +     3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928, 
1.141997 +     3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234, 
1.141998 +     4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504, 
1.141999 +     6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529, 
1.142000 +    61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726, 
1.142001 +    61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122, 
1.142002 +    62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536, 
1.142003 +    62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730, 
1.142004 +    62924, 63050, 63082, 63274, 63390, 
1.142005 +  };
1.142006 +  char aChar[] = {
1.142007 +    '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',  
1.142008 +    'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',  
1.142009 +    's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',  
1.142010 +    'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',  
1.142011 +    'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0', 
1.142012 +    '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',  
1.142013 +    'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',  
1.142014 +    'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',  
1.142015 +    'e',  'i',  'o',  'u',  'y',  
1.142016 +  };
1.142017 +
1.142018 +  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
1.142019 +  int iRes = 0;
1.142020 +  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
1.142021 +  int iLo = 0;
1.142022 +  while( iHi>=iLo ){
1.142023 +    int iTest = (iHi + iLo) / 2;
1.142024 +    if( key >= aDia[iTest] ){
1.142025 +      iRes = iTest;
1.142026 +      iLo = iTest+1;
1.142027 +    }else{
1.142028 +      iHi = iTest-1;
1.142029 +    }
1.142030 +  }
1.142031 +  assert( key>=aDia[iRes] );
1.142032 +  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
1.142033 +};
1.142034 +
1.142035 +
1.142036 +/*
1.142037 +** Return true if the argument interpreted as a unicode codepoint
1.142038 +** is a diacritical modifier character.
1.142039 +*/
1.142040 +SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
1.142041 +  unsigned int mask0 = 0x08029FDF;
1.142042 +  unsigned int mask1 = 0x000361F8;
1.142043 +  if( c<768 || c>817 ) return 0;
1.142044 +  return (c < 768+32) ?
1.142045 +      (mask0 & (1 << (c-768))) :
1.142046 +      (mask1 & (1 << (c-768-32)));
1.142047 +}
1.142048 +
1.142049 +
1.142050 +/*
1.142051 +** Interpret the argument as a unicode codepoint. If the codepoint
1.142052 +** is an upper case character that has a lower case equivalent,
1.142053 +** return the codepoint corresponding to the lower case version.
1.142054 +** Otherwise, return a copy of the argument.
1.142055 +**
1.142056 +** The results are undefined if the value passed to this function
1.142057 +** is less than zero.
1.142058 +*/
1.142059 +SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
1.142060 +  /* Each entry in the following array defines a rule for folding a range
1.142061 +  ** of codepoints to lower case. The rule applies to a range of nRange
1.142062 +  ** codepoints starting at codepoint iCode.
1.142063 +  **
1.142064 +  ** If the least significant bit in flags is clear, then the rule applies
1.142065 +  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
1.142066 +  ** need to be folded). Or, if it is set, then the rule only applies to
1.142067 +  ** every second codepoint in the range, starting with codepoint C.
1.142068 +  **
1.142069 +  ** The 7 most significant bits in flags are an index into the aiOff[]
1.142070 +  ** array. If a specific codepoint C does require folding, then its lower
1.142071 +  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
1.142072 +  **
1.142073 +  ** The contents of this array are generated by parsing the CaseFolding.txt
1.142074 +  ** file distributed as part of the "Unicode Character Database". See
1.142075 +  ** http://www.unicode.org for details.
1.142076 +  */
1.142077 +  static const struct TableEntry {
1.142078 +    unsigned short iCode;
1.142079 +    unsigned char flags;
1.142080 +    unsigned char nRange;
1.142081 +  } aEntry[] = {
1.142082 +    {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
1.142083 +    {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
1.142084 +    {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
1.142085 +    {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
1.142086 +    {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
1.142087 +    {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
1.142088 +    {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
1.142089 +    {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
1.142090 +    {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
1.142091 +    {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
1.142092 +    {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
1.142093 +    {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
1.142094 +    {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
1.142095 +    {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
1.142096 +    {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
1.142097 +    {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
1.142098 +    {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
1.142099 +    {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
1.142100 +    {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
1.142101 +    {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
1.142102 +    {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
1.142103 +    {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
1.142104 +    {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
1.142105 +    {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
1.142106 +    {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
1.142107 +    {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
1.142108 +    {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
1.142109 +    {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
1.142110 +    {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
1.142111 +    {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
1.142112 +    {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
1.142113 +    {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
1.142114 +    {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
1.142115 +    {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
1.142116 +    {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
1.142117 +    {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
1.142118 +    {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
1.142119 +    {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
1.142120 +    {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
1.142121 +    {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
1.142122 +    {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
1.142123 +    {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
1.142124 +    {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
1.142125 +    {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
1.142126 +    {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
1.142127 +    {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
1.142128 +    {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
1.142129 +    {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
1.142130 +    {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
1.142131 +    {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
1.142132 +    {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
1.142133 +    {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
1.142134 +    {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
1.142135 +    {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
1.142136 +    {65313, 14, 26},       
1.142137 +  };
1.142138 +  static const unsigned short aiOff[] = {
1.142139 +   1,     2,     8,     15,    16,    26,    28,    32,    
1.142140 +   37,    38,    40,    48,    63,    64,    69,    71,    
1.142141 +   79,    80,    116,   202,   203,   205,   206,   207,   
1.142142 +   209,   210,   211,   213,   214,   217,   218,   219,   
1.142143 +   775,   7264,  10792, 10795, 23228, 23256, 30204, 54721, 
1.142144 +   54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, 
1.142145 +   57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, 
1.142146 +   65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, 
1.142147 +   65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, 
1.142148 +   65514, 65521, 65527, 65528, 65529, 
1.142149 +  };
1.142150 +
1.142151 +  int ret = c;
1.142152 +
1.142153 +  assert( c>=0 );
1.142154 +  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
1.142155 +
1.142156 +  if( c<128 ){
1.142157 +    if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
1.142158 +  }else if( c<65536 ){
1.142159 +    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
1.142160 +    int iLo = 0;
1.142161 +    int iRes = -1;
1.142162 +
1.142163 +    while( iHi>=iLo ){
1.142164 +      int iTest = (iHi + iLo) / 2;
1.142165 +      int cmp = (c - aEntry[iTest].iCode);
1.142166 +      if( cmp>=0 ){
1.142167 +        iRes = iTest;
1.142168 +        iLo = iTest+1;
1.142169 +      }else{
1.142170 +        iHi = iTest-1;
1.142171 +      }
1.142172 +    }
1.142173 +    assert( iRes<0 || c>=aEntry[iRes].iCode );
1.142174 +
1.142175 +    if( iRes>=0 ){
1.142176 +      const struct TableEntry *p = &aEntry[iRes];
1.142177 +      if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
1.142178 +        ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
1.142179 +        assert( ret>0 );
1.142180 +      }
1.142181 +    }
1.142182 +
1.142183 +    if( bRemoveDiacritic ) ret = remove_diacritic(ret);
1.142184 +  }
1.142185 +  
1.142186 +  else if( c>=66560 && c<66600 ){
1.142187 +    ret = c + 40;
1.142188 +  }
1.142189 +
1.142190 +  return ret;
1.142191 +}
1.142192 +#endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
1.142193 +#endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */
1.142194 +
1.142195 +/************** End of fts3_unicode2.c ***************************************/
1.142196 +/************** Begin file rtree.c *******************************************/
1.142197 +/*
1.142198 +** 2001 September 15
1.142199 +**
1.142200 +** The author disclaims copyright to this source code.  In place of
1.142201 +** a legal notice, here is a blessing:
1.142202 +**
1.142203 +**    May you do good and not evil.
1.142204 +**    May you find forgiveness for yourself and forgive others.
1.142205 +**    May you share freely, never taking more than you give.
1.142206 +**
1.142207 +*************************************************************************
1.142208 +** This file contains code for implementations of the r-tree and r*-tree
1.142209 +** algorithms packaged as an SQLite virtual table module.
1.142210 +*/
1.142211 +
1.142212 +/*
1.142213 +** Database Format of R-Tree Tables
1.142214 +** --------------------------------
1.142215 +**
1.142216 +** The data structure for a single virtual r-tree table is stored in three 
1.142217 +** native SQLite tables declared as follows. In each case, the '%' character
1.142218 +** in the table name is replaced with the user-supplied name of the r-tree
1.142219 +** table.
1.142220 +**
1.142221 +**   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
1.142222 +**   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
1.142223 +**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
1.142224 +**
1.142225 +** The data for each node of the r-tree structure is stored in the %_node
1.142226 +** table. For each node that is not the root node of the r-tree, there is
1.142227 +** an entry in the %_parent table associating the node with its parent.
1.142228 +** And for each row of data in the table, there is an entry in the %_rowid
1.142229 +** table that maps from the entries rowid to the id of the node that it
1.142230 +** is stored on.
1.142231 +**
1.142232 +** The root node of an r-tree always exists, even if the r-tree table is
1.142233 +** empty. The nodeno of the root node is always 1. All other nodes in the
1.142234 +** table must be the same size as the root node. The content of each node
1.142235 +** is formatted as follows:
1.142236 +**
1.142237 +**   1. If the node is the root node (node 1), then the first 2 bytes
1.142238 +**      of the node contain the tree depth as a big-endian integer.
1.142239 +**      For non-root nodes, the first 2 bytes are left unused.
1.142240 +**
1.142241 +**   2. The next 2 bytes contain the number of entries currently 
1.142242 +**      stored in the node.
1.142243 +**
1.142244 +**   3. The remainder of the node contains the node entries. Each entry
1.142245 +**      consists of a single 8-byte integer followed by an even number
1.142246 +**      of 4-byte coordinates. For leaf nodes the integer is the rowid
1.142247 +**      of a record. For internal nodes it is the node number of a
1.142248 +**      child page.
1.142249 +*/
1.142250 +
1.142251 +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
1.142252 +
1.142253 +/*
1.142254 +** This file contains an implementation of a couple of different variants
1.142255 +** of the r-tree algorithm. See the README file for further details. The 
1.142256 +** same data-structure is used for all, but the algorithms for insert and
1.142257 +** delete operations vary. The variants used are selected at compile time 
1.142258 +** by defining the following symbols:
1.142259 +*/
1.142260 +
1.142261 +/* Either, both or none of the following may be set to activate 
1.142262 +** r*tree variant algorithms.
1.142263 +*/
1.142264 +#define VARIANT_RSTARTREE_CHOOSESUBTREE 0
1.142265 +#define VARIANT_RSTARTREE_REINSERT      1
1.142266 +
1.142267 +/* 
1.142268 +** Exactly one of the following must be set to 1.
1.142269 +*/
1.142270 +#define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
1.142271 +#define VARIANT_GUTTMAN_LINEAR_SPLIT    0
1.142272 +#define VARIANT_RSTARTREE_SPLIT         1
1.142273 +
1.142274 +#define VARIANT_GUTTMAN_SPLIT \
1.142275 +        (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
1.142276 +
1.142277 +#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
1.142278 +  #define PickNext QuadraticPickNext
1.142279 +  #define PickSeeds QuadraticPickSeeds
1.142280 +  #define AssignCells splitNodeGuttman
1.142281 +#endif
1.142282 +#if VARIANT_GUTTMAN_LINEAR_SPLIT
1.142283 +  #define PickNext LinearPickNext
1.142284 +  #define PickSeeds LinearPickSeeds
1.142285 +  #define AssignCells splitNodeGuttman
1.142286 +#endif
1.142287 +#if VARIANT_RSTARTREE_SPLIT
1.142288 +  #define AssignCells splitNodeStartree
1.142289 +#endif
1.142290 +
1.142291 +#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
1.142292 +# define NDEBUG 1
1.142293 +#endif
1.142294 +
1.142295 +#ifndef SQLITE_CORE
1.142296 +  SQLITE_EXTENSION_INIT1
1.142297 +#else
1.142298 +#endif
1.142299 +
1.142300 +/* #include <string.h> */
1.142301 +/* #include <assert.h> */
1.142302 +
1.142303 +#ifndef SQLITE_AMALGAMATION
1.142304 +#include "sqlite3rtree.h"
1.142305 +typedef sqlite3_int64 i64;
1.142306 +typedef unsigned char u8;
1.142307 +typedef unsigned int u32;
1.142308 +#endif
1.142309 +
1.142310 +/*  The following macro is used to suppress compiler warnings.
1.142311 +*/
1.142312 +#ifndef UNUSED_PARAMETER
1.142313 +# define UNUSED_PARAMETER(x) (void)(x)
1.142314 +#endif
1.142315 +
1.142316 +typedef struct Rtree Rtree;
1.142317 +typedef struct RtreeCursor RtreeCursor;
1.142318 +typedef struct RtreeNode RtreeNode;
1.142319 +typedef struct RtreeCell RtreeCell;
1.142320 +typedef struct RtreeConstraint RtreeConstraint;
1.142321 +typedef struct RtreeMatchArg RtreeMatchArg;
1.142322 +typedef struct RtreeGeomCallback RtreeGeomCallback;
1.142323 +typedef union RtreeCoord RtreeCoord;
1.142324 +
1.142325 +/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
1.142326 +#define RTREE_MAX_DIMENSIONS 5
1.142327 +
1.142328 +/* Size of hash table Rtree.aHash. This hash table is not expected to
1.142329 +** ever contain very many entries, so a fixed number of buckets is 
1.142330 +** used.
1.142331 +*/
1.142332 +#define HASHSIZE 128
1.142333 +
1.142334 +/* The xBestIndex method of this virtual table requires an estimate of
1.142335 +** the number of rows in the virtual table to calculate the costs of
1.142336 +** various strategies. If possible, this estimate is loaded from the
1.142337 +** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
1.142338 +** Otherwise, if no sqlite_stat1 entry is available, use 
1.142339 +** RTREE_DEFAULT_ROWEST.
1.142340 +*/
1.142341 +#define RTREE_DEFAULT_ROWEST 1048576
1.142342 +#define RTREE_MIN_ROWEST         100
1.142343 +
1.142344 +/* 
1.142345 +** An rtree virtual-table object.
1.142346 +*/
1.142347 +struct Rtree {
1.142348 +  sqlite3_vtab base;
1.142349 +  sqlite3 *db;                /* Host database connection */
1.142350 +  int iNodeSize;              /* Size in bytes of each node in the node table */
1.142351 +  int nDim;                   /* Number of dimensions */
1.142352 +  int nBytesPerCell;          /* Bytes consumed per cell */
1.142353 +  int iDepth;                 /* Current depth of the r-tree structure */
1.142354 +  char *zDb;                  /* Name of database containing r-tree table */
1.142355 +  char *zName;                /* Name of r-tree table */ 
1.142356 +  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
1.142357 +  int nBusy;                  /* Current number of users of this structure */
1.142358 +  i64 nRowEst;                /* Estimated number of rows in this table */
1.142359 +
1.142360 +  /* List of nodes removed during a CondenseTree operation. List is
1.142361 +  ** linked together via the pointer normally used for hash chains -
1.142362 +  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
1.142363 +  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
1.142364 +  */
1.142365 +  RtreeNode *pDeleted;
1.142366 +  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
1.142367 +
1.142368 +  /* Statements to read/write/delete a record from xxx_node */
1.142369 +  sqlite3_stmt *pReadNode;
1.142370 +  sqlite3_stmt *pWriteNode;
1.142371 +  sqlite3_stmt *pDeleteNode;
1.142372 +
1.142373 +  /* Statements to read/write/delete a record from xxx_rowid */
1.142374 +  sqlite3_stmt *pReadRowid;
1.142375 +  sqlite3_stmt *pWriteRowid;
1.142376 +  sqlite3_stmt *pDeleteRowid;
1.142377 +
1.142378 +  /* Statements to read/write/delete a record from xxx_parent */
1.142379 +  sqlite3_stmt *pReadParent;
1.142380 +  sqlite3_stmt *pWriteParent;
1.142381 +  sqlite3_stmt *pDeleteParent;
1.142382 +
1.142383 +  int eCoordType;
1.142384 +};
1.142385 +
1.142386 +/* Possible values for eCoordType: */
1.142387 +#define RTREE_COORD_REAL32 0
1.142388 +#define RTREE_COORD_INT32  1
1.142389 +
1.142390 +/*
1.142391 +** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
1.142392 +** only deal with integer coordinates.  No floating point operations
1.142393 +** will be done.
1.142394 +*/
1.142395 +#ifdef SQLITE_RTREE_INT_ONLY
1.142396 +  typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
1.142397 +  typedef int RtreeValue;                  /* Low accuracy coordinate */
1.142398 +#else
1.142399 +  typedef double RtreeDValue;              /* High accuracy coordinate */
1.142400 +  typedef float RtreeValue;                /* Low accuracy coordinate */
1.142401 +#endif
1.142402 +
1.142403 +/*
1.142404 +** The minimum number of cells allowed for a node is a third of the 
1.142405 +** maximum. In Gutman's notation:
1.142406 +**
1.142407 +**     m = M/3
1.142408 +**
1.142409 +** If an R*-tree "Reinsert" operation is required, the same number of
1.142410 +** cells are removed from the overfull node and reinserted into the tree.
1.142411 +*/
1.142412 +#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
1.142413 +#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
1.142414 +#define RTREE_MAXCELLS 51
1.142415 +
1.142416 +/*
1.142417 +** The smallest possible node-size is (512-64)==448 bytes. And the largest
1.142418 +** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
1.142419 +** Therefore all non-root nodes must contain at least 3 entries. Since 
1.142420 +** 2^40 is greater than 2^64, an r-tree structure always has a depth of
1.142421 +** 40 or less.
1.142422 +*/
1.142423 +#define RTREE_MAX_DEPTH 40
1.142424 +
1.142425 +/* 
1.142426 +** An rtree cursor object.
1.142427 +*/
1.142428 +struct RtreeCursor {
1.142429 +  sqlite3_vtab_cursor base;
1.142430 +  RtreeNode *pNode;                 /* Node cursor is currently pointing at */
1.142431 +  int iCell;                        /* Index of current cell in pNode */
1.142432 +  int iStrategy;                    /* Copy of idxNum search parameter */
1.142433 +  int nConstraint;                  /* Number of entries in aConstraint */
1.142434 +  RtreeConstraint *aConstraint;     /* Search constraints. */
1.142435 +};
1.142436 +
1.142437 +union RtreeCoord {
1.142438 +  RtreeValue f;
1.142439 +  int i;
1.142440 +};
1.142441 +
1.142442 +/*
1.142443 +** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
1.142444 +** formatted as a RtreeDValue (double or int64). This macro assumes that local
1.142445 +** variable pRtree points to the Rtree structure associated with the
1.142446 +** RtreeCoord.
1.142447 +*/
1.142448 +#ifdef SQLITE_RTREE_INT_ONLY
1.142449 +# define DCOORD(coord) ((RtreeDValue)coord.i)
1.142450 +#else
1.142451 +# define DCOORD(coord) (                           \
1.142452 +    (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
1.142453 +      ((double)coord.f) :                           \
1.142454 +      ((double)coord.i)                             \
1.142455 +  )
1.142456 +#endif
1.142457 +
1.142458 +/*
1.142459 +** A search constraint.
1.142460 +*/
1.142461 +struct RtreeConstraint {
1.142462 +  int iCoord;                     /* Index of constrained coordinate */
1.142463 +  int op;                         /* Constraining operation */
1.142464 +  RtreeDValue rValue;             /* Constraint value. */
1.142465 +  int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
1.142466 +  sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
1.142467 +};
1.142468 +
1.142469 +/* Possible values for RtreeConstraint.op */
1.142470 +#define RTREE_EQ    0x41
1.142471 +#define RTREE_LE    0x42
1.142472 +#define RTREE_LT    0x43
1.142473 +#define RTREE_GE    0x44
1.142474 +#define RTREE_GT    0x45
1.142475 +#define RTREE_MATCH 0x46
1.142476 +
1.142477 +/* 
1.142478 +** An rtree structure node.
1.142479 +*/
1.142480 +struct RtreeNode {
1.142481 +  RtreeNode *pParent;               /* Parent node */
1.142482 +  i64 iNode;
1.142483 +  int nRef;
1.142484 +  int isDirty;
1.142485 +  u8 *zData;
1.142486 +  RtreeNode *pNext;                 /* Next node in this hash chain */
1.142487 +};
1.142488 +#define NCELL(pNode) readInt16(&(pNode)->zData[2])
1.142489 +
1.142490 +/* 
1.142491 +** Structure to store a deserialized rtree record.
1.142492 +*/
1.142493 +struct RtreeCell {
1.142494 +  i64 iRowid;
1.142495 +  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
1.142496 +};
1.142497 +
1.142498 +
1.142499 +/*
1.142500 +** Value for the first field of every RtreeMatchArg object. The MATCH
1.142501 +** operator tests that the first field of a blob operand matches this
1.142502 +** value to avoid operating on invalid blobs (which could cause a segfault).
1.142503 +*/
1.142504 +#define RTREE_GEOMETRY_MAGIC 0x891245AB
1.142505 +
1.142506 +/*
1.142507 +** An instance of this structure must be supplied as a blob argument to
1.142508 +** the right-hand-side of an SQL MATCH operator used to constrain an
1.142509 +** r-tree query.
1.142510 +*/
1.142511 +struct RtreeMatchArg {
1.142512 +  u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
1.142513 +  int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *);
1.142514 +  void *pContext;
1.142515 +  int nParam;
1.142516 +  RtreeDValue aParam[1];
1.142517 +};
1.142518 +
1.142519 +/*
1.142520 +** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
1.142521 +** a single instance of the following structure is allocated. It is used
1.142522 +** as the context for the user-function created by by s_r_g_c(). The object
1.142523 +** is eventually deleted by the destructor mechanism provided by
1.142524 +** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
1.142525 +** the geometry callback function).
1.142526 +*/
1.142527 +struct RtreeGeomCallback {
1.142528 +  int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
1.142529 +  void *pContext;
1.142530 +};
1.142531 +
1.142532 +#ifndef MAX
1.142533 +# define MAX(x,y) ((x) < (y) ? (y) : (x))
1.142534 +#endif
1.142535 +#ifndef MIN
1.142536 +# define MIN(x,y) ((x) > (y) ? (y) : (x))
1.142537 +#endif
1.142538 +
1.142539 +/*
1.142540 +** Functions to deserialize a 16 bit integer, 32 bit real number and
1.142541 +** 64 bit integer. The deserialized value is returned.
1.142542 +*/
1.142543 +static int readInt16(u8 *p){
1.142544 +  return (p[0]<<8) + p[1];
1.142545 +}
1.142546 +static void readCoord(u8 *p, RtreeCoord *pCoord){
1.142547 +  u32 i = (
1.142548 +    (((u32)p[0]) << 24) + 
1.142549 +    (((u32)p[1]) << 16) + 
1.142550 +    (((u32)p[2]) <<  8) + 
1.142551 +    (((u32)p[3]) <<  0)
1.142552 +  );
1.142553 +  *(u32 *)pCoord = i;
1.142554 +}
1.142555 +static i64 readInt64(u8 *p){
1.142556 +  return (
1.142557 +    (((i64)p[0]) << 56) + 
1.142558 +    (((i64)p[1]) << 48) + 
1.142559 +    (((i64)p[2]) << 40) + 
1.142560 +    (((i64)p[3]) << 32) + 
1.142561 +    (((i64)p[4]) << 24) + 
1.142562 +    (((i64)p[5]) << 16) + 
1.142563 +    (((i64)p[6]) <<  8) + 
1.142564 +    (((i64)p[7]) <<  0)
1.142565 +  );
1.142566 +}
1.142567 +
1.142568 +/*
1.142569 +** Functions to serialize a 16 bit integer, 32 bit real number and
1.142570 +** 64 bit integer. The value returned is the number of bytes written
1.142571 +** to the argument buffer (always 2, 4 and 8 respectively).
1.142572 +*/
1.142573 +static int writeInt16(u8 *p, int i){
1.142574 +  p[0] = (i>> 8)&0xFF;
1.142575 +  p[1] = (i>> 0)&0xFF;
1.142576 +  return 2;
1.142577 +}
1.142578 +static int writeCoord(u8 *p, RtreeCoord *pCoord){
1.142579 +  u32 i;
1.142580 +  assert( sizeof(RtreeCoord)==4 );
1.142581 +  assert( sizeof(u32)==4 );
1.142582 +  i = *(u32 *)pCoord;
1.142583 +  p[0] = (i>>24)&0xFF;
1.142584 +  p[1] = (i>>16)&0xFF;
1.142585 +  p[2] = (i>> 8)&0xFF;
1.142586 +  p[3] = (i>> 0)&0xFF;
1.142587 +  return 4;
1.142588 +}
1.142589 +static int writeInt64(u8 *p, i64 i){
1.142590 +  p[0] = (i>>56)&0xFF;
1.142591 +  p[1] = (i>>48)&0xFF;
1.142592 +  p[2] = (i>>40)&0xFF;
1.142593 +  p[3] = (i>>32)&0xFF;
1.142594 +  p[4] = (i>>24)&0xFF;
1.142595 +  p[5] = (i>>16)&0xFF;
1.142596 +  p[6] = (i>> 8)&0xFF;
1.142597 +  p[7] = (i>> 0)&0xFF;
1.142598 +  return 8;
1.142599 +}
1.142600 +
1.142601 +/*
1.142602 +** Increment the reference count of node p.
1.142603 +*/
1.142604 +static void nodeReference(RtreeNode *p){
1.142605 +  if( p ){
1.142606 +    p->nRef++;
1.142607 +  }
1.142608 +}
1.142609 +
1.142610 +/*
1.142611 +** Clear the content of node p (set all bytes to 0x00).
1.142612 +*/
1.142613 +static void nodeZero(Rtree *pRtree, RtreeNode *p){
1.142614 +  memset(&p->zData[2], 0, pRtree->iNodeSize-2);
1.142615 +  p->isDirty = 1;
1.142616 +}
1.142617 +
1.142618 +/*
1.142619 +** Given a node number iNode, return the corresponding key to use
1.142620 +** in the Rtree.aHash table.
1.142621 +*/
1.142622 +static int nodeHash(i64 iNode){
1.142623 +  return (
1.142624 +    (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
1.142625 +    (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
1.142626 +  ) % HASHSIZE;
1.142627 +}
1.142628 +
1.142629 +/*
1.142630 +** Search the node hash table for node iNode. If found, return a pointer
1.142631 +** to it. Otherwise, return 0.
1.142632 +*/
1.142633 +static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
1.142634 +  RtreeNode *p;
1.142635 +  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
1.142636 +  return p;
1.142637 +}
1.142638 +
1.142639 +/*
1.142640 +** Add node pNode to the node hash table.
1.142641 +*/
1.142642 +static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
1.142643 +  int iHash;
1.142644 +  assert( pNode->pNext==0 );
1.142645 +  iHash = nodeHash(pNode->iNode);
1.142646 +  pNode->pNext = pRtree->aHash[iHash];
1.142647 +  pRtree->aHash[iHash] = pNode;
1.142648 +}
1.142649 +
1.142650 +/*
1.142651 +** Remove node pNode from the node hash table.
1.142652 +*/
1.142653 +static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
1.142654 +  RtreeNode **pp;
1.142655 +  if( pNode->iNode!=0 ){
1.142656 +    pp = &pRtree->aHash[nodeHash(pNode->iNode)];
1.142657 +    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
1.142658 +    *pp = pNode->pNext;
1.142659 +    pNode->pNext = 0;
1.142660 +  }
1.142661 +}
1.142662 +
1.142663 +/*
1.142664 +** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
1.142665 +** indicating that node has not yet been assigned a node number. It is
1.142666 +** assigned a node number when nodeWrite() is called to write the
1.142667 +** node contents out to the database.
1.142668 +*/
1.142669 +static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
1.142670 +  RtreeNode *pNode;
1.142671 +  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
1.142672 +  if( pNode ){
1.142673 +    memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
1.142674 +    pNode->zData = (u8 *)&pNode[1];
1.142675 +    pNode->nRef = 1;
1.142676 +    pNode->pParent = pParent;
1.142677 +    pNode->isDirty = 1;
1.142678 +    nodeReference(pParent);
1.142679 +  }
1.142680 +  return pNode;
1.142681 +}
1.142682 +
1.142683 +/*
1.142684 +** Obtain a reference to an r-tree node.
1.142685 +*/
1.142686 +static int
1.142687 +nodeAcquire(
1.142688 +  Rtree *pRtree,             /* R-tree structure */
1.142689 +  i64 iNode,                 /* Node number to load */
1.142690 +  RtreeNode *pParent,        /* Either the parent node or NULL */
1.142691 +  RtreeNode **ppNode         /* OUT: Acquired node */
1.142692 +){
1.142693 +  int rc;
1.142694 +  int rc2 = SQLITE_OK;
1.142695 +  RtreeNode *pNode;
1.142696 +
1.142697 +  /* Check if the requested node is already in the hash table. If so,
1.142698 +  ** increase its reference count and return it.
1.142699 +  */
1.142700 +  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
1.142701 +    assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
1.142702 +    if( pParent && !pNode->pParent ){
1.142703 +      nodeReference(pParent);
1.142704 +      pNode->pParent = pParent;
1.142705 +    }
1.142706 +    pNode->nRef++;
1.142707 +    *ppNode = pNode;
1.142708 +    return SQLITE_OK;
1.142709 +  }
1.142710 +
1.142711 +  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
1.142712 +  rc = sqlite3_step(pRtree->pReadNode);
1.142713 +  if( rc==SQLITE_ROW ){
1.142714 +    const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
1.142715 +    if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
1.142716 +      pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
1.142717 +      if( !pNode ){
1.142718 +        rc2 = SQLITE_NOMEM;
1.142719 +      }else{
1.142720 +        pNode->pParent = pParent;
1.142721 +        pNode->zData = (u8 *)&pNode[1];
1.142722 +        pNode->nRef = 1;
1.142723 +        pNode->iNode = iNode;
1.142724 +        pNode->isDirty = 0;
1.142725 +        pNode->pNext = 0;
1.142726 +        memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
1.142727 +        nodeReference(pParent);
1.142728 +      }
1.142729 +    }
1.142730 +  }
1.142731 +  rc = sqlite3_reset(pRtree->pReadNode);
1.142732 +  if( rc==SQLITE_OK ) rc = rc2;
1.142733 +
1.142734 +  /* If the root node was just loaded, set pRtree->iDepth to the height
1.142735 +  ** of the r-tree structure. A height of zero means all data is stored on
1.142736 +  ** the root node. A height of one means the children of the root node
1.142737 +  ** are the leaves, and so on. If the depth as specified on the root node
1.142738 +  ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
1.142739 +  */
1.142740 +  if( pNode && iNode==1 ){
1.142741 +    pRtree->iDepth = readInt16(pNode->zData);
1.142742 +    if( pRtree->iDepth>RTREE_MAX_DEPTH ){
1.142743 +      rc = SQLITE_CORRUPT_VTAB;
1.142744 +    }
1.142745 +  }
1.142746 +
1.142747 +  /* If no error has occurred so far, check if the "number of entries"
1.142748 +  ** field on the node is too large. If so, set the return code to 
1.142749 +  ** SQLITE_CORRUPT_VTAB.
1.142750 +  */
1.142751 +  if( pNode && rc==SQLITE_OK ){
1.142752 +    if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
1.142753 +      rc = SQLITE_CORRUPT_VTAB;
1.142754 +    }
1.142755 +  }
1.142756 +
1.142757 +  if( rc==SQLITE_OK ){
1.142758 +    if( pNode!=0 ){
1.142759 +      nodeHashInsert(pRtree, pNode);
1.142760 +    }else{
1.142761 +      rc = SQLITE_CORRUPT_VTAB;
1.142762 +    }
1.142763 +    *ppNode = pNode;
1.142764 +  }else{
1.142765 +    sqlite3_free(pNode);
1.142766 +    *ppNode = 0;
1.142767 +  }
1.142768 +
1.142769 +  return rc;
1.142770 +}
1.142771 +
1.142772 +/*
1.142773 +** Overwrite cell iCell of node pNode with the contents of pCell.
1.142774 +*/
1.142775 +static void nodeOverwriteCell(
1.142776 +  Rtree *pRtree, 
1.142777 +  RtreeNode *pNode,  
1.142778 +  RtreeCell *pCell, 
1.142779 +  int iCell
1.142780 +){
1.142781 +  int ii;
1.142782 +  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
1.142783 +  p += writeInt64(p, pCell->iRowid);
1.142784 +  for(ii=0; ii<(pRtree->nDim*2); ii++){
1.142785 +    p += writeCoord(p, &pCell->aCoord[ii]);
1.142786 +  }
1.142787 +  pNode->isDirty = 1;
1.142788 +}
1.142789 +
1.142790 +/*
1.142791 +** Remove cell the cell with index iCell from node pNode.
1.142792 +*/
1.142793 +static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
1.142794 +  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
1.142795 +  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
1.142796 +  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
1.142797 +  memmove(pDst, pSrc, nByte);
1.142798 +  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
1.142799 +  pNode->isDirty = 1;
1.142800 +}
1.142801 +
1.142802 +/*
1.142803 +** Insert the contents of cell pCell into node pNode. If the insert
1.142804 +** is successful, return SQLITE_OK.
1.142805 +**
1.142806 +** If there is not enough free space in pNode, return SQLITE_FULL.
1.142807 +*/
1.142808 +static int
1.142809 +nodeInsertCell(
1.142810 +  Rtree *pRtree, 
1.142811 +  RtreeNode *pNode, 
1.142812 +  RtreeCell *pCell 
1.142813 +){
1.142814 +  int nCell;                    /* Current number of cells in pNode */
1.142815 +  int nMaxCell;                 /* Maximum number of cells for pNode */
1.142816 +
1.142817 +  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
1.142818 +  nCell = NCELL(pNode);
1.142819 +
1.142820 +  assert( nCell<=nMaxCell );
1.142821 +  if( nCell<nMaxCell ){
1.142822 +    nodeOverwriteCell(pRtree, pNode, pCell, nCell);
1.142823 +    writeInt16(&pNode->zData[2], nCell+1);
1.142824 +    pNode->isDirty = 1;
1.142825 +  }
1.142826 +
1.142827 +  return (nCell==nMaxCell);
1.142828 +}
1.142829 +
1.142830 +/*
1.142831 +** If the node is dirty, write it out to the database.
1.142832 +*/
1.142833 +static int
1.142834 +nodeWrite(Rtree *pRtree, RtreeNode *pNode){
1.142835 +  int rc = SQLITE_OK;
1.142836 +  if( pNode->isDirty ){
1.142837 +    sqlite3_stmt *p = pRtree->pWriteNode;
1.142838 +    if( pNode->iNode ){
1.142839 +      sqlite3_bind_int64(p, 1, pNode->iNode);
1.142840 +    }else{
1.142841 +      sqlite3_bind_null(p, 1);
1.142842 +    }
1.142843 +    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
1.142844 +    sqlite3_step(p);
1.142845 +    pNode->isDirty = 0;
1.142846 +    rc = sqlite3_reset(p);
1.142847 +    if( pNode->iNode==0 && rc==SQLITE_OK ){
1.142848 +      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
1.142849 +      nodeHashInsert(pRtree, pNode);
1.142850 +    }
1.142851 +  }
1.142852 +  return rc;
1.142853 +}
1.142854 +
1.142855 +/*
1.142856 +** Release a reference to a node. If the node is dirty and the reference
1.142857 +** count drops to zero, the node data is written to the database.
1.142858 +*/
1.142859 +static int
1.142860 +nodeRelease(Rtree *pRtree, RtreeNode *pNode){
1.142861 +  int rc = SQLITE_OK;
1.142862 +  if( pNode ){
1.142863 +    assert( pNode->nRef>0 );
1.142864 +    pNode->nRef--;
1.142865 +    if( pNode->nRef==0 ){
1.142866 +      if( pNode->iNode==1 ){
1.142867 +        pRtree->iDepth = -1;
1.142868 +      }
1.142869 +      if( pNode->pParent ){
1.142870 +        rc = nodeRelease(pRtree, pNode->pParent);
1.142871 +      }
1.142872 +      if( rc==SQLITE_OK ){
1.142873 +        rc = nodeWrite(pRtree, pNode);
1.142874 +      }
1.142875 +      nodeHashDelete(pRtree, pNode);
1.142876 +      sqlite3_free(pNode);
1.142877 +    }
1.142878 +  }
1.142879 +  return rc;
1.142880 +}
1.142881 +
1.142882 +/*
1.142883 +** Return the 64-bit integer value associated with cell iCell of
1.142884 +** node pNode. If pNode is a leaf node, this is a rowid. If it is
1.142885 +** an internal node, then the 64-bit integer is a child page number.
1.142886 +*/
1.142887 +static i64 nodeGetRowid(
1.142888 +  Rtree *pRtree, 
1.142889 +  RtreeNode *pNode, 
1.142890 +  int iCell
1.142891 +){
1.142892 +  assert( iCell<NCELL(pNode) );
1.142893 +  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
1.142894 +}
1.142895 +
1.142896 +/*
1.142897 +** Return coordinate iCoord from cell iCell in node pNode.
1.142898 +*/
1.142899 +static void nodeGetCoord(
1.142900 +  Rtree *pRtree, 
1.142901 +  RtreeNode *pNode, 
1.142902 +  int iCell,
1.142903 +  int iCoord,
1.142904 +  RtreeCoord *pCoord           /* Space to write result to */
1.142905 +){
1.142906 +  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
1.142907 +}
1.142908 +
1.142909 +/*
1.142910 +** Deserialize cell iCell of node pNode. Populate the structure pointed
1.142911 +** to by pCell with the results.
1.142912 +*/
1.142913 +static void nodeGetCell(
1.142914 +  Rtree *pRtree, 
1.142915 +  RtreeNode *pNode, 
1.142916 +  int iCell,
1.142917 +  RtreeCell *pCell
1.142918 +){
1.142919 +  int ii;
1.142920 +  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
1.142921 +  for(ii=0; ii<pRtree->nDim*2; ii++){
1.142922 +    nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
1.142923 +  }
1.142924 +}
1.142925 +
1.142926 +
1.142927 +/* Forward declaration for the function that does the work of
1.142928 +** the virtual table module xCreate() and xConnect() methods.
1.142929 +*/
1.142930 +static int rtreeInit(
1.142931 +  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
1.142932 +);
1.142933 +
1.142934 +/* 
1.142935 +** Rtree virtual table module xCreate method.
1.142936 +*/
1.142937 +static int rtreeCreate(
1.142938 +  sqlite3 *db,
1.142939 +  void *pAux,
1.142940 +  int argc, const char *const*argv,
1.142941 +  sqlite3_vtab **ppVtab,
1.142942 +  char **pzErr
1.142943 +){
1.142944 +  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
1.142945 +}
1.142946 +
1.142947 +/* 
1.142948 +** Rtree virtual table module xConnect method.
1.142949 +*/
1.142950 +static int rtreeConnect(
1.142951 +  sqlite3 *db,
1.142952 +  void *pAux,
1.142953 +  int argc, const char *const*argv,
1.142954 +  sqlite3_vtab **ppVtab,
1.142955 +  char **pzErr
1.142956 +){
1.142957 +  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
1.142958 +}
1.142959 +
1.142960 +/*
1.142961 +** Increment the r-tree reference count.
1.142962 +*/
1.142963 +static void rtreeReference(Rtree *pRtree){
1.142964 +  pRtree->nBusy++;
1.142965 +}
1.142966 +
1.142967 +/*
1.142968 +** Decrement the r-tree reference count. When the reference count reaches
1.142969 +** zero the structure is deleted.
1.142970 +*/
1.142971 +static void rtreeRelease(Rtree *pRtree){
1.142972 +  pRtree->nBusy--;
1.142973 +  if( pRtree->nBusy==0 ){
1.142974 +    sqlite3_finalize(pRtree->pReadNode);
1.142975 +    sqlite3_finalize(pRtree->pWriteNode);
1.142976 +    sqlite3_finalize(pRtree->pDeleteNode);
1.142977 +    sqlite3_finalize(pRtree->pReadRowid);
1.142978 +    sqlite3_finalize(pRtree->pWriteRowid);
1.142979 +    sqlite3_finalize(pRtree->pDeleteRowid);
1.142980 +    sqlite3_finalize(pRtree->pReadParent);
1.142981 +    sqlite3_finalize(pRtree->pWriteParent);
1.142982 +    sqlite3_finalize(pRtree->pDeleteParent);
1.142983 +    sqlite3_free(pRtree);
1.142984 +  }
1.142985 +}
1.142986 +
1.142987 +/* 
1.142988 +** Rtree virtual table module xDisconnect method.
1.142989 +*/
1.142990 +static int rtreeDisconnect(sqlite3_vtab *pVtab){
1.142991 +  rtreeRelease((Rtree *)pVtab);
1.142992 +  return SQLITE_OK;
1.142993 +}
1.142994 +
1.142995 +/* 
1.142996 +** Rtree virtual table module xDestroy method.
1.142997 +*/
1.142998 +static int rtreeDestroy(sqlite3_vtab *pVtab){
1.142999 +  Rtree *pRtree = (Rtree *)pVtab;
1.143000 +  int rc;
1.143001 +  char *zCreate = sqlite3_mprintf(
1.143002 +    "DROP TABLE '%q'.'%q_node';"
1.143003 +    "DROP TABLE '%q'.'%q_rowid';"
1.143004 +    "DROP TABLE '%q'.'%q_parent';",
1.143005 +    pRtree->zDb, pRtree->zName, 
1.143006 +    pRtree->zDb, pRtree->zName,
1.143007 +    pRtree->zDb, pRtree->zName
1.143008 +  );
1.143009 +  if( !zCreate ){
1.143010 +    rc = SQLITE_NOMEM;
1.143011 +  }else{
1.143012 +    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
1.143013 +    sqlite3_free(zCreate);
1.143014 +  }
1.143015 +  if( rc==SQLITE_OK ){
1.143016 +    rtreeRelease(pRtree);
1.143017 +  }
1.143018 +
1.143019 +  return rc;
1.143020 +}
1.143021 +
1.143022 +/* 
1.143023 +** Rtree virtual table module xOpen method.
1.143024 +*/
1.143025 +static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
1.143026 +  int rc = SQLITE_NOMEM;
1.143027 +  RtreeCursor *pCsr;
1.143028 +
1.143029 +  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
1.143030 +  if( pCsr ){
1.143031 +    memset(pCsr, 0, sizeof(RtreeCursor));
1.143032 +    pCsr->base.pVtab = pVTab;
1.143033 +    rc = SQLITE_OK;
1.143034 +  }
1.143035 +  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
1.143036 +
1.143037 +  return rc;
1.143038 +}
1.143039 +
1.143040 +
1.143041 +/*
1.143042 +** Free the RtreeCursor.aConstraint[] array and its contents.
1.143043 +*/
1.143044 +static void freeCursorConstraints(RtreeCursor *pCsr){
1.143045 +  if( pCsr->aConstraint ){
1.143046 +    int i;                        /* Used to iterate through constraint array */
1.143047 +    for(i=0; i<pCsr->nConstraint; i++){
1.143048 +      sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
1.143049 +      if( pGeom ){
1.143050 +        if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
1.143051 +        sqlite3_free(pGeom);
1.143052 +      }
1.143053 +    }
1.143054 +    sqlite3_free(pCsr->aConstraint);
1.143055 +    pCsr->aConstraint = 0;
1.143056 +  }
1.143057 +}
1.143058 +
1.143059 +/* 
1.143060 +** Rtree virtual table module xClose method.
1.143061 +*/
1.143062 +static int rtreeClose(sqlite3_vtab_cursor *cur){
1.143063 +  Rtree *pRtree = (Rtree *)(cur->pVtab);
1.143064 +  int rc;
1.143065 +  RtreeCursor *pCsr = (RtreeCursor *)cur;
1.143066 +  freeCursorConstraints(pCsr);
1.143067 +  rc = nodeRelease(pRtree, pCsr->pNode);
1.143068 +  sqlite3_free(pCsr);
1.143069 +  return rc;
1.143070 +}
1.143071 +
1.143072 +/*
1.143073 +** Rtree virtual table module xEof method.
1.143074 +**
1.143075 +** Return non-zero if the cursor does not currently point to a valid 
1.143076 +** record (i.e if the scan has finished), or zero otherwise.
1.143077 +*/
1.143078 +static int rtreeEof(sqlite3_vtab_cursor *cur){
1.143079 +  RtreeCursor *pCsr = (RtreeCursor *)cur;
1.143080 +  return (pCsr->pNode==0);
1.143081 +}
1.143082 +
1.143083 +/*
1.143084 +** The r-tree constraint passed as the second argument to this function is
1.143085 +** guaranteed to be a MATCH constraint.
1.143086 +*/
1.143087 +static int testRtreeGeom(
1.143088 +  Rtree *pRtree,                  /* R-Tree object */
1.143089 +  RtreeConstraint *pConstraint,   /* MATCH constraint to test */
1.143090 +  RtreeCell *pCell,               /* Cell to test */
1.143091 +  int *pbRes                      /* OUT: Test result */
1.143092 +){
1.143093 +  int i;
1.143094 +  RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2];
1.143095 +  int nCoord = pRtree->nDim*2;
1.143096 +
1.143097 +  assert( pConstraint->op==RTREE_MATCH );
1.143098 +  assert( pConstraint->pGeom );
1.143099 +
1.143100 +  for(i=0; i<nCoord; i++){
1.143101 +    aCoord[i] = DCOORD(pCell->aCoord[i]);
1.143102 +  }
1.143103 +  return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
1.143104 +}
1.143105 +
1.143106 +/* 
1.143107 +** Cursor pCursor currently points to a cell in a non-leaf page.
1.143108 +** Set *pbEof to true if the sub-tree headed by the cell is filtered
1.143109 +** (excluded) by the constraints in the pCursor->aConstraint[] 
1.143110 +** array, or false otherwise.
1.143111 +**
1.143112 +** Return SQLITE_OK if successful or an SQLite error code if an error
1.143113 +** occurs within a geometry callback.
1.143114 +*/
1.143115 +static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
1.143116 +  RtreeCell cell;
1.143117 +  int ii;
1.143118 +  int bRes = 0;
1.143119 +  int rc = SQLITE_OK;
1.143120 +
1.143121 +  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
1.143122 +  for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
1.143123 +    RtreeConstraint *p = &pCursor->aConstraint[ii];
1.143124 +    RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
1.143125 +    RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
1.143126 +
1.143127 +    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
1.143128 +        || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
1.143129 +    );
1.143130 +
1.143131 +    switch( p->op ){
1.143132 +      case RTREE_LE: case RTREE_LT: 
1.143133 +        bRes = p->rValue<cell_min; 
1.143134 +        break;
1.143135 +
1.143136 +      case RTREE_GE: case RTREE_GT: 
1.143137 +        bRes = p->rValue>cell_max; 
1.143138 +        break;
1.143139 +
1.143140 +      case RTREE_EQ:
1.143141 +        bRes = (p->rValue>cell_max || p->rValue<cell_min);
1.143142 +        break;
1.143143 +
1.143144 +      default: {
1.143145 +        assert( p->op==RTREE_MATCH );
1.143146 +        rc = testRtreeGeom(pRtree, p, &cell, &bRes);
1.143147 +        bRes = !bRes;
1.143148 +        break;
1.143149 +      }
1.143150 +    }
1.143151 +  }
1.143152 +
1.143153 +  *pbEof = bRes;
1.143154 +  return rc;
1.143155 +}
1.143156 +
1.143157 +/* 
1.143158 +** Test if the cell that cursor pCursor currently points to
1.143159 +** would be filtered (excluded) by the constraints in the 
1.143160 +** pCursor->aConstraint[] array. If so, set *pbEof to true before
1.143161 +** returning. If the cell is not filtered (excluded) by the constraints,
1.143162 +** set pbEof to zero.
1.143163 +**
1.143164 +** Return SQLITE_OK if successful or an SQLite error code if an error
1.143165 +** occurs within a geometry callback.
1.143166 +**
1.143167 +** This function assumes that the cell is part of a leaf node.
1.143168 +*/
1.143169 +static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
1.143170 +  RtreeCell cell;
1.143171 +  int ii;
1.143172 +  *pbEof = 0;
1.143173 +
1.143174 +  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
1.143175 +  for(ii=0; ii<pCursor->nConstraint; ii++){
1.143176 +    RtreeConstraint *p = &pCursor->aConstraint[ii];
1.143177 +    RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]);
1.143178 +    int res;
1.143179 +    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
1.143180 +        || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
1.143181 +    );
1.143182 +    switch( p->op ){
1.143183 +      case RTREE_LE: res = (coord<=p->rValue); break;
1.143184 +      case RTREE_LT: res = (coord<p->rValue);  break;
1.143185 +      case RTREE_GE: res = (coord>=p->rValue); break;
1.143186 +      case RTREE_GT: res = (coord>p->rValue);  break;
1.143187 +      case RTREE_EQ: res = (coord==p->rValue); break;
1.143188 +      default: {
1.143189 +        int rc;
1.143190 +        assert( p->op==RTREE_MATCH );
1.143191 +        rc = testRtreeGeom(pRtree, p, &cell, &res);
1.143192 +        if( rc!=SQLITE_OK ){
1.143193 +          return rc;
1.143194 +        }
1.143195 +        break;
1.143196 +      }
1.143197 +    }
1.143198 +
1.143199 +    if( !res ){
1.143200 +      *pbEof = 1;
1.143201 +      return SQLITE_OK;
1.143202 +    }
1.143203 +  }
1.143204 +
1.143205 +  return SQLITE_OK;
1.143206 +}
1.143207 +
1.143208 +/*
1.143209 +** Cursor pCursor currently points at a node that heads a sub-tree of
1.143210 +** height iHeight (if iHeight==0, then the node is a leaf). Descend
1.143211 +** to point to the left-most cell of the sub-tree that matches the 
1.143212 +** configured constraints.
1.143213 +*/
1.143214 +static int descendToCell(
1.143215 +  Rtree *pRtree, 
1.143216 +  RtreeCursor *pCursor, 
1.143217 +  int iHeight,
1.143218 +  int *pEof                 /* OUT: Set to true if cannot descend */
1.143219 +){
1.143220 +  int isEof;
1.143221 +  int rc;
1.143222 +  int ii;
1.143223 +  RtreeNode *pChild;
1.143224 +  sqlite3_int64 iRowid;
1.143225 +
1.143226 +  RtreeNode *pSavedNode = pCursor->pNode;
1.143227 +  int iSavedCell = pCursor->iCell;
1.143228 +
1.143229 +  assert( iHeight>=0 );
1.143230 +
1.143231 +  if( iHeight==0 ){
1.143232 +    rc = testRtreeEntry(pRtree, pCursor, &isEof);
1.143233 +  }else{
1.143234 +    rc = testRtreeCell(pRtree, pCursor, &isEof);
1.143235 +  }
1.143236 +  if( rc!=SQLITE_OK || isEof || iHeight==0 ){
1.143237 +    goto descend_to_cell_out;
1.143238 +  }
1.143239 +
1.143240 +  iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
1.143241 +  rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
1.143242 +  if( rc!=SQLITE_OK ){
1.143243 +    goto descend_to_cell_out;
1.143244 +  }
1.143245 +
1.143246 +  nodeRelease(pRtree, pCursor->pNode);
1.143247 +  pCursor->pNode = pChild;
1.143248 +  isEof = 1;
1.143249 +  for(ii=0; isEof && ii<NCELL(pChild); ii++){
1.143250 +    pCursor->iCell = ii;
1.143251 +    rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
1.143252 +    if( rc!=SQLITE_OK ){
1.143253 +      goto descend_to_cell_out;
1.143254 +    }
1.143255 +  }
1.143256 +
1.143257 +  if( isEof ){
1.143258 +    assert( pCursor->pNode==pChild );
1.143259 +    nodeReference(pSavedNode);
1.143260 +    nodeRelease(pRtree, pChild);
1.143261 +    pCursor->pNode = pSavedNode;
1.143262 +    pCursor->iCell = iSavedCell;
1.143263 +  }
1.143264 +
1.143265 +descend_to_cell_out:
1.143266 +  *pEof = isEof;
1.143267 +  return rc;
1.143268 +}
1.143269 +
1.143270 +/*
1.143271 +** One of the cells in node pNode is guaranteed to have a 64-bit 
1.143272 +** integer value equal to iRowid. Return the index of this cell.
1.143273 +*/
1.143274 +static int nodeRowidIndex(
1.143275 +  Rtree *pRtree, 
1.143276 +  RtreeNode *pNode, 
1.143277 +  i64 iRowid,
1.143278 +  int *piIndex
1.143279 +){
1.143280 +  int ii;
1.143281 +  int nCell = NCELL(pNode);
1.143282 +  for(ii=0; ii<nCell; ii++){
1.143283 +    if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
1.143284 +      *piIndex = ii;
1.143285 +      return SQLITE_OK;
1.143286 +    }
1.143287 +  }
1.143288 +  return SQLITE_CORRUPT_VTAB;
1.143289 +}
1.143290 +
1.143291 +/*
1.143292 +** Return the index of the cell containing a pointer to node pNode
1.143293 +** in its parent. If pNode is the root node, return -1.
1.143294 +*/
1.143295 +static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
1.143296 +  RtreeNode *pParent = pNode->pParent;
1.143297 +  if( pParent ){
1.143298 +    return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
1.143299 +  }
1.143300 +  *piIndex = -1;
1.143301 +  return SQLITE_OK;
1.143302 +}
1.143303 +
1.143304 +/* 
1.143305 +** Rtree virtual table module xNext method.
1.143306 +*/
1.143307 +static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
1.143308 +  Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
1.143309 +  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1.143310 +  int rc = SQLITE_OK;
1.143311 +
1.143312 +  /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
1.143313 +  ** already at EOF. It is against the rules to call the xNext() method of
1.143314 +  ** a cursor that has already reached EOF.
1.143315 +  */
1.143316 +  assert( pCsr->pNode );
1.143317 +
1.143318 +  if( pCsr->iStrategy==1 ){
1.143319 +    /* This "scan" is a direct lookup by rowid. There is no next entry. */
1.143320 +    nodeRelease(pRtree, pCsr->pNode);
1.143321 +    pCsr->pNode = 0;
1.143322 +  }else{
1.143323 +    /* Move to the next entry that matches the configured constraints. */
1.143324 +    int iHeight = 0;
1.143325 +    while( pCsr->pNode ){
1.143326 +      RtreeNode *pNode = pCsr->pNode;
1.143327 +      int nCell = NCELL(pNode);
1.143328 +      for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
1.143329 +        int isEof;
1.143330 +        rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
1.143331 +        if( rc!=SQLITE_OK || !isEof ){
1.143332 +          return rc;
1.143333 +        }
1.143334 +      }
1.143335 +      pCsr->pNode = pNode->pParent;
1.143336 +      rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
1.143337 +      if( rc!=SQLITE_OK ){
1.143338 +        return rc;
1.143339 +      }
1.143340 +      nodeReference(pCsr->pNode);
1.143341 +      nodeRelease(pRtree, pNode);
1.143342 +      iHeight++;
1.143343 +    }
1.143344 +  }
1.143345 +
1.143346 +  return rc;
1.143347 +}
1.143348 +
1.143349 +/* 
1.143350 +** Rtree virtual table module xRowid method.
1.143351 +*/
1.143352 +static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
1.143353 +  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
1.143354 +  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1.143355 +
1.143356 +  assert(pCsr->pNode);
1.143357 +  *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
1.143358 +
1.143359 +  return SQLITE_OK;
1.143360 +}
1.143361 +
1.143362 +/* 
1.143363 +** Rtree virtual table module xColumn method.
1.143364 +*/
1.143365 +static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
1.143366 +  Rtree *pRtree = (Rtree *)cur->pVtab;
1.143367 +  RtreeCursor *pCsr = (RtreeCursor *)cur;
1.143368 +
1.143369 +  if( i==0 ){
1.143370 +    i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
1.143371 +    sqlite3_result_int64(ctx, iRowid);
1.143372 +  }else{
1.143373 +    RtreeCoord c;
1.143374 +    nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
1.143375 +#ifndef SQLITE_RTREE_INT_ONLY
1.143376 +    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
1.143377 +      sqlite3_result_double(ctx, c.f);
1.143378 +    }else
1.143379 +#endif
1.143380 +    {
1.143381 +      assert( pRtree->eCoordType==RTREE_COORD_INT32 );
1.143382 +      sqlite3_result_int(ctx, c.i);
1.143383 +    }
1.143384 +  }
1.143385 +
1.143386 +  return SQLITE_OK;
1.143387 +}
1.143388 +
1.143389 +/* 
1.143390 +** Use nodeAcquire() to obtain the leaf node containing the record with 
1.143391 +** rowid iRowid. If successful, set *ppLeaf to point to the node and
1.143392 +** return SQLITE_OK. If there is no such record in the table, set
1.143393 +** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
1.143394 +** to zero and return an SQLite error code.
1.143395 +*/
1.143396 +static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
1.143397 +  int rc;
1.143398 +  *ppLeaf = 0;
1.143399 +  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
1.143400 +  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
1.143401 +    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
1.143402 +    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
1.143403 +    sqlite3_reset(pRtree->pReadRowid);
1.143404 +  }else{
1.143405 +    rc = sqlite3_reset(pRtree->pReadRowid);
1.143406 +  }
1.143407 +  return rc;
1.143408 +}
1.143409 +
1.143410 +/*
1.143411 +** This function is called to configure the RtreeConstraint object passed
1.143412 +** as the second argument for a MATCH constraint. The value passed as the
1.143413 +** first argument to this function is the right-hand operand to the MATCH
1.143414 +** operator.
1.143415 +*/
1.143416 +static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
1.143417 +  RtreeMatchArg *p;
1.143418 +  sqlite3_rtree_geometry *pGeom;
1.143419 +  int nBlob;
1.143420 +
1.143421 +  /* Check that value is actually a blob. */
1.143422 +  if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
1.143423 +
1.143424 +  /* Check that the blob is roughly the right size. */
1.143425 +  nBlob = sqlite3_value_bytes(pValue);
1.143426 +  if( nBlob<(int)sizeof(RtreeMatchArg) 
1.143427 +   || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
1.143428 +  ){
1.143429 +    return SQLITE_ERROR;
1.143430 +  }
1.143431 +
1.143432 +  pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
1.143433 +      sizeof(sqlite3_rtree_geometry) + nBlob
1.143434 +  );
1.143435 +  if( !pGeom ) return SQLITE_NOMEM;
1.143436 +  memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
1.143437 +  p = (RtreeMatchArg *)&pGeom[1];
1.143438 +
1.143439 +  memcpy(p, sqlite3_value_blob(pValue), nBlob);
1.143440 +  if( p->magic!=RTREE_GEOMETRY_MAGIC 
1.143441 +   || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue))
1.143442 +  ){
1.143443 +    sqlite3_free(pGeom);
1.143444 +    return SQLITE_ERROR;
1.143445 +  }
1.143446 +
1.143447 +  pGeom->pContext = p->pContext;
1.143448 +  pGeom->nParam = p->nParam;
1.143449 +  pGeom->aParam = p->aParam;
1.143450 +
1.143451 +  pCons->xGeom = p->xGeom;
1.143452 +  pCons->pGeom = pGeom;
1.143453 +  return SQLITE_OK;
1.143454 +}
1.143455 +
1.143456 +/* 
1.143457 +** Rtree virtual table module xFilter method.
1.143458 +*/
1.143459 +static int rtreeFilter(
1.143460 +  sqlite3_vtab_cursor *pVtabCursor, 
1.143461 +  int idxNum, const char *idxStr,
1.143462 +  int argc, sqlite3_value **argv
1.143463 +){
1.143464 +  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
1.143465 +  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1.143466 +
1.143467 +  RtreeNode *pRoot = 0;
1.143468 +  int ii;
1.143469 +  int rc = SQLITE_OK;
1.143470 +
1.143471 +  rtreeReference(pRtree);
1.143472 +
1.143473 +  freeCursorConstraints(pCsr);
1.143474 +  pCsr->iStrategy = idxNum;
1.143475 +
1.143476 +  if( idxNum==1 ){
1.143477 +    /* Special case - lookup by rowid. */
1.143478 +    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
1.143479 +    i64 iRowid = sqlite3_value_int64(argv[0]);
1.143480 +    rc = findLeafNode(pRtree, iRowid, &pLeaf);
1.143481 +    pCsr->pNode = pLeaf; 
1.143482 +    if( pLeaf ){
1.143483 +      assert( rc==SQLITE_OK );
1.143484 +      rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
1.143485 +    }
1.143486 +  }else{
1.143487 +    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
1.143488 +    ** with the configured constraints. 
1.143489 +    */
1.143490 +    if( argc>0 ){
1.143491 +      pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
1.143492 +      pCsr->nConstraint = argc;
1.143493 +      if( !pCsr->aConstraint ){
1.143494 +        rc = SQLITE_NOMEM;
1.143495 +      }else{
1.143496 +        memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
1.143497 +        assert( (idxStr==0 && argc==0)
1.143498 +                || (idxStr && (int)strlen(idxStr)==argc*2) );
1.143499 +        for(ii=0; ii<argc; ii++){
1.143500 +          RtreeConstraint *p = &pCsr->aConstraint[ii];
1.143501 +          p->op = idxStr[ii*2];
1.143502 +          p->iCoord = idxStr[ii*2+1]-'a';
1.143503 +          if( p->op==RTREE_MATCH ){
1.143504 +            /* A MATCH operator. The right-hand-side must be a blob that
1.143505 +            ** can be cast into an RtreeMatchArg object. One created using
1.143506 +            ** an sqlite3_rtree_geometry_callback() SQL user function.
1.143507 +            */
1.143508 +            rc = deserializeGeometry(argv[ii], p);
1.143509 +            if( rc!=SQLITE_OK ){
1.143510 +              break;
1.143511 +            }
1.143512 +          }else{
1.143513 +#ifdef SQLITE_RTREE_INT_ONLY
1.143514 +            p->rValue = sqlite3_value_int64(argv[ii]);
1.143515 +#else
1.143516 +            p->rValue = sqlite3_value_double(argv[ii]);
1.143517 +#endif
1.143518 +          }
1.143519 +        }
1.143520 +      }
1.143521 +    }
1.143522 +  
1.143523 +    if( rc==SQLITE_OK ){
1.143524 +      pCsr->pNode = 0;
1.143525 +      rc = nodeAcquire(pRtree, 1, 0, &pRoot);
1.143526 +    }
1.143527 +    if( rc==SQLITE_OK ){
1.143528 +      int isEof = 1;
1.143529 +      int nCell = NCELL(pRoot);
1.143530 +      pCsr->pNode = pRoot;
1.143531 +      for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
1.143532 +        assert( pCsr->pNode==pRoot );
1.143533 +        rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
1.143534 +        if( !isEof ){
1.143535 +          break;
1.143536 +        }
1.143537 +      }
1.143538 +      if( rc==SQLITE_OK && isEof ){
1.143539 +        assert( pCsr->pNode==pRoot );
1.143540 +        nodeRelease(pRtree, pRoot);
1.143541 +        pCsr->pNode = 0;
1.143542 +      }
1.143543 +      assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
1.143544 +    }
1.143545 +  }
1.143546 +
1.143547 +  rtreeRelease(pRtree);
1.143548 +  return rc;
1.143549 +}
1.143550 +
1.143551 +/*
1.143552 +** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
1.143553 +** extension is currently being used by a version of SQLite too old to
1.143554 +** support estimatedRows. In that case this function is a no-op.
1.143555 +*/
1.143556 +static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
1.143557 +#if SQLITE_VERSION_NUMBER>=3008002
1.143558 +  if( sqlite3_libversion_number()>=3008002 ){
1.143559 +    pIdxInfo->estimatedRows = nRow;
1.143560 +  }
1.143561 +#endif
1.143562 +}
1.143563 +
1.143564 +/*
1.143565 +** Rtree virtual table module xBestIndex method. There are three
1.143566 +** table scan strategies to choose from (in order from most to 
1.143567 +** least desirable):
1.143568 +**
1.143569 +**   idxNum     idxStr        Strategy
1.143570 +**   ------------------------------------------------
1.143571 +**     1        Unused        Direct lookup by rowid.
1.143572 +**     2        See below     R-tree query or full-table scan.
1.143573 +**   ------------------------------------------------
1.143574 +**
1.143575 +** If strategy 1 is used, then idxStr is not meaningful. If strategy
1.143576 +** 2 is used, idxStr is formatted to contain 2 bytes for each 
1.143577 +** constraint used. The first two bytes of idxStr correspond to 
1.143578 +** the constraint in sqlite3_index_info.aConstraintUsage[] with
1.143579 +** (argvIndex==1) etc.
1.143580 +**
1.143581 +** The first of each pair of bytes in idxStr identifies the constraint
1.143582 +** operator as follows:
1.143583 +**
1.143584 +**   Operator    Byte Value
1.143585 +**   ----------------------
1.143586 +**      =        0x41 ('A')
1.143587 +**     <=        0x42 ('B')
1.143588 +**      <        0x43 ('C')
1.143589 +**     >=        0x44 ('D')
1.143590 +**      >        0x45 ('E')
1.143591 +**   MATCH       0x46 ('F')
1.143592 +**   ----------------------
1.143593 +**
1.143594 +** The second of each pair of bytes identifies the coordinate column
1.143595 +** to which the constraint applies. The leftmost coordinate column
1.143596 +** is 'a', the second from the left 'b' etc.
1.143597 +*/
1.143598 +static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
1.143599 +  Rtree *pRtree = (Rtree*)tab;
1.143600 +  int rc = SQLITE_OK;
1.143601 +  int ii;
1.143602 +  i64 nRow;                       /* Estimated rows returned by this scan */
1.143603 +
1.143604 +  int iIdx = 0;
1.143605 +  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
1.143606 +  memset(zIdxStr, 0, sizeof(zIdxStr));
1.143607 +
1.143608 +  assert( pIdxInfo->idxStr==0 );
1.143609 +  for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
1.143610 +    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
1.143611 +
1.143612 +    if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
1.143613 +      /* We have an equality constraint on the rowid. Use strategy 1. */
1.143614 +      int jj;
1.143615 +      for(jj=0; jj<ii; jj++){
1.143616 +        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
1.143617 +        pIdxInfo->aConstraintUsage[jj].omit = 0;
1.143618 +      }
1.143619 +      pIdxInfo->idxNum = 1;
1.143620 +      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
1.143621 +      pIdxInfo->aConstraintUsage[jj].omit = 1;
1.143622 +
1.143623 +      /* This strategy involves a two rowid lookups on an B-Tree structures
1.143624 +      ** and then a linear search of an R-Tree node. This should be 
1.143625 +      ** considered almost as quick as a direct rowid lookup (for which 
1.143626 +      ** sqlite uses an internal cost of 0.0). It is expected to return
1.143627 +      ** a single row.
1.143628 +      */ 
1.143629 +      pIdxInfo->estimatedCost = 30.0;
1.143630 +      setEstimatedRows(pIdxInfo, 1);
1.143631 +      return SQLITE_OK;
1.143632 +    }
1.143633 +
1.143634 +    if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
1.143635 +      u8 op;
1.143636 +      switch( p->op ){
1.143637 +        case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
1.143638 +        case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
1.143639 +        case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
1.143640 +        case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
1.143641 +        case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
1.143642 +        default:
1.143643 +          assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
1.143644 +          op = RTREE_MATCH; 
1.143645 +          break;
1.143646 +      }
1.143647 +      zIdxStr[iIdx++] = op;
1.143648 +      zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
1.143649 +      pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
1.143650 +      pIdxInfo->aConstraintUsage[ii].omit = 1;
1.143651 +    }
1.143652 +  }
1.143653 +
1.143654 +  pIdxInfo->idxNum = 2;
1.143655 +  pIdxInfo->needToFreeIdxStr = 1;
1.143656 +  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
1.143657 +    return SQLITE_NOMEM;
1.143658 +  }
1.143659 +
1.143660 +  nRow = pRtree->nRowEst / (iIdx + 1);
1.143661 +  pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
1.143662 +  setEstimatedRows(pIdxInfo, nRow);
1.143663 +
1.143664 +  return rc;
1.143665 +}
1.143666 +
1.143667 +/*
1.143668 +** Return the N-dimensional volumn of the cell stored in *p.
1.143669 +*/
1.143670 +static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
1.143671 +  RtreeDValue area = (RtreeDValue)1;
1.143672 +  int ii;
1.143673 +  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1.143674 +    area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
1.143675 +  }
1.143676 +  return area;
1.143677 +}
1.143678 +
1.143679 +/*
1.143680 +** Return the margin length of cell p. The margin length is the sum
1.143681 +** of the objects size in each dimension.
1.143682 +*/
1.143683 +static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
1.143684 +  RtreeDValue margin = (RtreeDValue)0;
1.143685 +  int ii;
1.143686 +  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1.143687 +    margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
1.143688 +  }
1.143689 +  return margin;
1.143690 +}
1.143691 +
1.143692 +/*
1.143693 +** Store the union of cells p1 and p2 in p1.
1.143694 +*/
1.143695 +static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
1.143696 +  int ii;
1.143697 +  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
1.143698 +    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1.143699 +      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
1.143700 +      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
1.143701 +    }
1.143702 +  }else{
1.143703 +    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1.143704 +      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
1.143705 +      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
1.143706 +    }
1.143707 +  }
1.143708 +}
1.143709 +
1.143710 +/*
1.143711 +** Return true if the area covered by p2 is a subset of the area covered
1.143712 +** by p1. False otherwise.
1.143713 +*/
1.143714 +static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
1.143715 +  int ii;
1.143716 +  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
1.143717 +  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1.143718 +    RtreeCoord *a1 = &p1->aCoord[ii];
1.143719 +    RtreeCoord *a2 = &p2->aCoord[ii];
1.143720 +    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
1.143721 +     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
1.143722 +    ){
1.143723 +      return 0;
1.143724 +    }
1.143725 +  }
1.143726 +  return 1;
1.143727 +}
1.143728 +
1.143729 +/*
1.143730 +** Return the amount cell p would grow by if it were unioned with pCell.
1.143731 +*/
1.143732 +static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
1.143733 +  RtreeDValue area;
1.143734 +  RtreeCell cell;
1.143735 +  memcpy(&cell, p, sizeof(RtreeCell));
1.143736 +  area = cellArea(pRtree, &cell);
1.143737 +  cellUnion(pRtree, &cell, pCell);
1.143738 +  return (cellArea(pRtree, &cell)-area);
1.143739 +}
1.143740 +
1.143741 +#if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
1.143742 +static RtreeDValue cellOverlap(
1.143743 +  Rtree *pRtree, 
1.143744 +  RtreeCell *p, 
1.143745 +  RtreeCell *aCell, 
1.143746 +  int nCell, 
1.143747 +  int iExclude
1.143748 +){
1.143749 +  int ii;
1.143750 +  RtreeDValue overlap = 0.0;
1.143751 +  for(ii=0; ii<nCell; ii++){
1.143752 +#if VARIANT_RSTARTREE_CHOOSESUBTREE
1.143753 +    if( ii!=iExclude )
1.143754 +#else
1.143755 +    assert( iExclude==-1 );
1.143756 +    UNUSED_PARAMETER(iExclude);
1.143757 +#endif
1.143758 +    {
1.143759 +      int jj;
1.143760 +      RtreeDValue o = (RtreeDValue)1;
1.143761 +      for(jj=0; jj<(pRtree->nDim*2); jj+=2){
1.143762 +        RtreeDValue x1, x2;
1.143763 +
1.143764 +        x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
1.143765 +        x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
1.143766 +
1.143767 +        if( x2<x1 ){
1.143768 +          o = 0.0;
1.143769 +          break;
1.143770 +        }else{
1.143771 +          o = o * (x2-x1);
1.143772 +        }
1.143773 +      }
1.143774 +      overlap += o;
1.143775 +    }
1.143776 +  }
1.143777 +  return overlap;
1.143778 +}
1.143779 +#endif
1.143780 +
1.143781 +#if VARIANT_RSTARTREE_CHOOSESUBTREE
1.143782 +static RtreeDValue cellOverlapEnlargement(
1.143783 +  Rtree *pRtree, 
1.143784 +  RtreeCell *p, 
1.143785 +  RtreeCell *pInsert, 
1.143786 +  RtreeCell *aCell, 
1.143787 +  int nCell, 
1.143788 +  int iExclude
1.143789 +){
1.143790 +  RtreeDValue before, after;
1.143791 +  before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
1.143792 +  cellUnion(pRtree, p, pInsert);
1.143793 +  after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
1.143794 +  return (after-before);
1.143795 +}
1.143796 +#endif
1.143797 +
1.143798 +
1.143799 +/*
1.143800 +** This function implements the ChooseLeaf algorithm from Gutman[84].
1.143801 +** ChooseSubTree in r*tree terminology.
1.143802 +*/
1.143803 +static int ChooseLeaf(
1.143804 +  Rtree *pRtree,               /* Rtree table */
1.143805 +  RtreeCell *pCell,            /* Cell to insert into rtree */
1.143806 +  int iHeight,                 /* Height of sub-tree rooted at pCell */
1.143807 +  RtreeNode **ppLeaf           /* OUT: Selected leaf page */
1.143808 +){
1.143809 +  int rc;
1.143810 +  int ii;
1.143811 +  RtreeNode *pNode;
1.143812 +  rc = nodeAcquire(pRtree, 1, 0, &pNode);
1.143813 +
1.143814 +  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
1.143815 +    int iCell;
1.143816 +    sqlite3_int64 iBest = 0;
1.143817 +
1.143818 +    RtreeDValue fMinGrowth = 0.0;
1.143819 +    RtreeDValue fMinArea = 0.0;
1.143820 +#if VARIANT_RSTARTREE_CHOOSESUBTREE
1.143821 +    RtreeDValue fMinOverlap = 0.0;
1.143822 +    RtreeDValue overlap;
1.143823 +#endif
1.143824 +
1.143825 +    int nCell = NCELL(pNode);
1.143826 +    RtreeCell cell;
1.143827 +    RtreeNode *pChild;
1.143828 +
1.143829 +    RtreeCell *aCell = 0;
1.143830 +
1.143831 +#if VARIANT_RSTARTREE_CHOOSESUBTREE
1.143832 +    if( ii==(pRtree->iDepth-1) ){
1.143833 +      int jj;
1.143834 +      aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
1.143835 +      if( !aCell ){
1.143836 +        rc = SQLITE_NOMEM;
1.143837 +        nodeRelease(pRtree, pNode);
1.143838 +        pNode = 0;
1.143839 +        continue;
1.143840 +      }
1.143841 +      for(jj=0; jj<nCell; jj++){
1.143842 +        nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
1.143843 +      }
1.143844 +    }
1.143845 +#endif
1.143846 +
1.143847 +    /* Select the child node which will be enlarged the least if pCell
1.143848 +    ** is inserted into it. Resolve ties by choosing the entry with
1.143849 +    ** the smallest area.
1.143850 +    */
1.143851 +    for(iCell=0; iCell<nCell; iCell++){
1.143852 +      int bBest = 0;
1.143853 +      RtreeDValue growth;
1.143854 +      RtreeDValue area;
1.143855 +      nodeGetCell(pRtree, pNode, iCell, &cell);
1.143856 +      growth = cellGrowth(pRtree, &cell, pCell);
1.143857 +      area = cellArea(pRtree, &cell);
1.143858 +
1.143859 +#if VARIANT_RSTARTREE_CHOOSESUBTREE
1.143860 +      if( ii==(pRtree->iDepth-1) ){
1.143861 +        overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
1.143862 +      }else{
1.143863 +        overlap = 0.0;
1.143864 +      }
1.143865 +      if( (iCell==0) 
1.143866 +       || (overlap<fMinOverlap) 
1.143867 +       || (overlap==fMinOverlap && growth<fMinGrowth)
1.143868 +       || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
1.143869 +      ){
1.143870 +        bBest = 1;
1.143871 +        fMinOverlap = overlap;
1.143872 +      }
1.143873 +#else
1.143874 +      if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
1.143875 +        bBest = 1;
1.143876 +      }
1.143877 +#endif
1.143878 +      if( bBest ){
1.143879 +        fMinGrowth = growth;
1.143880 +        fMinArea = area;
1.143881 +        iBest = cell.iRowid;
1.143882 +      }
1.143883 +    }
1.143884 +
1.143885 +    sqlite3_free(aCell);
1.143886 +    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
1.143887 +    nodeRelease(pRtree, pNode);
1.143888 +    pNode = pChild;
1.143889 +  }
1.143890 +
1.143891 +  *ppLeaf = pNode;
1.143892 +  return rc;
1.143893 +}
1.143894 +
1.143895 +/*
1.143896 +** A cell with the same content as pCell has just been inserted into
1.143897 +** the node pNode. This function updates the bounding box cells in
1.143898 +** all ancestor elements.
1.143899 +*/
1.143900 +static int AdjustTree(
1.143901 +  Rtree *pRtree,                    /* Rtree table */
1.143902 +  RtreeNode *pNode,                 /* Adjust ancestry of this node. */
1.143903 +  RtreeCell *pCell                  /* This cell was just inserted */
1.143904 +){
1.143905 +  RtreeNode *p = pNode;
1.143906 +  while( p->pParent ){
1.143907 +    RtreeNode *pParent = p->pParent;
1.143908 +    RtreeCell cell;
1.143909 +    int iCell;
1.143910 +
1.143911 +    if( nodeParentIndex(pRtree, p, &iCell) ){
1.143912 +      return SQLITE_CORRUPT_VTAB;
1.143913 +    }
1.143914 +
1.143915 +    nodeGetCell(pRtree, pParent, iCell, &cell);
1.143916 +    if( !cellContains(pRtree, &cell, pCell) ){
1.143917 +      cellUnion(pRtree, &cell, pCell);
1.143918 +      nodeOverwriteCell(pRtree, pParent, &cell, iCell);
1.143919 +    }
1.143920 + 
1.143921 +    p = pParent;
1.143922 +  }
1.143923 +  return SQLITE_OK;
1.143924 +}
1.143925 +
1.143926 +/*
1.143927 +** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
1.143928 +*/
1.143929 +static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
1.143930 +  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
1.143931 +  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
1.143932 +  sqlite3_step(pRtree->pWriteRowid);
1.143933 +  return sqlite3_reset(pRtree->pWriteRowid);
1.143934 +}
1.143935 +
1.143936 +/*
1.143937 +** Write mapping (iNode->iPar) to the <rtree>_parent table.
1.143938 +*/
1.143939 +static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
1.143940 +  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
1.143941 +  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
1.143942 +  sqlite3_step(pRtree->pWriteParent);
1.143943 +  return sqlite3_reset(pRtree->pWriteParent);
1.143944 +}
1.143945 +
1.143946 +static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
1.143947 +
1.143948 +#if VARIANT_GUTTMAN_LINEAR_SPLIT
1.143949 +/*
1.143950 +** Implementation of the linear variant of the PickNext() function from
1.143951 +** Guttman[84].
1.143952 +*/
1.143953 +static RtreeCell *LinearPickNext(
1.143954 +  Rtree *pRtree,
1.143955 +  RtreeCell *aCell, 
1.143956 +  int nCell, 
1.143957 +  RtreeCell *pLeftBox, 
1.143958 +  RtreeCell *pRightBox,
1.143959 +  int *aiUsed
1.143960 +){
1.143961 +  int ii;
1.143962 +  for(ii=0; aiUsed[ii]; ii++);
1.143963 +  aiUsed[ii] = 1;
1.143964 +  return &aCell[ii];
1.143965 +}
1.143966 +
1.143967 +/*
1.143968 +** Implementation of the linear variant of the PickSeeds() function from
1.143969 +** Guttman[84].
1.143970 +*/
1.143971 +static void LinearPickSeeds(
1.143972 +  Rtree *pRtree,
1.143973 +  RtreeCell *aCell, 
1.143974 +  int nCell, 
1.143975 +  int *piLeftSeed, 
1.143976 +  int *piRightSeed
1.143977 +){
1.143978 +  int i;
1.143979 +  int iLeftSeed = 0;
1.143980 +  int iRightSeed = 1;
1.143981 +  RtreeDValue maxNormalInnerWidth = (RtreeDValue)0;
1.143982 +
1.143983 +  /* Pick two "seed" cells from the array of cells. The algorithm used
1.143984 +  ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
1.143985 +  ** indices of the two seed cells in the array are stored in local
1.143986 +  ** variables iLeftSeek and iRightSeed.
1.143987 +  */
1.143988 +  for(i=0; i<pRtree->nDim; i++){
1.143989 +    RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]);
1.143990 +    RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]);
1.143991 +    RtreeDValue x3 = x1;
1.143992 +    RtreeDValue x4 = x2;
1.143993 +    int jj;
1.143994 +
1.143995 +    int iCellLeft = 0;
1.143996 +    int iCellRight = 0;
1.143997 +
1.143998 +    for(jj=1; jj<nCell; jj++){
1.143999 +      RtreeDValue left = DCOORD(aCell[jj].aCoord[i*2]);
1.144000 +      RtreeDValue right = DCOORD(aCell[jj].aCoord[i*2+1]);
1.144001 +
1.144002 +      if( left<x1 ) x1 = left;
1.144003 +      if( right>x4 ) x4 = right;
1.144004 +      if( left>x3 ){
1.144005 +        x3 = left;
1.144006 +        iCellRight = jj;
1.144007 +      }
1.144008 +      if( right<x2 ){
1.144009 +        x2 = right;
1.144010 +        iCellLeft = jj;
1.144011 +      }
1.144012 +    }
1.144013 +
1.144014 +    if( x4!=x1 ){
1.144015 +      RtreeDValue normalwidth = (x3 - x2) / (x4 - x1);
1.144016 +      if( normalwidth>maxNormalInnerWidth ){
1.144017 +        iLeftSeed = iCellLeft;
1.144018 +        iRightSeed = iCellRight;
1.144019 +      }
1.144020 +    }
1.144021 +  }
1.144022 +
1.144023 +  *piLeftSeed = iLeftSeed;
1.144024 +  *piRightSeed = iRightSeed;
1.144025 +}
1.144026 +#endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
1.144027 +
1.144028 +#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
1.144029 +/*
1.144030 +** Implementation of the quadratic variant of the PickNext() function from
1.144031 +** Guttman[84].
1.144032 +*/
1.144033 +static RtreeCell *QuadraticPickNext(
1.144034 +  Rtree *pRtree,
1.144035 +  RtreeCell *aCell, 
1.144036 +  int nCell, 
1.144037 +  RtreeCell *pLeftBox, 
1.144038 +  RtreeCell *pRightBox,
1.144039 +  int *aiUsed
1.144040 +){
1.144041 +  #define FABS(a) ((a)<0.0?-1.0*(a):(a))
1.144042 +
1.144043 +  int iSelect = -1;
1.144044 +  RtreeDValue fDiff;
1.144045 +  int ii;
1.144046 +  for(ii=0; ii<nCell; ii++){
1.144047 +    if( aiUsed[ii]==0 ){
1.144048 +      RtreeDValue left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
1.144049 +      RtreeDValue right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
1.144050 +      RtreeDValue diff = FABS(right-left);
1.144051 +      if( iSelect<0 || diff>fDiff ){
1.144052 +        fDiff = diff;
1.144053 +        iSelect = ii;
1.144054 +      }
1.144055 +    }
1.144056 +  }
1.144057 +  aiUsed[iSelect] = 1;
1.144058 +  return &aCell[iSelect];
1.144059 +}
1.144060 +
1.144061 +/*
1.144062 +** Implementation of the quadratic variant of the PickSeeds() function from
1.144063 +** Guttman[84].
1.144064 +*/
1.144065 +static void QuadraticPickSeeds(
1.144066 +  Rtree *pRtree,
1.144067 +  RtreeCell *aCell, 
1.144068 +  int nCell, 
1.144069 +  int *piLeftSeed, 
1.144070 +  int *piRightSeed
1.144071 +){
1.144072 +  int ii;
1.144073 +  int jj;
1.144074 +
1.144075 +  int iLeftSeed = 0;
1.144076 +  int iRightSeed = 1;
1.144077 +  RtreeDValue fWaste = 0.0;
1.144078 +
1.144079 +  for(ii=0; ii<nCell; ii++){
1.144080 +    for(jj=ii+1; jj<nCell; jj++){
1.144081 +      RtreeDValue right = cellArea(pRtree, &aCell[jj]);
1.144082 +      RtreeDValue growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
1.144083 +      RtreeDValue waste = growth - right;
1.144084 +
1.144085 +      if( waste>fWaste ){
1.144086 +        iLeftSeed = ii;
1.144087 +        iRightSeed = jj;
1.144088 +        fWaste = waste;
1.144089 +      }
1.144090 +    }
1.144091 +  }
1.144092 +
1.144093 +  *piLeftSeed = iLeftSeed;
1.144094 +  *piRightSeed = iRightSeed;
1.144095 +}
1.144096 +#endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
1.144097 +
1.144098 +/*
1.144099 +** Arguments aIdx, aDistance and aSpare all point to arrays of size
1.144100 +** nIdx. The aIdx array contains the set of integers from 0 to 
1.144101 +** (nIdx-1) in no particular order. This function sorts the values
1.144102 +** in aIdx according to the indexed values in aDistance. For
1.144103 +** example, assuming the inputs:
1.144104 +**
1.144105 +**   aIdx      = { 0,   1,   2,   3 }
1.144106 +**   aDistance = { 5.0, 2.0, 7.0, 6.0 }
1.144107 +**
1.144108 +** this function sets the aIdx array to contain:
1.144109 +**
1.144110 +**   aIdx      = { 0,   1,   2,   3 }
1.144111 +**
1.144112 +** The aSpare array is used as temporary working space by the
1.144113 +** sorting algorithm.
1.144114 +*/
1.144115 +static void SortByDistance(
1.144116 +  int *aIdx, 
1.144117 +  int nIdx, 
1.144118 +  RtreeDValue *aDistance, 
1.144119 +  int *aSpare
1.144120 +){
1.144121 +  if( nIdx>1 ){
1.144122 +    int iLeft = 0;
1.144123 +    int iRight = 0;
1.144124 +
1.144125 +    int nLeft = nIdx/2;
1.144126 +    int nRight = nIdx-nLeft;
1.144127 +    int *aLeft = aIdx;
1.144128 +    int *aRight = &aIdx[nLeft];
1.144129 +
1.144130 +    SortByDistance(aLeft, nLeft, aDistance, aSpare);
1.144131 +    SortByDistance(aRight, nRight, aDistance, aSpare);
1.144132 +
1.144133 +    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
1.144134 +    aLeft = aSpare;
1.144135 +
1.144136 +    while( iLeft<nLeft || iRight<nRight ){
1.144137 +      if( iLeft==nLeft ){
1.144138 +        aIdx[iLeft+iRight] = aRight[iRight];
1.144139 +        iRight++;
1.144140 +      }else if( iRight==nRight ){
1.144141 +        aIdx[iLeft+iRight] = aLeft[iLeft];
1.144142 +        iLeft++;
1.144143 +      }else{
1.144144 +        RtreeDValue fLeft = aDistance[aLeft[iLeft]];
1.144145 +        RtreeDValue fRight = aDistance[aRight[iRight]];
1.144146 +        if( fLeft<fRight ){
1.144147 +          aIdx[iLeft+iRight] = aLeft[iLeft];
1.144148 +          iLeft++;
1.144149 +        }else{
1.144150 +          aIdx[iLeft+iRight] = aRight[iRight];
1.144151 +          iRight++;
1.144152 +        }
1.144153 +      }
1.144154 +    }
1.144155 +
1.144156 +#if 0
1.144157 +    /* Check that the sort worked */
1.144158 +    {
1.144159 +      int jj;
1.144160 +      for(jj=1; jj<nIdx; jj++){
1.144161 +        RtreeDValue left = aDistance[aIdx[jj-1]];
1.144162 +        RtreeDValue right = aDistance[aIdx[jj]];
1.144163 +        assert( left<=right );
1.144164 +      }
1.144165 +    }
1.144166 +#endif
1.144167 +  }
1.144168 +}
1.144169 +
1.144170 +/*
1.144171 +** Arguments aIdx, aCell and aSpare all point to arrays of size
1.144172 +** nIdx. The aIdx array contains the set of integers from 0 to 
1.144173 +** (nIdx-1) in no particular order. This function sorts the values
1.144174 +** in aIdx according to dimension iDim of the cells in aCell. The
1.144175 +** minimum value of dimension iDim is considered first, the
1.144176 +** maximum used to break ties.
1.144177 +**
1.144178 +** The aSpare array is used as temporary working space by the
1.144179 +** sorting algorithm.
1.144180 +*/
1.144181 +static void SortByDimension(
1.144182 +  Rtree *pRtree,
1.144183 +  int *aIdx, 
1.144184 +  int nIdx, 
1.144185 +  int iDim, 
1.144186 +  RtreeCell *aCell, 
1.144187 +  int *aSpare
1.144188 +){
1.144189 +  if( nIdx>1 ){
1.144190 +
1.144191 +    int iLeft = 0;
1.144192 +    int iRight = 0;
1.144193 +
1.144194 +    int nLeft = nIdx/2;
1.144195 +    int nRight = nIdx-nLeft;
1.144196 +    int *aLeft = aIdx;
1.144197 +    int *aRight = &aIdx[nLeft];
1.144198 +
1.144199 +    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
1.144200 +    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
1.144201 +
1.144202 +    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
1.144203 +    aLeft = aSpare;
1.144204 +    while( iLeft<nLeft || iRight<nRight ){
1.144205 +      RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
1.144206 +      RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
1.144207 +      RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
1.144208 +      RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
1.144209 +      if( (iLeft!=nLeft) && ((iRight==nRight)
1.144210 +       || (xleft1<xright1)
1.144211 +       || (xleft1==xright1 && xleft2<xright2)
1.144212 +      )){
1.144213 +        aIdx[iLeft+iRight] = aLeft[iLeft];
1.144214 +        iLeft++;
1.144215 +      }else{
1.144216 +        aIdx[iLeft+iRight] = aRight[iRight];
1.144217 +        iRight++;
1.144218 +      }
1.144219 +    }
1.144220 +
1.144221 +#if 0
1.144222 +    /* Check that the sort worked */
1.144223 +    {
1.144224 +      int jj;
1.144225 +      for(jj=1; jj<nIdx; jj++){
1.144226 +        RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
1.144227 +        RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
1.144228 +        RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
1.144229 +        RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
1.144230 +        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
1.144231 +      }
1.144232 +    }
1.144233 +#endif
1.144234 +  }
1.144235 +}
1.144236 +
1.144237 +#if VARIANT_RSTARTREE_SPLIT
1.144238 +/*
1.144239 +** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
1.144240 +*/
1.144241 +static int splitNodeStartree(
1.144242 +  Rtree *pRtree,
1.144243 +  RtreeCell *aCell,
1.144244 +  int nCell,
1.144245 +  RtreeNode *pLeft,
1.144246 +  RtreeNode *pRight,
1.144247 +  RtreeCell *pBboxLeft,
1.144248 +  RtreeCell *pBboxRight
1.144249 +){
1.144250 +  int **aaSorted;
1.144251 +  int *aSpare;
1.144252 +  int ii;
1.144253 +
1.144254 +  int iBestDim = 0;
1.144255 +  int iBestSplit = 0;
1.144256 +  RtreeDValue fBestMargin = 0.0;
1.144257 +
1.144258 +  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
1.144259 +
1.144260 +  aaSorted = (int **)sqlite3_malloc(nByte);
1.144261 +  if( !aaSorted ){
1.144262 +    return SQLITE_NOMEM;
1.144263 +  }
1.144264 +
1.144265 +  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
1.144266 +  memset(aaSorted, 0, nByte);
1.144267 +  for(ii=0; ii<pRtree->nDim; ii++){
1.144268 +    int jj;
1.144269 +    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
1.144270 +    for(jj=0; jj<nCell; jj++){
1.144271 +      aaSorted[ii][jj] = jj;
1.144272 +    }
1.144273 +    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
1.144274 +  }
1.144275 +
1.144276 +  for(ii=0; ii<pRtree->nDim; ii++){
1.144277 +    RtreeDValue margin = 0.0;
1.144278 +    RtreeDValue fBestOverlap = 0.0;
1.144279 +    RtreeDValue fBestArea = 0.0;
1.144280 +    int iBestLeft = 0;
1.144281 +    int nLeft;
1.144282 +
1.144283 +    for(
1.144284 +      nLeft=RTREE_MINCELLS(pRtree); 
1.144285 +      nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
1.144286 +      nLeft++
1.144287 +    ){
1.144288 +      RtreeCell left;
1.144289 +      RtreeCell right;
1.144290 +      int kk;
1.144291 +      RtreeDValue overlap;
1.144292 +      RtreeDValue area;
1.144293 +
1.144294 +      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
1.144295 +      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
1.144296 +      for(kk=1; kk<(nCell-1); kk++){
1.144297 +        if( kk<nLeft ){
1.144298 +          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
1.144299 +        }else{
1.144300 +          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
1.144301 +        }
1.144302 +      }
1.144303 +      margin += cellMargin(pRtree, &left);
1.144304 +      margin += cellMargin(pRtree, &right);
1.144305 +      overlap = cellOverlap(pRtree, &left, &right, 1, -1);
1.144306 +      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
1.144307 +      if( (nLeft==RTREE_MINCELLS(pRtree))
1.144308 +       || (overlap<fBestOverlap)
1.144309 +       || (overlap==fBestOverlap && area<fBestArea)
1.144310 +      ){
1.144311 +        iBestLeft = nLeft;
1.144312 +        fBestOverlap = overlap;
1.144313 +        fBestArea = area;
1.144314 +      }
1.144315 +    }
1.144316 +
1.144317 +    if( ii==0 || margin<fBestMargin ){
1.144318 +      iBestDim = ii;
1.144319 +      fBestMargin = margin;
1.144320 +      iBestSplit = iBestLeft;
1.144321 +    }
1.144322 +  }
1.144323 +
1.144324 +  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
1.144325 +  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
1.144326 +  for(ii=0; ii<nCell; ii++){
1.144327 +    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
1.144328 +    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
1.144329 +    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
1.144330 +    nodeInsertCell(pRtree, pTarget, pCell);
1.144331 +    cellUnion(pRtree, pBbox, pCell);
1.144332 +  }
1.144333 +
1.144334 +  sqlite3_free(aaSorted);
1.144335 +  return SQLITE_OK;
1.144336 +}
1.144337 +#endif
1.144338 +
1.144339 +#if VARIANT_GUTTMAN_SPLIT
1.144340 +/*
1.144341 +** Implementation of the regular R-tree SplitNode from Guttman[1984].
1.144342 +*/
1.144343 +static int splitNodeGuttman(
1.144344 +  Rtree *pRtree,
1.144345 +  RtreeCell *aCell,
1.144346 +  int nCell,
1.144347 +  RtreeNode *pLeft,
1.144348 +  RtreeNode *pRight,
1.144349 +  RtreeCell *pBboxLeft,
1.144350 +  RtreeCell *pBboxRight
1.144351 +){
1.144352 +  int iLeftSeed = 0;
1.144353 +  int iRightSeed = 1;
1.144354 +  int *aiUsed;
1.144355 +  int i;
1.144356 +
1.144357 +  aiUsed = sqlite3_malloc(sizeof(int)*nCell);
1.144358 +  if( !aiUsed ){
1.144359 +    return SQLITE_NOMEM;
1.144360 +  }
1.144361 +  memset(aiUsed, 0, sizeof(int)*nCell);
1.144362 +
1.144363 +  PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
1.144364 +
1.144365 +  memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
1.144366 +  memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
1.144367 +  nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
1.144368 +  nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
1.144369 +  aiUsed[iLeftSeed] = 1;
1.144370 +  aiUsed[iRightSeed] = 1;
1.144371 +
1.144372 +  for(i=nCell-2; i>0; i--){
1.144373 +    RtreeCell *pNext;
1.144374 +    pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
1.144375 +    RtreeDValue diff =  
1.144376 +      cellGrowth(pRtree, pBboxLeft, pNext) - 
1.144377 +      cellGrowth(pRtree, pBboxRight, pNext)
1.144378 +    ;
1.144379 +    if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
1.144380 +     || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
1.144381 +    ){
1.144382 +      nodeInsertCell(pRtree, pRight, pNext);
1.144383 +      cellUnion(pRtree, pBboxRight, pNext);
1.144384 +    }else{
1.144385 +      nodeInsertCell(pRtree, pLeft, pNext);
1.144386 +      cellUnion(pRtree, pBboxLeft, pNext);
1.144387 +    }
1.144388 +  }
1.144389 +
1.144390 +  sqlite3_free(aiUsed);
1.144391 +  return SQLITE_OK;
1.144392 +}
1.144393 +#endif
1.144394 +
1.144395 +static int updateMapping(
1.144396 +  Rtree *pRtree, 
1.144397 +  i64 iRowid, 
1.144398 +  RtreeNode *pNode, 
1.144399 +  int iHeight
1.144400 +){
1.144401 +  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
1.144402 +  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
1.144403 +  if( iHeight>0 ){
1.144404 +    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
1.144405 +    if( pChild ){
1.144406 +      nodeRelease(pRtree, pChild->pParent);
1.144407 +      nodeReference(pNode);
1.144408 +      pChild->pParent = pNode;
1.144409 +    }
1.144410 +  }
1.144411 +  return xSetMapping(pRtree, iRowid, pNode->iNode);
1.144412 +}
1.144413 +
1.144414 +static int SplitNode(
1.144415 +  Rtree *pRtree,
1.144416 +  RtreeNode *pNode,
1.144417 +  RtreeCell *pCell,
1.144418 +  int iHeight
1.144419 +){
1.144420 +  int i;
1.144421 +  int newCellIsRight = 0;
1.144422 +
1.144423 +  int rc = SQLITE_OK;
1.144424 +  int nCell = NCELL(pNode);
1.144425 +  RtreeCell *aCell;
1.144426 +  int *aiUsed;
1.144427 +
1.144428 +  RtreeNode *pLeft = 0;
1.144429 +  RtreeNode *pRight = 0;
1.144430 +
1.144431 +  RtreeCell leftbbox;
1.144432 +  RtreeCell rightbbox;
1.144433 +
1.144434 +  /* Allocate an array and populate it with a copy of pCell and 
1.144435 +  ** all cells from node pLeft. Then zero the original node.
1.144436 +  */
1.144437 +  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
1.144438 +  if( !aCell ){
1.144439 +    rc = SQLITE_NOMEM;
1.144440 +    goto splitnode_out;
1.144441 +  }
1.144442 +  aiUsed = (int *)&aCell[nCell+1];
1.144443 +  memset(aiUsed, 0, sizeof(int)*(nCell+1));
1.144444 +  for(i=0; i<nCell; i++){
1.144445 +    nodeGetCell(pRtree, pNode, i, &aCell[i]);
1.144446 +  }
1.144447 +  nodeZero(pRtree, pNode);
1.144448 +  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
1.144449 +  nCell++;
1.144450 +
1.144451 +  if( pNode->iNode==1 ){
1.144452 +    pRight = nodeNew(pRtree, pNode);
1.144453 +    pLeft = nodeNew(pRtree, pNode);
1.144454 +    pRtree->iDepth++;
1.144455 +    pNode->isDirty = 1;
1.144456 +    writeInt16(pNode->zData, pRtree->iDepth);
1.144457 +  }else{
1.144458 +    pLeft = pNode;
1.144459 +    pRight = nodeNew(pRtree, pLeft->pParent);
1.144460 +    nodeReference(pLeft);
1.144461 +  }
1.144462 +
1.144463 +  if( !pLeft || !pRight ){
1.144464 +    rc = SQLITE_NOMEM;
1.144465 +    goto splitnode_out;
1.144466 +  }
1.144467 +
1.144468 +  memset(pLeft->zData, 0, pRtree->iNodeSize);
1.144469 +  memset(pRight->zData, 0, pRtree->iNodeSize);
1.144470 +
1.144471 +  rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
1.144472 +  if( rc!=SQLITE_OK ){
1.144473 +    goto splitnode_out;
1.144474 +  }
1.144475 +
1.144476 +  /* Ensure both child nodes have node numbers assigned to them by calling
1.144477 +  ** nodeWrite(). Node pRight always needs a node number, as it was created
1.144478 +  ** by nodeNew() above. But node pLeft sometimes already has a node number.
1.144479 +  ** In this case avoid the all to nodeWrite().
1.144480 +  */
1.144481 +  if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
1.144482 +   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
1.144483 +  ){
1.144484 +    goto splitnode_out;
1.144485 +  }
1.144486 +
1.144487 +  rightbbox.iRowid = pRight->iNode;
1.144488 +  leftbbox.iRowid = pLeft->iNode;
1.144489 +
1.144490 +  if( pNode->iNode==1 ){
1.144491 +    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
1.144492 +    if( rc!=SQLITE_OK ){
1.144493 +      goto splitnode_out;
1.144494 +    }
1.144495 +  }else{
1.144496 +    RtreeNode *pParent = pLeft->pParent;
1.144497 +    int iCell;
1.144498 +    rc = nodeParentIndex(pRtree, pLeft, &iCell);
1.144499 +    if( rc==SQLITE_OK ){
1.144500 +      nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
1.144501 +      rc = AdjustTree(pRtree, pParent, &leftbbox);
1.144502 +    }
1.144503 +    if( rc!=SQLITE_OK ){
1.144504 +      goto splitnode_out;
1.144505 +    }
1.144506 +  }
1.144507 +  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
1.144508 +    goto splitnode_out;
1.144509 +  }
1.144510 +
1.144511 +  for(i=0; i<NCELL(pRight); i++){
1.144512 +    i64 iRowid = nodeGetRowid(pRtree, pRight, i);
1.144513 +    rc = updateMapping(pRtree, iRowid, pRight, iHeight);
1.144514 +    if( iRowid==pCell->iRowid ){
1.144515 +      newCellIsRight = 1;
1.144516 +    }
1.144517 +    if( rc!=SQLITE_OK ){
1.144518 +      goto splitnode_out;
1.144519 +    }
1.144520 +  }
1.144521 +  if( pNode->iNode==1 ){
1.144522 +    for(i=0; i<NCELL(pLeft); i++){
1.144523 +      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
1.144524 +      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
1.144525 +      if( rc!=SQLITE_OK ){
1.144526 +        goto splitnode_out;
1.144527 +      }
1.144528 +    }
1.144529 +  }else if( newCellIsRight==0 ){
1.144530 +    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
1.144531 +  }
1.144532 +
1.144533 +  if( rc==SQLITE_OK ){
1.144534 +    rc = nodeRelease(pRtree, pRight);
1.144535 +    pRight = 0;
1.144536 +  }
1.144537 +  if( rc==SQLITE_OK ){
1.144538 +    rc = nodeRelease(pRtree, pLeft);
1.144539 +    pLeft = 0;
1.144540 +  }
1.144541 +
1.144542 +splitnode_out:
1.144543 +  nodeRelease(pRtree, pRight);
1.144544 +  nodeRelease(pRtree, pLeft);
1.144545 +  sqlite3_free(aCell);
1.144546 +  return rc;
1.144547 +}
1.144548 +
1.144549 +/*
1.144550 +** If node pLeaf is not the root of the r-tree and its pParent pointer is 
1.144551 +** still NULL, load all ancestor nodes of pLeaf into memory and populate
1.144552 +** the pLeaf->pParent chain all the way up to the root node.
1.144553 +**
1.144554 +** This operation is required when a row is deleted (or updated - an update
1.144555 +** is implemented as a delete followed by an insert). SQLite provides the
1.144556 +** rowid of the row to delete, which can be used to find the leaf on which
1.144557 +** the entry resides (argument pLeaf). Once the leaf is located, this 
1.144558 +** function is called to determine its ancestry.
1.144559 +*/
1.144560 +static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
1.144561 +  int rc = SQLITE_OK;
1.144562 +  RtreeNode *pChild = pLeaf;
1.144563 +  while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
1.144564 +    int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
1.144565 +    sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
1.144566 +    rc = sqlite3_step(pRtree->pReadParent);
1.144567 +    if( rc==SQLITE_ROW ){
1.144568 +      RtreeNode *pTest;           /* Used to test for reference loops */
1.144569 +      i64 iNode;                  /* Node number of parent node */
1.144570 +
1.144571 +      /* Before setting pChild->pParent, test that we are not creating a
1.144572 +      ** loop of references (as we would if, say, pChild==pParent). We don't
1.144573 +      ** want to do this as it leads to a memory leak when trying to delete
1.144574 +      ** the referenced counted node structures.
1.144575 +      */
1.144576 +      iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
1.144577 +      for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
1.144578 +      if( !pTest ){
1.144579 +        rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
1.144580 +      }
1.144581 +    }
1.144582 +    rc = sqlite3_reset(pRtree->pReadParent);
1.144583 +    if( rc==SQLITE_OK ) rc = rc2;
1.144584 +    if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
1.144585 +    pChild = pChild->pParent;
1.144586 +  }
1.144587 +  return rc;
1.144588 +}
1.144589 +
1.144590 +static int deleteCell(Rtree *, RtreeNode *, int, int);
1.144591 +
1.144592 +static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
1.144593 +  int rc;
1.144594 +  int rc2;
1.144595 +  RtreeNode *pParent = 0;
1.144596 +  int iCell;
1.144597 +
1.144598 +  assert( pNode->nRef==1 );
1.144599 +
1.144600 +  /* Remove the entry in the parent cell. */
1.144601 +  rc = nodeParentIndex(pRtree, pNode, &iCell);
1.144602 +  if( rc==SQLITE_OK ){
1.144603 +    pParent = pNode->pParent;
1.144604 +    pNode->pParent = 0;
1.144605 +    rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
1.144606 +  }
1.144607 +  rc2 = nodeRelease(pRtree, pParent);
1.144608 +  if( rc==SQLITE_OK ){
1.144609 +    rc = rc2;
1.144610 +  }
1.144611 +  if( rc!=SQLITE_OK ){
1.144612 +    return rc;
1.144613 +  }
1.144614 +
1.144615 +  /* Remove the xxx_node entry. */
1.144616 +  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
1.144617 +  sqlite3_step(pRtree->pDeleteNode);
1.144618 +  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
1.144619 +    return rc;
1.144620 +  }
1.144621 +
1.144622 +  /* Remove the xxx_parent entry. */
1.144623 +  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
1.144624 +  sqlite3_step(pRtree->pDeleteParent);
1.144625 +  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
1.144626 +    return rc;
1.144627 +  }
1.144628 +  
1.144629 +  /* Remove the node from the in-memory hash table and link it into
1.144630 +  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
1.144631 +  */
1.144632 +  nodeHashDelete(pRtree, pNode);
1.144633 +  pNode->iNode = iHeight;
1.144634 +  pNode->pNext = pRtree->pDeleted;
1.144635 +  pNode->nRef++;
1.144636 +  pRtree->pDeleted = pNode;
1.144637 +
1.144638 +  return SQLITE_OK;
1.144639 +}
1.144640 +
1.144641 +static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
1.144642 +  RtreeNode *pParent = pNode->pParent;
1.144643 +  int rc = SQLITE_OK; 
1.144644 +  if( pParent ){
1.144645 +    int ii; 
1.144646 +    int nCell = NCELL(pNode);
1.144647 +    RtreeCell box;                            /* Bounding box for pNode */
1.144648 +    nodeGetCell(pRtree, pNode, 0, &box);
1.144649 +    for(ii=1; ii<nCell; ii++){
1.144650 +      RtreeCell cell;
1.144651 +      nodeGetCell(pRtree, pNode, ii, &cell);
1.144652 +      cellUnion(pRtree, &box, &cell);
1.144653 +    }
1.144654 +    box.iRowid = pNode->iNode;
1.144655 +    rc = nodeParentIndex(pRtree, pNode, &ii);
1.144656 +    if( rc==SQLITE_OK ){
1.144657 +      nodeOverwriteCell(pRtree, pParent, &box, ii);
1.144658 +      rc = fixBoundingBox(pRtree, pParent);
1.144659 +    }
1.144660 +  }
1.144661 +  return rc;
1.144662 +}
1.144663 +
1.144664 +/*
1.144665 +** Delete the cell at index iCell of node pNode. After removing the
1.144666 +** cell, adjust the r-tree data structure if required.
1.144667 +*/
1.144668 +static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
1.144669 +  RtreeNode *pParent;
1.144670 +  int rc;
1.144671 +
1.144672 +  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
1.144673 +    return rc;
1.144674 +  }
1.144675 +
1.144676 +  /* Remove the cell from the node. This call just moves bytes around
1.144677 +  ** the in-memory node image, so it cannot fail.
1.144678 +  */
1.144679 +  nodeDeleteCell(pRtree, pNode, iCell);
1.144680 +
1.144681 +  /* If the node is not the tree root and now has less than the minimum
1.144682 +  ** number of cells, remove it from the tree. Otherwise, update the
1.144683 +  ** cell in the parent node so that it tightly contains the updated
1.144684 +  ** node.
1.144685 +  */
1.144686 +  pParent = pNode->pParent;
1.144687 +  assert( pParent || pNode->iNode==1 );
1.144688 +  if( pParent ){
1.144689 +    if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
1.144690 +      rc = removeNode(pRtree, pNode, iHeight);
1.144691 +    }else{
1.144692 +      rc = fixBoundingBox(pRtree, pNode);
1.144693 +    }
1.144694 +  }
1.144695 +
1.144696 +  return rc;
1.144697 +}
1.144698 +
1.144699 +static int Reinsert(
1.144700 +  Rtree *pRtree, 
1.144701 +  RtreeNode *pNode, 
1.144702 +  RtreeCell *pCell, 
1.144703 +  int iHeight
1.144704 +){
1.144705 +  int *aOrder;
1.144706 +  int *aSpare;
1.144707 +  RtreeCell *aCell;
1.144708 +  RtreeDValue *aDistance;
1.144709 +  int nCell;
1.144710 +  RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
1.144711 +  int iDim;
1.144712 +  int ii;
1.144713 +  int rc = SQLITE_OK;
1.144714 +  int n;
1.144715 +
1.144716 +  memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
1.144717 +
1.144718 +  nCell = NCELL(pNode)+1;
1.144719 +  n = (nCell+1)&(~1);
1.144720 +
1.144721 +  /* Allocate the buffers used by this operation. The allocation is
1.144722 +  ** relinquished before this function returns.
1.144723 +  */
1.144724 +  aCell = (RtreeCell *)sqlite3_malloc(n * (
1.144725 +    sizeof(RtreeCell)     +         /* aCell array */
1.144726 +    sizeof(int)           +         /* aOrder array */
1.144727 +    sizeof(int)           +         /* aSpare array */
1.144728 +    sizeof(RtreeDValue)             /* aDistance array */
1.144729 +  ));
1.144730 +  if( !aCell ){
1.144731 +    return SQLITE_NOMEM;
1.144732 +  }
1.144733 +  aOrder    = (int *)&aCell[n];
1.144734 +  aSpare    = (int *)&aOrder[n];
1.144735 +  aDistance = (RtreeDValue *)&aSpare[n];
1.144736 +
1.144737 +  for(ii=0; ii<nCell; ii++){
1.144738 +    if( ii==(nCell-1) ){
1.144739 +      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
1.144740 +    }else{
1.144741 +      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
1.144742 +    }
1.144743 +    aOrder[ii] = ii;
1.144744 +    for(iDim=0; iDim<pRtree->nDim; iDim++){
1.144745 +      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
1.144746 +      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
1.144747 +    }
1.144748 +  }
1.144749 +  for(iDim=0; iDim<pRtree->nDim; iDim++){
1.144750 +    aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
1.144751 +  }
1.144752 +
1.144753 +  for(ii=0; ii<nCell; ii++){
1.144754 +    aDistance[ii] = 0.0;
1.144755 +    for(iDim=0; iDim<pRtree->nDim; iDim++){
1.144756 +      RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
1.144757 +                               DCOORD(aCell[ii].aCoord[iDim*2]));
1.144758 +      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
1.144759 +    }
1.144760 +  }
1.144761 +
1.144762 +  SortByDistance(aOrder, nCell, aDistance, aSpare);
1.144763 +  nodeZero(pRtree, pNode);
1.144764 +
1.144765 +  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
1.144766 +    RtreeCell *p = &aCell[aOrder[ii]];
1.144767 +    nodeInsertCell(pRtree, pNode, p);
1.144768 +    if( p->iRowid==pCell->iRowid ){
1.144769 +      if( iHeight==0 ){
1.144770 +        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
1.144771 +      }else{
1.144772 +        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
1.144773 +      }
1.144774 +    }
1.144775 +  }
1.144776 +  if( rc==SQLITE_OK ){
1.144777 +    rc = fixBoundingBox(pRtree, pNode);
1.144778 +  }
1.144779 +  for(; rc==SQLITE_OK && ii<nCell; ii++){
1.144780 +    /* Find a node to store this cell in. pNode->iNode currently contains
1.144781 +    ** the height of the sub-tree headed by the cell.
1.144782 +    */
1.144783 +    RtreeNode *pInsert;
1.144784 +    RtreeCell *p = &aCell[aOrder[ii]];
1.144785 +    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
1.144786 +    if( rc==SQLITE_OK ){
1.144787 +      int rc2;
1.144788 +      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
1.144789 +      rc2 = nodeRelease(pRtree, pInsert);
1.144790 +      if( rc==SQLITE_OK ){
1.144791 +        rc = rc2;
1.144792 +      }
1.144793 +    }
1.144794 +  }
1.144795 +
1.144796 +  sqlite3_free(aCell);
1.144797 +  return rc;
1.144798 +}
1.144799 +
1.144800 +/*
1.144801 +** Insert cell pCell into node pNode. Node pNode is the head of a 
1.144802 +** subtree iHeight high (leaf nodes have iHeight==0).
1.144803 +*/
1.144804 +static int rtreeInsertCell(
1.144805 +  Rtree *pRtree,
1.144806 +  RtreeNode *pNode,
1.144807 +  RtreeCell *pCell,
1.144808 +  int iHeight
1.144809 +){
1.144810 +  int rc = SQLITE_OK;
1.144811 +  if( iHeight>0 ){
1.144812 +    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
1.144813 +    if( pChild ){
1.144814 +      nodeRelease(pRtree, pChild->pParent);
1.144815 +      nodeReference(pNode);
1.144816 +      pChild->pParent = pNode;
1.144817 +    }
1.144818 +  }
1.144819 +  if( nodeInsertCell(pRtree, pNode, pCell) ){
1.144820 +#if VARIANT_RSTARTREE_REINSERT
1.144821 +    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
1.144822 +      rc = SplitNode(pRtree, pNode, pCell, iHeight);
1.144823 +    }else{
1.144824 +      pRtree->iReinsertHeight = iHeight;
1.144825 +      rc = Reinsert(pRtree, pNode, pCell, iHeight);
1.144826 +    }
1.144827 +#else
1.144828 +    rc = SplitNode(pRtree, pNode, pCell, iHeight);
1.144829 +#endif
1.144830 +  }else{
1.144831 +    rc = AdjustTree(pRtree, pNode, pCell);
1.144832 +    if( rc==SQLITE_OK ){
1.144833 +      if( iHeight==0 ){
1.144834 +        rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
1.144835 +      }else{
1.144836 +        rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
1.144837 +      }
1.144838 +    }
1.144839 +  }
1.144840 +  return rc;
1.144841 +}
1.144842 +
1.144843 +static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
1.144844 +  int ii;
1.144845 +  int rc = SQLITE_OK;
1.144846 +  int nCell = NCELL(pNode);
1.144847 +
1.144848 +  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
1.144849 +    RtreeNode *pInsert;
1.144850 +    RtreeCell cell;
1.144851 +    nodeGetCell(pRtree, pNode, ii, &cell);
1.144852 +
1.144853 +    /* Find a node to store this cell in. pNode->iNode currently contains
1.144854 +    ** the height of the sub-tree headed by the cell.
1.144855 +    */
1.144856 +    rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
1.144857 +    if( rc==SQLITE_OK ){
1.144858 +      int rc2;
1.144859 +      rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
1.144860 +      rc2 = nodeRelease(pRtree, pInsert);
1.144861 +      if( rc==SQLITE_OK ){
1.144862 +        rc = rc2;
1.144863 +      }
1.144864 +    }
1.144865 +  }
1.144866 +  return rc;
1.144867 +}
1.144868 +
1.144869 +/*
1.144870 +** Select a currently unused rowid for a new r-tree record.
1.144871 +*/
1.144872 +static int newRowid(Rtree *pRtree, i64 *piRowid){
1.144873 +  int rc;
1.144874 +  sqlite3_bind_null(pRtree->pWriteRowid, 1);
1.144875 +  sqlite3_bind_null(pRtree->pWriteRowid, 2);
1.144876 +  sqlite3_step(pRtree->pWriteRowid);
1.144877 +  rc = sqlite3_reset(pRtree->pWriteRowid);
1.144878 +  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
1.144879 +  return rc;
1.144880 +}
1.144881 +
1.144882 +/*
1.144883 +** Remove the entry with rowid=iDelete from the r-tree structure.
1.144884 +*/
1.144885 +static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
1.144886 +  int rc;                         /* Return code */
1.144887 +  RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
1.144888 +  int iCell;                      /* Index of iDelete cell in pLeaf */
1.144889 +  RtreeNode *pRoot;               /* Root node of rtree structure */
1.144890 +
1.144891 +
1.144892 +  /* Obtain a reference to the root node to initialize Rtree.iDepth */
1.144893 +  rc = nodeAcquire(pRtree, 1, 0, &pRoot);
1.144894 +
1.144895 +  /* Obtain a reference to the leaf node that contains the entry 
1.144896 +  ** about to be deleted. 
1.144897 +  */
1.144898 +  if( rc==SQLITE_OK ){
1.144899 +    rc = findLeafNode(pRtree, iDelete, &pLeaf);
1.144900 +  }
1.144901 +
1.144902 +  /* Delete the cell in question from the leaf node. */
1.144903 +  if( rc==SQLITE_OK ){
1.144904 +    int rc2;
1.144905 +    rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
1.144906 +    if( rc==SQLITE_OK ){
1.144907 +      rc = deleteCell(pRtree, pLeaf, iCell, 0);
1.144908 +    }
1.144909 +    rc2 = nodeRelease(pRtree, pLeaf);
1.144910 +    if( rc==SQLITE_OK ){
1.144911 +      rc = rc2;
1.144912 +    }
1.144913 +  }
1.144914 +
1.144915 +  /* Delete the corresponding entry in the <rtree>_rowid table. */
1.144916 +  if( rc==SQLITE_OK ){
1.144917 +    sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
1.144918 +    sqlite3_step(pRtree->pDeleteRowid);
1.144919 +    rc = sqlite3_reset(pRtree->pDeleteRowid);
1.144920 +  }
1.144921 +
1.144922 +  /* Check if the root node now has exactly one child. If so, remove
1.144923 +  ** it, schedule the contents of the child for reinsertion and 
1.144924 +  ** reduce the tree height by one.
1.144925 +  **
1.144926 +  ** This is equivalent to copying the contents of the child into
1.144927 +  ** the root node (the operation that Gutman's paper says to perform 
1.144928 +  ** in this scenario).
1.144929 +  */
1.144930 +  if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
1.144931 +    int rc2;
1.144932 +    RtreeNode *pChild;
1.144933 +    i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
1.144934 +    rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
1.144935 +    if( rc==SQLITE_OK ){
1.144936 +      rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
1.144937 +    }
1.144938 +    rc2 = nodeRelease(pRtree, pChild);
1.144939 +    if( rc==SQLITE_OK ) rc = rc2;
1.144940 +    if( rc==SQLITE_OK ){
1.144941 +      pRtree->iDepth--;
1.144942 +      writeInt16(pRoot->zData, pRtree->iDepth);
1.144943 +      pRoot->isDirty = 1;
1.144944 +    }
1.144945 +  }
1.144946 +
1.144947 +  /* Re-insert the contents of any underfull nodes removed from the tree. */
1.144948 +  for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
1.144949 +    if( rc==SQLITE_OK ){
1.144950 +      rc = reinsertNodeContent(pRtree, pLeaf);
1.144951 +    }
1.144952 +    pRtree->pDeleted = pLeaf->pNext;
1.144953 +    sqlite3_free(pLeaf);
1.144954 +  }
1.144955 +
1.144956 +  /* Release the reference to the root node. */
1.144957 +  if( rc==SQLITE_OK ){
1.144958 +    rc = nodeRelease(pRtree, pRoot);
1.144959 +  }else{
1.144960 +    nodeRelease(pRtree, pRoot);
1.144961 +  }
1.144962 +
1.144963 +  return rc;
1.144964 +}
1.144965 +
1.144966 +/*
1.144967 +** Rounding constants for float->double conversion.
1.144968 +*/
1.144969 +#define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
1.144970 +#define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
1.144971 +
1.144972 +#if !defined(SQLITE_RTREE_INT_ONLY)
1.144973 +/*
1.144974 +** Convert an sqlite3_value into an RtreeValue (presumably a float)
1.144975 +** while taking care to round toward negative or positive, respectively.
1.144976 +*/
1.144977 +static RtreeValue rtreeValueDown(sqlite3_value *v){
1.144978 +  double d = sqlite3_value_double(v);
1.144979 +  float f = (float)d;
1.144980 +  if( f>d ){
1.144981 +    f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
1.144982 +  }
1.144983 +  return f;
1.144984 +}
1.144985 +static RtreeValue rtreeValueUp(sqlite3_value *v){
1.144986 +  double d = sqlite3_value_double(v);
1.144987 +  float f = (float)d;
1.144988 +  if( f<d ){
1.144989 +    f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
1.144990 +  }
1.144991 +  return f;
1.144992 +}
1.144993 +#endif /* !defined(SQLITE_RTREE_INT_ONLY) */
1.144994 +
1.144995 +
1.144996 +/*
1.144997 +** The xUpdate method for rtree module virtual tables.
1.144998 +*/
1.144999 +static int rtreeUpdate(
1.145000 +  sqlite3_vtab *pVtab, 
1.145001 +  int nData, 
1.145002 +  sqlite3_value **azData, 
1.145003 +  sqlite_int64 *pRowid
1.145004 +){
1.145005 +  Rtree *pRtree = (Rtree *)pVtab;
1.145006 +  int rc = SQLITE_OK;
1.145007 +  RtreeCell cell;                 /* New cell to insert if nData>1 */
1.145008 +  int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
1.145009 +
1.145010 +  rtreeReference(pRtree);
1.145011 +  assert(nData>=1);
1.145012 +
1.145013 +  /* Constraint handling. A write operation on an r-tree table may return
1.145014 +  ** SQLITE_CONSTRAINT for two reasons:
1.145015 +  **
1.145016 +  **   1. A duplicate rowid value, or
1.145017 +  **   2. The supplied data violates the "x2>=x1" constraint.
1.145018 +  **
1.145019 +  ** In the first case, if the conflict-handling mode is REPLACE, then
1.145020 +  ** the conflicting row can be removed before proceeding. In the second
1.145021 +  ** case, SQLITE_CONSTRAINT must be returned regardless of the
1.145022 +  ** conflict-handling mode specified by the user.
1.145023 +  */
1.145024 +  if( nData>1 ){
1.145025 +    int ii;
1.145026 +
1.145027 +    /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
1.145028 +    assert( nData==(pRtree->nDim*2 + 3) );
1.145029 +#ifndef SQLITE_RTREE_INT_ONLY
1.145030 +    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
1.145031 +      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1.145032 +        cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
1.145033 +        cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
1.145034 +        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
1.145035 +          rc = SQLITE_CONSTRAINT;
1.145036 +          goto constraint;
1.145037 +        }
1.145038 +      }
1.145039 +    }else
1.145040 +#endif
1.145041 +    {
1.145042 +      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1.145043 +        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
1.145044 +        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
1.145045 +        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
1.145046 +          rc = SQLITE_CONSTRAINT;
1.145047 +          goto constraint;
1.145048 +        }
1.145049 +      }
1.145050 +    }
1.145051 +
1.145052 +    /* If a rowid value was supplied, check if it is already present in 
1.145053 +    ** the table. If so, the constraint has failed. */
1.145054 +    if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
1.145055 +      cell.iRowid = sqlite3_value_int64(azData[2]);
1.145056 +      if( sqlite3_value_type(azData[0])==SQLITE_NULL
1.145057 +       || sqlite3_value_int64(azData[0])!=cell.iRowid
1.145058 +      ){
1.145059 +        int steprc;
1.145060 +        sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
1.145061 +        steprc = sqlite3_step(pRtree->pReadRowid);
1.145062 +        rc = sqlite3_reset(pRtree->pReadRowid);
1.145063 +        if( SQLITE_ROW==steprc ){
1.145064 +          if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
1.145065 +            rc = rtreeDeleteRowid(pRtree, cell.iRowid);
1.145066 +          }else{
1.145067 +            rc = SQLITE_CONSTRAINT;
1.145068 +            goto constraint;
1.145069 +          }
1.145070 +        }
1.145071 +      }
1.145072 +      bHaveRowid = 1;
1.145073 +    }
1.145074 +  }
1.145075 +
1.145076 +  /* If azData[0] is not an SQL NULL value, it is the rowid of a
1.145077 +  ** record to delete from the r-tree table. The following block does
1.145078 +  ** just that.
1.145079 +  */
1.145080 +  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
1.145081 +    rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
1.145082 +  }
1.145083 +
1.145084 +  /* If the azData[] array contains more than one element, elements
1.145085 +  ** (azData[2]..azData[argc-1]) contain a new record to insert into
1.145086 +  ** the r-tree structure.
1.145087 +  */
1.145088 +  if( rc==SQLITE_OK && nData>1 ){
1.145089 +    /* Insert the new record into the r-tree */
1.145090 +    RtreeNode *pLeaf = 0;
1.145091 +
1.145092 +    /* Figure out the rowid of the new row. */
1.145093 +    if( bHaveRowid==0 ){
1.145094 +      rc = newRowid(pRtree, &cell.iRowid);
1.145095 +    }
1.145096 +    *pRowid = cell.iRowid;
1.145097 +
1.145098 +    if( rc==SQLITE_OK ){
1.145099 +      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
1.145100 +    }
1.145101 +    if( rc==SQLITE_OK ){
1.145102 +      int rc2;
1.145103 +      pRtree->iReinsertHeight = -1;
1.145104 +      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
1.145105 +      rc2 = nodeRelease(pRtree, pLeaf);
1.145106 +      if( rc==SQLITE_OK ){
1.145107 +        rc = rc2;
1.145108 +      }
1.145109 +    }
1.145110 +  }
1.145111 +
1.145112 +constraint:
1.145113 +  rtreeRelease(pRtree);
1.145114 +  return rc;
1.145115 +}
1.145116 +
1.145117 +/*
1.145118 +** The xRename method for rtree module virtual tables.
1.145119 +*/
1.145120 +static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
1.145121 +  Rtree *pRtree = (Rtree *)pVtab;
1.145122 +  int rc = SQLITE_NOMEM;
1.145123 +  char *zSql = sqlite3_mprintf(
1.145124 +    "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
1.145125 +    "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
1.145126 +    "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
1.145127 +    , pRtree->zDb, pRtree->zName, zNewName 
1.145128 +    , pRtree->zDb, pRtree->zName, zNewName 
1.145129 +    , pRtree->zDb, pRtree->zName, zNewName
1.145130 +  );
1.145131 +  if( zSql ){
1.145132 +    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
1.145133 +    sqlite3_free(zSql);
1.145134 +  }
1.145135 +  return rc;
1.145136 +}
1.145137 +
1.145138 +/*
1.145139 +** This function populates the pRtree->nRowEst variable with an estimate
1.145140 +** of the number of rows in the virtual table. If possible, this is based
1.145141 +** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
1.145142 +*/
1.145143 +static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
1.145144 +  const char *zSql = "SELECT stat FROM sqlite_stat1 WHERE tbl= ? || '_rowid'";
1.145145 +  sqlite3_stmt *p;
1.145146 +  int rc;
1.145147 +  i64 nRow = 0;
1.145148 +
1.145149 +  rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
1.145150 +  if( rc==SQLITE_OK ){
1.145151 +    sqlite3_bind_text(p, 1, pRtree->zName, -1, SQLITE_STATIC);
1.145152 +    if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
1.145153 +    rc = sqlite3_finalize(p);
1.145154 +  }else if( rc!=SQLITE_NOMEM ){
1.145155 +    rc = SQLITE_OK;
1.145156 +  }
1.145157 +
1.145158 +  if( rc==SQLITE_OK ){
1.145159 +    if( nRow==0 ){
1.145160 +      pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
1.145161 +    }else{
1.145162 +      pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
1.145163 +    }
1.145164 +  }
1.145165 +
1.145166 +  return rc;
1.145167 +}
1.145168 +
1.145169 +static sqlite3_module rtreeModule = {
1.145170 +  0,                          /* iVersion */
1.145171 +  rtreeCreate,                /* xCreate - create a table */
1.145172 +  rtreeConnect,               /* xConnect - connect to an existing table */
1.145173 +  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
1.145174 +  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
1.145175 +  rtreeDestroy,               /* xDestroy - Drop a table */
1.145176 +  rtreeOpen,                  /* xOpen - open a cursor */
1.145177 +  rtreeClose,                 /* xClose - close a cursor */
1.145178 +  rtreeFilter,                /* xFilter - configure scan constraints */
1.145179 +  rtreeNext,                  /* xNext - advance a cursor */
1.145180 +  rtreeEof,                   /* xEof */
1.145181 +  rtreeColumn,                /* xColumn - read data */
1.145182 +  rtreeRowid,                 /* xRowid - read data */
1.145183 +  rtreeUpdate,                /* xUpdate - write data */
1.145184 +  0,                          /* xBegin - begin transaction */
1.145185 +  0,                          /* xSync - sync transaction */
1.145186 +  0,                          /* xCommit - commit transaction */
1.145187 +  0,                          /* xRollback - rollback transaction */
1.145188 +  0,                          /* xFindFunction - function overloading */
1.145189 +  rtreeRename,                /* xRename - rename the table */
1.145190 +  0,                          /* xSavepoint */
1.145191 +  0,                          /* xRelease */
1.145192 +  0                           /* xRollbackTo */
1.145193 +};
1.145194 +
1.145195 +static int rtreeSqlInit(
1.145196 +  Rtree *pRtree, 
1.145197 +  sqlite3 *db, 
1.145198 +  const char *zDb, 
1.145199 +  const char *zPrefix, 
1.145200 +  int isCreate
1.145201 +){
1.145202 +  int rc = SQLITE_OK;
1.145203 +
1.145204 +  #define N_STATEMENT 9
1.145205 +  static const char *azSql[N_STATEMENT] = {
1.145206 +    /* Read and write the xxx_node table */
1.145207 +    "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
1.145208 +    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
1.145209 +    "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
1.145210 +
1.145211 +    /* Read and write the xxx_rowid table */
1.145212 +    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
1.145213 +    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
1.145214 +    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
1.145215 +
1.145216 +    /* Read and write the xxx_parent table */
1.145217 +    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
1.145218 +    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
1.145219 +    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
1.145220 +  };
1.145221 +  sqlite3_stmt **appStmt[N_STATEMENT];
1.145222 +  int i;
1.145223 +
1.145224 +  pRtree->db = db;
1.145225 +
1.145226 +  if( isCreate ){
1.145227 +    char *zCreate = sqlite3_mprintf(
1.145228 +"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
1.145229 +"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
1.145230 +"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
1.145231 +"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
1.145232 +      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
1.145233 +    );
1.145234 +    if( !zCreate ){
1.145235 +      return SQLITE_NOMEM;
1.145236 +    }
1.145237 +    rc = sqlite3_exec(db, zCreate, 0, 0, 0);
1.145238 +    sqlite3_free(zCreate);
1.145239 +    if( rc!=SQLITE_OK ){
1.145240 +      return rc;
1.145241 +    }
1.145242 +  }
1.145243 +
1.145244 +  appStmt[0] = &pRtree->pReadNode;
1.145245 +  appStmt[1] = &pRtree->pWriteNode;
1.145246 +  appStmt[2] = &pRtree->pDeleteNode;
1.145247 +  appStmt[3] = &pRtree->pReadRowid;
1.145248 +  appStmt[4] = &pRtree->pWriteRowid;
1.145249 +  appStmt[5] = &pRtree->pDeleteRowid;
1.145250 +  appStmt[6] = &pRtree->pReadParent;
1.145251 +  appStmt[7] = &pRtree->pWriteParent;
1.145252 +  appStmt[8] = &pRtree->pDeleteParent;
1.145253 +
1.145254 +  rc = rtreeQueryStat1(db, pRtree);
1.145255 +  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
1.145256 +    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
1.145257 +    if( zSql ){
1.145258 +      rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
1.145259 +    }else{
1.145260 +      rc = SQLITE_NOMEM;
1.145261 +    }
1.145262 +    sqlite3_free(zSql);
1.145263 +  }
1.145264 +
1.145265 +  return rc;
1.145266 +}
1.145267 +
1.145268 +/*
1.145269 +** The second argument to this function contains the text of an SQL statement
1.145270 +** that returns a single integer value. The statement is compiled and executed
1.145271 +** using database connection db. If successful, the integer value returned
1.145272 +** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
1.145273 +** code is returned and the value of *piVal after returning is not defined.
1.145274 +*/
1.145275 +static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
1.145276 +  int rc = SQLITE_NOMEM;
1.145277 +  if( zSql ){
1.145278 +    sqlite3_stmt *pStmt = 0;
1.145279 +    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
1.145280 +    if( rc==SQLITE_OK ){
1.145281 +      if( SQLITE_ROW==sqlite3_step(pStmt) ){
1.145282 +        *piVal = sqlite3_column_int(pStmt, 0);
1.145283 +      }
1.145284 +      rc = sqlite3_finalize(pStmt);
1.145285 +    }
1.145286 +  }
1.145287 +  return rc;
1.145288 +}
1.145289 +
1.145290 +/*
1.145291 +** This function is called from within the xConnect() or xCreate() method to
1.145292 +** determine the node-size used by the rtree table being created or connected
1.145293 +** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
1.145294 +** Otherwise, an SQLite error code is returned.
1.145295 +**
1.145296 +** If this function is being called as part of an xConnect(), then the rtree
1.145297 +** table already exists. In this case the node-size is determined by inspecting
1.145298 +** the root node of the tree.
1.145299 +**
1.145300 +** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
1.145301 +** This ensures that each node is stored on a single database page. If the 
1.145302 +** database page-size is so large that more than RTREE_MAXCELLS entries 
1.145303 +** would fit in a single node, use a smaller node-size.
1.145304 +*/
1.145305 +static int getNodeSize(
1.145306 +  sqlite3 *db,                    /* Database handle */
1.145307 +  Rtree *pRtree,                  /* Rtree handle */
1.145308 +  int isCreate,                   /* True for xCreate, false for xConnect */
1.145309 +  char **pzErr                    /* OUT: Error message, if any */
1.145310 +){
1.145311 +  int rc;
1.145312 +  char *zSql;
1.145313 +  if( isCreate ){
1.145314 +    int iPageSize = 0;
1.145315 +    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
1.145316 +    rc = getIntFromStmt(db, zSql, &iPageSize);
1.145317 +    if( rc==SQLITE_OK ){
1.145318 +      pRtree->iNodeSize = iPageSize-64;
1.145319 +      if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
1.145320 +        pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
1.145321 +      }
1.145322 +    }else{
1.145323 +      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
1.145324 +    }
1.145325 +  }else{
1.145326 +    zSql = sqlite3_mprintf(
1.145327 +        "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
1.145328 +        pRtree->zDb, pRtree->zName
1.145329 +    );
1.145330 +    rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
1.145331 +    if( rc!=SQLITE_OK ){
1.145332 +      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
1.145333 +    }
1.145334 +  }
1.145335 +
1.145336 +  sqlite3_free(zSql);
1.145337 +  return rc;
1.145338 +}
1.145339 +
1.145340 +/* 
1.145341 +** This function is the implementation of both the xConnect and xCreate
1.145342 +** methods of the r-tree virtual table.
1.145343 +**
1.145344 +**   argv[0]   -> module name
1.145345 +**   argv[1]   -> database name
1.145346 +**   argv[2]   -> table name
1.145347 +**   argv[...] -> column names...
1.145348 +*/
1.145349 +static int rtreeInit(
1.145350 +  sqlite3 *db,                        /* Database connection */
1.145351 +  void *pAux,                         /* One of the RTREE_COORD_* constants */
1.145352 +  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
1.145353 +  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
1.145354 +  char **pzErr,                       /* OUT: Error message, if any */
1.145355 +  int isCreate                        /* True for xCreate, false for xConnect */
1.145356 +){
1.145357 +  int rc = SQLITE_OK;
1.145358 +  Rtree *pRtree;
1.145359 +  int nDb;              /* Length of string argv[1] */
1.145360 +  int nName;            /* Length of string argv[2] */
1.145361 +  int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
1.145362 +
1.145363 +  const char *aErrMsg[] = {
1.145364 +    0,                                                    /* 0 */
1.145365 +    "Wrong number of columns for an rtree table",         /* 1 */
1.145366 +    "Too few columns for an rtree table",                 /* 2 */
1.145367 +    "Too many columns for an rtree table"                 /* 3 */
1.145368 +  };
1.145369 +
1.145370 +  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
1.145371 +  if( aErrMsg[iErr] ){
1.145372 +    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
1.145373 +    return SQLITE_ERROR;
1.145374 +  }
1.145375 +
1.145376 +  sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
1.145377 +
1.145378 +  /* Allocate the sqlite3_vtab structure */
1.145379 +  nDb = (int)strlen(argv[1]);
1.145380 +  nName = (int)strlen(argv[2]);
1.145381 +  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
1.145382 +  if( !pRtree ){
1.145383 +    return SQLITE_NOMEM;
1.145384 +  }
1.145385 +  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
1.145386 +  pRtree->nBusy = 1;
1.145387 +  pRtree->base.pModule = &rtreeModule;
1.145388 +  pRtree->zDb = (char *)&pRtree[1];
1.145389 +  pRtree->zName = &pRtree->zDb[nDb+1];
1.145390 +  pRtree->nDim = (argc-4)/2;
1.145391 +  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
1.145392 +  pRtree->eCoordType = eCoordType;
1.145393 +  memcpy(pRtree->zDb, argv[1], nDb);
1.145394 +  memcpy(pRtree->zName, argv[2], nName);
1.145395 +
1.145396 +  /* Figure out the node size to use. */
1.145397 +  rc = getNodeSize(db, pRtree, isCreate, pzErr);
1.145398 +
1.145399 +  /* Create/Connect to the underlying relational database schema. If
1.145400 +  ** that is successful, call sqlite3_declare_vtab() to configure
1.145401 +  ** the r-tree table schema.
1.145402 +  */
1.145403 +  if( rc==SQLITE_OK ){
1.145404 +    if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
1.145405 +      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
1.145406 +    }else{
1.145407 +      char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
1.145408 +      char *zTmp;
1.145409 +      int ii;
1.145410 +      for(ii=4; zSql && ii<argc; ii++){
1.145411 +        zTmp = zSql;
1.145412 +        zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
1.145413 +        sqlite3_free(zTmp);
1.145414 +      }
1.145415 +      if( zSql ){
1.145416 +        zTmp = zSql;
1.145417 +        zSql = sqlite3_mprintf("%s);", zTmp);
1.145418 +        sqlite3_free(zTmp);
1.145419 +      }
1.145420 +      if( !zSql ){
1.145421 +        rc = SQLITE_NOMEM;
1.145422 +      }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
1.145423 +        *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
1.145424 +      }
1.145425 +      sqlite3_free(zSql);
1.145426 +    }
1.145427 +  }
1.145428 +
1.145429 +  if( rc==SQLITE_OK ){
1.145430 +    *ppVtab = (sqlite3_vtab *)pRtree;
1.145431 +  }else{
1.145432 +    rtreeRelease(pRtree);
1.145433 +  }
1.145434 +  return rc;
1.145435 +}
1.145436 +
1.145437 +
1.145438 +/*
1.145439 +** Implementation of a scalar function that decodes r-tree nodes to
1.145440 +** human readable strings. This can be used for debugging and analysis.
1.145441 +**
1.145442 +** The scalar function takes two arguments, a blob of data containing
1.145443 +** an r-tree node, and the number of dimensions the r-tree indexes.
1.145444 +** For a two-dimensional r-tree structure called "rt", to deserialize
1.145445 +** all nodes, a statement like:
1.145446 +**
1.145447 +**   SELECT rtreenode(2, data) FROM rt_node;
1.145448 +**
1.145449 +** The human readable string takes the form of a Tcl list with one
1.145450 +** entry for each cell in the r-tree node. Each entry is itself a
1.145451 +** list, containing the 8-byte rowid/pageno followed by the 
1.145452 +** <num-dimension>*2 coordinates.
1.145453 +*/
1.145454 +static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
1.145455 +  char *zText = 0;
1.145456 +  RtreeNode node;
1.145457 +  Rtree tree;
1.145458 +  int ii;
1.145459 +
1.145460 +  UNUSED_PARAMETER(nArg);
1.145461 +  memset(&node, 0, sizeof(RtreeNode));
1.145462 +  memset(&tree, 0, sizeof(Rtree));
1.145463 +  tree.nDim = sqlite3_value_int(apArg[0]);
1.145464 +  tree.nBytesPerCell = 8 + 8 * tree.nDim;
1.145465 +  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
1.145466 +
1.145467 +  for(ii=0; ii<NCELL(&node); ii++){
1.145468 +    char zCell[512];
1.145469 +    int nCell = 0;
1.145470 +    RtreeCell cell;
1.145471 +    int jj;
1.145472 +
1.145473 +    nodeGetCell(&tree, &node, ii, &cell);
1.145474 +    sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
1.145475 +    nCell = (int)strlen(zCell);
1.145476 +    for(jj=0; jj<tree.nDim*2; jj++){
1.145477 +#ifndef SQLITE_RTREE_INT_ONLY
1.145478 +      sqlite3_snprintf(512-nCell,&zCell[nCell], " %f",
1.145479 +                       (double)cell.aCoord[jj].f);
1.145480 +#else
1.145481 +      sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
1.145482 +                       cell.aCoord[jj].i);
1.145483 +#endif
1.145484 +      nCell = (int)strlen(zCell);
1.145485 +    }
1.145486 +
1.145487 +    if( zText ){
1.145488 +      char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
1.145489 +      sqlite3_free(zText);
1.145490 +      zText = zTextNew;
1.145491 +    }else{
1.145492 +      zText = sqlite3_mprintf("{%s}", zCell);
1.145493 +    }
1.145494 +  }
1.145495 +  
1.145496 +  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
1.145497 +}
1.145498 +
1.145499 +static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
1.145500 +  UNUSED_PARAMETER(nArg);
1.145501 +  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
1.145502 +   || sqlite3_value_bytes(apArg[0])<2
1.145503 +  ){
1.145504 +    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
1.145505 +  }else{
1.145506 +    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
1.145507 +    sqlite3_result_int(ctx, readInt16(zBlob));
1.145508 +  }
1.145509 +}
1.145510 +
1.145511 +/*
1.145512 +** Register the r-tree module with database handle db. This creates the
1.145513 +** virtual table module "rtree" and the debugging/analysis scalar 
1.145514 +** function "rtreenode".
1.145515 +*/
1.145516 +SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
1.145517 +  const int utf8 = SQLITE_UTF8;
1.145518 +  int rc;
1.145519 +
1.145520 +  rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
1.145521 +  if( rc==SQLITE_OK ){
1.145522 +    rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
1.145523 +  }
1.145524 +  if( rc==SQLITE_OK ){
1.145525 +#ifdef SQLITE_RTREE_INT_ONLY
1.145526 +    void *c = (void *)RTREE_COORD_INT32;
1.145527 +#else
1.145528 +    void *c = (void *)RTREE_COORD_REAL32;
1.145529 +#endif
1.145530 +    rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
1.145531 +  }
1.145532 +  if( rc==SQLITE_OK ){
1.145533 +    void *c = (void *)RTREE_COORD_INT32;
1.145534 +    rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
1.145535 +  }
1.145536 +
1.145537 +  return rc;
1.145538 +}
1.145539 +
1.145540 +/*
1.145541 +** A version of sqlite3_free() that can be used as a callback. This is used
1.145542 +** in two places - as the destructor for the blob value returned by the
1.145543 +** invocation of a geometry function, and as the destructor for the geometry
1.145544 +** functions themselves.
1.145545 +*/
1.145546 +static void doSqlite3Free(void *p){
1.145547 +  sqlite3_free(p);
1.145548 +}
1.145549 +
1.145550 +/*
1.145551 +** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
1.145552 +** scalar user function. This C function is the callback used for all such
1.145553 +** registered SQL functions.
1.145554 +**
1.145555 +** The scalar user functions return a blob that is interpreted by r-tree
1.145556 +** table MATCH operators.
1.145557 +*/
1.145558 +static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
1.145559 +  RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
1.145560 +  RtreeMatchArg *pBlob;
1.145561 +  int nBlob;
1.145562 +
1.145563 +  nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
1.145564 +  pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
1.145565 +  if( !pBlob ){
1.145566 +    sqlite3_result_error_nomem(ctx);
1.145567 +  }else{
1.145568 +    int i;
1.145569 +    pBlob->magic = RTREE_GEOMETRY_MAGIC;
1.145570 +    pBlob->xGeom = pGeomCtx->xGeom;
1.145571 +    pBlob->pContext = pGeomCtx->pContext;
1.145572 +    pBlob->nParam = nArg;
1.145573 +    for(i=0; i<nArg; i++){
1.145574 +#ifdef SQLITE_RTREE_INT_ONLY
1.145575 +      pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
1.145576 +#else
1.145577 +      pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
1.145578 +#endif
1.145579 +    }
1.145580 +    sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
1.145581 +  }
1.145582 +}
1.145583 +
1.145584 +/*
1.145585 +** Register a new geometry function for use with the r-tree MATCH operator.
1.145586 +*/
1.145587 +SQLITE_API int sqlite3_rtree_geometry_callback(
1.145588 +  sqlite3 *db,
1.145589 +  const char *zGeom,
1.145590 +  int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *),
1.145591 +  void *pContext
1.145592 +){
1.145593 +  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
1.145594 +
1.145595 +  /* Allocate and populate the context object. */
1.145596 +  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
1.145597 +  if( !pGeomCtx ) return SQLITE_NOMEM;
1.145598 +  pGeomCtx->xGeom = xGeom;
1.145599 +  pGeomCtx->pContext = pContext;
1.145600 +
1.145601 +  /* Create the new user-function. Register a destructor function to delete
1.145602 +  ** the context object when it is no longer required.  */
1.145603 +  return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, 
1.145604 +      (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
1.145605 +  );
1.145606 +}
1.145607 +
1.145608 +#if !SQLITE_CORE
1.145609 +#ifdef _WIN32
1.145610 +__declspec(dllexport)
1.145611 +#endif
1.145612 +SQLITE_API int sqlite3_rtree_init(
1.145613 +  sqlite3 *db,
1.145614 +  char **pzErrMsg,
1.145615 +  const sqlite3_api_routines *pApi
1.145616 +){
1.145617 +  SQLITE_EXTENSION_INIT2(pApi)
1.145618 +  return sqlite3RtreeInit(db);
1.145619 +}
1.145620 +#endif
1.145621 +
1.145622 +#endif
1.145623 +
1.145624 +/************** End of rtree.c ***********************************************/
1.145625 +/************** Begin file icu.c *********************************************/
1.145626 +/*
1.145627 +** 2007 May 6
1.145628 +**
1.145629 +** The author disclaims copyright to this source code.  In place of
1.145630 +** a legal notice, here is a blessing:
1.145631 +**
1.145632 +**    May you do good and not evil.
1.145633 +**    May you find forgiveness for yourself and forgive others.
1.145634 +**    May you share freely, never taking more than you give.
1.145635 +**
1.145636 +*************************************************************************
1.145637 +** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
1.145638 +**
1.145639 +** This file implements an integration between the ICU library 
1.145640 +** ("International Components for Unicode", an open-source library 
1.145641 +** for handling unicode data) and SQLite. The integration uses 
1.145642 +** ICU to provide the following to SQLite:
1.145643 +**
1.145644 +**   * An implementation of the SQL regexp() function (and hence REGEXP
1.145645 +**     operator) using the ICU uregex_XX() APIs.
1.145646 +**
1.145647 +**   * Implementations of the SQL scalar upper() and lower() functions
1.145648 +**     for case mapping.
1.145649 +**
1.145650 +**   * Integration of ICU and SQLite collation sequences.
1.145651 +**
1.145652 +**   * An implementation of the LIKE operator that uses ICU to 
1.145653 +**     provide case-independent matching.
1.145654 +*/
1.145655 +
1.145656 +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
1.145657 +
1.145658 +/* Include ICU headers */
1.145659 +#include <unicode/utypes.h>
1.145660 +#include <unicode/uregex.h>
1.145661 +#include <unicode/ustring.h>
1.145662 +#include <unicode/ucol.h>
1.145663 +
1.145664 +/* #include <assert.h> */
1.145665 +
1.145666 +#ifndef SQLITE_CORE
1.145667 +  SQLITE_EXTENSION_INIT1
1.145668 +#else
1.145669 +#endif
1.145670 +
1.145671 +/*
1.145672 +** Maximum length (in bytes) of the pattern in a LIKE or GLOB
1.145673 +** operator.
1.145674 +*/
1.145675 +#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
1.145676 +# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
1.145677 +#endif
1.145678 +
1.145679 +/*
1.145680 +** Version of sqlite3_free() that is always a function, never a macro.
1.145681 +*/
1.145682 +static void xFree(void *p){
1.145683 +  sqlite3_free(p);
1.145684 +}
1.145685 +
1.145686 +/*
1.145687 +** Compare two UTF-8 strings for equality where the first string is
1.145688 +** a "LIKE" expression. Return true (1) if they are the same and 
1.145689 +** false (0) if they are different.
1.145690 +*/
1.145691 +static int icuLikeCompare(
1.145692 +  const uint8_t *zPattern,   /* LIKE pattern */
1.145693 +  const uint8_t *zString,    /* The UTF-8 string to compare against */
1.145694 +  const UChar32 uEsc         /* The escape character */
1.145695 +){
1.145696 +  static const int MATCH_ONE = (UChar32)'_';
1.145697 +  static const int MATCH_ALL = (UChar32)'%';
1.145698 +
1.145699 +  int iPattern = 0;       /* Current byte index in zPattern */
1.145700 +  int iString = 0;        /* Current byte index in zString */
1.145701 +
1.145702 +  int prevEscape = 0;     /* True if the previous character was uEsc */
1.145703 +
1.145704 +  while( zPattern[iPattern]!=0 ){
1.145705 +
1.145706 +    /* Read (and consume) the next character from the input pattern. */
1.145707 +    UChar32 uPattern;
1.145708 +    U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
1.145709 +    assert(uPattern!=0);
1.145710 +
1.145711 +    /* There are now 4 possibilities:
1.145712 +    **
1.145713 +    **     1. uPattern is an unescaped match-all character "%",
1.145714 +    **     2. uPattern is an unescaped match-one character "_",
1.145715 +    **     3. uPattern is an unescaped escape character, or
1.145716 +    **     4. uPattern is to be handled as an ordinary character
1.145717 +    */
1.145718 +    if( !prevEscape && uPattern==MATCH_ALL ){
1.145719 +      /* Case 1. */
1.145720 +      uint8_t c;
1.145721 +
1.145722 +      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
1.145723 +      ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
1.145724 +      ** test string.
1.145725 +      */
1.145726 +      while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
1.145727 +        if( c==MATCH_ONE ){
1.145728 +          if( zString[iString]==0 ) return 0;
1.145729 +          U8_FWD_1_UNSAFE(zString, iString);
1.145730 +        }
1.145731 +        iPattern++;
1.145732 +      }
1.145733 +
1.145734 +      if( zPattern[iPattern]==0 ) return 1;
1.145735 +
1.145736 +      while( zString[iString] ){
1.145737 +        if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
1.145738 +          return 1;
1.145739 +        }
1.145740 +        U8_FWD_1_UNSAFE(zString, iString);
1.145741 +      }
1.145742 +      return 0;
1.145743 +
1.145744 +    }else if( !prevEscape && uPattern==MATCH_ONE ){
1.145745 +      /* Case 2. */
1.145746 +      if( zString[iString]==0 ) return 0;
1.145747 +      U8_FWD_1_UNSAFE(zString, iString);
1.145748 +
1.145749 +    }else if( !prevEscape && uPattern==uEsc){
1.145750 +      /* Case 3. */
1.145751 +      prevEscape = 1;
1.145752 +
1.145753 +    }else{
1.145754 +      /* Case 4. */
1.145755 +      UChar32 uString;
1.145756 +      U8_NEXT_UNSAFE(zString, iString, uString);
1.145757 +      uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
1.145758 +      uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
1.145759 +      if( uString!=uPattern ){
1.145760 +        return 0;
1.145761 +      }
1.145762 +      prevEscape = 0;
1.145763 +    }
1.145764 +  }
1.145765 +
1.145766 +  return zString[iString]==0;
1.145767 +}
1.145768 +
1.145769 +/*
1.145770 +** Implementation of the like() SQL function.  This function implements
1.145771 +** the build-in LIKE operator.  The first argument to the function is the
1.145772 +** pattern and the second argument is the string.  So, the SQL statements:
1.145773 +**
1.145774 +**       A LIKE B
1.145775 +**
1.145776 +** is implemented as like(B, A). If there is an escape character E, 
1.145777 +**
1.145778 +**       A LIKE B ESCAPE E
1.145779 +**
1.145780 +** is mapped to like(B, A, E).
1.145781 +*/
1.145782 +static void icuLikeFunc(
1.145783 +  sqlite3_context *context, 
1.145784 +  int argc, 
1.145785 +  sqlite3_value **argv
1.145786 +){
1.145787 +  const unsigned char *zA = sqlite3_value_text(argv[0]);
1.145788 +  const unsigned char *zB = sqlite3_value_text(argv[1]);
1.145789 +  UChar32 uEsc = 0;
1.145790 +
1.145791 +  /* Limit the length of the LIKE or GLOB pattern to avoid problems
1.145792 +  ** of deep recursion and N*N behavior in patternCompare().
1.145793 +  */
1.145794 +  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
1.145795 +    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
1.145796 +    return;
1.145797 +  }
1.145798 +
1.145799 +
1.145800 +  if( argc==3 ){
1.145801 +    /* The escape character string must consist of a single UTF-8 character.
1.145802 +    ** Otherwise, return an error.
1.145803 +    */
1.145804 +    int nE= sqlite3_value_bytes(argv[2]);
1.145805 +    const unsigned char *zE = sqlite3_value_text(argv[2]);
1.145806 +    int i = 0;
1.145807 +    if( zE==0 ) return;
1.145808 +    U8_NEXT(zE, i, nE, uEsc);
1.145809 +    if( i!=nE){
1.145810 +      sqlite3_result_error(context, 
1.145811 +          "ESCAPE expression must be a single character", -1);
1.145812 +      return;
1.145813 +    }
1.145814 +  }
1.145815 +
1.145816 +  if( zA && zB ){
1.145817 +    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
1.145818 +  }
1.145819 +}
1.145820 +
1.145821 +/*
1.145822 +** This function is called when an ICU function called from within
1.145823 +** the implementation of an SQL scalar function returns an error.
1.145824 +**
1.145825 +** The scalar function context passed as the first argument is 
1.145826 +** loaded with an error message based on the following two args.
1.145827 +*/
1.145828 +static void icuFunctionError(
1.145829 +  sqlite3_context *pCtx,       /* SQLite scalar function context */
1.145830 +  const char *zName,           /* Name of ICU function that failed */
1.145831 +  UErrorCode e                 /* Error code returned by ICU function */
1.145832 +){
1.145833 +  char zBuf[128];
1.145834 +  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
1.145835 +  zBuf[127] = '\0';
1.145836 +  sqlite3_result_error(pCtx, zBuf, -1);
1.145837 +}
1.145838 +
1.145839 +/*
1.145840 +** Function to delete compiled regexp objects. Registered as
1.145841 +** a destructor function with sqlite3_set_auxdata().
1.145842 +*/
1.145843 +static void icuRegexpDelete(void *p){
1.145844 +  URegularExpression *pExpr = (URegularExpression *)p;
1.145845 +  uregex_close(pExpr);
1.145846 +}
1.145847 +
1.145848 +/*
1.145849 +** Implementation of SQLite REGEXP operator. This scalar function takes
1.145850 +** two arguments. The first is a regular expression pattern to compile
1.145851 +** the second is a string to match against that pattern. If either 
1.145852 +** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
1.145853 +** is 1 if the string matches the pattern, or 0 otherwise.
1.145854 +**
1.145855 +** SQLite maps the regexp() function to the regexp() operator such
1.145856 +** that the following two are equivalent:
1.145857 +**
1.145858 +**     zString REGEXP zPattern
1.145859 +**     regexp(zPattern, zString)
1.145860 +**
1.145861 +** Uses the following ICU regexp APIs:
1.145862 +**
1.145863 +**     uregex_open()
1.145864 +**     uregex_matches()
1.145865 +**     uregex_close()
1.145866 +*/
1.145867 +static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
1.145868 +  UErrorCode status = U_ZERO_ERROR;
1.145869 +  URegularExpression *pExpr;
1.145870 +  UBool res;
1.145871 +  const UChar *zString = sqlite3_value_text16(apArg[1]);
1.145872 +
1.145873 +  (void)nArg;  /* Unused parameter */
1.145874 +
1.145875 +  /* If the left hand side of the regexp operator is NULL, 
1.145876 +  ** then the result is also NULL. 
1.145877 +  */
1.145878 +  if( !zString ){
1.145879 +    return;
1.145880 +  }
1.145881 +
1.145882 +  pExpr = sqlite3_get_auxdata(p, 0);
1.145883 +  if( !pExpr ){
1.145884 +    const UChar *zPattern = sqlite3_value_text16(apArg[0]);
1.145885 +    if( !zPattern ){
1.145886 +      return;
1.145887 +    }
1.145888 +    pExpr = uregex_open(zPattern, -1, 0, 0, &status);
1.145889 +
1.145890 +    if( U_SUCCESS(status) ){
1.145891 +      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
1.145892 +    }else{
1.145893 +      assert(!pExpr);
1.145894 +      icuFunctionError(p, "uregex_open", status);
1.145895 +      return;
1.145896 +    }
1.145897 +  }
1.145898 +
1.145899 +  /* Configure the text that the regular expression operates on. */
1.145900 +  uregex_setText(pExpr, zString, -1, &status);
1.145901 +  if( !U_SUCCESS(status) ){
1.145902 +    icuFunctionError(p, "uregex_setText", status);
1.145903 +    return;
1.145904 +  }
1.145905 +
1.145906 +  /* Attempt the match */
1.145907 +  res = uregex_matches(pExpr, 0, &status);
1.145908 +  if( !U_SUCCESS(status) ){
1.145909 +    icuFunctionError(p, "uregex_matches", status);
1.145910 +    return;
1.145911 +  }
1.145912 +
1.145913 +  /* Set the text that the regular expression operates on to a NULL
1.145914 +  ** pointer. This is not really necessary, but it is tidier than 
1.145915 +  ** leaving the regular expression object configured with an invalid
1.145916 +  ** pointer after this function returns.
1.145917 +  */
1.145918 +  uregex_setText(pExpr, 0, 0, &status);
1.145919 +
1.145920 +  /* Return 1 or 0. */
1.145921 +  sqlite3_result_int(p, res ? 1 : 0);
1.145922 +}
1.145923 +
1.145924 +/*
1.145925 +** Implementations of scalar functions for case mapping - upper() and 
1.145926 +** lower(). Function upper() converts its input to upper-case (ABC).
1.145927 +** Function lower() converts to lower-case (abc).
1.145928 +**
1.145929 +** ICU provides two types of case mapping, "general" case mapping and
1.145930 +** "language specific". Refer to ICU documentation for the differences
1.145931 +** between the two.
1.145932 +**
1.145933 +** To utilise "general" case mapping, the upper() or lower() scalar 
1.145934 +** functions are invoked with one argument:
1.145935 +**
1.145936 +**     upper('ABC') -> 'abc'
1.145937 +**     lower('abc') -> 'ABC'
1.145938 +**
1.145939 +** To access ICU "language specific" case mapping, upper() or lower()
1.145940 +** should be invoked with two arguments. The second argument is the name
1.145941 +** of the locale to use. Passing an empty string ("") or SQL NULL value
1.145942 +** as the second argument is the same as invoking the 1 argument version
1.145943 +** of upper() or lower().
1.145944 +**
1.145945 +**     lower('I', 'en_us') -> 'i'
1.145946 +**     lower('I', 'tr_tr') -> 'ı' (small dotless i)
1.145947 +**
1.145948 +** http://www.icu-project.org/userguide/posix.html#case_mappings
1.145949 +*/
1.145950 +static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
1.145951 +  const UChar *zInput;
1.145952 +  UChar *zOutput;
1.145953 +  int nInput;
1.145954 +  int nOutput;
1.145955 +
1.145956 +  UErrorCode status = U_ZERO_ERROR;
1.145957 +  const char *zLocale = 0;
1.145958 +
1.145959 +  assert(nArg==1 || nArg==2);
1.145960 +  if( nArg==2 ){
1.145961 +    zLocale = (const char *)sqlite3_value_text(apArg[1]);
1.145962 +  }
1.145963 +
1.145964 +  zInput = sqlite3_value_text16(apArg[0]);
1.145965 +  if( !zInput ){
1.145966 +    return;
1.145967 +  }
1.145968 +  nInput = sqlite3_value_bytes16(apArg[0]);
1.145969 +
1.145970 +  nOutput = nInput * 2 + 2;
1.145971 +  zOutput = sqlite3_malloc(nOutput);
1.145972 +  if( !zOutput ){
1.145973 +    return;
1.145974 +  }
1.145975 +
1.145976 +  if( sqlite3_user_data(p) ){
1.145977 +    u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
1.145978 +  }else{
1.145979 +    u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
1.145980 +  }
1.145981 +
1.145982 +  if( !U_SUCCESS(status) ){
1.145983 +    icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
1.145984 +    return;
1.145985 +  }
1.145986 +
1.145987 +  sqlite3_result_text16(p, zOutput, -1, xFree);
1.145988 +}
1.145989 +
1.145990 +/*
1.145991 +** Collation sequence destructor function. The pCtx argument points to
1.145992 +** a UCollator structure previously allocated using ucol_open().
1.145993 +*/
1.145994 +static void icuCollationDel(void *pCtx){
1.145995 +  UCollator *p = (UCollator *)pCtx;
1.145996 +  ucol_close(p);
1.145997 +}
1.145998 +
1.145999 +/*
1.146000 +** Collation sequence comparison function. The pCtx argument points to
1.146001 +** a UCollator structure previously allocated using ucol_open().
1.146002 +*/
1.146003 +static int icuCollationColl(
1.146004 +  void *pCtx,
1.146005 +  int nLeft,
1.146006 +  const void *zLeft,
1.146007 +  int nRight,
1.146008 +  const void *zRight
1.146009 +){
1.146010 +  UCollationResult res;
1.146011 +  UCollator *p = (UCollator *)pCtx;
1.146012 +  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
1.146013 +  switch( res ){
1.146014 +    case UCOL_LESS:    return -1;
1.146015 +    case UCOL_GREATER: return +1;
1.146016 +    case UCOL_EQUAL:   return 0;
1.146017 +  }
1.146018 +  assert(!"Unexpected return value from ucol_strcoll()");
1.146019 +  return 0;
1.146020 +}
1.146021 +
1.146022 +/*
1.146023 +** Implementation of the scalar function icu_load_collation().
1.146024 +**
1.146025 +** This scalar function is used to add ICU collation based collation 
1.146026 +** types to an SQLite database connection. It is intended to be called
1.146027 +** as follows:
1.146028 +**
1.146029 +**     SELECT icu_load_collation(<locale>, <collation-name>);
1.146030 +**
1.146031 +** Where <locale> is a string containing an ICU locale identifier (i.e.
1.146032 +** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
1.146033 +** collation sequence to create.
1.146034 +*/
1.146035 +static void icuLoadCollation(
1.146036 +  sqlite3_context *p, 
1.146037 +  int nArg, 
1.146038 +  sqlite3_value **apArg
1.146039 +){
1.146040 +  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
1.146041 +  UErrorCode status = U_ZERO_ERROR;
1.146042 +  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
1.146043 +  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
1.146044 +  UCollator *pUCollator;    /* ICU library collation object */
1.146045 +  int rc;                   /* Return code from sqlite3_create_collation_x() */
1.146046 +
1.146047 +  assert(nArg==2);
1.146048 +  zLocale = (const char *)sqlite3_value_text(apArg[0]);
1.146049 +  zName = (const char *)sqlite3_value_text(apArg[1]);
1.146050 +
1.146051 +  if( !zLocale || !zName ){
1.146052 +    return;
1.146053 +  }
1.146054 +
1.146055 +  pUCollator = ucol_open(zLocale, &status);
1.146056 +  if( !U_SUCCESS(status) ){
1.146057 +    icuFunctionError(p, "ucol_open", status);
1.146058 +    return;
1.146059 +  }
1.146060 +  assert(p);
1.146061 +
1.146062 +  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
1.146063 +      icuCollationColl, icuCollationDel
1.146064 +  );
1.146065 +  if( rc!=SQLITE_OK ){
1.146066 +    ucol_close(pUCollator);
1.146067 +    sqlite3_result_error(p, "Error registering collation function", -1);
1.146068 +  }
1.146069 +}
1.146070 +
1.146071 +/*
1.146072 +** Register the ICU extension functions with database db.
1.146073 +*/
1.146074 +SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
1.146075 +  struct IcuScalar {
1.146076 +    const char *zName;                        /* Function name */
1.146077 +    int nArg;                                 /* Number of arguments */
1.146078 +    int enc;                                  /* Optimal text encoding */
1.146079 +    void *pContext;                           /* sqlite3_user_data() context */
1.146080 +    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
1.146081 +  } scalars[] = {
1.146082 +    {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
1.146083 +
1.146084 +    {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
1.146085 +    {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
1.146086 +    {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
1.146087 +    {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
1.146088 +
1.146089 +    {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
1.146090 +    {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
1.146091 +    {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
1.146092 +    {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
1.146093 +
1.146094 +    {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
1.146095 +    {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
1.146096 +
1.146097 +    {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
1.146098 +  };
1.146099 +
1.146100 +  int rc = SQLITE_OK;
1.146101 +  int i;
1.146102 +
1.146103 +  for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
1.146104 +    struct IcuScalar *p = &scalars[i];
1.146105 +    rc = sqlite3_create_function(
1.146106 +        db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
1.146107 +    );
1.146108 +  }
1.146109 +
1.146110 +  return rc;
1.146111 +}
1.146112 +
1.146113 +#if !SQLITE_CORE
1.146114 +#ifdef _WIN32
1.146115 +__declspec(dllexport)
1.146116 +#endif
1.146117 +SQLITE_API int sqlite3_icu_init(
1.146118 +  sqlite3 *db, 
1.146119 +  char **pzErrMsg,
1.146120 +  const sqlite3_api_routines *pApi
1.146121 +){
1.146122 +  SQLITE_EXTENSION_INIT2(pApi)
1.146123 +  return sqlite3IcuInit(db);
1.146124 +}
1.146125 +#endif
1.146126 +
1.146127 +#endif
1.146128 +
1.146129 +/************** End of icu.c *************************************************/
1.146130 +/************** Begin file fts3_icu.c ****************************************/
1.146131 +/*
1.146132 +** 2007 June 22
1.146133 +**
1.146134 +** The author disclaims copyright to this source code.  In place of
1.146135 +** a legal notice, here is a blessing:
1.146136 +**
1.146137 +**    May you do good and not evil.
1.146138 +**    May you find forgiveness for yourself and forgive others.
1.146139 +**    May you share freely, never taking more than you give.
1.146140 +**
1.146141 +*************************************************************************
1.146142 +** This file implements a tokenizer for fts3 based on the ICU library.
1.146143 +*/
1.146144 +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
1.146145 +#ifdef SQLITE_ENABLE_ICU
1.146146 +
1.146147 +/* #include <assert.h> */
1.146148 +/* #include <string.h> */
1.146149 +
1.146150 +#include <unicode/ubrk.h>
1.146151 +/* #include <unicode/ucol.h> */
1.146152 +/* #include <unicode/ustring.h> */
1.146153 +#include <unicode/utf16.h>
1.146154 +
1.146155 +typedef struct IcuTokenizer IcuTokenizer;
1.146156 +typedef struct IcuCursor IcuCursor;
1.146157 +
1.146158 +struct IcuTokenizer {
1.146159 +  sqlite3_tokenizer base;
1.146160 +  char *zLocale;
1.146161 +};
1.146162 +
1.146163 +struct IcuCursor {
1.146164 +  sqlite3_tokenizer_cursor base;
1.146165 +
1.146166 +  UBreakIterator *pIter;      /* ICU break-iterator object */
1.146167 +  int nChar;                  /* Number of UChar elements in pInput */
1.146168 +  UChar *aChar;               /* Copy of input using utf-16 encoding */
1.146169 +  int *aOffset;               /* Offsets of each character in utf-8 input */
1.146170 +
1.146171 +  int nBuffer;
1.146172 +  char *zBuffer;
1.146173 +
1.146174 +  int iToken;
1.146175 +};
1.146176 +
1.146177 +/*
1.146178 +** Create a new tokenizer instance.
1.146179 +*/
1.146180 +static int icuCreate(
1.146181 +  int argc,                            /* Number of entries in argv[] */
1.146182 +  const char * const *argv,            /* Tokenizer creation arguments */
1.146183 +  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
1.146184 +){
1.146185 +  IcuTokenizer *p;
1.146186 +  int n = 0;
1.146187 +
1.146188 +  if( argc>0 ){
1.146189 +    n = strlen(argv[0])+1;
1.146190 +  }
1.146191 +  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
1.146192 +  if( !p ){
1.146193 +    return SQLITE_NOMEM;
1.146194 +  }
1.146195 +  memset(p, 0, sizeof(IcuTokenizer));
1.146196 +
1.146197 +  if( n ){
1.146198 +    p->zLocale = (char *)&p[1];
1.146199 +    memcpy(p->zLocale, argv[0], n);
1.146200 +  }
1.146201 +
1.146202 +  *ppTokenizer = (sqlite3_tokenizer *)p;
1.146203 +
1.146204 +  return SQLITE_OK;
1.146205 +}
1.146206 +
1.146207 +/*
1.146208 +** Destroy a tokenizer
1.146209 +*/
1.146210 +static int icuDestroy(sqlite3_tokenizer *pTokenizer){
1.146211 +  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
1.146212 +  sqlite3_free(p);
1.146213 +  return SQLITE_OK;
1.146214 +}
1.146215 +
1.146216 +/*
1.146217 +** Prepare to begin tokenizing a particular string.  The input
1.146218 +** string to be tokenized is pInput[0..nBytes-1].  A cursor
1.146219 +** used to incrementally tokenize this string is returned in 
1.146220 +** *ppCursor.
1.146221 +*/
1.146222 +static int icuOpen(
1.146223 +  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
1.146224 +  const char *zInput,                    /* Input string */
1.146225 +  int nInput,                            /* Length of zInput in bytes */
1.146226 +  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
1.146227 +){
1.146228 +  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
1.146229 +  IcuCursor *pCsr;
1.146230 +
1.146231 +  const int32_t opt = U_FOLD_CASE_DEFAULT;
1.146232 +  UErrorCode status = U_ZERO_ERROR;
1.146233 +  int nChar;
1.146234 +
1.146235 +  UChar32 c;
1.146236 +  int iInput = 0;
1.146237 +  int iOut = 0;
1.146238 +
1.146239 +  *ppCursor = 0;
1.146240 +
1.146241 +  if( zInput==0 ){
1.146242 +    nInput = 0;
1.146243 +    zInput = "";
1.146244 +  }else if( nInput<0 ){
1.146245 +    nInput = strlen(zInput);
1.146246 +  }
1.146247 +  nChar = nInput+1;
1.146248 +  pCsr = (IcuCursor *)sqlite3_malloc(
1.146249 +      sizeof(IcuCursor) +                /* IcuCursor */
1.146250 +      ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
1.146251 +      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
1.146252 +  );
1.146253 +  if( !pCsr ){
1.146254 +    return SQLITE_NOMEM;
1.146255 +  }
1.146256 +  memset(pCsr, 0, sizeof(IcuCursor));
1.146257 +  pCsr->aChar = (UChar *)&pCsr[1];
1.146258 +  pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
1.146259 +
1.146260 +  pCsr->aOffset[iOut] = iInput;
1.146261 +  U8_NEXT(zInput, iInput, nInput, c); 
1.146262 +  while( c>0 ){
1.146263 +    int isError = 0;
1.146264 +    c = u_foldCase(c, opt);
1.146265 +    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
1.146266 +    if( isError ){
1.146267 +      sqlite3_free(pCsr);
1.146268 +      return SQLITE_ERROR;
1.146269 +    }
1.146270 +    pCsr->aOffset[iOut] = iInput;
1.146271 +
1.146272 +    if( iInput<nInput ){
1.146273 +      U8_NEXT(zInput, iInput, nInput, c);
1.146274 +    }else{
1.146275 +      c = 0;
1.146276 +    }
1.146277 +  }
1.146278 +
1.146279 +  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
1.146280 +  if( !U_SUCCESS(status) ){
1.146281 +    sqlite3_free(pCsr);
1.146282 +    return SQLITE_ERROR;
1.146283 +  }
1.146284 +  pCsr->nChar = iOut;
1.146285 +
1.146286 +  ubrk_first(pCsr->pIter);
1.146287 +  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
1.146288 +  return SQLITE_OK;
1.146289 +}
1.146290 +
1.146291 +/*
1.146292 +** Close a tokenization cursor previously opened by a call to icuOpen().
1.146293 +*/
1.146294 +static int icuClose(sqlite3_tokenizer_cursor *pCursor){
1.146295 +  IcuCursor *pCsr = (IcuCursor *)pCursor;
1.146296 +  ubrk_close(pCsr->pIter);
1.146297 +  sqlite3_free(pCsr->zBuffer);
1.146298 +  sqlite3_free(pCsr);
1.146299 +  return SQLITE_OK;
1.146300 +}
1.146301 +
1.146302 +/*
1.146303 +** Extract the next token from a tokenization cursor.
1.146304 +*/
1.146305 +static int icuNext(
1.146306 +  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
1.146307 +  const char **ppToken,               /* OUT: *ppToken is the token text */
1.146308 +  int *pnBytes,                       /* OUT: Number of bytes in token */
1.146309 +  int *piStartOffset,                 /* OUT: Starting offset of token */
1.146310 +  int *piEndOffset,                   /* OUT: Ending offset of token */
1.146311 +  int *piPosition                     /* OUT: Position integer of token */
1.146312 +){
1.146313 +  IcuCursor *pCsr = (IcuCursor *)pCursor;
1.146314 +
1.146315 +  int iStart = 0;
1.146316 +  int iEnd = 0;
1.146317 +  int nByte = 0;
1.146318 +
1.146319 +  while( iStart==iEnd ){
1.146320 +    UChar32 c;
1.146321 +
1.146322 +    iStart = ubrk_current(pCsr->pIter);
1.146323 +    iEnd = ubrk_next(pCsr->pIter);
1.146324 +    if( iEnd==UBRK_DONE ){
1.146325 +      return SQLITE_DONE;
1.146326 +    }
1.146327 +
1.146328 +    while( iStart<iEnd ){
1.146329 +      int iWhite = iStart;
1.146330 +      U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
1.146331 +      if( u_isspace(c) ){
1.146332 +        iStart = iWhite;
1.146333 +      }else{
1.146334 +        break;
1.146335 +      }
1.146336 +    }
1.146337 +    assert(iStart<=iEnd);
1.146338 +  }
1.146339 +
1.146340 +  do {
1.146341 +    UErrorCode status = U_ZERO_ERROR;
1.146342 +    if( nByte ){
1.146343 +      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
1.146344 +      if( !zNew ){
1.146345 +        return SQLITE_NOMEM;
1.146346 +      }
1.146347 +      pCsr->zBuffer = zNew;
1.146348 +      pCsr->nBuffer = nByte;
1.146349 +    }
1.146350 +
1.146351 +    u_strToUTF8(
1.146352 +        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
1.146353 +        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
1.146354 +        &status                                  /* Output success/failure */
1.146355 +    );
1.146356 +  } while( nByte>pCsr->nBuffer );
1.146357 +
1.146358 +  *ppToken = pCsr->zBuffer;
1.146359 +  *pnBytes = nByte;
1.146360 +  *piStartOffset = pCsr->aOffset[iStart];
1.146361 +  *piEndOffset = pCsr->aOffset[iEnd];
1.146362 +  *piPosition = pCsr->iToken++;
1.146363 +
1.146364 +  return SQLITE_OK;
1.146365 +}
1.146366 +
1.146367 +/*
1.146368 +** The set of routines that implement the simple tokenizer
1.146369 +*/
1.146370 +static const sqlite3_tokenizer_module icuTokenizerModule = {
1.146371 +  0,                           /* iVersion */
1.146372 +  icuCreate,                   /* xCreate  */
1.146373 +  icuDestroy,                  /* xCreate  */
1.146374 +  icuOpen,                     /* xOpen    */
1.146375 +  icuClose,                    /* xClose   */
1.146376 +  icuNext,                     /* xNext    */
1.146377 +};
1.146378 +
1.146379 +/*
1.146380 +** Set *ppModule to point at the implementation of the ICU tokenizer.
1.146381 +*/
1.146382 +SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
1.146383 +  sqlite3_tokenizer_module const**ppModule
1.146384 +){
1.146385 +  *ppModule = &icuTokenizerModule;
1.146386 +}
1.146387 +
1.146388 +#endif /* defined(SQLITE_ENABLE_ICU) */
1.146389 +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
1.146390 +
1.146391 +/************** End of fts3_icu.c ********************************************/

mercurial